pathauto.module

Tracking 5.x-2.x branch
  1. drupal
    1. 5 contributions/pathauto/pathauto.module
    2. 6 contributions/pathauto/pathauto.module
    3. 7 contributions/pathauto/pathauto.module

Main file for the Pathauto module, which automatically generates aliases for content.

Functions & methods

NameDescription
pathauto_admin_deleteMenu callback; select certain alias types to delete.
pathauto_admin_delete_submitProcess pathauto_admin_delete form submissions.
pathauto_admin_settingsForm builder; Configure the Pathauto system.
pathauto_admin_settings_validateValidate pathauto_admin_settings form submissions.
pathauto_form_alterImplementation of hook_form_alter().
pathauto_helpImplementation of hook_help().
pathauto_menuImplementation of hook_menu().
pathauto_nodeapiImplementation of hook_nodeapi().
pathauto_node_operationsImplementation of hook_node_operations().
pathauto_node_operations_updateCallback function for updating node aliases.
pathauto_path_alias_typesImplementation of hook_path_alias_types().
pathauto_permImplementation of hook_perm().
pathauto_taxonomyImplementation of hook_taxonomy().
pathauto_token_listImplementation of hook_token_list() for Pathauto specific tokens.
pathauto_token_valuesImplementation of hook_token_values() for Pathauto specific tokens.
pathauto_userImplementation of hook_user() for users, trackers, and blogs.
_pathauto_check_patternHelper function for pathauto_admin_settings().
_pathauto_includeInclude all Pathauto include files.

File

