<?php
// $Id: pathauto.module,v 1.44.4.101 2008/06/24 16:04:11 greggles Exp $

/**
 * @defgroup pathauto Pathauto: Automatically generates aliases for content
 *
 * The Pathauto module automatically generates path aliases for various kinds of
 * content (nodes, categories, users) without requiring the user to manually
 * specify the path alias. This allows you to get aliases like
 * /category/my-node-title.html instead of /node/123. The aliases are based upon
 * a "pattern" system which the administrator can control.
 */

/**
 * @file
 * Main file for the Pathauto module, which automatically generates aliases for content.
 *
 * @ingroup pathauto
 */

/**
 * Implementation of hook_help().
 */
function pathauto_help($section) {
  switch ($section) {
    case 'admin/help#pathauto':
      $output = t('<p>Provides a mechanism for modules to automatically generate aliases for the content they manage.</p>
                  <h2>Settings</h2>
                  <p>The <strong>Maximum Alias Length</strong> and <strong>Maximum component length</strong> values
                  default to 100 and have a limit of 128 from pathauto. This length is limited by the length of the dst
                  column of the url_alias database table. The default database schema for this column is 128. If you
                  set a length that is equal to that of the one set in the dst column it will cause problems in situations
                  where the system needs to append additional words to the aliased URL. For example... URLs generated
                  for feeds will have "/feed" added to the end. You should enter a value that is the length of the dst
                  column minus the length of any strings that might get added to the end of the URL. The length of
                  strings that might get added to the end of your URLs depends on which modules you have enabled and
                  on your Pathauto settings. The recommended and default value is 100.</p>
                  <p><strong>Raw Tokens</strong> In Pathauto it is appropriate to use the -raw form of tokens. Paths are
                  sent through a filtering system which ensures that raw user content is filtered. Failure to use -raw
                  tokens can cause problems with the Pathauto punctuation filtering system.</p>');
      return $output;
  }
}

/**
 * Implementation of hook_perm().
 */
function pathauto_perm() {
  return array('administer pathauto', 'notify of path changes');
}

/**
 * Implementation of hook_menu().
 */
function pathauto_menu($may_cache) {
  $items = array();
  if ($may_cache) {
    $items[] = array(
      'path' => 'admin/settings/pathauto',
      'title' => t('Pathauto'),
      'description' => t('Configure how pathauto generates clean URLs for your content.'),
      'callback' => 'drupal_get_form',
      'callback arguments' => array('pathauto_admin_settings'),
      'access' => user_access('administer pathauto'),
      'type' => MENU_NORMAL_ITEM,
    );
    $items[] = array(
      'path' => 'admin/build/path/delete_bulk',
      'title' => t('Delete aliases'),
      'callback' => 'drupal_get_form',
      'callback arguments' => array('pathauto_admin_delete'),
      'access' => user_access('administer url aliases'),
      'type' => MENU_LOCAL_TASK,
    );
  }

  return $items;
}

/**
 * Include all Pathauto include files.
 */
function _pathauto_include() {
  $pathauto_path = drupal_get_path('module', 'pathauto');
  require_once("$pathauto_path/pathauto.inc");
  require_once("$pathauto_path/pathauto_node.inc");
  require_once("$pathauto_path/pathauto_taxonomy.inc");
  require_once("$pathauto_path/pathauto_user.inc");
}

/**
 * Implementation of hook_token_values() for Pathauto specific tokens.
 */
function pathauto_token_values($type, $object = NULL) {
  if (module_exists('taxonomy')) {
    if ($type == 'taxonomy' || $type == 'node' || $type == 'all') {
      _pathauto_include();
      switch ($type) {
        case 'node':
          // We're on a node and it's a book and it has a parent? Get the book path alias
          if (module_exists('book')) {
            if ($object->type == 'book' && $object->parent) {
              $values['bookpathalias'] = drupal_get_path_alias('node/'. $object->parent);
            }
            else {
              $values['bookpathalias'] = '';
            }
          }

          $vid = db_result(db_query_range("SELECT t.vid FROM {term_node} r INNER JOIN {term_data} t ON r.tid = t.tid INNER JOIN {vocabulary} v ON t.vid = v.vid WHERE r.nid = %d ORDER BY v.weight, t.weight, t.name", $object->nid, 0, 1));
          $category = db_fetch_object(db_query_range("SELECT t.tid, t.name FROM {term_data} t INNER JOIN {term_node} r ON r.tid = t.tid WHERE t.vid = %d AND r.nid = %d ORDER BY weight", $vid, $object->nid, 0, 1));
          $category->vid = $vid;
          // In the realm of nodes these are terms, in the realm of Taxonomy, cats
          $label = 'term';

        case 'taxonomy':
        default:
          if (!isset($category)) {
            $category = $object;
          }
          if (!isset($label)) {
            $label = 'cat';
          }
          if (isset($category->tid)) {
            $separator = variable_get('pathauto_separator', '-');
            $parents = taxonomy_get_parents_all($category->tid);
            array_shift($parents);
            $catpath = '';
            $catpath_raw = '';
            foreach ($parents as $parent) {
              // Replace any / characters in individual terms which might create confusing URLs
              $catpath = pathauto_cleanstring(check_plain(preg_replace('/\//', '', $parent->name))) .'/'. $catpath;
              $catpath_raw = pathauto_cleanstring(preg_replace('/\//', '', $parent->name)) .'/'. $catpath_raw;
            }
            $values[$label .'path'] = $catpath .'/'. check_plain($category->name);
            $values[$label .'path-raw'] = $catpath_raw .'/'. $category->name;

            // We only do this for taxonomy because token already provides the [term] value but has problem with [cat] TODO: fix that?
            if ($type == 'taxonomy') {
              $values[$label] = check_plain($category->name);
              $values[$label .'-raw'] = $category->name;
            }

            $values[$label .'alias'] = drupal_get_path_alias('taxonomy/term/'. $category->tid);
            if (!strncasecmp($values[$label .'alias'], 'taxonomy', 8)) {
              $values[$label .'alias'] = $values[$label];
            }
          }
          else { // Provide some defaults if they aren't set.
            $values[$label .'path'] = '';
            $values[$label .'path-raw'] = '';
            $values[$label .'alias'] = '';
          }
      }
      return $values;
    }
  }
}

/**
 * Implementation of hook_token_list() for Pathauto specific tokens.
 */
function pathauto_token_list($type = 'all') {
  $tokens = array();
  if (module_exists('taxonomy')) {
    if ($type == 'taxonomy' || $type == 'all') {
      $tokens['taxonomy']['catpath'] = t('As [cat], but including its supercategories separated by /.');
      $tokens['taxonomy']['catpath-raw'] = t('As [cat-raw], but including its supercategories separated by /. WARNING - raw user input.');
      $tokens['taxonomy']['catalias'] = t('URL alias for the category.');
    }
    if ($type == 'node' || $type == 'all') {
      $tokens['node']['termpath'] = t('As [term], but including its supercategories separated by /.');
      $tokens['node']['termpath-raw'] = t('As [term-raw], but including its supercategories separated by /. WARNING - raw user input.');
      $tokens['node']['termalias'] = t('URL alias for the term.');
    }
  }
  if (module_exists('book')) {
    if ($type == 'node' || $type == 'all') {
      $tokens['node']['bookpathalias'] = t('URL alias for the parent book.');
    }
  }
  return $tokens;
}

/**
 * Implementation of hook_path_alias_types().
 *
 * Used primarily by the bulk delete form.
 */
function pathauto_path_alias_types() {
  $objects = array('user/' => t('users'), 'node/' => t('content'));
  if (module_exists('blog')) {
    $objects['blog/'] = t('user blogs');
  }
  if (module_exists('taxonomy')) {
    $objects['taxonomy/'] = t('vocabularies and terms');
  }
  if (module_exists('taxonomy')) {
    $objects['user/%/track'] = t('user trackers');
  }
  if (module_exists('forum')) {
    $objects['forum/%'] = t('forums');
  }
  return $objects;
}

//==============================================================================
// Some node related functions.

/**
 * Implementation of hook_nodeapi().
 */
function pathauto_nodeapi(&$node, $op, $teaser, $page) {
  _pathauto_include();
  if (module_exists('path')) {
    switch ($op) {
      case 'insert':
      case 'update':
        // Get the specific pattern or the default
        $pattern = trim(variable_get('pathauto_node_'. $node->type .'_pattern', FALSE));
        if (!$pattern) {
          $pattern = trim(variable_get('pathauto_node_pattern', FALSE));
        }
        // Only do work if there's a pattern
        if ($pattern) {
          // Only create an alias if the checkbox was not provided or if the checkbox was provided and is checked
          if (!isset($node->pathauto_perform_alias) || $node->pathauto_perform_alias) {
            $placeholders = pathauto_get_placeholders('node', $node);
            $src = "node/$node->nid";
            $alias = pathauto_create_alias('node', $op, $placeholders, $src, $node->nid, $node->type);
          }
        }
        break;
      case 'delete':
        path_set_alias('node/'. $node->nid);
        path_set_alias('node/'. $node->nid .'/feed');
        break;
      default:
        break;
    }
  }
}

/**
 * Implementation of hook_form_alter().
 *
 * This allows alias creators to override Pathauto and specify their
 * own aliases (Pathauto will be invisible to other users). Inserted
 * into the path module's fieldset in the node form.
 */
function pathauto_form_alter($formid, &$form) {
  // Only do this for node forms
  if (isset($form['#id']) && ($form['#id'] == 'node-form') && arg(0) == 'node') {
    // See if there is a pathauto pattern or default applicable
    $pattern = trim(variable_get('pathauto_node_'. $form['type']['#value'] .'_pattern', FALSE));
    if (!$pattern) {
      $pattern = trim(variable_get('pathauto_node_pattern', FALSE));
    }
    // If there is a pattern AND the user is allowed to create aliases AND the path textbox is present on this form
    if (!empty($pattern) && user_access('create url aliases') && isset($form['path']['path'])) {
      $output = t('An alias will be generated for you. If you wish to create your own alias below, untick this option.');
      if (user_access('administer pathauto')) {
        $output .= t(' To control the format of the generated aliases, see the <a href="@pathauto">Pathauto settings</a>.', array('@pathauto' => url('admin/settings/pathauto')));
      }

      drupal_add_js(drupal_get_path('module', 'pathauto') .'/pathauto.js');
      $form['path']['#collapsed'] = FALSE;

      $form['path']['pathauto_perform_alias'] = array(
        '#type' => 'checkbox',
        '#title' => t('Automatic alias'),
        '#default_value' => TRUE,
        '#description' => $output,
        '#weight' => -1,
      );
    }
  }
}

/**
 * Implementation of hook_node_operations().
 */
function pathauto_node_operations() {
  $operations = array(
    'update_alias' => array(
      'label' => t('Update path alias'),
      'callback' => 'pathauto_node_operations_update',
    ),
  );
  return $operations;
}

/**
 * Callback function for updating node aliases.
 *
 * @param $nodes
 *   Array of node nid's.
 */
function pathauto_node_operations_update($nodes) {
  foreach ($nodes as $nid) {
    $node = node_load($nid);
    $placeholders = pathauto_get_placeholders('node', $node);
    pathauto_create_alias('node', 'bulkupdate', $placeholders, "node/$node->nid", $node->nid, $node->type);
  }
}

//==============================================================================
// Taxonomy related functions.

/**
 * Implementation of hook_taxonomy().
 */
function pathauto_taxonomy($op, $type, $object = NULL) {
  _pathauto_include();
  switch ($type) {
    case 'term':
      switch ($op) {
        case 'insert':
        case 'update':
          // Use the category info to automatically create an alias
          $category = (object) $object;
          if ($category->name) {
            $count = _taxonomy_pathauto_alias($category, $op);
          }

          // For all children generate new alias (important if [catpath] used)
          foreach (taxonomy_get_tree($category->vid, $category->tid) as $subcategory) {
            $count = _taxonomy_pathauto_alias($subcategory, $op);
          }

          break;
        case 'delete':
          // If the category is deleted, remove the path aliases
          $category = (object) $object;
          path_set_alias('taxonomy/term/'. $category->tid);
          path_set_alias(taxonomy_term_path($category));
          path_set_alias('forum/'. $category->tid);
          path_set_alias('taxonomy/term/'. $category->tid .'/0/feed');
          break;
        default:
          break;
      }
      break;
    default:
      break;
  }
}

//==============================================================================
// User related functions.

/**
 * Implementation of hook_user() for users, trackers, and blogs.
 */
function pathauto_user($op, &$edit, &$user, $category = FALSE) {
  _pathauto_include();
  switch ($op) {
    case 'insert':
    case 'update':
      // Use the username to automatically create an alias
      $pathauto_user = (object) array_merge((array) $user, $edit);
      if ($user->name) {
        $placeholders = pathauto_get_placeholders('user', $pathauto_user);
        $src = 'user/'. $user->uid;
        $alias = pathauto_create_alias('user', $op, $placeholders, $src, $user->uid);

        if (module_exists('blog')) {
          $new_user = $user;
          if ($category == 'account') {
            $new_user->roles = isset($edit['roles']) ? $edit['roles'] : array();
            $new_user->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user'; // Add this back
          }
          if (user_access('edit own blog', $new_user)) {
            $src = 'blog/'. $user->uid;
            $alias = pathauto_create_alias('blog', $op, $placeholders, $src, $user->uid);
          }
          else {
            path_set_alias('blog/'. $user->uid);
            path_set_alias('blog/'. $user->uid .'/feed');
          }
        }
        if (module_exists('tracker')) {
          $src = 'user/'. $user->uid .'/track';
          $alias = pathauto_create_alias('tracker', $op, $placeholders, $src, $user->uid);
        }
      }
      break;
    case 'delete':
      // If the user is deleted, remove the path aliases
      $user = (object) $user;
      path_set_alias('user/'. $user->uid);

      // They may have enabled these modules and/or feeds when the user was created, so let's try to delete all of them
      path_set_alias('blog/'. $user->uid);
      path_set_alias('blog/'. $user->uid .'/feed');
      path_set_alias('user/'. $user->uid .'/track');
      path_set_alias('user/'. $user->uid .'/track/feed');
      break;
    default:
      break;
  }
}

//==============================================================================
// Admin page related functions.

/**
 * Form builder; Configure the Pathauto system.
 *
 * @ingroup forms
 * @see system_settings_form()
 */
function pathauto_admin_settings() {
  _pathauto_include();

  // Make sure they have token
  if (!function_exists('token_get_list')) {
    drupal_set_message(t('It appears that the <a href="@token_link">Token module</a> is not installed. Please ensure that you have it installed so that Pathauto can work properly. You may need to disable Pathauto and re-enable it to get Token enabled.', array('@token_link' => 'http://drupal.org/project/token')), 'error');
    return;
  }

  // Default words to ignore
  $ignore_words = array(
    'a', 'an', 'as', 'at', 'before', 'but', 'by', 'for', 'from', 'is', 'in',
    'into', 'like', 'of', 'off', 'on', 'onto', 'per', 'since', 'than', 'the',
    'this', 'that', 'to', 'up', 'via', 'with',
  );

  // Generate the form - settings applying to all patterns first
  $group_weight = -20;
  $form['general'] = array(
    '#type' => 'fieldset',
    '#weight' => $group_weight,
    '#title' => t('General settings'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $group_weight++;

  $form['general']['pathauto_verbose'] = array(
    '#type' => 'checkbox',
    '#title' => t('Verbose'),
    '#default_value' => variable_get('pathauto_verbose', FALSE),
    '#description' => t('Display alias changes (except during bulk updates).'),
  );

  $form['general']['pathauto_separator'] = array(
    '#type' => 'textfield',
    '#title' => t('Separator'),
    '#size' => 1,
    '#maxlength' => 1,
    '#default_value' => variable_get('pathauto_separator', '-'),
    '#description' => t('Character used to separate words in titles. This will replace any spaces and punctuation characters. Using a space or + character can cause unexpected results.'),
  );

  $form['general']['pathauto_case'] = array(
    '#type' => 'radios',
    '#title' => t('Character case'),
    '#default_value' => variable_get('pathauto_case', 1),
    '#options' => array(t('Leave case the same as source token values.'), t('Change to lower case')),
  );

  $form['general']['pathauto_max_length'] = array(
    '#type' => 'textfield',
    '#title' => t('Maximum alias length'),
    '#size' => 3,
    '#maxlength' => 3,
    '#default_value' => variable_get('pathauto_max_length', 100),
    '#description' => t('Maximum length of aliases to generate. 100 is recommended. See <a href="@pathauto-help">Pathauto help</a> for details.', array('@pathauto-help' => url('admin/help/pathauto'))),
  );

  $form['general']['pathauto_max_component_length'] = array(
    '#type' => 'textfield',
    '#title' => t('Maximum component length'),
    '#size' => 3,
    '#maxlength' => 3,
    '#default_value' => variable_get('pathauto_max_component_length', 100),
    '#description' => t('Maximum text length of any component in the alias (e.g., [title]). 100 is recommended. See <a href="@pathauto-help">Pathauto help</a> for details.', array('@pathauto-help' => url('admin/help/pathauto'))),
  );

  $form['general']['pathauto_max_bulk_update'] = array(
    '#type' => 'textfield',
    '#title' => t('Maximum number of objects to alias in a bulk update'),
    '#size' => 4,
    '#maxlength' => 4,
    '#default_value' => variable_get('pathauto_max_bulk_update', 50),
    '#description' => t('Maximum number of objects of a given type which should be aliased during a bulk update. The default is 50 and the recommended number depends on the speed of your server. If bulk updates "time out" or result in a "white screen" then reduce the number.'),
  );

  $actions = array(
    t('Do nothing. Leave the old alias intact.'),
    t('Create a new alias. Leave the existing alias functioning.'),
    t('Create a new alias. Delete the old alias.'));

  if (function_exists('path_redirect_save')) {
    $actions[] = t('Create a new alias. Redirect from old alias.');
  }
  elseif (variable_get('pathauto_update_action', 2) == 3) {
    // the redirect action is selected, but path_redirect is not enabled
    // let's set the variable back to the default
    variable_set('pathauto_update_action', 2);
  }

  $form['general']['pathauto_update_action'] = array(
    '#type' => 'radios',
    '#title' => t('Update action'),
    '#default_value' => variable_get('pathauto_update_action', 2),
    '#options' => $actions,
    '#description' => t('What should pathauto do when updating an existing content item which already has an alias?'),
  );

  $disable_transliteration = TRUE;
  $path = drupal_get_path('module', 'pathauto');
  $transliteration_help = t('When a pattern includes certain characters (such as those with accents) should Pathauto attempt to transliterate them into the ASCII-96 alphabet? Transliteration is determined by the i18n-ascii.txt file in the Pathauto directory. <strong>This option is disabled on your site because you do not have an i18n-ascii.txt file in the Pathauto directory.</strong>');
  if (is_file($path .'/i18n-ascii.txt')) {
    $disable_transliteration = FALSE;
    $transliteration_help = t('When a pattern includes certain characters (such as those with accents) should Pathauto attempt to transliterate them into the ASCII-96 alphabet? Transliteration is determined by the i18n-ascii.txt file in the Pathauto directory.');
  }
  else {
    // Perhaps they've removed the file, set the transliterate option to FALSE
    variable_set('pathauto_transliterate', FALSE);
  }
  $form['general']['pathauto_transliterate'] = array(
    '#type' => 'checkbox',
    '#title' => t('Transliterate prior to creating alias'),
    '#default_value' => variable_get('pathauto_transliterate', FALSE),
    '#description' => $transliteration_help,
    '#disabled' => $disable_transliteration,
  );
  $form['general']['pathauto_reduce_ascii'] = array(
    '#type' => 'checkbox',
    '#title' => t('Reduce strings to letters and numbers from ASCII-96'),
    '#default_value' => variable_get('pathauto_reduce_ascii', FALSE),
    '#description' => t('Filters the new alias to only letters and numbers found in the ASCII-96 set.'),
  );

  $form['general']['pathauto_ignore_words'] = array(
    '#type' => 'textarea',
    '#title' => t('Strings to Remove'), '#default_value' => variable_get('pathauto_ignore_words', implode(',', $ignore_words)),
    '#description' => t('Words to strip out of the URL alias, separated by commas. Do not place punctuation in here and do not use WYSIWYG editors on this field.'),
  );

  $form['punctuation'] = array(
    '#type' => 'fieldset',
    '#weight' => $group_weight,
    '#title' => t('Punctuation settings'), '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $group_weight++;

  $punctuation = pathauto_punctuation_chars();
  foreach ($punctuation as $name => $details) {
    $form['punctuation']['pathauto_punctuation_'. $name ] = array(
      '#type' => 'select',
      '#title' => $details['name'],
      '#default_value' => variable_get('pathauto_punctuation_'. $name, 0),
      '#options' => array('0' => t('Remove'), '1' => t('Replace by separator'), '2' => t('No action (do not replace)')),
    );
  }

  // Call the hook on all modules - an array of 'settings' objects is returned
  $all_settings = module_invoke_all('pathauto', 'settings');
  $modulelist = '';
  $indexcount = 0;
  foreach ($all_settings as $settings) {
    $items = '';
    $module = $settings->module;
    $modulelist[] = $module;
    $patterndescr = $settings->patterndescr;
    $patterndefault = $settings->patterndefault;
    $groupheader = $settings->groupheader;
    $supportsfeeds = isset($settings->supportsfeeds) ? $settings->supportsfeeds : NULL;
    variable_set('pathauto_'. $module .'_supportsfeeds', $supportsfeeds);

    $form[$module] = array(
      '#type' => 'fieldset',
      '#title' => $groupheader,
      '#weight' => $group_weight,
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
    );
    $group_weight++;

    // Prompt for the default pattern for this module
    $variable = 'pathauto_'. $module .'_pattern';
    $description = '';
    if (!count($_POST)) {
      $error = _pathauto_check_pattern(variable_get($variable, $patterndefault), $settings->token_type);
      if ($error) {
        $form[$module]['#collapsed'] = FALSE;
        $description = $error;
      }
    }
    $form[$module][$variable] = array(
      '#type' => 'textfield',
      '#title' => $patterndescr,
      '#default_value' => variable_get($variable, $patterndefault),
      '#description' => $description,
      '#size' => 65,
      '#maxlength' => 1280,
    );

    // If the module supports a set of specialized patterns, set
    // them up here
    if (isset($settings->patternitems)) {
      foreach ($settings->patternitems as $itemname => $itemlabel) {
        $variable = 'pathauto_'. $module .'_'. $itemname .'_pattern';
        $description = '';
        if (!count($_POST)) {
          $error = _pathauto_check_pattern(variable_get($variable, $patterndefault), $settings->token_type);
          if ($error) {
            $form[$module]['#collapsed'] = FALSE;
            $description = $error;
          }
        }

        $form[$module][$variable] = array('#type' => 'textfield',
          '#title' => $itemlabel,
          '#default_value' => variable_get($variable, ''),
          '#description' => $description,
          '#size' => 65,
          '#maxlength' => 1280);
      }
    }

    // Display the user documentation of placeholders supported by
    // this module, as a description on the last pattern
    $doc = "<dl>\n";
    foreach ($settings->placeholders as $name => $description) {
      $doc .= '<dt>'. $name .'</dt>';
      $doc .= '<dd>'. $description .'</dd>';
    }
    $doc .= "</dl>\n";
    $form[$module]['token_help'] = array(
      '#title' => t('Replacement patterns'),
      '#type' => 'fieldset',
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
      '#description' => t('Use -raw replacements for text to avoid problems with HTML entities.'),
    );
    $form[$module]['token_help']['help'] = array(
      '#value' => $doc,
    );

    // If the module supports bulk updates, offer the update action here
    if ($settings->bulkname) {
      $variable = 'pathauto_'. $module .'_bulkupdate';
      if (variable_get($variable, FALSE)) {
        variable_set($variable, FALSE);
        $function = $module .'_pathauto_bulkupdate';
        call_user_func($function);
      }
      $form[$module][$variable] = array(
        '#type' => 'checkbox',
        '#title' => $settings->bulkname,
        '#default_value' => FALSE,
        '#description' => $settings->bulkdescr,
      );
    }

    // If the module supports feeds, offer to generate aliases for them
    if ($supportsfeeds) {
      $variable = 'pathauto_'. $module .'_applytofeeds';
      $current = variable_get($variable, $supportsfeeds);
      // This checks for the old style from 2.0 and earlier. TODO: At some point we can drop that.
      if (is_numeric($current)) {
        $current = $supportsfeeds;
      }

      $form[$module][$variable] = array(
        '#type' => 'textfield',
        '#title' => t('Internal feed alias text (leave blank to disable)'),
        '#size' => 65,
        '#maxlength' => 1280,
        '#default_value' => $current,
        '#description' => t('The text to use for aliases for RSS feeds. Examples are "feed" and "0/feed".'),
      );
    }

  }

  if (isset($do_index_bulkupdate) && $do_index_bulkupdate) {
    drupal_set_message(format_plural($indexcount,
      'Bulk generation of index aliases completed, one alias generated.',
      'Bulk generation of index aliases completed, @count aliases generated.'));
  }

  // Keep track of which modules currently support pathauto
  variable_set('pathauto_modulelist', $modulelist);

  return system_settings_form($form);
}

/**
 * Helper function for pathauto_admin_settings().
 *
 * See if they are using all -raw tokens available
 * and if all the tokens are valid in the given context.
 *
 * @param $pattern
 *   A string containing the pattern to be tested.
 * @param $type
 *   A flag indicating the class of substitution tokens to use.
 * @return
 *   A status flag, telling whether there is an error or not.
 * @see token_get_list()
 *   For more information on the $type parameter.
 */
function _pathauto_check_pattern($pattern, $type) {
  // Hold items we've warned about so we only warn once per token
  static $warned;
  $return = FALSE;

  // Build up a set of all tokens in a format that's easy to search
  $all_tokens = array();
  $tokens = token_get_list($type);
  foreach ($tokens as $actual_tokens) {
    foreach (array_keys($actual_tokens) as $token) {
      $all_tokens[$token] = $token;
    }
  }

  // Now, search the pattern and evaluate its contents.
  $matches = array();
  if (preg_match_all('/\[[a-zA-z_\-]+?\]/i', $pattern, $matches)) {
    // Loop over each found token.
    foreach ($matches[0] as $id => $token) {
      $token = str_replace('[', '', str_replace(']', '', $token));
      // Check if the token is even valid in this context.
      if (!array_key_exists($token, $all_tokens)) {
        drupal_set_message(t('You are using the token [%token] which is not valid within the scope of tokens where you are using it.', array('%token' => $token)), 'error');
        $return[] = $token;
      }
      // Check if there is a raw companion that they should be using.
      elseif (!preg_match('/\-raw/i', $token)) {
        $raw_token = $token .'-raw';
        if (array_key_exists($raw_token, $all_tokens)) {
          if (!isset($warned) || !array_key_exists($token, $warned)) {
            drupal_set_message(t('You are using the token [%token] which has a -raw companion available [%raw_token]. For Pathauto patterns you should use the -raw version of tokens unless you really know what you are doing. See the <a href="@pathauto-help">Pathauto help</a> for more details.', array('%token' => $token, '%raw_token' => $raw_token, '@pathauto-help' => url('admin/help/pathauto'))), 'error');
            $warned[$token] = $token;
          }
          $return[] = $token;
        }
      }
    }
  }

  if ($return) {
    $description = t('NOTE: This field contains potentially incorrect patterns. ');
    $description .= format_plural(count($return), 'Problem token: ', 'Problem tokens: ');
    $description .= t('%problems', array('%problems' => implode(', ', $return)));
    $return = $description;
  }

  return $return;
}

/**
 * Validate pathauto_admin_settings form submissions.
 */
function pathauto_admin_settings_validate($form_id, $form_values) {
  // Validate that the separator is not set to be removed per http://drupal.org/node/184119
  // This isn't really all that bad so warn, but still allow them to save the value.
  $separator = $form_values['pathauto_separator'];
  $punctuation = pathauto_punctuation_chars();
  foreach ($punctuation as $name => $details) {
    if ($details['value'] == $separator) {
      $action = $form_values['pathauto_punctuation_'. $name];
      if ($action == 0) {
        drupal_set_message(t('You have configured the @name to be the separator and to be removed when encountered in strings. This can cause problems with your patterns and especially with the catpath and termpath patterns. You should probably set the action for @name to be "replace by separator"', array('@name' => $details['name'])), 'error');
      }
    }
  }
}

/**
 * Menu callback; select certain alias types to delete.
 */
function pathauto_admin_delete() {
  /* TODO:
   1) all - DONE
   2) all node aliases - DONE
   4) all user aliases - DONE
   5) all taxonomy aliases - DONE
   6) by node type
   7) by taxonomy vocabulary
   8) no longer existing aliases (see http://drupal.org/node/128366 )
   9) where src like 'pattern' - DON'T DO
   10) where dst like 'pattern' - DON'T DO
  */

  $form = array();
  $form['delete'] = array(
    '#type' => 'fieldset',
    '#title' => t('Choose Aliases to Delete'),
    '#collapsible' => FALSE,
    '#collapsed' => FALSE,
  );

  // First we do the "all" case
  $total_count = db_result(db_query('SELECT count(1) FROM {url_alias}'));
  $form['delete']['all_aliases'] = array(
    '#type' => 'checkbox',
    '#title' => t('all aliases'),
    '#default_value' => FALSE,
    '#description' => t('Delete all aliases. Number of aliases which will be deleted: %count.', array('%count' => $total_count)),
  );

  // Next, iterate over an array of objects/alias types which can be deleted and provide checkboxes
  $objects = module_invoke_all('path_alias_types');
  foreach ($objects as $internal_name => $label) {
    $count = db_result(db_query("SELECT count(1) FROM {url_alias} WHERE src LIKE '%s%%'", $internal_name));
    $form['delete'][$internal_name] = array(
      '#type' => 'checkbox',
      '#title' => $label, // This label is sent through t() in the hard coded function where it is defined
      '#default_value' => FALSE,
      '#description' => t('Delete aliases for all @label. Number of aliases which will be deleted: %count.', array('@label' => $label, '%count' => $count)),
    );
  }

  // Warn them and give a button that shows we mean business
  $form['warning'] = array('#value' => t('<p><strong>Note:</strong> there is no confirmation. Be sure of your action before clicking the "Delete aliases now!" button.<br />You may want to make a backup of the database and/or the url_alias table prior to using this feature.</p>'));
  $form['buttons']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Delete aliases now!'),
  );

  return $form;
}

/**
 * Process pathauto_admin_delete form submissions.
 */
function pathauto_admin_delete_submit($form_id, $form_values) {
  foreach ($form_values as $key => $value) {
    if ($value) {
      if ($key === 'all_aliases') {
        db_query('DELETE FROM {url_alias}');
        drupal_set_message(t('All of your path aliases have been deleted.'));
      }
      $objects = module_invoke_all('path_alias_types');
      if (array_key_exists($key, $objects)) {
        db_query("DELETE FROM {url_alias} WHERE src LIKE '%s%%'", $key);
        drupal_set_message(t('All of your %type path aliases have been deleted.', array('%type' => $objects[$key])));
      }
    }
  }
  return 'admin/build/path/delete_bulk';
}
