<?php
// $Id: path.module,v 1.105.2.3 2009/01/14 05:59:09 drumm Exp $

/**
 * @file
 * Enables users to rename URLs.
 */

/**
 * Implementation of hook_help().
 */
function path_help($section) {
  switch ($section) {
    case 'admin/help#path':
      $output = '<p>'. t('The path module allows you to specify aliases for Drupal URLs. Such aliases improve readability of URLs for your users and may help internet search engines to index your content more effectively. More than one alias may be created for a given page.') .'</p>';
      $output .= t('<p>Some examples of URL aliases are:</p>
<ul>
<li>user/login =&gt; login</li>
<li>image/tid/16 =&gt; store</li>
<li>taxonomy/term/7+19+20+21 =&gt; store/products/whirlygigs</li>
<li>node/3 =&gt; contact</li>
</ul>
');
      $output .= '<p>'. t('The path module enables an extra field for aliases in all node input and editing forms (when users have the appropriate permissions). It also provides an interface to view and edit all URL aliases. The two permissions related to URL aliasing are "administer url aliases" and "create url aliases". ') .'</p>';
      $output .= '<p>'. t('This module also comes with user-defined mass URL aliasing capabilities, which is useful if you wish to uniformly use URLs different from the default. For example, you may want to have your URLs presented in a different language. Access to the Drupal source code on the web server is required to set up these kinds of aliases. ') .'</p>';
      $output .= '<p>'. t('For more information please read the configuration and customization handbook <a href="@path">Path page</a>.', array('@path' => 'http://drupal.org/handbook/modules/path/')) .'</p>';
      return $output;
    case 'admin/build/path':
      return '<p>'. t("Drupal provides users complete control over URLs through aliasing. This feature is typically used to make URLs human-readable or easy to remember. For example, one could map the relative URL 'node/1' onto 'about'. Each system path can have multiple aliases.") .'</p>';
    case 'admin/build/path/add':
      return '<p>'. t('Enter the path you wish to create the alias for, followed by the name of the new alias.') .'</p>';
  }
}

/**
 * Implementation of hook_menu().
 */
function path_menu($may_cache) {
  $items = array();

  if ($may_cache) {
    $items[] = array('path' => 'admin/build/path', 'title' => t('URL aliases'),
      'description' => t('Change your site\'s URL paths by aliasing them.'),
      'callback' => 'path_admin',
      'access' => user_access('administer url aliases'));
    $items[] = array('path' => 'admin/build/path/edit', 'title' => t('Edit alias'),
      'callback' => 'drupal_get_form',
      'callback arguments' => array('path_admin_edit'),
      'access' => user_access('administer url aliases'),
      'type' => MENU_CALLBACK);
    $items[] = array('path' => 'admin/build/path/delete', 'title' => t('Delete alias'),
      'callback' => 'drupal_get_form',
      'callback arguments' => array('path_admin_delete_confirm'),
      'access' => user_access('administer url aliases'),
      'type' => MENU_CALLBACK);
    $items[] = array('path' => 'admin/build/path/list', 'title' => t('List'),
      'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => -10);
    $items[] = array('path' => 'admin/build/path/add', 'title' => t('Add alias'),
      'callback' => 'drupal_get_form',
      'callback arguments' => array('path_admin_edit'),
      'access' => user_access('administer url aliases'),
      'type' => MENU_LOCAL_TASK);
  }

  return $items;
}

/**
 * Menu callback; presents an overview of all URL aliases.
 */
function path_admin() {
  return path_overview();
}

/**
 * Menu callback; handles pages for creating and editing URL aliases.
 */
function path_admin_edit($pid = 0) {
  if ($pid) {
    $alias = path_load($pid);
    drupal_set_title(check_plain($alias['dst']));
    $output = path_form($alias);
  }
  else {
    $output = path_form();
  }

  return $output;
}

/**
 * Menu callback; confirms deleting an URL alias
 **/
function path_admin_delete_confirm($pid) {
  $path = path_load($pid);
  if (user_access('administer url aliases')) {
    $form['pid'] = array('#type' => 'value', '#value' => $pid);
    $output = confirm_form($form,
  t('Are you sure you want to delete path alias %title?', array('%title' => $path['dst'])),
   isset($_GET['destination']) ? $_GET['destination'] : 'admin/build/path', t('This action cannot be undone.'),
  t('Delete'), t('Cancel') );
  }

  return $output;
}

/**
 * Execute URL alias deletion
 **/
function path_admin_delete_confirm_submit($form_id, $form_values) {
  if ($form_values['confirm']) {
    path_admin_delete($form_values['pid']);
    return 'admin/build/path';
  }
}

/**
 * Post-confirmation; delete an URL alias.
 */
function path_admin_delete($pid = 0) {
  db_query('DELETE FROM {url_alias} WHERE pid = %d', $pid);
  drupal_set_message(t('The alias has been deleted.'));
}



/**
 * Set an aliased path for a given Drupal path, preventing duplicates.
 */
function path_set_alias($path = NULL, $alias = NULL, $pid = NULL) {
  if ($path && !$alias) {
    db_query("DELETE FROM {url_alias} WHERE src = '%s'", $path);
    drupal_clear_path_cache();
  }
  else if (!$path && $alias) {
    db_query("DELETE FROM {url_alias} WHERE dst = '%s'", $alias);
    drupal_clear_path_cache();
  }
  else if ($path && $alias) {
    $path = urldecode($path);
    $path_count = db_result(db_query("SELECT COUNT(src) FROM {url_alias} WHERE src = '%s'", $path));
    $alias = urldecode($alias);
    $alias_count = db_result(db_query("SELECT COUNT(dst) FROM {url_alias} WHERE dst = '%s'", $alias));

    // We have an insert:
    if ($path_count == 0 && $alias_count == 0) {
      db_query("INSERT INTO {url_alias} (src, dst) VALUES ('%s', '%s')", $path, $alias);
      drupal_clear_path_cache();
    }
    else if ($path_count >= 1 && $alias_count == 0) {
      if ($pid) {
        db_query("UPDATE {url_alias} SET dst = '%s', src = '%s' WHERE pid = %d", $alias, $path, $pid);
      }
      else {
        db_query("INSERT INTO {url_alias} (src, dst) VALUES ('%s', '%s')", $path, $alias);
      }
      drupal_clear_path_cache();
    }
    else if ($path_count == 0 && $alias_count == 1) {
      db_query("UPDATE {url_alias} SET src = '%s' WHERE dst = '%s'", $path, $alias);
      drupal_clear_path_cache();
    }
    else if ($path_count == 1 && $alias_count == 1) {
      // This will delete the path that alias was originally pointing to:
      path_set_alias(NULL, $alias);
      path_set_alias($path);
      path_set_alias($path, $alias);
    }
  }
}

/**
 * Return a form for editing or creating an individual URL alias.
 */
function path_form($edit = '') {
  $form['#base'] = 'path_form';

  $form['src'] = array(
    '#type' => 'textfield',
    '#title' => t('Existing system path'),
    '#default_value' => $edit['src'],
    '#maxlength' => 128,
    '#size' => 45,
    '#description' => t('Specify the existing path you wish to alias. For example: node/28, forum/1, taxonomy/term/1+2.'),
    '#field_prefix' => url(NULL, NULL, NULL, TRUE) . (variable_get('clean_url', 0) ? '' : '?q=')
  );
  $form['dst'] = array(
    '#type' => 'textfield',
    '#default_value' => $edit['dst'],
    '#maxlength' => 128,
    '#size' => 45,
    '#description' => t('Specify an alternative path by which this data can be accessed. For example, type "about" when writing an about page. Use a relative path and don\'t add a trailing slash or the URL alias won\'t work.'),
    '#field_prefix' => url(NULL, NULL, NULL, TRUE) . (variable_get('clean_url', 0) ? '' : '?q=')
  );

  if ($edit['pid']) {
    $form['pid'] = array('#type' => 'hidden', '#value' => $edit['pid']);
    $form['submit'] = array('#type' => 'submit', '#value' => t('Update alias'));
  }
  else {
    $form['submit'] = array('#type' => 'submit', '#value' => t('Create new alias'));
  }

  return $form;
}

/**
 * Implementation of hook_nodeapi().
 *
 * Allows URL aliases for nodes to be specified at node edit time rather
 * than through the administrative interface.
 */
function path_nodeapi(&$node, $op, $arg) {
  if (user_access('create url aliases') || user_access('administer url aliases') || ($op == 'load')) {
    switch ($op) {
      case 'validate':
        $node->path = trim($node->path);
        if (db_result(db_query("SELECT COUNT(dst) FROM {url_alias} WHERE dst = '%s' AND src != '%s'", $node->path, "node/$node->nid"))) {
          form_set_error('path', t('The path is already in use.'));
        }
        break;

      case 'load':
        $path = "node/$node->nid";
        // We don't use drupal_get_path_alias() to avoid custom rewrite functions.
        // We only care about exact aliases.
        $result = db_query("SELECT dst FROM {url_alias} WHERE src = '%s'", $path);
        if (db_num_rows($result)) {
          $node->path = db_result($result);
        }
        break;

      case 'insert':
        // Don't try to insert if path is NULL. We may have already set
        // the alias ahead of time.
        if ($node->path) {
          path_set_alias("node/$node->nid", $node->path);
        }
        break;

      case 'update':
        path_set_alias("node/$node->nid", $node->path, $node->pid);
        break;

      case 'delete':
        $path = "node/$node->nid";
        if (drupal_get_path_alias($path) != $path) {
          path_set_alias($path);
        }
        break;
    }
  }
}

/**
 * Implementation of hook_form_alter().
 */
function path_form_alter($form_id, &$form) {
  if (isset($form['type']) && $form['type']['#value'] .'_node_form' == $form_id) {
    $path = $form['#node']->path;
    $form['path'] = array(
      '#type' => 'fieldset',
      '#title' => t('URL path settings'),
      '#collapsible' => TRUE,
      '#collapsed' => empty($path),
      '#access' => user_access('create url aliases'),
      '#weight' => 30,
    );
    $form['path']['path'] = array(
      '#type' => 'textfield',
      '#default_value' => $path,
      '#maxlength' => 128,
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
      '#description' => t('Optionally specify an alternative URL by which this node can be accessed. For example, type "about" when writing an about page. Use a relative path and don\'t add a trailing slash or the URL alias won\'t work.'),
    );
    if ($path) {
      $form['path']['pid'] = array(
        '#type' => 'value',
        '#value' => db_result(db_query("SELECT pid FROM {url_alias} WHERE dst = '%s'", $path))
      );
    }
  }
}


/**
 * Implementation of hook_perm().
 */
function path_perm() {
  return array('create url aliases', 'administer url aliases');
}

/**
 * Return a listing of all defined URL aliases.
 */
function path_overview() {
  $sql = 'SELECT * FROM {url_alias}';
  $header = array(
    array('data' => t('Alias'), 'field' => 'dst', 'sort' => 'asc'),
    array('data' => t('System'), 'field' => 'src'),
    array('data' => t('Operations'), 'colspan' => '2')
  );
  $sql .= tablesort_sql($header);
  $result = pager_query($sql, 50);

  $destination = drupal_get_destination();
  while ($data = db_fetch_object($result)) {
    $rows[] = array(check_plain($data->dst), check_plain($data->src), l(t('edit'), "admin/build/path/edit/$data->pid", array(), $destination), l(t('delete'), "admin/build/path/delete/$data->pid", array(), $destination));
  }

  if (!$rows) {
    $rows[] = array(array('data' => t('No URL aliases available.'), 'colspan' => '4'));
  }

  $output = theme('table', $header, $rows);
  $output .= theme('pager', NULL, 50, 0);
  return $output;
}

/**
 * Fetch a specific URL alias from the database.
 */
function path_load($pid) {
  return db_fetch_array(db_query('SELECT * FROM {url_alias} WHERE pid = %d', $pid));
}

/**
 * Verify that a new URL alias is valid
 */
function path_form_validate($form_id, $form_values) {
  $src = $form_values['src'];
  $dst = $form_values['dst'];
  $pid = $form_values['pid'];

  if (db_result(db_query("SELECT COUNT(dst) FROM {url_alias} WHERE pid != %d AND dst = '%s'", $pid, $dst))) {
    form_set_error('dst', t('The alias %alias is already in use.', array('%alias' => $dst)));
  }
}

/**
 * Save a new URL alias to the database.
 */
function path_form_submit($form_id, $form_values) {
  path_set_alias($form_values['src'], $form_values['dst'], $form_values['pid']);

  drupal_set_message(t('The alias has been saved.'));
  return 'admin/build/path';
}
