redis.path.inc 20 KB

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