path.inc 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  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. The path is untrusted user input and must be
  330. * treated as such.
  331. *
  332. * @see request_path()
  333. */
  334. function current_path() {
  335. return $_GET['q'];
  336. }
  337. /**
  338. * Rebuild the path alias white list.
  339. *
  340. * @param $source
  341. * An optional system path for which an alias is being inserted.
  342. *
  343. * @return
  344. * An array containing a white list of path aliases.
  345. */
  346. function drupal_path_alias_whitelist_rebuild($source = NULL) {
  347. // When paths are inserted, only rebuild the whitelist if the system path
  348. // has a top level component which is not already in the whitelist.
  349. if (!empty($source)) {
  350. $whitelist = variable_get('path_alias_whitelist', NULL);
  351. if (isset($whitelist[strtok($source, '/')])) {
  352. return $whitelist;
  353. }
  354. }
  355. // For each alias in the database, get the top level component of the system
  356. // path it corresponds to. This is the portion of the path before the first
  357. // '/', if present, otherwise the whole path itself.
  358. $whitelist = array();
  359. $result = db_query("SELECT DISTINCT SUBSTRING_INDEX(source, '/', 1) AS path FROM {url_alias}");
  360. foreach ($result as $row) {
  361. $whitelist[$row->path] = TRUE;
  362. }
  363. variable_set('path_alias_whitelist', $whitelist);
  364. return $whitelist;
  365. }
  366. /**
  367. * Fetches a specific URL alias from the database.
  368. *
  369. * @param $conditions
  370. * A string representing the source, a number representing the pid, or an
  371. * array of query conditions.
  372. *
  373. * @return
  374. * FALSE if no alias was found or an associative array containing the
  375. * following keys:
  376. * - source: The internal system path.
  377. * - alias: The URL alias.
  378. * - pid: Unique path alias identifier.
  379. * - language: The language of the alias.
  380. */
  381. function path_load($conditions) {
  382. if (is_numeric($conditions)) {
  383. $conditions = array('pid' => $conditions);
  384. }
  385. elseif (is_string($conditions)) {
  386. $conditions = array('source' => $conditions);
  387. }
  388. elseif (!is_array($conditions)) {
  389. return FALSE;
  390. }
  391. $select = db_select('url_alias');
  392. foreach ($conditions as $field => $value) {
  393. $select->condition($field, $value);
  394. }
  395. return $select
  396. ->fields('url_alias')
  397. ->execute()
  398. ->fetchAssoc();
  399. }
  400. /**
  401. * Save a path alias to the database.
  402. *
  403. * @param $path
  404. * An associative array containing the following keys:
  405. * - source: The internal system path.
  406. * - alias: The URL alias.
  407. * - pid: (optional) Unique path alias identifier.
  408. * - language: (optional) The language of the alias.
  409. */
  410. function path_save(&$path) {
  411. $path += array('language' => LANGUAGE_NONE);
  412. // Load the stored alias, if any.
  413. if (!empty($path['pid']) && !isset($path['original'])) {
  414. $path['original'] = path_load($path['pid']);
  415. }
  416. if (empty($path['pid'])) {
  417. drupal_write_record('url_alias', $path);
  418. module_invoke_all('path_insert', $path);
  419. }
  420. else {
  421. drupal_write_record('url_alias', $path, array('pid'));
  422. module_invoke_all('path_update', $path);
  423. }
  424. // Clear internal properties.
  425. unset($path['original']);
  426. // Clear the static alias cache.
  427. drupal_clear_path_cache($path['source']);
  428. }
  429. /**
  430. * Delete a URL alias.
  431. *
  432. * @param $criteria
  433. * A number representing the pid or an array of criteria.
  434. */
  435. function path_delete($criteria) {
  436. if (!is_array($criteria)) {
  437. $criteria = array('pid' => $criteria);
  438. }
  439. $path = path_load($criteria);
  440. $query = db_delete('url_alias');
  441. foreach ($criteria as $field => $value) {
  442. $query->condition($field, $value);
  443. }
  444. $query->execute();
  445. module_invoke_all('path_delete', $path);
  446. drupal_clear_path_cache($path['source']);
  447. }
  448. /**
  449. * Determines whether a path is in the administrative section of the site.
  450. *
  451. * By default, paths are considered to be non-administrative. If a path does
  452. * not match any of the patterns in path_get_admin_paths(), or if it matches
  453. * both administrative and non-administrative patterns, it is considered
  454. * non-administrative.
  455. *
  456. * @param $path
  457. * A Drupal path.
  458. *
  459. * @return
  460. * TRUE if the path is administrative, FALSE otherwise.
  461. *
  462. * @see path_get_admin_paths()
  463. * @see hook_admin_paths()
  464. * @see hook_admin_paths_alter()
  465. */
  466. function path_is_admin($path) {
  467. $path_map = &drupal_static(__FUNCTION__);
  468. if (!isset($path_map['admin'][$path])) {
  469. $patterns = path_get_admin_paths();
  470. $path_map['admin'][$path] = drupal_match_path($path, $patterns['admin']);
  471. $path_map['non_admin'][$path] = drupal_match_path($path, $patterns['non_admin']);
  472. }
  473. return $path_map['admin'][$path] && !$path_map['non_admin'][$path];
  474. }
  475. /**
  476. * Gets a list of administrative and non-administrative paths.
  477. *
  478. * @return array
  479. * An associative array containing the following keys:
  480. * 'admin': An array of administrative paths and regular expressions
  481. * in a format suitable for drupal_match_path().
  482. * 'non_admin': An array of non-administrative paths and regular expressions.
  483. *
  484. * @see hook_admin_paths()
  485. * @see hook_admin_paths_alter()
  486. */
  487. function path_get_admin_paths() {
  488. $patterns = &drupal_static(__FUNCTION__);
  489. if (!isset($patterns)) {
  490. $paths = module_invoke_all('admin_paths');
  491. drupal_alter('admin_paths', $paths);
  492. // Combine all admin paths into one array, and likewise for non-admin paths,
  493. // for easier handling.
  494. $patterns = array();
  495. $patterns['admin'] = array();
  496. $patterns['non_admin'] = array();
  497. foreach ($paths as $path => $enabled) {
  498. if ($enabled) {
  499. $patterns['admin'][] = $path;
  500. }
  501. else {
  502. $patterns['non_admin'][] = $path;
  503. }
  504. }
  505. $patterns['admin'] = implode("\n", $patterns['admin']);
  506. $patterns['non_admin'] = implode("\n", $patterns['non_admin']);
  507. }
  508. return $patterns;
  509. }
  510. /**
  511. * Checks a path exists and the current user has access to it.
  512. *
  513. * @param $path
  514. * The path to check.
  515. * @param $dynamic_allowed
  516. * Whether paths with menu wildcards (like user/%) should be allowed.
  517. *
  518. * @return
  519. * TRUE if it is a valid path AND the current user has access permission,
  520. * FALSE otherwise.
  521. */
  522. function drupal_valid_path($path, $dynamic_allowed = FALSE) {
  523. global $menu_admin;
  524. // We indicate that a menu administrator is running the menu access check.
  525. $menu_admin = TRUE;
  526. if ($path == '<front>' || url_is_external($path)) {
  527. $item = array('access' => TRUE);
  528. }
  529. elseif ($dynamic_allowed && preg_match('/\/\%/', $path)) {
  530. // Path is dynamic (ie 'user/%'), so check directly against menu_router table.
  531. if ($item = db_query("SELECT * FROM {menu_router} where path = :path", array(':path' => $path))->fetchAssoc()) {
  532. $item['link_path'] = $item['path'];
  533. $item['link_title'] = $item['title'];
  534. $item['external'] = FALSE;
  535. $item['options'] = '';
  536. _menu_link_translate($item);
  537. }
  538. }
  539. else {
  540. $item = menu_get_item($path);
  541. }
  542. $menu_admin = FALSE;
  543. return $item && $item['access'];
  544. }
  545. /**
  546. * Clear the path cache.
  547. *
  548. * @param $source
  549. * An optional system path for which an alias is being changed.
  550. */
  551. function drupal_clear_path_cache($source = NULL) {
  552. // Clear the drupal_lookup_path() static cache.
  553. drupal_static_reset('drupal_lookup_path');
  554. drupal_path_alias_whitelist_rebuild($source);
  555. }