path.inc

  1. 7.x drupal-7.x/includes/path.inc
  2. 6.x drupal-6.x/includes/path.inc

Functions to handle paths in Drupal, including path aliasing.

These functions are not loaded for cached pages, but modules that need to use them in hook_boot() or hook exit() can make them available, by executing "drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);".

File

drupal-7.x/includes/path.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * Functions to handle paths in Drupal, including path aliasing.
  5. *
  6. * These functions are not loaded for cached pages, but modules that need
  7. * to use them in hook_boot() or hook exit() can make them available, by
  8. * executing "drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);".
  9. */
  10. /**
  11. * Initialize the $_GET['q'] variable to the proper normal path.
  12. */
  13. function drupal_path_initialize() {
  14. // Ensure $_GET['q'] is set before calling drupal_normal_path(), to support
  15. // path caching with hook_url_inbound_alter().
  16. if (empty($_GET['q'])) {
  17. $_GET['q'] = variable_get('site_frontpage', 'node');
  18. }
  19. $_GET['q'] = drupal_get_normal_path($_GET['q']);
  20. }
  21. /**
  22. * Given an alias, return its Drupal system URL if one exists. Given a Drupal
  23. * system URL return one of its aliases if such a one exists. Otherwise,
  24. * return FALSE.
  25. *
  26. * @param $action
  27. * One of the following values:
  28. * - wipe: delete the alias cache.
  29. * - alias: return an alias for a given Drupal system path (if one exists).
  30. * - source: return the Drupal system URL for a path alias (if one exists).
  31. * @param $path
  32. * The path to investigate for corresponding aliases or system URLs.
  33. * @param $path_language
  34. * Optional language code to search the path with. Defaults to the page language.
  35. * If there's no path defined for that language it will search paths without
  36. * language.
  37. *
  38. * @return
  39. * Either a Drupal system path, an aliased path, or FALSE if no path was
  40. * found.
  41. */
  42. function drupal_lookup_path($action, $path = '', $path_language = NULL) {
  43. global $language_url;
  44. // Use the advanced drupal_static() pattern, since this is called very often.
  45. static $drupal_static_fast;
  46. if (!isset($drupal_static_fast)) {
  47. $drupal_static_fast['cache'] = &drupal_static(__FUNCTION__);
  48. }
  49. $cache = &$drupal_static_fast['cache'];
  50. if (!isset($cache)) {
  51. $cache = array(
  52. 'map' => array(),
  53. 'no_source' => array(),
  54. 'whitelist' => NULL,
  55. 'system_paths' => array(),
  56. 'no_aliases' => array(),
  57. 'first_call' => TRUE,
  58. );
  59. }
  60. // Retrieve the path alias whitelist.
  61. if (!isset($cache['whitelist'])) {
  62. $cache['whitelist'] = variable_get('path_alias_whitelist', NULL);
  63. if (!isset($cache['whitelist'])) {
  64. $cache['whitelist'] = drupal_path_alias_whitelist_rebuild();
  65. }
  66. }
  67. // If no language is explicitly specified we default to the current URL
  68. // language. If we used a language different from the one conveyed by the
  69. // requested URL, we might end up being unable to check if there is a path
  70. // alias matching the URL path.
  71. $path_language = $path_language ? $path_language : $language_url->language;
  72. if ($action == 'wipe') {
  73. $cache = array();
  74. $cache['whitelist'] = drupal_path_alias_whitelist_rebuild();
  75. }
  76. elseif ($cache['whitelist'] && $path != '') {
  77. if ($action == 'alias') {
  78. // During the first call to drupal_lookup_path() per language, load the
  79. // expected system paths for the page from cache.
  80. if (!empty($cache['first_call'])) {
  81. $cache['first_call'] = FALSE;
  82. $cache['map'][$path_language] = array();
  83. // Load system paths from cache.
  84. $cid = current_path();
  85. if ($cached = cache_get($cid, 'cache_path')) {
  86. $cache['system_paths'] = $cached->data;
  87. // Now fetch the aliases corresponding to these system paths.
  88. $args = array(
  89. ':system' => $cache['system_paths'],
  90. ':language' => $path_language,
  91. ':language_none' => LANGUAGE_NONE,
  92. );
  93. // Always get the language-specific alias before the language-neutral
  94. // one. For example 'de' is less than 'und' so the order needs to be
  95. // ASC, while 'xx-lolspeak' is more than 'und' so the order needs to
  96. // be DESC. We also order by pid ASC so that fetchAllKeyed() returns
  97. // the most recently created alias for each source. Subsequent queries
  98. // using fetchField() must use pid DESC to have the same effect.
  99. // For performance reasons, the query builder is not used here.
  100. if ($path_language == LANGUAGE_NONE) {
  101. // Prevent PDO from complaining about a token the query doesn't use.
  102. unset($args[':language']);
  103. $result = db_query('SELECT source, alias FROM {url_alias} WHERE source IN (:system) AND language = :language_none ORDER BY pid ASC', $args);
  104. }
  105. elseif ($path_language < LANGUAGE_NONE) {
  106. $result = db_query('SELECT source, alias FROM {url_alias} WHERE source IN (:system) AND language IN (:language, :language_none) ORDER BY language ASC, pid ASC', $args);
  107. }
  108. else {
  109. $result = db_query('SELECT source, alias FROM {url_alias} WHERE source IN (:system) AND language IN (:language, :language_none) ORDER BY language DESC, pid ASC', $args);
  110. }
  111. $cache['map'][$path_language] = $result->fetchAllKeyed();
  112. // Keep a record of paths with no alias to avoid querying twice.
  113. $cache['no_aliases'][$path_language] = array_flip(array_diff_key($cache['system_paths'], array_keys($cache['map'][$path_language])));
  114. }
  115. }
  116. // If the alias has already been loaded, return it.
  117. if (isset($cache['map'][$path_language][$path])) {
  118. return $cache['map'][$path_language][$path];
  119. }
  120. // Check the path whitelist, if the top_level part before the first /
  121. // is not in the list, then there is no need to do anything further,
  122. // it is not in the database.
  123. elseif (!isset($cache['whitelist'][strtok($path, '/')])) {
  124. return FALSE;
  125. }
  126. // For system paths which were not cached, query aliases individually.
  127. elseif (!isset($cache['no_aliases'][$path_language][$path])) {
  128. $args = array(
  129. ':source' => $path,
  130. ':language' => $path_language,
  131. ':language_none' => LANGUAGE_NONE,
  132. );
  133. // See the queries above.
  134. if ($path_language == LANGUAGE_NONE) {
  135. unset($args[':language']);
  136. $alias = db_query("SELECT alias FROM {url_alias} WHERE source = :source AND language = :language_none ORDER BY pid DESC", $args)->fetchField();
  137. }
  138. elseif ($path_language > LANGUAGE_NONE) {
  139. $alias = db_query("SELECT alias FROM {url_alias} WHERE source = :source AND language IN (:language, :language_none) ORDER BY language DESC, pid DESC", $args)->fetchField();
  140. }
  141. else {
  142. $alias = db_query("SELECT alias FROM {url_alias} WHERE source = :source AND language IN (:language, :language_none) ORDER BY language ASC, pid DESC", $args)->fetchField();
  143. }
  144. $cache['map'][$path_language][$path] = $alias;
  145. return $alias;
  146. }
  147. }
  148. // Check $no_source for this $path in case we've already determined that there
  149. // isn't a path that has this alias
  150. elseif ($action == 'source' && !isset($cache['no_source'][$path_language][$path])) {
  151. // Look for the value $path within the cached $map
  152. $source = FALSE;
  153. if (!isset($cache['map'][$path_language]) || !($source = array_search($path, $cache['map'][$path_language]))) {
  154. $args = array(
  155. ':alias' => $path,
  156. ':language' => $path_language,
  157. ':language_none' => LANGUAGE_NONE,
  158. );
  159. // See the queries above.
  160. if ($path_language == LANGUAGE_NONE) {
  161. unset($args[':language']);
  162. $result = db_query("SELECT source FROM {url_alias} WHERE alias = :alias AND language = :language_none ORDER BY pid DESC", $args);
  163. }
  164. elseif ($path_language > LANGUAGE_NONE) {
  165. $result = db_query("SELECT source FROM {url_alias} WHERE alias = :alias AND language IN (:language, :language_none) ORDER BY language DESC, pid DESC", $args);
  166. }
  167. else {
  168. $result = db_query("SELECT source FROM {url_alias} WHERE alias = :alias AND language IN (:language, :language_none) ORDER BY language ASC, pid DESC", $args);
  169. }
  170. if ($source = $result->fetchField()) {
  171. $cache['map'][$path_language][$source] = $path;
  172. }
  173. else {
  174. // We can't record anything into $map because we do not have a valid
  175. // index and there is no need because we have not learned anything
  176. // about any Drupal path. Thus cache to $no_source.
  177. $cache['no_source'][$path_language][$path] = TRUE;
  178. }
  179. }
  180. return $source;
  181. }
  182. }
  183. return FALSE;
  184. }
  185. /**
  186. * Cache system paths for a page.
  187. *
  188. * Cache an array of the system paths available on each page. We assume
  189. * that aliases will be needed for the majority of these paths during
  190. * subsequent requests, and load them in a single query during
  191. * drupal_lookup_path().
  192. */
  193. function drupal_cache_system_paths() {
  194. // Check if the system paths for this page were loaded from cache in this
  195. // request to avoid writing to cache on every request.
  196. $cache = &drupal_static('drupal_lookup_path', array());
  197. if (empty($cache['system_paths']) && !empty($cache['map'])) {
  198. // Generate a cache ID (cid) specifically for this page.
  199. $cid = current_path();
  200. // The static $map array used by drupal_lookup_path() includes all
  201. // system paths for the page request.
  202. if ($paths = current($cache['map'])) {
  203. $data = array_keys($paths);
  204. $expire = REQUEST_TIME + (60 * 60 * 24);
  205. cache_set($cid, $data, 'cache_path', $expire);
  206. }
  207. }
  208. }
  209. /**
  210. * Given an internal Drupal path, return the alias set by the administrator.
  211. *
  212. * If no path is provided, the function will return the alias of the current
  213. * page.
  214. *
  215. * @param $path
  216. * An internal Drupal path.
  217. * @param $path_language
  218. * An optional language code to look up the path in.
  219. *
  220. * @return
  221. * An aliased path if one was found, or the original path if no alias was
  222. * found.
  223. */
  224. function drupal_get_path_alias($path = NULL, $path_language = NULL) {
  225. // If no path is specified, use the current page's path.
  226. if ($path == NULL) {
  227. $path = $_GET['q'];
  228. }
  229. $result = $path;
  230. if ($alias = drupal_lookup_path('alias', $path, $path_language)) {
  231. $result = $alias;
  232. }
  233. return $result;
  234. }
  235. /**
  236. * Given a path alias, return the internal path it represents.
  237. *
  238. * @param $path
  239. * A Drupal path alias.
  240. * @param $path_language
  241. * An optional language code to look up the path in.
  242. *
  243. * @return
  244. * The internal path represented by the alias, or the original alias if no
  245. * internal path was found.
  246. */
  247. function drupal_get_normal_path($path, $path_language = NULL) {
  248. $original_path = $path;
  249. // Lookup the path alias first.
  250. if ($source = drupal_lookup_path('source', $path, $path_language)) {
  251. $path = $source;
  252. }
  253. // Allow other modules to alter the inbound URL. We cannot use drupal_alter()
  254. // here because we need to run hook_url_inbound_alter() in the reverse order
  255. // of hook_url_outbound_alter().
  256. foreach (array_reverse(module_implements('url_inbound_alter')) as $module) {
  257. $function = $module . '_url_inbound_alter';
  258. $function($path, $original_path, $path_language);
  259. }
  260. return $path;
  261. }
  262. /**
  263. * Check if the current page is the front page.
  264. *
  265. * @return
  266. * Boolean value: TRUE if the current page is the front page; FALSE if otherwise.
  267. */
  268. function drupal_is_front_page() {
  269. // Use the advanced drupal_static() pattern, since this is called very often.
  270. static $drupal_static_fast;
  271. if (!isset($drupal_static_fast)) {
  272. $drupal_static_fast['is_front_page'] = &drupal_static(__FUNCTION__);
  273. }
  274. $is_front_page = &$drupal_static_fast['is_front_page'];
  275. if (!isset($is_front_page)) {
  276. // As drupal_path_initialize updates $_GET['q'] with the 'site_frontpage' path,
  277. // we can check it against the 'site_frontpage' variable.
  278. $is_front_page = ($_GET['q'] == variable_get('site_frontpage', 'node'));
  279. }
  280. return $is_front_page;
  281. }
  282. /**
  283. * Check if a path matches any pattern in a set of patterns.
  284. *
  285. * @param $path
  286. * The path to match.
  287. * @param $patterns
  288. * String containing a set of patterns separated by \n, \r or \r\n.
  289. *
  290. * @return
  291. * Boolean value: TRUE if the path matches a pattern, FALSE otherwise.
  292. */
  293. function drupal_match_path($path, $patterns) {
  294. $regexps = &drupal_static(__FUNCTION__);
  295. if (!isset($regexps[$patterns])) {
  296. // Convert path settings to a regular expression.
  297. // Therefore replace newlines with a logical or, /* with asterisks and the <front> with the frontpage.
  298. $to_replace = array(
  299. '/(\r\n?|\n)/', // newlines
  300. '/\\\\\*/', // asterisks
  301. '/(^|\|)\\\\<front\\\\>($|\|)/' // <front>
  302. );
  303. $replacements = array(
  304. '|',
  305. '.*',
  306. '\1' . preg_quote(variable_get('site_frontpage', 'node'), '/') . '\2'
  307. );
  308. $patterns_quoted = preg_quote($patterns, '/');
  309. $regexps[$patterns] = '/^(' . preg_replace($to_replace, $replacements, $patterns_quoted) . ')$/';
  310. }
  311. return (bool)preg_match($regexps[$patterns], $path);
  312. }
  313. /**
  314. * Return the current URL path of the page being viewed.
  315. *
  316. * Examples:
  317. * - http://example.com/node/306 returns "node/306".
  318. * - http://example.com/drupalfolder/node/306 returns "node/306" while
  319. * base_path() returns "/drupalfolder/".
  320. * - http://example.com/path/alias (which is a path alias for node/306) returns
  321. * "node/306" as opposed to the path alias.
  322. *
  323. * This function is not available in hook_boot() so use $_GET['q'] instead.
  324. * However, be careful when doing that because in the case of Example #3
  325. * $_GET['q'] will contain "path/alias". If "node/306" is needed, calling
  326. * drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL) makes this function available.
  327. *
  328. * @return
  329. * The current Drupal URL path.
  330. *
  331. * @see request_path()
  332. */
  333. function current_path() {
  334. return $_GET['q'];
  335. }
  336. /**
  337. * Rebuild the path alias white list.
  338. *
  339. * @param $source
  340. * An optional system path for which an alias is being inserted.
  341. *
  342. * @return
  343. * An array containing a white list of path aliases.
  344. */
  345. function drupal_path_alias_whitelist_rebuild($source = NULL) {
  346. // When paths are inserted, only rebuild the whitelist if the system path
  347. // has a top level component which is not already in the whitelist.
  348. if (!empty($source)) {
  349. $whitelist = variable_get('path_alias_whitelist', NULL);
  350. if (isset($whitelist[strtok($source, '/')])) {
  351. return $whitelist;
  352. }
  353. }
  354. // For each alias in the database, get the top level component of the system
  355. // path it corresponds to. This is the portion of the path before the first
  356. // '/', if present, otherwise the whole path itself.
  357. $whitelist = array();
  358. $result = db_query("SELECT DISTINCT SUBSTRING_INDEX(source, '/', 1) AS path FROM {url_alias}");
  359. foreach ($result as $row) {
  360. $whitelist[$row->path] = TRUE;
  361. }
  362. variable_set('path_alias_whitelist', $whitelist);
  363. return $whitelist;
  364. }
  365. /**
  366. * Fetches a specific URL alias from the database.
  367. *
  368. * @param $conditions
  369. * A string representing the source, a number representing the pid, or an
  370. * array of query conditions.
  371. *
  372. * @return
  373. * FALSE if no alias was found or an associative array containing the
  374. * following keys:
  375. * - source: The internal system path.
  376. * - alias: The URL alias.
  377. * - pid: Unique path alias identifier.
  378. * - language: The language of the alias.
  379. */
  380. function path_load($conditions) {
  381. if (is_numeric($conditions)) {
  382. $conditions = array('pid' => $conditions);
  383. }
  384. elseif (is_string($conditions)) {
  385. $conditions = array('source' => $conditions);
  386. }
  387. elseif (!is_array($conditions)) {
  388. return FALSE;
  389. }
  390. $select = db_select('url_alias');
  391. foreach ($conditions as $field => $value) {
  392. $select->condition($field, $value);
  393. }
  394. return $select
  395. ->fields('url_alias')
  396. ->execute()
  397. ->fetchAssoc();
  398. }
  399. /**
  400. * Save a path alias to the database.
  401. *
  402. * @param $path
  403. * An associative array containing the following keys:
  404. * - source: The internal system path.
  405. * - alias: The URL alias.
  406. * - pid: (optional) Unique path alias identifier.
  407. * - language: (optional) The language of the alias.
  408. */
  409. function path_save(&$path) {
  410. $path += array('language' => LANGUAGE_NONE);
  411. // Load the stored alias, if any.
  412. if (!empty($path['pid']) && !isset($path['original'])) {
  413. $path['original'] = path_load($path['pid']);
  414. }
  415. if (empty($path['pid'])) {
  416. drupal_write_record('url_alias', $path);
  417. module_invoke_all('path_insert', $path);
  418. }
  419. else {
  420. drupal_write_record('url_alias', $path, array('pid'));
  421. module_invoke_all('path_update', $path);
  422. }
  423. // Clear internal properties.
  424. unset($path['original']);
  425. // Clear the static alias cache.
  426. drupal_clear_path_cache($path['source']);
  427. }
  428. /**
  429. * Delete a URL alias.
  430. *
  431. * @param $criteria
  432. * A number representing the pid or an array of criteria.
  433. */
  434. function path_delete($criteria) {
  435. if (!is_array($criteria)) {
  436. $criteria = array('pid' => $criteria);
  437. }
  438. $path = path_load($criteria);
  439. $query = db_delete('url_alias');
  440. foreach ($criteria as $field => $value) {
  441. $query->condition($field, $value);
  442. }
  443. $query->execute();
  444. module_invoke_all('path_delete', $path);
  445. drupal_clear_path_cache($path['source']);
  446. }
  447. /**
  448. * Determines whether a path is in the administrative section of the site.
  449. *
  450. * By default, paths are considered to be non-administrative. If a path does
  451. * not match any of the patterns in path_get_admin_paths(), or if it matches
  452. * both administrative and non-administrative patterns, it is considered
  453. * non-administrative.
  454. *
  455. * @param $path
  456. * A Drupal path.
  457. *
  458. * @return
  459. * TRUE if the path is administrative, FALSE otherwise.
  460. *
  461. * @see path_get_admin_paths()
  462. * @see hook_admin_paths()
  463. * @see hook_admin_paths_alter()
  464. */
  465. function path_is_admin($path) {
  466. $path_map = &drupal_static(__FUNCTION__);
  467. if (!isset($path_map['admin'][$path])) {
  468. $patterns = path_get_admin_paths();
  469. $path_map['admin'][$path] = drupal_match_path($path, $patterns['admin']);
  470. $path_map['non_admin'][$path] = drupal_match_path($path, $patterns['non_admin']);
  471. }
  472. return $path_map['admin'][$path] && !$path_map['non_admin'][$path];
  473. }
  474. /**
  475. * Gets a list of administrative and non-administrative paths.
  476. *
  477. * @return array
  478. * An associative array containing the following keys:
  479. * 'admin': An array of administrative paths and regular expressions
  480. * in a format suitable for drupal_match_path().
  481. * 'non_admin': An array of non-administrative paths and regular expressions.
  482. *
  483. * @see hook_admin_paths()
  484. * @see hook_admin_paths_alter()
  485. */
  486. function path_get_admin_paths() {
  487. $patterns = &drupal_static(__FUNCTION__);
  488. if (!isset($patterns)) {
  489. $paths = module_invoke_all('admin_paths');
  490. drupal_alter('admin_paths', $paths);
  491. // Combine all admin paths into one array, and likewise for non-admin paths,
  492. // for easier handling.
  493. $patterns = array();
  494. $patterns['admin'] = array();
  495. $patterns['non_admin'] = array();
  496. foreach ($paths as $path => $enabled) {
  497. if ($enabled) {
  498. $patterns['admin'][] = $path;
  499. }
  500. else {
  501. $patterns['non_admin'][] = $path;
  502. }
  503. }
  504. $patterns['admin'] = implode("\n", $patterns['admin']);
  505. $patterns['non_admin'] = implode("\n", $patterns['non_admin']);
  506. }
  507. return $patterns;
  508. }
  509. /**
  510. * Checks a path exists and the current user has access to it.
  511. *
  512. * @param $path
  513. * The path to check.
  514. * @param $dynamic_allowed
  515. * Whether paths with menu wildcards (like user/%) should be allowed.
  516. *
  517. * @return
  518. * TRUE if it is a valid path AND the current user has access permission,
  519. * FALSE otherwise.
  520. */
  521. function drupal_valid_path($path, $dynamic_allowed = FALSE) {
  522. global $menu_admin;
  523. // We indicate that a menu administrator is running the menu access check.
  524. $menu_admin = TRUE;
  525. if ($path == '<front>' || url_is_external($path)) {
  526. $item = array('access' => TRUE);
  527. }
  528. elseif ($dynamic_allowed && preg_match('/\/\%/', $path)) {
  529. // Path is dynamic (ie 'user/%'), so check directly against menu_router table.
  530. if ($item = db_query("SELECT * FROM {menu_router} where path = :path", array(':path' => $path))->fetchAssoc()) {
  531. $item['link_path'] = $form_item['link_path'];
  532. $item['link_title'] = $form_item['link_title'];
  533. $item['external'] = FALSE;
  534. $item['options'] = '';
  535. _menu_link_translate($item);
  536. }
  537. }
  538. else {
  539. $item = menu_get_item($path);
  540. }
  541. $menu_admin = FALSE;
  542. return $item && $item['access'];
  543. }
  544. /**
  545. * Clear the path cache.
  546. *
  547. * @param $source
  548. * An optional system path for which an alias is being changed.
  549. */
  550. function drupal_clear_path_cache($source = NULL) {
  551. // Clear the drupal_lookup_path() static cache.
  552. drupal_static_reset('drupal_lookup_path');
  553. drupal_path_alias_whitelist_rebuild($source);
  554. }