View source
  1. <?php
  2. /**
  3. * @defgroup pathauto Pathauto: Automatically generates aliases for content
  4. *
  5. * The Pathauto module automatically generates path aliases for various kinds of
  6. * content (nodes, categories, users) without requiring the user to manually
  7. * specify the path alias. This allows you to get aliases like
  8. * /category/my-node-title.html instead of /node/123. The aliases are based upon
  9. * a "pattern" system which the administrator can control.
  10. */
  11. /**
  12. * @file
  13. * Main file for the Pathauto module, which automatically generates aliases for content.
  14. *
  15. * @ingroup pathauto
  16. */
  17. /**
  18. * Implementation of hook_help().
  19. */
  20. function pathauto_help($section) {
  21. switch ($section) {
  22. case 'admin/help#pathauto':
  23. $output = t('<p>Provides a mechanism for modules to automatically generate aliases for the content they manage.</p>
  24. <h2>Settings</h2>
  25. <p>The <strong>Maximum Alias Length</strong> and <strong>Maximum component length</strong> values
  26. default to 100 and have a limit of 128 from pathauto. This length is limited by the length of the dst
  27. column of the url_alias database table. The default database schema for this column is 128. If you
  28. set a length that is equal to that of the one set in the dst column it will cause problems in situations
  29. where the system needs to append additional words to the aliased URL. For example... URLs generated
  30. for feeds will have "/feed" added to the end. You should enter a value that is the length of the dst
  31. column minus the length of any strings that might get added to the end of the URL. The length of
  32. strings that might get added to the end of your URLs depends on which modules you have enabled and
  33. on your Pathauto settings. The recommended and default value is 100.</p>
  34. <p><strong>Raw Tokens</strong> In Pathauto it is appropriate to use the -raw form of tokens. Paths are
  35. sent through a filtering system which ensures that raw user content is filtered. Failure to use -raw
  36. tokens can cause problems with the Pathauto punctuation filtering system.</p>');
  37. return $output;
  38. }
  39. }
  40. /**
  41. * Implementation of hook_perm().
  42. */
  43. function pathauto_perm() {
  44. return array('administer pathauto', 'notify of path changes');
  45. }
  46. /**
  47. * Implementation of hook_menu().
  48. */
  49. function pathauto_menu($may_cache) {
  50. $items = array();
  51. if ($may_cache) {
  52. $items[] = array(
  53. 'path' => 'admin/settings/pathauto',
  54. 'title' => t('Pathauto'),
  55. 'description' => t('Configure how pathauto generates clean URLs for your content.'),
  56. 'callback' => 'drupal_get_form',
  57. 'callback arguments' => array('pathauto_admin_settings'),
  58. 'access' => user_access('administer pathauto'),
  59. 'type' => MENU_NORMAL_ITEM,
  60. );
  61. $items[] = array(
  62. 'path' => 'admin/build/path/delete_bulk',
  63. 'title' => t('Delete aliases'),
  64. 'callback' => 'drupal_get_form',
  65. 'callback arguments' => array('pathauto_admin_delete'),
  66. 'access' => user_access('administer url aliases'),
  67. 'type' => MENU_LOCAL_TASK,
  68. );
  69. }
  70. return $items;
  71. }
  72. /**
  73. * Include all Pathauto include files.
  74. */
  75. function _pathauto_include() {
  76. $pathauto_path = './'. drupal_get_path('module', 'pathauto');
  77. require_once("$pathauto_path/pathauto.inc");
  78. require_once("$pathauto_path/pathauto_node.inc");
  79. require_once("$pathauto_path/pathauto_taxonomy.inc");
  80. require_once("$pathauto_path/pathauto_user.inc");
  81. }
  82. /**
  83. * Implementation of hook_token_list() for Pathauto specific tokens.
  84. */
  85. function pathauto_token_list($type = 'all') {
  86. $tokens = array();
  87. if (module_exists('taxonomy')) {
  88. if ($type == 'taxonomy' || $type == 'all') {
  89. $tokens['taxonomy']['catpath'] = t('As [cat], but including its supercategories separated by /.');
  90. $tokens['taxonomy']['catpath-raw'] = t('As [cat-raw], but including its supercategories separated by /.');
  91. $tokens['taxonomy']['catalias'] = t('The URL alias of the category.');
  92. $tokens['taxonomy']['catalias-raw'] = t('The URL alias of the category.');
  93. }
  94. if ($type == 'node' || $type == 'all') {
  95. $tokens['node']['termpath'] = t('As [term], but including its supercategories separated by /.');
  96. $tokens['node']['termpath-raw'] = t('As [term-raw], but including its supercategories separated by /.');
  97. $tokens['node']['termalias'] = t('The URL alias of the taxonomy term.');
  98. $tokens['node']['termalias-raw'] = t('The URL alias of the taxonomy term.');
  99. }
  100. }
  101. if (module_exists('book')) {
  102. if ($type == 'node' || $type == 'all') {
  103. $tokens['node']['bookpathalias'] = t('The URL alias of the parent book of the node.');
  104. $tokens['node']['bookpathalias-raw'] = t('The URL alias of the parent book of the node.');
  105. }
  106. }
  107. return $tokens;
  108. }
  109. /**
  110. * Implementation of hook_token_values() for Pathauto specific tokens.
  111. */
  112. function pathauto_token_values($type, $object = NULL) {
  113. if (module_exists('taxonomy')) {
  114. if ($type == 'taxonomy' || $type == 'node' || $type == 'all') {
  115. _pathauto_include();
  116. switch ($type) {
  117. case 'node':
  118. // We're on a node and it's a book and it has a parent? Get the book path alias
  119. if (module_exists('book')) {
  120. if ($object->type == 'book' && $object->parent) {
  121. $values['bookpathalias-raw'] = drupal_get_path_alias('node/'. $object->parent);
  122. $values['bookpathalias'] = check_plain($values['bookpathalias-raw']);
  123. }
  124. else {
  125. $values['bookpathalias'] = '';
  126. $values['bookpathalias-raw'] = '';
  127. }
  128. }
  129. // Get taxonomy related data.
  130. $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));
  131. $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));
  132. $category->vid = $vid;
  133. // In the realm of nodes these are terms, in the realm of Taxonomy, cats
  134. $label = 'term';
  135. case 'taxonomy':
  136. default:
  137. if (!isset($category)) {
  138. $category = $object;
  139. }
  140. if (!isset($label)) {
  141. $label = 'cat';
  142. }
  143. if (isset($category->tid)) {
  144. $separator = variable_get('pathauto_separator', '-');
  145. $parents = taxonomy_get_parents_all($category->tid);
  146. array_shift($parents);
  147. $catpath = '';
  148. $catpath_raw = '';
  149. foreach ($parents as $parent) {
  150. // Replace any / characters in individual terms which might create confusing URLs
  151. $catpath = pathauto_cleanstring(check_plain(preg_replace('/\//', '', $parent->name))) .'/'. $catpath;
  152. $catpath_raw = pathauto_cleanstring(preg_replace('/\//', '', $parent->name)) .'/'. $catpath_raw;
  153. }
  154. $values[$label .'path'] = $catpath .'/'. check_plain($category->name);
  155. $values[$label .'path-raw'] = $catpath_raw .'/'. $category->name;
  156. // We only do this for taxonomy because token already provides the [term] value but has problem with [cat] TODO: fix that?
  157. if ($type == 'taxonomy') {
  158. $values[$label] = check_plain($category->name);
  159. $values[$label .'-raw'] = $category->name;
  160. }
  161. $values[$label .'alias-raw'] = drupal_get_path_alias('taxonomy/term/'. $category->tid);
  162. $values[$label .'alias'] = check_plain($values[$label .'alias-raw']);
  163. }
  164. else { // Provide some defaults if they aren't set.
  165. $values[$label .'path'] = '';
  166. $values[$label .'path-raw'] = '';
  167. $values[$label .'alias'] = '';
  168. $values[$label .'alias-raw'] = '';
  169. }
  170. }
  171. return $values;
  172. }
  173. }
  174. }
  175. /**
  176. * Implementation of hook_path_alias_types().
  177. *
  178. * Used primarily by the bulk delete form.
  179. */
  180. function pathauto_path_alias_types() {
  181. $objects = array('user/' => t('users'), 'node/' => t('content'));
  182. if (module_exists('blog')) {
  183. $objects['blog/'] = t('user blogs');
  184. }
  185. if (module_exists('taxonomy')) {
  186. $objects['taxonomy/'] = t('vocabularies and terms');
  187. }
  188. if (module_exists('taxonomy')) {
  189. $objects['user/%/track'] = t('user trackers');
  190. }
  191. if (module_exists('forum')) {
  192. $objects['forum/%'] = t('forums');
  193. }
  194. return $objects;
  195. }
  196. //==============================================================================
  197. // Some node related functions.
  198. /**
  199. * Implementation of hook_nodeapi().
  200. */
  201. function pathauto_nodeapi(&$node, $op, $teaser, $page) {
  202. if (module_exists('path')) {
  203. switch ($op) {
  204. case 'insert':
  205. case 'update':
  206. _pathauto_include();
  207. // Get the specific pattern or the default
  208. $pattern = trim(variable_get('pathauto_node_'. $node->type .'_pattern', FALSE));
  209. if (!$pattern) {
  210. $pattern = trim(variable_get('pathauto_node_pattern', FALSE));
  211. }
  212. // Only do work if there's a pattern
  213. if ($pattern) {
  214. // Only create an alias if the checkbox was not provided or if the checkbox was provided and is checked
  215. if (!isset($node->pathauto_perform_alias) || $node->pathauto_perform_alias) {
  216. $placeholders = pathauto_get_placeholders('node', $node);
  217. $src = "node/$node->nid";
  218. $alias = pathauto_create_alias('node', $op, $placeholders, $src, $node->nid, $node->type);
  219. }
  220. }
  221. break;
  222. case 'delete':
  223. path_set_alias('node/'. $node->nid);
  224. path_set_alias('node/'. $node->nid .'/feed');
  225. break;
  226. default:
  227. break;
  228. }
  229. }
  230. }
  231. /**
  232. * Implementation of hook_form_alter().
  233. *
  234. * This allows alias creators to override Pathauto and specify their
  235. * own aliases (Pathauto will be invisible to other users). Inserted
  236. * into the path module's fieldset in the node form.
  237. */
  238. function pathauto_form_alter($formid, &$form) {
  239. // Only do this for node forms
  240. if (isset($form['#id']) && ($form['#id'] == 'node-form') && arg(0) == 'node') {
  241. // See if there is a pathauto pattern or default applicable
  242. $pattern = trim(variable_get('pathauto_node_'. $form['type']['#value'] .'_pattern', FALSE));
  243. if (!$pattern) {
  244. $pattern = trim(variable_get('pathauto_node_pattern', FALSE));
  245. }
  246. // If there is a pattern AND the user is allowed to create aliases AND the path textbox is present on this form
  247. if (!empty($pattern) && user_access('create url aliases') && isset($form['path']['path'])) {
  248. $output = t('An alias will be generated for you. If you wish to create your own alias below, untick this option.');
  249. if (user_access('administer pathauto')) {
  250. $output .= t(' To control the format of the generated aliases, see the <a href="@pathauto">Pathauto settings</a>.', array('@pathauto' => url('admin/settings/pathauto')));
  251. }
  252. drupal_add_js(drupal_get_path('module', 'pathauto') .'/pathauto.js');
  253. $form['path']['#collapsed'] = FALSE;
  254. $form['path']['pathauto_perform_alias'] = array(
  255. '#type' => 'checkbox',
  256. '#title' => t('Automatic alias'),
  257. '#default_value' => TRUE,
  258. '#description' => $output,
  259. '#weight' => -1,
  260. );
  261. }
  262. }
  263. }
  264. /**
  265. * Implementation of hook_node_operations().
  266. */
  267. function pathauto_node_operations() {
  268. $operations = array(
  269. 'update_alias' => array(
  270. 'label' => t('Update path alias'),
  271. 'callback' => 'pathauto_node_operations_update',
  272. ),
  273. );
  274. return $operations;
  275. }
  276. /**
  277. * Callback function for updating node aliases.
  278. *
  279. * @param $nodes
  280. * Array of node nid's.
  281. */
  282. function pathauto_node_operations_update($nodes) {
  283. _pathauto_include();
  284. foreach ($nodes as $nid) {
  285. $node = node_load($nid);
  286. $placeholders = pathauto_get_placeholders('node', $node);
  287. pathauto_create_alias('node', 'bulkupdate', $placeholders, "node/$node->nid", $node->nid, $node->type);
  288. }
  289. }
  290. //==============================================================================
  291. // Taxonomy related functions.
  292. /**
  293. * Implementation of hook_taxonomy().
  294. */
  295. function pathauto_taxonomy($op, $type, $object = NULL) {
  296. switch ($type) {
  297. case 'term':
  298. switch ($op) {
  299. case 'insert':
  300. case 'update':
  301. _pathauto_include();
  302. // Use the category info to automatically create an alias
  303. $category = (object) $object;
  304. if ($category->name) {
  305. $count = _taxonomy_pathauto_alias($category, $op);
  306. }
  307. // For all children generate new alias (important if [catpath] used)
  308. foreach (taxonomy_get_tree($category->vid, $category->tid) as $subcategory) {
  309. $count = _taxonomy_pathauto_alias($subcategory, $op);
  310. }
  311. break;
  312. case 'delete':
  313. // If the category is deleted, remove the path aliases
  314. $category = (object) $object;
  315. path_set_alias('taxonomy/term/'. $category->tid);
  316. path_set_alias(taxonomy_term_path($category));
  317. path_set_alias('forum/'. $category->tid);
  318. path_set_alias('taxonomy/term/'. $category->tid .'/0/feed');
  319. break;
  320. default:
  321. break;
  322. }
  323. break;
  324. default:
  325. break;
  326. }
  327. }
  328. //==============================================================================
  329. // User related functions.
  330. /**
  331. * Implementation of hook_user() for users, trackers, and blogs.
  332. */
  333. function pathauto_user($op, &$edit, &$user, $category = FALSE) {
  334. switch ($op) {
  335. case 'insert':
  336. case 'update':
  337. _pathauto_include();
  338. // Use the username to automatically create an alias
  339. $pathauto_user = (object) array_merge((array) $user, $edit);
  340. if ($user->name) {
  341. $placeholders = pathauto_get_placeholders('user', $pathauto_user);
  342. $src = 'user/'. $user->uid;
  343. $alias = pathauto_create_alias('user', $op, $placeholders, $src, $user->uid);
  344. if (module_exists('blog')) {
  345. $new_user = drupal_clone($user);
  346. if ($category == 'account') {
  347. $new_user->roles = isset($edit['roles']) ? $edit['roles'] : array();
  348. $new_user->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user'; // Add this back
  349. }
  350. if (user_access('edit own blog', $new_user)) {
  351. $src = 'blog/'. $user->uid;
  352. $alias = pathauto_create_alias('blog', $op, $placeholders, $src, $user->uid);
  353. }
  354. else {
  355. path_set_alias('blog/'. $user->uid);
  356. path_set_alias('blog/'. $user->uid .'/feed');
  357. }
  358. }
  359. if (module_exists('tracker')) {
  360. $src = 'user/'. $user->uid .'/track';
  361. $alias = pathauto_create_alias('tracker', $op, $placeholders, $src, $user->uid);
  362. }
  363. }
  364. break;
  365. case 'delete':
  366. // If the user is deleted, remove the path aliases
  367. $user = (object) $user;
  368. path_set_alias('user/'. $user->uid);
  369. // They may have enabled these modules and/or feeds when the user was created, so let's try to delete all of them
  370. path_set_alias('blog/'. $user->uid);
  371. path_set_alias('blog/'. $user->uid .'/feed');
  372. path_set_alias('user/'. $user->uid .'/track');
  373. path_set_alias('user/'. $user->uid .'/track/feed');
  374. break;
  375. default:
  376. break;
  377. }
  378. }
  379. //==============================================================================
  380. // Admin page related functions.
  381. /**
  382. * Form builder; Configure the Pathauto system.
  383. *
  384. * @ingroup forms
  385. * @see system_settings_form()
  386. */
  387. function pathauto_admin_settings() {
  388. _pathauto_include();
  389. // Make sure they have token
  390. if (!function_exists('token_get_list')) {
  391. 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');
  392. return;
  393. }
  394. // Default words to ignore
  395. $ignore_words = array(
  396. 'a', 'an', 'as', 'at', 'before', 'but', 'by', 'for', 'from', 'is', 'in',
  397. 'into', 'like', 'of', 'off', 'on', 'onto', 'per', 'since', 'than', 'the',
  398. 'this', 'that', 'to', 'up', 'via', 'with',
  399. );
  400. // Generate the form - settings applying to all patterns first
  401. $group_weight = -20;
  402. $form['general'] = array(
  403. '#type' => 'fieldset',
  404. '#weight' => $group_weight,
  405. '#title' => t('General settings'),
  406. '#collapsible' => TRUE,
  407. '#collapsed' => TRUE,
  408. );
  409. $group_weight++;
  410. $form['general']['pathauto_verbose'] = array(
  411. '#type' => 'checkbox',
  412. '#title' => t('Verbose'),
  413. '#default_value' => variable_get('pathauto_verbose', FALSE),
  414. '#description' => t('Display alias changes (except during bulk updates).'),
  415. );
  416. $form['general']['pathauto_separator'] = array(
  417. '#type' => 'textfield',
  418. '#title' => t('Separator'),
  419. '#size' => 1,
  420. '#maxlength' => 1,
  421. '#default_value' => variable_get('pathauto_separator', '-'),
  422. '#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.'),
  423. );
  424. $form['general']['pathauto_case'] = array(
  425. '#type' => 'radios',
  426. '#title' => t('Character case'),
  427. '#default_value' => variable_get('pathauto_case', 1),
  428. '#options' => array(t('Leave case the same as source token values.'), t('Change to lower case')),
  429. );
  430. $form['general']['pathauto_max_length'] = array(
  431. '#type' => 'textfield',
  432. '#title' => t('Maximum alias length'),
  433. '#size' => 3,
  434. '#maxlength' => 3,
  435. '#default_value' => variable_get('pathauto_max_length', 100),
  436. '#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'))),
  437. );
  438. $form['general']['pathauto_max_component_length'] = array(
  439. '#type' => 'textfield',
  440. '#title' => t('Maximum component length'),
  441. '#size' => 3,
  442. '#maxlength' => 3,
  443. '#default_value' => variable_get('pathauto_max_component_length', 100),
  444. '#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'))),
  445. );
  446. $form['general']['pathauto_max_bulk_update'] = array(
  447. '#type' => 'textfield',
  448. '#title' => t('Maximum number of objects to alias in a bulk update'),
  449. '#size' => 4,
  450. '#maxlength' => 4,
  451. '#default_value' => variable_get('pathauto_max_bulk_update', 50),
  452. '#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.'),
  453. );
  454. $actions = array(
  455. t('Do nothing. Leave the old alias intact.'),
  456. t('Create a new alias. Leave the existing alias functioning.'),
  457. t('Create a new alias. Delete the old alias.'));
  458. if (function_exists('path_redirect_save')) {
  459. $actions[] = t('Create a new alias. Redirect from old alias.');
  460. }
  461. elseif (variable_get('pathauto_update_action', 2) == 3) {
  462. // the redirect action is selected, but path_redirect is not enabled
  463. // let's set the variable back to the default
  464. variable_set('pathauto_update_action', 2);
  465. }
  466. $form['general']['pathauto_update_action'] = array(
  467. '#type' => 'radios',
  468. '#title' => t('Update action'),
  469. '#default_value' => variable_get('pathauto_update_action', 2),
  470. '#options' => $actions,
  471. '#description' => t('What should pathauto do when updating an existing content item which already has an alias?'),
  472. );
  473. $disable_transliteration = TRUE;
  474. $path = drupal_get_path('module', 'pathauto');
  475. $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>');
  476. if (is_file($path .'/i18n-ascii.txt')) {
  477. $disable_transliteration = FALSE;
  478. $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.');
  479. }
  480. else {
  481. // Perhaps they've removed the file, set the transliterate option to FALSE
  482. variable_set('pathauto_transliterate', FALSE);
  483. }
  484. $form['general']['pathauto_transliterate'] = array(
  485. '#type' => 'checkbox',
  486. '#title' => t('Transliterate prior to creating alias'),
  487. '#default_value' => variable_get('pathauto_transliterate', FALSE),
  488. '#description' => $transliteration_help,
  489. '#disabled' => $disable_transliteration,
  490. );
  491. $form['general']['pathauto_reduce_ascii'] = array(
  492. '#type' => 'checkbox',
  493. '#title' => t('Reduce strings to letters and numbers from ASCII-96'),
  494. '#default_value' => variable_get('pathauto_reduce_ascii', FALSE),
  495. '#description' => t('Filters the new alias to only letters and numbers found in the ASCII-96 set.'),
  496. );
  497. $form['general']['pathauto_ignore_words'] = array(
  498. '#type' => 'textarea',
  499. '#title' => t('Strings to Remove'), '#default_value' => variable_get('pathauto_ignore_words', implode(',', $ignore_words)),
  500. '#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.'),
  501. );
  502. $form['punctuation'] = array(
  503. '#type' => 'fieldset',
  504. '#weight' => $group_weight,
  505. '#title' => t('Punctuation settings'), '#collapsible' => TRUE,
  506. '#collapsed' => TRUE,
  507. );
  508. $group_weight++;
  509. $punctuation = pathauto_punctuation_chars();
  510. foreach ($punctuation as $name => $details) {
  511. $form['punctuation']['pathauto_punctuation_'. $name ] = array(
  512. '#type' => 'select',
  513. '#title' => $details['name'],
  514. '#default_value' => variable_get('pathauto_punctuation_'. $name, 0),
  515. '#options' => array('0' => t('Remove'), '1' => t('Replace by separator'), '2' => t('No action (do not replace)')),
  516. );
  517. }
  518. // Call the hook on all modules - an array of 'settings' objects is returned
  519. $all_settings = module_invoke_all('pathauto', 'settings');
  520. $modulelist = '';
  521. $indexcount = 0;
  522. foreach ($all_settings as $settings) {
  523. $items = '';
  524. $module = $settings->module;
  525. $modulelist[] = $module;
  526. $patterndescr = $settings->patterndescr;
  527. $patterndefault = $settings->patterndefault;
  528. $groupheader = $settings->groupheader;
  529. $supportsfeeds = isset($settings->supportsfeeds) ? $settings->supportsfeeds : NULL;
  530. variable_set('pathauto_'. $module .'_supportsfeeds', $supportsfeeds);
  531. $form[$module] = array(
  532. '#type' => 'fieldset',
  533. '#title' => $groupheader,
  534. '#weight' => $group_weight,
  535. '#collapsible' => TRUE,
  536. '#collapsed' => TRUE,
  537. );
  538. $group_weight++;
  539. // Prompt for the default pattern for this module
  540. $variable = 'pathauto_'. $module .'_pattern';
  541. $description = '';
  542. if (!count($_POST)) {
  543. $error = _pathauto_check_pattern(variable_get($variable, $patterndefault), $settings->token_type);
  544. if ($error) {
  545. $form[$module]['#collapsed'] = FALSE;
  546. $description = $error;
  547. }
  548. }
  549. $form[$module][$variable] = array(
  550. '#type' => 'textfield',
  551. '#title' => $patterndescr,
  552. '#default_value' => variable_get($variable, $patterndefault),
  553. '#description' => $description,
  554. '#size' => 65,
  555. '#maxlength' => 1280,
  556. );
  557. // If the module supports a set of specialized patterns, set
  558. // them up here
  559. if (isset($settings->patternitems)) {
  560. foreach ($settings->patternitems as $itemname => $itemlabel) {
  561. $variable = 'pathauto_'. $module .'_'. $itemname .'_pattern';
  562. $description = '';
  563. if (!count($_POST)) {
  564. $error = _pathauto_check_pattern(variable_get($variable, $patterndefault), $settings->token_type);
  565. if ($error) {
  566. $form[$module]['#collapsed'] = FALSE;
  567. $description = $error;
  568. }
  569. }
  570. $form[$module][$variable] = array('#type' => 'textfield',
  571. '#title' => $itemlabel,
  572. '#default_value' => variable_get($variable, ''),
  573. '#description' => $description,
  574. '#size' => 65,
  575. '#maxlength' => 1280);
  576. }
  577. }
  578. // Display the user documentation of placeholders supported by
  579. // this module, as a description on the last pattern
  580. $doc = "<dl>\n";
  581. foreach ($settings->placeholders as $name => $description) {
  582. $doc .= '<dt>'. $name .'</dt>';
  583. $doc .= '<dd>'. $description .'</dd>';
  584. }
  585. $doc .= "</dl>\n";
  586. $form[$module]['token_help'] = array(
  587. '#title' => t('Replacement patterns'),
  588. '#type' => 'fieldset',
  589. '#collapsible' => TRUE,
  590. '#collapsed' => TRUE,
  591. '#description' => t('Use -raw replacements for text to avoid problems with HTML entities.'),
  592. );
  593. $form[$module]['token_help']['help'] = array(
  594. '#value' => $doc,
  595. );
  596. // If the module supports bulk updates, offer the update action here
  597. if ($settings->bulkname) {
  598. $variable = 'pathauto_'. $module .'_bulkupdate';
  599. if (variable_get($variable, FALSE)) {
  600. variable_set($variable, FALSE);
  601. $function = $module .'_pathauto_bulkupdate';
  602. call_user_func($function);
  603. }
  604. $form[$module][$variable] = array(
  605. '#type' => 'checkbox',
  606. '#title' => $settings->bulkname,
  607. '#default_value' => FALSE,
  608. '#description' => $settings->bulkdescr,
  609. );
  610. }
  611. // If the module supports feeds, offer to generate aliases for them
  612. if ($supportsfeeds) {
  613. $variable = 'pathauto_'. $module .'_applytofeeds';
  614. $current = variable_get($variable, $supportsfeeds);
  615. // This checks for the old style from 2.0 and earlier. TODO: At some point we can drop that.
  616. if (is_numeric($current)) {
  617. $current = $supportsfeeds;
  618. }
  619. $form[$module][$variable] = array(
  620. '#type' => 'textfield',
  621. '#title' => t('Internal feed alias text (leave blank to disable)'),
  622. '#size' => 65,
  623. '#maxlength' => 1280,
  624. '#default_value' => $current,
  625. '#description' => t('The text to use for aliases for RSS feeds. Examples are "feed" and "0/feed".'),
  626. );
  627. }
  628. }
  629. if (isset($do_index_bulkupdate) && $do_index_bulkupdate) {
  630. drupal_set_message(format_plural($indexcount,
  631. 'Bulk generation of index aliases completed, one alias generated.',
  632. 'Bulk generation of index aliases completed, @count aliases generated.'));
  633. }
  634. // Keep track of which modules currently support pathauto
  635. variable_set('pathauto_modulelist', $modulelist);
  636. return system_settings_form($form);
  637. }
  638. /**
  639. * Helper function for pathauto_admin_settings().
  640. *
  641. * See if they are using all -raw tokens available
  642. * and if all the tokens are valid in the given context.
  643. *
  644. * @param $pattern
  645. * A string containing the pattern to be tested.
  646. * @param $type
  647. * A flag indicating the class of substitution tokens to use.
  648. * @return
  649. * A status flag, telling whether there is an error or not.
  650. * @see token_get_list()
  651. * For more information on the $type parameter.
  652. */
  653. function _pathauto_check_pattern($pattern, $type) {
  654. // Hold items we've warned about so we only warn once per token
  655. static $warned;
  656. $return = FALSE;
  657. // Build up a set of all tokens in a format that's easy to search
  658. $all_tokens = array();
  659. $tokens = token_get_list($type);
  660. foreach ($tokens as $actual_tokens) {
  661. foreach (array_keys($actual_tokens) as $token) {
  662. $all_tokens[$token] = $token;
  663. }
  664. }
  665. // Now, search the pattern and evaluate its contents.
  666. $matches = array();
  667. if (preg_match_all('/\[[a-zA-z_\-]+?\]/i', $pattern, $matches)) {
  668. // Loop over each found token.
  669. foreach ($matches[0] as $id => $token) {
  670. $token = str_replace('[', '', str_replace(']', '', $token));
  671. // Check if the token is even valid in this context.
  672. if (!array_key_exists($token, $all_tokens)) {
  673. 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');
  674. $return[] = $token;
  675. }
  676. // Check if there is a raw companion that they should be using.
  677. elseif (!preg_match('/\-raw/i', $token)) {
  678. $raw_token = $token .'-raw';
  679. if (array_key_exists($raw_token, $all_tokens)) {
  680. if (!isset($warned) || !array_key_exists($token, $warned)) {
  681. 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');
  682. $warned[$token] = $token;
  683. }
  684. $return[] = $token;
  685. }
  686. }
  687. }
  688. }
  689. if ($return) {
  690. $description = t('NOTE: This field contains potentially incorrect patterns. ');
  691. $description .= format_plural(count($return), 'Problem token: ', 'Problem tokens: ');
  692. $description .= t('%problems', array('%problems' => implode(', ', $return)));
  693. $return = $description;
  694. }
  695. return $return;
  696. }
  697. /**
  698. * Validate pathauto_admin_settings form submissions.
  699. */
  700. function pathauto_admin_settings_validate($form_id, $form_values) {
  701. // Validate that the separator is not set to be removed per http://drupal.org/node/184119
  702. // This isn't really all that bad so warn, but still allow them to save the value.
  703. $separator = $form_values['pathauto_separator'];
  704. $punctuation = pathauto_punctuation_chars();
  705. foreach ($punctuation as $name => $details) {
  706. if ($details['value'] == $separator) {
  707. $action = $form_values['pathauto_punctuation_'. $name];
  708. if ($action == 0) {
  709. 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');
  710. }
  711. }
  712. }
  713. }
  714. /**
  715. * Menu callback; select certain alias types to delete.
  716. */
  717. function pathauto_admin_delete() {
  718. /* TODO:
  719. 1) all - DONE
  720. 2) all node aliases - DONE
  721. 4) all user aliases - DONE
  722. 5) all taxonomy aliases - DONE
  723. 6) by node type
  724. 7) by taxonomy vocabulary
  725. 8) no longer existing aliases (see http://drupal.org/node/128366 )
  726. 9) where src like 'pattern' - DON'T DO
  727. 10) where dst like 'pattern' - DON'T DO
  728. */
  729. $form = array();
  730. $form['delete'] = array(
  731. '#type' => 'fieldset',
  732. '#title' => t('Choose Aliases to Delete'),
  733. '#collapsible' => FALSE,
  734. '#collapsed' => FALSE,
  735. );
  736. // First we do the "all" case
  737. $total_count = db_result(db_query('SELECT count(1) FROM {url_alias}'));
  738. $form['delete']['all_aliases'] = array(
  739. '#type' => 'checkbox',
  740. '#title' => t('all aliases'),
  741. '#default_value' => FALSE,
  742. '#description' => t('Delete all aliases. Number of aliases which will be deleted: %count.', array('%count' => $total_count)),
  743. );
  744. // Next, iterate over an array of objects/alias types which can be deleted and provide checkboxes
  745. $objects = module_invoke_all('path_alias_types');
  746. foreach ($objects as $internal_name => $label) {
  747. $count = db_result(db_query("SELECT count(1) FROM {url_alias} WHERE src LIKE '%s%%'", $internal_name));
  748. $form['delete'][$internal_name] = array(
  749. '#type' => 'checkbox',
  750. '#title' => $label, // This label is sent through t() in the hard coded function where it is defined
  751. '#default_value' => FALSE,
  752. '#description' => t('Delete aliases for all @label. Number of aliases which will be deleted: %count.', array('@label' => $label, '%count' => $count)),
  753. );
  754. }
  755. // Warn them and give a button that shows we mean business
  756. $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>'));
  757. $form['buttons']['submit'] = array(
  758. '#type' => 'submit',
  759. '#value' => t('Delete aliases now!'),
  760. );
  761. return $form;
  762. }
  763. /**
  764. * Process pathauto_admin_delete form submissions.
  765. */
  766. function pathauto_admin_delete_submit($form_id, $form_values) {
  767. foreach ($form_values as $key => $value) {
  768. if ($value) {
  769. if ($key === 'all_aliases') {
  770. db_query('DELETE FROM {url_alias}');
  771. drupal_set_message(t('All of your path aliases have been deleted.'));
  772. }
  773. $objects = module_invoke_all('path_alias_types');
  774. if (array_key_exists($key, $objects)) {
  775. db_query("DELETE FROM {url_alias} WHERE src LIKE '%s%%'", $key);
  776. drupal_set_message(t('All of your %type path aliases have been deleted.', array('%type' => $objects[$key])));
  777. }
  778. }
  779. }
  780. return 'admin/build/path/delete_bulk';
  781. }

Related topics