redirect.module 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568
  1. <?php
  2. /**
  3. * @defgroup redirect_api Redirection API
  4. * @{
  5. * Functions related to URL redirects.
  6. *
  7. * @} End of "defgroup redirect_api".
  8. */
  9. /**
  10. * Modules should return this value from hook_redirect_access() to allow access
  11. * to a redirect.
  12. */
  13. define('REDIRECT_ACCESS_ALLOW', 'allow');
  14. /**
  15. * Modules should return this value from hook_redirect_access() to deny access
  16. * to a redirect.
  17. */
  18. define('REDIRECT_ACCESS_DENY', 'deny');
  19. /**
  20. * Modules should return this value from hook_redirect_access() to not affect
  21. * redirect access.
  22. */
  23. define('REDIRECT_ACCESS_IGNORE', NULL);
  24. /**
  25. * Implements hook_entity_info().
  26. */
  27. function redirect_entity_info() {
  28. $info['redirect'] = array(
  29. 'label' => t('Redirect'),
  30. 'base table' => 'redirect',
  31. 'controller class' => 'RedirectController',
  32. 'entity keys' => array(
  33. 'id' => 'rid',
  34. 'bundle' => 'type',
  35. ),
  36. 'fieldable' => FALSE,
  37. 'uuid' => FALSE,
  38. 'redirect' => FALSE,
  39. );
  40. return $info;
  41. }
  42. /**
  43. * Controller class for redirects.
  44. *
  45. * This extends the DrupalDefaultEntityController class, adding required
  46. * special handling for redirect objects.
  47. */
  48. class RedirectController extends DrupalDefaultEntityController {
  49. protected function attachLoad(&$redirects, $revision_id = FALSE) {
  50. // Unserialize the URL option fields.
  51. foreach ($redirects as $key => $redirect) {
  52. $redirects[$key]->source_options = unserialize($redirect->source_options);
  53. $redirects[$key]->redirect_options = unserialize($redirect->redirect_options);
  54. }
  55. parent::attachLoad($redirects, $revision_id);
  56. }
  57. }
  58. /**
  59. * Implements hook_hook_info().
  60. */
  61. function redirect_hook_info() {
  62. $hooks = array(
  63. 'redirect_load',
  64. 'redirect_load_by_source_alter',
  65. 'redirect_access',
  66. 'redirect_prepare',
  67. 'redirect_validate',
  68. 'redirect_presave',
  69. 'redirect_insert',
  70. 'redirect_update',
  71. 'redirect_delete',
  72. 'redirect_alter',
  73. );
  74. return array_fill_keys($hooks, array('group' => 'redirect'));
  75. }
  76. /**
  77. * Implements hook_permission().
  78. */
  79. function redirect_permission() {
  80. $permissions['administer redirects'] = array(
  81. 'title' => t('Administer URL redirections'),
  82. );
  83. return $permissions;
  84. }
  85. /**
  86. * Implements hook_help().
  87. */
  88. function redirect_help($path, $arg) {
  89. $output = '';
  90. switch ($path) {
  91. case 'admin/config/search/redirect/404':
  92. $output = '<p>' . t('This page lists all paths that have resulted in 404 errors and do not yet have any redirects assigned to them.') . '</p>';
  93. break;
  94. case 'admin/reports/page-not-found':
  95. break;
  96. }
  97. return $output;
  98. }
  99. /**
  100. * Implements hook_menu().
  101. */
  102. function redirect_menu() {
  103. $items['admin/config/search/redirect'] = array(
  104. 'title' => 'URL redirects',
  105. 'description' => 'Redirect users from one URL to another.',
  106. 'page callback' => 'drupal_get_form',
  107. 'page arguments' => array('redirect_list_form'),
  108. 'access arguments' => array('administer redirects'),
  109. 'file' => 'redirect.admin.inc',
  110. );
  111. $items['admin/config/search/redirect/list'] = array(
  112. 'title' => 'List',
  113. 'type' => MENU_DEFAULT_LOCAL_TASK,
  114. 'weight' => -10,
  115. );
  116. $items['admin/config/search/redirect/add'] = array(
  117. 'title' => 'Add redirect',
  118. 'page callback' => 'drupal_get_form',
  119. 'page arguments' => array('redirect_edit_form'),
  120. 'access callback' => 'redirect_access',
  121. 'access arguments' => array('create', 'redirect'),
  122. 'file' => 'redirect.admin.inc',
  123. 'type' => MENU_LOCAL_ACTION,
  124. );
  125. $items['admin/config/search/redirect/edit/%redirect'] = array(
  126. 'title' => 'Edit redirect',
  127. 'page callback' => 'drupal_get_form',
  128. 'page arguments' => array('redirect_edit_form', 5),
  129. 'access callback' => 'redirect_access',
  130. 'access arguments' => array('update', 5),
  131. 'file' => 'redirect.admin.inc',
  132. );
  133. $items['admin/config/search/redirect/delete/%redirect'] = array(
  134. 'title' => 'Delete redirect',
  135. 'page callback' => 'drupal_get_form',
  136. 'page arguments' => array('redirect_delete_form', 5),
  137. 'access callback' => 'redirect_access',
  138. 'access arguments' => array('delete', 5),
  139. 'file' => 'redirect.admin.inc',
  140. );
  141. $items['admin/config/search/redirect/settings'] = array(
  142. 'title' => 'Settings',
  143. 'description' => 'Configure behavior for URL redirects.',
  144. 'page callback' => 'drupal_get_form',
  145. 'page arguments' => array('redirect_settings_form'),
  146. 'access arguments' => array('administer redirects'),
  147. 'file' => 'redirect.admin.inc',
  148. 'type' => MENU_LOCAL_TASK,
  149. 'weight' => 50,
  150. );
  151. // If the database logging module is enabled, add special 404 listing pages.
  152. if (module_exists('dblog')) {
  153. $items['admin/config/search/redirect/404'] = array(
  154. 'title' => 'Fix 404 pages',
  155. 'description' => 'Add redirects for 404 pages.',
  156. 'page callback' => 'redirect_404_list',
  157. 'access arguments' => array('administer redirects'),
  158. 'file' => 'redirect.admin.inc',
  159. 'type' => MENU_LOCAL_TASK,
  160. 'weight' => 20,
  161. );
  162. $items['admin/reports/page-not-found/redirect'] = array(
  163. 'title' => 'Fix 404 pages with URL redirects',
  164. 'page callback' => 'drupal_goto',
  165. 'page arguments' => array('admin/config/search/redirect/404'),
  166. 'access arguments' => array('administer redirects'),
  167. 'type' => MENU_LOCAL_ACTION,
  168. );
  169. }
  170. // Devel generate integration.
  171. if (module_exists('devel_generate')) {
  172. $items['admin/config/development/generate/redirects'] = array(
  173. 'title' => 'Generate redirects',
  174. 'description' => 'Generate a given number of redirects. Optionally delete current redirects.',
  175. 'page callback' => 'drupal_get_form',
  176. 'page arguments' => array('redirect_generate_form'),
  177. 'access arguments' => array('administer redirects'),
  178. 'file' => 'redirect.generate.inc',
  179. );
  180. $items['admin/config/search/redirect/generate'] = $items['admin/config/development/generate/redirects'];
  181. $items['admin/config/search/redirect/generate']['type'] = MENU_LOCAL_ACTION;
  182. }
  183. return $items;
  184. }
  185. function redirect_set_current_redirect($redirect) {
  186. $static = &drupal_static(__FUNCTION__);
  187. $static = $redirect;
  188. }
  189. function redirect_get_current_redirect() {
  190. $redirect = drupal_static('redirect_set_current_redirect', NULL);
  191. // If a redirect has not been set with redirect_set_current_redirect(), then
  192. // attempt to find a redirect matching the current path, query string, and
  193. // language code.
  194. if (!isset($redirect)) {
  195. $redirect = redirect_load_by_source(current_path(), $GLOBALS['language']->language, drupal_get_query_parameters());
  196. }
  197. // @todo Add an alter hook here?
  198. return $redirect;
  199. }
  200. /**
  201. * Implements hook_url_inbound_alter().
  202. */
  203. function redirect_url_inbound_alter(&$path, $original_path, $path_language) {
  204. // If the current path global does not exist, then drupal_get_path_alias()
  205. // will fail. This condition only happens when $path is the front page.
  206. // @todo Remove when http://drupal.org/node/1329914 is fixed in core.
  207. if (empty($_GET['q'])) {
  208. $_GET['q'] = variable_get('site_frontpage', 'node');
  209. return;
  210. }
  211. // If the inbound path has been changed, then attempt to find a redirect
  212. // matching the original path and save it for processing later in
  213. // redirect_init(). For example, if the Sub-pathauto module changes the path
  214. // 'foo/redirect' to 'node/1/redirect', and there is a redirect enabled for
  215. // the path 'foo/redirect', then redirect_init() would normally fail since it
  216. // would not find a match.
  217. if ($path != $original_path && $original_path == current_path()) {
  218. $current_langcode = !empty($path_language) ? $path_language : $GLOBALS['language']->language;
  219. $current_query = drupal_get_query_parameters();
  220. if ($redirect = redirect_load_by_source($original_path, $current_langcode, $current_query)) {
  221. redirect_set_current_redirect($redirect);
  222. }
  223. }
  224. // Redirect to canonical URLs.
  225. if ($path && variable_get('redirect_canonical', 1)) {
  226. $alias = drupal_get_path_alias($path, $path_language);
  227. if ($alias != $path && $alias != $original_path) {
  228. //return redirect_redirect(array('redirect' => $alias, 'type' => 'global'));
  229. }
  230. // Redirect from default entity paths to the proper entity path.
  231. //if ($path_entity = redirect_load_entity_from_path($path)) {
  232. // if ($uri = entity_uri($path_entity['entity_type'], $path_entity['entity'])) {
  233. // if ($path != $uri['path']) {
  234. // return redirect_redirect(array('redirect' => $uri['path'], 'redirect_options' => $uri['options'], 'type' => 'global'));
  235. // }
  236. // }
  237. //}
  238. }
  239. }
  240. /**
  241. * Implements hook_entity_info_alter().
  242. */
  243. function redirect_entity_info_alter(&$info) {
  244. $default_paths = array(
  245. 'node' => 'node/%node',
  246. 'user' => 'user/%user',
  247. 'taxonomy_term' => 'taxonomy/term/%taxonomy_term',
  248. );
  249. foreach ($default_paths as $entity_type => $default_path) {
  250. if (isset($info[$entity_type]) && !isset($info[$entity_type]['default path'])) {
  251. $info[$entity_type]['default path'] = $default_path;
  252. }
  253. }
  254. // Disable support for some entity types that cause problems.
  255. $unsupported_entity_types = array(
  256. 'comment',
  257. 'media',
  258. );
  259. foreach ($unsupported_entity_types as $unsupported_entity_type) {
  260. if (isset($info[$unsupported_entity_type])) {
  261. $info[$unsupported_entity_type]['redirect'] = FALSE;
  262. }
  263. }
  264. }
  265. /**
  266. * Check if an entity type supports redirects.
  267. *
  268. * @param $entity_type
  269. * An entity type.
  270. *
  271. * @return
  272. * TRUE if the entity type has an uri callback and supports redirects, or
  273. * FALSE otherwise.
  274. */
  275. function redirect_entity_type_supports_redirects($entity_type) {
  276. $types = &drupal_static(__FUNCTION__);
  277. if (!isset($types)) {
  278. $types = array();
  279. foreach (entity_get_info() as $type => $entity_info) {
  280. $types[$type] = !empty($entity_info['uri callback']) && (!isset($entity_info['redirect']) || !empty($entity_info['redirect']));
  281. }
  282. }
  283. return isset($types[$entity_type]) ? $types[$entity_type] : FALSE;
  284. }
  285. /**
  286. * Implements hook_init().
  287. */
  288. function redirect_init() {
  289. if (!redirect_can_redirect()) {
  290. return;
  291. }
  292. // Fetch the current redirect.
  293. if ($redirect = redirect_get_current_redirect()) {
  294. redirect_redirect($redirect);
  295. }
  296. $redirect_global = FALSE;
  297. $request_uri = $original_uri = ltrim(request_uri(), '/');
  298. // Redirect from non-clean URLs to clean URLs.
  299. if (variable_get('redirect_global_clean', 1) && variable_get('clean_url', 0) && strpos($request_uri, '?q=') !== FALSE) {
  300. //$redirect_global = TRUE;
  301. //$request_uri = str_replace('?q=', '', $request_uri);
  302. }
  303. if (strpos($request_uri, 'index.php') !== FALSE) {
  304. //$redirect_global = TRUE;
  305. //$request_uri = str_replace('index.php', '', $request_uri);
  306. }
  307. //$request_uri = ltrim($request_uri, '/');
  308. //$parsed = parse_url($request_uri);
  309. if ($redirect_global && $request_uri != $original_uri) {
  310. redirect_redirect(array(/*'redirect' => $request_uri,*/ 'type' => 'global'));
  311. }
  312. }
  313. /**
  314. * Implements hook_cron().
  315. */
  316. function redirect_cron() {
  317. // Purge inactive self-managed redirects from the database.
  318. redirect_purge_inactive_redirects();
  319. }
  320. /**
  321. * Implements hook_exit().
  322. */
  323. function redirect_exit($destination = NULL) {
  324. // If the current page is being cached, track it.
  325. if (drupal_get_http_header('Location') && $rid = drupal_get_http_header('X-Redirect-ID')) {
  326. // Ensure the database is loaded. This is only the next bootstrap step
  327. // after DRUPAL_BOOTSTRAP_DATABASE
  328. drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);
  329. db_update('redirect')
  330. ->fields(array('access' => REQUEST_TIME))
  331. ->expression('count', 'count + 1')
  332. ->condition('rid', $rid)
  333. ->execute();
  334. }
  335. }
  336. /**
  337. * Implements hook_entity_delete().
  338. */
  339. function redirect_entity_delete($entity, $entity_type) {
  340. if (redirect_entity_type_supports_redirects($entity_type)) {
  341. redirect_delete_by_entity_path($entity_type, $entity);
  342. }
  343. }
  344. /**
  345. * Implements hook_path_update().
  346. */
  347. function redirect_path_update(array $path) {
  348. if (!variable_get('redirect_auto_redirect', TRUE)) {
  349. return;
  350. }
  351. elseif (isset($path['redirect']) && !$path['redirect']) {
  352. return;
  353. }
  354. if (!empty($path['original']['pid']) && $path['original']['pid'] == $path['pid'] && $path['original']['alias'] != $path['alias']) {
  355. $redirect = new stdClass();
  356. redirect_object_prepare($redirect);
  357. $redirect->source = $path['original']['alias'];
  358. $redirect->redirect = $path['source'];
  359. $redirect->language = $path['original']['language'];
  360. // Check if the redirect exists before saving.
  361. $hash = redirect_hash($redirect);
  362. if (!redirect_load_by_hash($hash)) {
  363. redirect_save($redirect);
  364. }
  365. }
  366. }
  367. /**
  368. * Implements hook_path_delete().
  369. */
  370. function redirect_path_delete($path) {
  371. if (!variable_get('redirect_auto_redirect', TRUE)) {
  372. return;
  373. }
  374. elseif (isset($path['redirect']) && !$path['redirect']) {
  375. return;
  376. }
  377. elseif (empty($path)) {
  378. // @todo Remove this condition and allow $path to use an array type hint
  379. // when http://drupal.org/node/1025904 is fixed.
  380. return;
  381. }
  382. // Redirect from a deleted alias to the system path.
  383. //if (!redirect_load_by_source($path['alias'], $path['language'])) {
  384. // $redirect = new stdClass();
  385. // redirect_object_prepare($redirect);
  386. // $redirect->source = $path['alias'];
  387. // $redirect->redirect = $path['source'];
  388. // $redirect->language = $path['language'];
  389. // redirect_save($redirect);
  390. //}
  391. }
  392. /**
  393. * Implements hook_views_api().
  394. */
  395. function redirect_views_api() {
  396. return array(
  397. 'api' => 2,
  398. 'path' => drupal_get_path('module', 'redirect') . '/views',
  399. );
  400. }
  401. /**
  402. * Implements hook_page_build().
  403. *
  404. * Adds an action on 404 pages to create a redirect.
  405. */
  406. function redirect_page_build(&$page) {
  407. if (redirect_is_current_page_404() && user_access('administer redirects')) {
  408. if (!isset($page['content']['system_main']['actions'])) {
  409. $page['content']['system_main']['actions'] = array(
  410. '#theme' => 'links',
  411. '#links' => array(),
  412. '#attributes' => array('class' => array('action-links')),
  413. '#weight' => -100,
  414. );
  415. }
  416. // We cannot simply use current_path() because if a 404 path is set, then
  417. // that value overrides whatever is in $_GET['q']. The
  418. // drupal_deliver_html_page() function thankfully puts the original current
  419. // path into $_GET['destination'].
  420. $destination = drupal_get_destination();
  421. $page['content']['system_main']['actions']['#links']['add_redirect'] = array(
  422. 'title' => t('Add URL redirect from this page to another location'),
  423. 'href' => 'admin/config/search/redirect/add',
  424. 'query' => array('source' => $destination['destination']) + drupal_get_destination(),
  425. );
  426. }
  427. }
  428. /**
  429. * Implements hook_form_FORM_ID_alter().
  430. *
  431. * Adds support for creating redirects if a node URL alias is changed.
  432. */
  433. function redirect_form_node_form_alter(&$form, $form_state) {
  434. if (!empty($form['path']['pid']['#value']) && !isset($form['path']['original'])) {
  435. $form['path']['original'] = array('#type' => 'value', '#value' => path_load($form['path']['pid']['#value']));
  436. }
  437. }
  438. /**
  439. * Implements hook_form_FORM_ID_alter().
  440. *
  441. * Adds support for creating redirects if a taxonomy term URL alias is changed.
  442. */
  443. function redirect_form_taxonomy_form_term_alter(&$form, $form_state) {
  444. if (!empty($form['path']['pid']['#value']) && !isset($form['path']['original'])) {
  445. $form['path']['original'] = array('#type' => 'value', '#value' => path_load($form['path']['pid']['#value']));
  446. }
  447. }
  448. /**
  449. * Implements hook_form_FORM_ID_alter().
  450. *
  451. * Adds support for creating redirects if an URL alias is changed.
  452. */
  453. function redirect_form_path_admin_form_alter(&$form, $form_state) {
  454. if (!empty($form['pid']['#value']) && !isset($form['original'])) {
  455. $form['original'] = array('#type' => 'value', '#value' => path_load($form['pid']['#value']));
  456. }
  457. }
  458. /**
  459. * Load an URL redirect from the database.
  460. *
  461. * @param $rid
  462. * The URL redirect ID.
  463. * @param $reset
  464. * Whether to reset the redirect_load_multiple cache.
  465. *
  466. * @return
  467. * An URL redirect object, or FALSE if loading failed.
  468. *
  469. * @ingroup redirect_api
  470. */
  471. function redirect_load($rid, $reset = FALSE) {
  472. $redirects = entity_load('redirect', array($rid), array(), $reset);
  473. return !empty($redirects) ? reset($redirects) : FALSE;
  474. }
  475. /**
  476. * Load an URL redirect from the database by {redirect}.hash.
  477. *
  478. * @param $hash
  479. * The hash of the URL redirect.
  480. * @param $reset
  481. * Whether to reset the redirect_load_multiple cache.
  482. *
  483. * @return
  484. * An URL redirect object, or FALSE if loading failed.
  485. *
  486. * @ingroup redirect_api
  487. */
  488. function redirect_load_by_hash($hash, $reset = FALSE) {
  489. $redirects = entity_load('redirect', FALSE, array('hash' => $hash), $reset);
  490. return !empty($redirects) ? reset($redirects) : FALSE;
  491. }
  492. /**
  493. * Load multiple URL redirects from the database by {redirect}.source.
  494. *
  495. * @param $source
  496. * The source of the URL redirect.
  497. *
  498. * @return
  499. * An array of URL redirect objects indexed by redirect IDs.
  500. *
  501. * @see redirect_load_multiple()
  502. * @see _redirect_uasort()
  503. * @see redirect_compare_array_recursive()
  504. *
  505. * @ingroup redirect_api
  506. */
  507. function redirect_load_by_source($source, $language = LANGUAGE_NONE, array $query = array()) {
  508. // Run a case-insensitive query for matching RIDs first.
  509. $rid_query = db_select('redirect');
  510. $rid_query->addField('redirect', 'rid');
  511. if ($source != variable_get('site_frontpage', 'node')) {
  512. $rid_query->condition('source', db_like($source), 'LIKE');
  513. }
  514. else {
  515. $source_condition = db_or();
  516. $source_condition->condition('source', db_like($source), 'LIKE');
  517. $source_condition->condition('source', '');
  518. $rid_query->condition($source_condition);
  519. }
  520. $rid_query->condition('language', array($language, LANGUAGE_NONE));
  521. $rids = $rid_query->execute()->fetchCol();
  522. if ($rids && $redirects = redirect_load_multiple($rids)) {
  523. // Narrow down the list of candidates.
  524. foreach ($redirects as $rid => $redirect) {
  525. if (!empty($redirect->source_options['query'])) {
  526. if (empty($query) || !redirect_compare_array_recursive($redirect->source_options['query'], $query)) {
  527. unset($redirects[$rid]);
  528. continue;
  529. }
  530. }
  531. // Add a case sensitive matches condition to be used in sorting.
  532. if ($source !== $redirect->source) {
  533. $redirects[$rid]->weight = 1;
  534. }
  535. }
  536. if (!empty($redirects)) {
  537. // Sort the redirects in the proper order.
  538. uasort($redirects, '_redirect_uasort');
  539. // Allow other modules to alter the redirect candidates before selecting the top one.
  540. $context = array('language' => $language, 'query' => $query);
  541. drupal_alter('redirect_load_by_source', $redirects, $source, $context);
  542. return !empty($redirects) ? reset($redirects) : FALSE;
  543. }
  544. }
  545. return FALSE;
  546. }
  547. /**
  548. * Load multiple URL redirects from the database.
  549. *
  550. * @param $rids
  551. * An array of redirect IDs.
  552. * @param $conditions
  553. * An array of conditions on the {redirect} table in the form 'field' =>
  554. * $value.
  555. * @param $reset
  556. * Whether to reset the redirect_load_multiple cache.
  557. *
  558. * @return
  559. * An array of URL redirect objects indexed by redirect IDs.
  560. *
  561. * @ingroup redirect_api
  562. */
  563. function redirect_load_multiple($rids = array(), array $conditions = array(), $reset = FALSE) {
  564. return entity_load('redirect', $rids, $conditions, $reset);
  565. }
  566. /**
  567. * Determine whether the current user may perform the given operation on the
  568. * specified redirect.
  569. *
  570. * @param $op
  571. * The operation to be performed on the redirect. Possible values are:
  572. * - "create"
  573. * - "update"
  574. * - "delete"
  575. * @param $redirect
  576. * The redirect object on which the operation is to be performed, or redirect
  577. * type (e.g. 'feedburner') for the "create" operation.
  578. * @param $account
  579. * Optional, a user object representing the user for whom the operation is to
  580. * be performed. Determines access for a user other than the current user.
  581. *
  582. * @return
  583. * TRUE if the operation may be performed, FALSE otherwise.
  584. */
  585. function redirect_access($op, $redirect, $account = NULL) {
  586. global $user;
  587. $rights = &drupal_static(__FUNCTION__, array());
  588. if (!$redirect || !in_array($op, array('create', 'update', 'delete'), TRUE)) {
  589. // If there was no redirect to check against, or the $op was not one of the
  590. // supported ones, we return access denied.
  591. return FALSE;
  592. }
  593. // If no user object is supplied, the access check is for the current user.
  594. if (empty($account)) {
  595. $account = $user;
  596. }
  597. $cid = isset($redirect->rid) ? $redirect->rid : $redirect;
  598. // Return cached value if access already checked for this redirect, user and op.
  599. if (isset($rights[$account->uid][$cid][$op])) {
  600. return $rights[$account->uid][$cid][$op];
  601. }
  602. // Administrators can access all redirects.
  603. if (user_access('administer redirects', $account)) {
  604. $rights[$account->uid][$cid][$op] = TRUE;
  605. return TRUE;
  606. }
  607. // We grant access to the redirect if both of the following conditions are met:
  608. // - No modules say to deny access.
  609. // - At least one module says to grant access.
  610. $access = module_invoke_all('redirect_access', $op, $redirect, $account);
  611. if (in_array(REDIRECT_ACCESS_DENY, $access, TRUE)) {
  612. $rights[$account->uid][$cid][$op] = FALSE;
  613. return FALSE;
  614. }
  615. elseif (in_array(REDIRECT_ACCESS_ALLOW, $access, TRUE)) {
  616. $rights[$account->uid][$cid][$op] = TRUE;
  617. return TRUE;
  618. }
  619. return FALSE;
  620. }
  621. /**
  622. * Validate a redirect.
  623. */
  624. function redirect_validate($redirect, $form, &$form_state) {
  625. $redirect = (object) $redirect;
  626. // check that there there are no redirect loops
  627. if (url($redirect->source) == url($redirect->redirect)) {
  628. form_set_error('redirect', t('You are attempting to redirect the page to itself. This will result in an infinite loop.'));
  629. }
  630. redirect_hash($redirect);
  631. if ($existing = redirect_load_by_hash($redirect->hash)) {
  632. if ($redirect->rid != $existing->rid) {
  633. form_set_error('source', t('The source path %source is already being redirected. Do you want to <a href="@edit-page">edit the existing redirect</a>?', array('%source' => redirect_url($redirect->source, $redirect->source_options), '@edit-page' => url('admin/config/search/redirect/edit/'. $existing->rid))));
  634. }
  635. }
  636. // Allow other modules to validate the SSH public key.
  637. foreach (module_implements('redirect_validate') as $module) {
  638. $function = $module . '_redirect_validate';
  639. $function($redirect, $form, $form_state);
  640. }
  641. }
  642. function redirect_object_prepare($redirect, $defaults = array()) {
  643. $defaults += array(
  644. 'rid' => NULL,
  645. 'type' => 'redirect',
  646. 'uid' => $GLOBALS['user']->uid,
  647. 'source_options' => array(),
  648. 'redirect_options' => array(),
  649. 'language' => LANGUAGE_NONE,
  650. 'status_code' => 0,
  651. 'count' => 0,
  652. 'access' => 0,
  653. 'hash' => '',
  654. );
  655. foreach ($defaults as $key => $default) {
  656. if (!isset($redirect->{$key})) {
  657. $redirect->{$key} = $default;
  658. }
  659. }
  660. module_invoke_all('redirect_prepare', $redirect);
  661. }
  662. /**
  663. * Save an URL redirect.
  664. *
  665. * @param $redirect
  666. * The URL redirect object to be saved. If $redirect->rid is omitted (or
  667. * $redirect->is_new is TRUE), a new redirect will be added.
  668. *
  669. * @ingroup redirect_api
  670. */
  671. function redirect_save($redirect) {
  672. $transaction = db_transaction();
  673. try {
  674. if (!empty($redirect->rid) && !isset($redirect->original)) {
  675. $redirect->original = entity_load_unchanged('redirect', $redirect->rid);
  676. }
  677. // Determine if we will be inserting a new node.
  678. if (!isset($redirect->is_new)) {
  679. $redirect->is_new = empty($redirect->rid);
  680. }
  681. // The changed timestamp is always updated for bookkeeping purposes.
  682. //$redirect->changed = time();
  683. redirect_hash($redirect);
  684. if ($redirect->is_new || $redirect->hash != $redirect->original->hash) {
  685. // Only new or changed redirects reset the last used value.
  686. $redirect->count = 0;
  687. $redirect->access = 0;
  688. }
  689. // Allow other modules to alter the redirect before saving.
  690. module_invoke_all('redirect_presave', $redirect);
  691. module_invoke_all('entity_presave', $redirect, 'redirect');
  692. // Save the redirect to the database and invoke the post-save hooks.
  693. if ($redirect->is_new) {
  694. drupal_write_record('redirect', $redirect);
  695. module_invoke_all('redirect_insert', $redirect);
  696. module_invoke_all('entity_insert', $redirect, 'redirect');
  697. }
  698. else {
  699. drupal_write_record('redirect', $redirect, array('rid'));
  700. module_invoke_all('redirect_update', $redirect);
  701. module_invoke_all('entity_update', $redirect, 'redirect');
  702. }
  703. // Clear internal properties.
  704. unset($redirect->is_new);
  705. unset($redirect->original);
  706. // Clear the static loading cache.
  707. entity_get_controller('redirect')->resetCache(array($redirect->rid));
  708. // Ignore slave server temporarily to give time for the
  709. // saved node to be propagated to the slave.
  710. db_ignore_slave();
  711. }
  712. catch (Exception $e) {
  713. $transaction->rollback();
  714. watchdog_exception('redirect', $e);
  715. throw $e;
  716. }
  717. }
  718. /**
  719. * Implements hook_redirect_insert().
  720. */
  721. function redirect_redirect_insert($redirect) {
  722. redirect_page_cache_clear($redirect);
  723. }
  724. /**
  725. * Implements hook_redirect_update().
  726. */
  727. function redirect_redirect_update($redirect) {
  728. redirect_page_cache_clear($redirect);
  729. // Clear the page cache for the original redirect as well.
  730. if (!empty($redirect->original) && $redirect->original->source != $redirect->source) {
  731. redirect_page_cache_clear($redirect->original);
  732. }
  733. }
  734. /**
  735. * Implements hook_redirect_delete().
  736. */
  737. function redirect_redirect_delete($redirect) {
  738. redirect_page_cache_clear($redirect);
  739. }
  740. /**
  741. * Delete a single URL redirect.
  742. *
  743. * @param $rid
  744. * The ID of the redirect to delete.
  745. *
  746. * @ingroup redirect_api
  747. */
  748. function redirect_delete($rid) {
  749. return redirect_delete_multiple(array($rid));
  750. }
  751. /**
  752. * Delete any redirects associated with a path or any of its sub-paths.
  753. *
  754. * Given a source like 'node/1' this function will delete any redirects that
  755. * have that specific source or any sources that match 'node/1/%'.
  756. *
  757. * @param $path
  758. * An string with an internal Drupal path.
  759. *
  760. * @ingroup redirect_api
  761. */
  762. function redirect_delete_by_path($path) {
  763. $query = db_select('redirect');
  764. $query->addField('redirect', 'rid');
  765. $query_or = db_or();
  766. $query_or->condition('source', db_like($path), 'LIKE');
  767. $query_or->condition('source', db_like($path . '/') . '%', 'LIKE');
  768. $query_or->condition('redirect', db_like($path), 'LIKE');
  769. $query_or->condition('redirect', db_like($path . '/') . '%', 'LIKE');
  770. $query->condition($query_or);
  771. $rids = $query->execute()->fetchCol();
  772. if ($rids) {
  773. return redirect_delete_multiple($rids);
  774. }
  775. }
  776. /**
  777. * Delete an entity URL alias and any of its sub-paths.
  778. *
  779. * This function also checks to see if the default entity URI is different from
  780. * the current entity URI and will delete any of the default aliases.
  781. *
  782. * @param $entity_type
  783. * A string with the entity type.
  784. * @param $entity
  785. * An entity object.
  786. *
  787. * @ingroup redirect_api
  788. */
  789. function redirect_delete_by_entity_path($entity_type, $entity) {
  790. if ($uri = entity_uri($entity_type, $entity)) {
  791. redirect_delete_by_path($uri['path']);
  792. }
  793. //$info = entity_get_info($entity_type);
  794. //if (isset($info['default path'])) {
  795. // list($id) = entity_extract_ids($entity_type, $entity);
  796. // $default_path = str_replace('[id]', $id, $info['default path']);
  797. // if ($uri['path'] !== $default_path) {
  798. // redirect_delete_by_path($default_path);
  799. // }
  800. //}
  801. }
  802. /**
  803. * Delete multiple URL redirects.
  804. *
  805. * @param $rids
  806. * An array of redirect IDs to delete.
  807. *
  808. * @ingroup redirect_api
  809. */
  810. function redirect_delete_multiple(array $rids) {
  811. $transaction = db_transaction();
  812. if (!empty($rids)) {
  813. $redirects = redirect_load_multiple($rids);
  814. try {
  815. // Let modules react to the individual redirects being deleted.
  816. foreach ($redirects as $rid => $redirect) {
  817. module_invoke_all('redirect_delete', $redirect);
  818. module_invoke_all('entity_delete', $redirect, 'redirect');
  819. }
  820. db_delete('redirect')
  821. ->condition('rid', $rids, 'IN')
  822. ->execute();
  823. }
  824. catch (Exception $e) {
  825. $transaction->rollback();
  826. watchdog_exception('redirect', $e);
  827. throw $e;
  828. }
  829. // Clear the redirect_load_multiple cache.
  830. entity_get_controller('redirect')->resetCache();
  831. }
  832. }
  833. /**
  834. * Purge inactive redirects from the database.
  835. *
  836. * @param $types
  837. * An array of redirect types to remove. Default is only the self-managed
  838. * 'redirect'. If not provided all redirect types will be eligible for
  839. * removal.
  840. * @param $interval
  841. * The number of seconds to subtract from the current time and used to
  842. * find the inactive redirects.
  843. *
  844. * @return
  845. * An array of redirect IDs that were deleted or FALSE if none were.
  846. */
  847. function redirect_purge_inactive_redirects(array $types = array('redirect'), $interval = NULL) {
  848. if (!isset($interval)) {
  849. $interval = variable_get('redirect_purge_inactive', 0);
  850. }
  851. if (!$interval || !variable_get('redirect_page_cache', 0) || !variable_get('page_cache_invoke_hooks', TRUE)) {
  852. // If serving redirects from the page cache is enabled and hooks are not
  853. // executed during page caching, then we cannot track when a redirect is
  854. // used. Therefore, we cannot remove unused redirects.
  855. return FALSE;
  856. }
  857. $query = db_select('redirect');
  858. $query->addField('redirect', 'rid');
  859. if (!empty($types)) {
  860. $query->condition('type', $types);
  861. }
  862. $query->condition('access', REQUEST_TIME - $interval, '<');
  863. $query->addTag('redirect_purge');
  864. $rids = $query->execute()->fetchCol();
  865. if (count($rids)) {
  866. redirect_delete_multiple($rids);
  867. watchdog('redirect', format_plural(count($rids), 'Removed 1 inactive redirect from the database.', 'Removed @count inactive redirects from the database.'));
  868. return $rids;
  869. }
  870. }
  871. /**
  872. * Perform an URL redirect.
  873. *
  874. * @param $redirect
  875. * An optional URL redirect array.
  876. *
  877. * @ingroup redirect_api
  878. */
  879. function redirect_redirect($redirect = NULL) {
  880. // First check if we're in an infinite loop.
  881. $session_id = session_id();
  882. if (flood_is_allowed('redirection', 5, 15, $session_id ? $session_id : NULL)) {
  883. flood_register_event('redirection', 60, $session_id ? $session_id : NULL);
  884. }
  885. else {
  886. watchdog('redirect', 'Infinite loop stopped.');
  887. drupal_set_message('Oops, looks like this request tried to create an infinite loop. We do not allow such things here. We are a professional website!');
  888. return FALSE;
  889. }
  890. if (!isset($redirect)) {
  891. $redirect = new stdClass();
  892. }
  893. redirect_object_prepare($redirect, array('redirect' => current_path(), 'type' => 'manual', 'callback' => 'redirect_goto', 'cache' => TRUE));
  894. if (empty($redirect->status_code)) {
  895. $redirect->status_code = variable_get('redirect_default_status_code', 301);
  896. }
  897. if (variable_get('redirect_passthrough_querystring', 1)) {
  898. // Preserve the current query parameters in the redirect.
  899. $redirect->redirect_options += array('query' => array());
  900. $redirect->redirect_options['query'] += drupal_get_query_parameters();
  901. }
  902. // Prevent the destination query parameter from overriding this redirect.
  903. //if (isset($_GET['destination'])) {
  904. // Simply unset the parameter since it has already been passed into
  905. // $options['query'] in the previous code.
  906. // unset($_GET['destination']);
  907. //}
  908. // Allow other modules to alter the redirect before passing to drupal_goto().
  909. drupal_alter('redirect', $redirect);
  910. // Continue if the redirect has not been disabled by hook_redirect_alter().
  911. if (isset($redirect->redirect) && isset($redirect->callback) && $redirect->redirect !== FALSE && function_exists($redirect->callback)) {
  912. // Perform the actual redirect.
  913. $callback = $redirect->callback;
  914. $callback($redirect);
  915. }
  916. }
  917. /**
  918. * Redirect callback; perform an URL redirect.
  919. */
  920. function redirect_goto($redirect) {
  921. $redirect->redirect_options['absolute'] = TRUE;
  922. $url = url($redirect->redirect, $redirect->redirect_options);
  923. drupal_add_http_header('Location', $url);
  924. drupal_add_http_header('Status', redirect_status_code_options($redirect->status_code));
  925. if (!empty($redirect->rid)) {
  926. // Add a custom header for the redirect ID so when the redirect is served
  927. // from the page cache, we can track it.
  928. drupal_add_http_header('X-Redirect-ID', $redirect->rid);
  929. }
  930. if (!variable_get('redirect_page_cache', 0) || !variable_get('cache', 0) || !drupal_page_is_cacheable() || empty($redirect->cache)) {
  931. drupal_exit($url);
  932. }
  933. // @see drupal_exit()
  934. if (drupal_get_bootstrap_phase() == DRUPAL_BOOTSTRAP_FULL) {
  935. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
  936. module_invoke_all('exit', $url);
  937. }
  938. drupal_session_commit();
  939. if (variable_get('cache', 0)) {
  940. // We must output something to allow the request to be cached.
  941. echo ' ';
  942. if ($cache = drupal_page_set_cache()) {
  943. // When caching this redirect for the first time we still need to ensure
  944. // that the correct cache headers are sent.
  945. // @see drupal_page_footer()
  946. drupal_serve_page_from_cache($cache);
  947. }
  948. }
  949. }
  950. exit;
  951. }
  952. function redirect_hash($redirect) {
  953. $hash = array(
  954. 'source' => $redirect->source,
  955. 'language' => $redirect->language,
  956. );
  957. if (!empty($redirect->source_options['query'])) {
  958. $hash['source_query'] = $redirect->source_options['query'];
  959. }
  960. drupal_alter('redirect_hash', $hash, $redirect);
  961. redirect_sort_recursive($hash, 'ksort');
  962. $redirect->hash = drupal_hash_base64(serialize($hash));
  963. return $redirect->hash;
  964. }
  965. /**
  966. * Clear a page from the page cache.
  967. */
  968. function redirect_page_cache_clear($redirect = NULL) {
  969. if (!variable_get('redirect_page_cache', 0)) {
  970. return;
  971. }
  972. if (isset($redirect)) {
  973. $path = url($redirect->source, array('absolute' => TRUE));
  974. // Use a wildcard to catch paths with query strings.
  975. cache_clear_all($path, 'cache_page', TRUE);
  976. }
  977. else {
  978. // Clear the entire page cache.
  979. cache_clear_all('*', 'cache_page', TRUE);
  980. }
  981. }
  982. /**
  983. * Given a path determine if it is an entity default path.
  984. *
  985. * @param $path
  986. * The internal path. The id of the entity should be in the string as '[id]'.
  987. * @return
  988. * An array with the entity type and the loaded entity object.
  989. */
  990. function redirect_load_entity_from_path($path) {
  991. $entity_paths = &drupal_static(__FUNCTION__);
  992. if (!isset($entity_paths)) {
  993. $entity_paths = array();
  994. foreach (entity_get_info() as $entity_type => $entity_info) {
  995. if (isset($entity_info['default path'])) {
  996. $default_path = $entity_info['default path'];
  997. $default_path = preg_quote($default_path, '/');
  998. $default_path = str_replace(preg_quote('%' . $entity_type, '/'), '(\d+)', $default_path);
  999. $entity_paths[$entity_type] = $default_path;
  1000. }
  1001. }
  1002. }
  1003. foreach ($entity_paths as $entity_type => $default_path) {
  1004. if (preg_match("/^{$default_path}$/", $path, $matches)) {
  1005. if ($entity = entity_load($entity_type, array($matches[1]))) {
  1006. return array('entity_type' => $entity_type, 'entity' => reset($entity));
  1007. }
  1008. break;
  1009. }
  1010. }
  1011. }
  1012. /**
  1013. * Check the ability to perform redirects with the current request context.
  1014. *
  1015. * This function checks the following conditions:
  1016. * - If the PHP entry point is the root index.php file.
  1017. * - If PHP is not running as CLI.
  1018. * - If the site is not offline or in install/update mode.
  1019. * - If the curerent page is not an admin page (check can be disabled).
  1020. * - If the current request does not have any POST data since a redirect
  1021. * may interrupt form submission.
  1022. *
  1023. * @return
  1024. * TRUE if redirections can be performed, or FALSE otherwise.
  1025. */
  1026. function redirect_can_redirect() {
  1027. $can_redirect = &drupal_static(__FUNCTION__);
  1028. if (!isset($can_redirect)) {
  1029. $path = current_path();
  1030. $can_redirect = TRUE;
  1031. if ($_SERVER['SCRIPT_NAME'] != $GLOBALS['base_path'] . 'index.php') {
  1032. // Do not redirect if the root script is not /index.php.
  1033. $can_redirect = FALSE;
  1034. }
  1035. elseif (!empty($_POST)) {
  1036. // Do not redirect if this is a post request with data.
  1037. $can_redirect = FALSE;
  1038. }
  1039. elseif (drupal_is_cli()) {
  1040. // If this is a command line request (Drush, etc), skip processing.
  1041. $can_redirect = FALSE;
  1042. }
  1043. elseif (variable_get('maintenance_mode', 0) || defined('MAINTENANCE_MODE')) {
  1044. // Do not redirect in offline or maintenance mode.
  1045. $can_redirect = FALSE;
  1046. }
  1047. elseif (!variable_get('redirect_global_admin_paths', 0) && path_is_admin($path)) {
  1048. // Do not redirect on admin paths.
  1049. $can_redirect = FALSE;
  1050. }
  1051. }
  1052. return $can_redirect;
  1053. }
  1054. /**
  1055. * Compare tha all values and associations in one array match another array.
  1056. *
  1057. * We cannot use array_diff_assoc() here because we need to be recursive.
  1058. *
  1059. * @param $match
  1060. * The array that has the values.
  1061. * @param $haystack
  1062. * The array that will be searched for values.
  1063. * @return
  1064. * TRUE if all the elements of $match were found in $haystack, or FALSE
  1065. * otherwise.
  1066. */
  1067. function redirect_compare_array_recursive($match, $haystack) {
  1068. foreach ($match as $key => $value) {
  1069. if (!array_key_exists($key, $haystack)) {
  1070. return FALSE;
  1071. }
  1072. elseif (is_array($value)) {
  1073. if (!is_array($haystack[$key])) {
  1074. return FALSE;
  1075. }
  1076. elseif (!redirect_compare_array_recursive($value, $haystack[$key])) {
  1077. return FALSE;
  1078. }
  1079. }
  1080. elseif ($value != $haystack[$key]) {
  1081. return FALSE;
  1082. }
  1083. }
  1084. return TRUE;
  1085. }
  1086. /**
  1087. * Sort an array recusively.
  1088. *
  1089. * @param $array
  1090. * The array to sort, by reference.
  1091. * @param $callback
  1092. * The sorting callback to use (e.g. 'sort', 'ksort', 'asort').
  1093. *
  1094. * @return
  1095. * TRUE on success or FALSE on failure.
  1096. */
  1097. function redirect_sort_recursive(&$array, $callback = 'sort') {
  1098. $result = $callback($array);
  1099. foreach ($array as $key => $value) {
  1100. if (is_array($value)) {
  1101. $result &= redirect_sort_recursive($array[$key], $callback);
  1102. }
  1103. }
  1104. return $result;
  1105. }
  1106. /**
  1107. * Load a language object by its language code.
  1108. *
  1109. * @todo Remove when http://drupal.org/node/660736 is fixed in Drupal core.
  1110. *
  1111. * @param $language
  1112. * A language code. If not provided the default language will be returned.
  1113. * @return
  1114. * A language object.
  1115. */
  1116. function redirect_language_load($language = LANGUAGE_NONE) {
  1117. $languages = &drupal_static(__FUNCTION__);
  1118. if (!isset($languages)) {
  1119. $languages = language_list();
  1120. $languages[LANGUAGE_NONE] = NULL;
  1121. }
  1122. return isset($languages[$language]) ? $languages[$language] : NULL;
  1123. }
  1124. /**
  1125. * Build the URL of a redirect for display purposes only.
  1126. */
  1127. function redirect_url($path, array $options = array(), $clean_url = NULL) {
  1128. if (!isset($clean_url)) {
  1129. $clean_url = variable_get('clean_url', 0);
  1130. }
  1131. if ($path == '') {
  1132. $path = '<front>';
  1133. }
  1134. if (!isset($options['alter']) || !empty($options['alter'])) {
  1135. drupal_alter('redirect_url', $path, $options);
  1136. }
  1137. // The base_url might be rewritten from the language rewrite in domain mode.
  1138. if (!isset($options['base_url'])) {
  1139. if (isset($options['https']) && variable_get('https', FALSE)) {
  1140. if ($options['https'] === TRUE) {
  1141. $options['base_url'] = $GLOBALS['base_secure_url'];
  1142. $options['absolute'] = TRUE;
  1143. }
  1144. elseif ($options['https'] === FALSE) {
  1145. $options['base_url'] = $GLOBALS['base_insecure_url'];
  1146. $options['absolute'] = TRUE;
  1147. }
  1148. }
  1149. else {
  1150. $options['base_url'] = $GLOBALS['base_url'];
  1151. }
  1152. }
  1153. if (empty($options['absolute']) || url_is_external($path)) {
  1154. $url = $path;
  1155. }
  1156. else {
  1157. $url = $options['base_url'] . base_path() . $path;
  1158. }
  1159. if (isset($options['query'])) {
  1160. $url .= $clean_url ? '?' : '&';
  1161. $url .= drupal_http_build_query($options['query']);
  1162. }
  1163. if (isset($options['fragment'])) {
  1164. $url .= '#' . $options['fragment'];
  1165. }
  1166. return $url;
  1167. }
  1168. function redirect_variables() {
  1169. return array(
  1170. 'redirect_default_status_code' => 301,
  1171. 'redirect_auto_redirect' => TRUE,
  1172. 'redirect_warning' => FALSE,
  1173. 'redirect_passthrough_querystring' => 1,
  1174. 'redirect_page_cache' => 0,
  1175. 'redirect_purge_inactive' => 0,
  1176. 'redirect_global_home' => 1,
  1177. 'redirect_global_clean' => 1,
  1178. 'redirect_global_canonical' => 1,
  1179. 'redirect_global_admin_paths' => 0,
  1180. );
  1181. }
  1182. //function redirect_get_redirect_info() {
  1183. // $info = &drupal_static(__FUNCTION__);
  1184. //
  1185. // if (!isset($info)) {
  1186. // if ($cache = cache_get('redirect:info')) {
  1187. // $info = $cache->data;
  1188. // }
  1189. // else {
  1190. // $info = module_invoke_all('redirect_info');
  1191. // drupal_alter('redirect_info', $info);
  1192. // cache_set('redirect:info', $info);
  1193. // }
  1194. // }
  1195. //
  1196. // return $info;
  1197. //}
  1198. function redirect_parse_url($url) {
  1199. $original_url = $url;
  1200. $url = trim($url, " \t\n\r\0\x0B\/");
  1201. $parsed = parse_url($url);
  1202. if (isset($parsed['fragment'])) {
  1203. $url = substr($url, 0, -strlen($parsed['fragment']));
  1204. $url = trim($url, '#');
  1205. }
  1206. if (isset($parsed['query'])) {
  1207. $url = substr($url, 0, -strlen($parsed['query']));
  1208. $url = trim($url, '?&');
  1209. $parsed['query'] = drupal_get_query_array($parsed['query']);
  1210. }
  1211. // Convert absolute to relative.
  1212. if (isset($parsed['scheme']) && isset($parsed['host'])) {
  1213. $base_secure_url = rtrim($GLOBALS['base_secure_url'] . base_path(), '/');
  1214. $base_insecure_url = rtrim($GLOBALS['base_insecure_url'] . base_path(), '/');
  1215. if (strpos($url, $base_secure_url) === 0) {
  1216. $url = str_replace($base_secure_url, '', $url);
  1217. $parsed['https'] = TRUE;
  1218. }
  1219. elseif (strpos($url, $base_insecure_url) === 0) {
  1220. $url = str_replace($base_insecure_url, '', $url);
  1221. }
  1222. }
  1223. $url = trim($url, '/');
  1224. // Convert to frontpage paths.
  1225. if ($url == '<front>') {
  1226. $url = '';
  1227. }
  1228. //$parsed['url'] = http_build_query($url, HTTP_URL_STRIP_QUERY | HTTP_URL_STRIP_FRAGMENT);
  1229. $parsed['url'] = $url;
  1230. // Allow modules to alter the parsed URL.
  1231. drupal_alter('redirect_parse_url', $parsed, $original_url);
  1232. return $parsed;
  1233. }
  1234. function redirect_status_code_options($code = NULL) {
  1235. $codes = array(
  1236. 300 => t('300 Multiple Choices'),
  1237. 301 => t('301 Moved Permanently'),
  1238. 302 => t('302 Found'),
  1239. 303 => t('303 See Other'),
  1240. 304 => t('304 Not Modified'),
  1241. 305 => t('305 Use Proxy'),
  1242. 307 => t('307 Temporary Redirect'),
  1243. );
  1244. return isset($codes[$code]) ? $codes[$code] : $codes;
  1245. }
  1246. /**
  1247. * Returns if the current page request is a page not found (404 status error).
  1248. *
  1249. * Why the fuck do we have to do this? Why is there not an easier way???
  1250. *
  1251. * @return
  1252. * TRUE if the current page is a 404, or FALSE otherwise.
  1253. */
  1254. function redirect_is_current_page_404() {
  1255. return drupal_get_http_header('Status') == '404 Not Found';
  1256. }
  1257. /**
  1258. * uasort callback; Compare redirects based on language neutrality and rids.
  1259. */
  1260. function _redirect_uasort($a, $b) {
  1261. $a_weight = isset($a->weight) ? $a->weight : 0;
  1262. $b_weight = isset($b->weight) ? $b->weight : 0;
  1263. if ($a_weight != $b_weight) {
  1264. // First sort by weight (case sensitivity).
  1265. return $a_weight > $b_weight;
  1266. }
  1267. elseif ($a->language != $b->language) {
  1268. // Then sort by language specific over language neutral.
  1269. return $a->language == LANGUAGE_NONE;
  1270. }
  1271. elseif (!empty($a->source_options['query']) != !empty($b->source_options['query'])) {
  1272. // Then sort by redirects that do not have query strings over ones that do.
  1273. return empty($a->source_options['query']);
  1274. }
  1275. else {
  1276. // Lastly sort by the highest redirect ID.
  1277. return $a->rid < $b->rid;
  1278. }
  1279. }
  1280. /**
  1281. * Implements hook_form_FORM_ID_alter() on behalf of locale.module.
  1282. */
  1283. function locale_form_redirect_edit_form_alter(&$form, &$form_state) {
  1284. $form['language'] = array(
  1285. '#type' => 'select',
  1286. '#title' => t('Language'),
  1287. '#options' => array(LANGUAGE_NONE => t('All languages')) + locale_language_list('name'),
  1288. '#default_value' => $form['language']['#value'],
  1289. '#description' => t('A redirect set for a specific language will always be used when requesting this page in that language, and takes precedence over redirects set for <em>All languages</em>.'),
  1290. );
  1291. }
  1292. /**
  1293. * Implements hook_field_attach_form().
  1294. *
  1295. * @todo Investigate using hook_entity_load() to load all entity redirects.
  1296. * @todo Figure out how to support entity URIs that contain query strings.
  1297. */
  1298. function redirect_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode) {
  1299. list($id) = entity_extract_ids($entity_type, $entity);
  1300. if (!empty($form['redirect']) || empty($id)) {
  1301. return;
  1302. }
  1303. // Check if this entity type supports redirects.
  1304. if (!redirect_entity_type_supports_redirects($entity_type)) {
  1305. return;
  1306. }
  1307. $uri = entity_uri($entity_type, $entity);
  1308. if (empty($uri)) {
  1309. // If the entity has no source path, then we cannot lookup the existing
  1310. // redirects.
  1311. return;
  1312. }
  1313. $info = entity_get_info($entity_type);
  1314. $form['redirect'] = array(
  1315. '#type' => 'fieldset',
  1316. '#title' => t('URL redirects'),
  1317. '#description' => t('The following are a list of URL redirects that point to this @entitytype.', array('@entitytype' => drupal_strtolower($info['label']))),
  1318. '#collapsible' => TRUE,
  1319. '#collapsed' => TRUE,
  1320. '#access' => user_access('administer redirects'),
  1321. '#weight' => 30,
  1322. '#attributes' => array('class' => array('redirect-list')),
  1323. );
  1324. // Only support vertical tabs if there is a vertical tab element.
  1325. foreach (element_children($form) as $key) {
  1326. if (isset($form[$key]['#type']) && $form[$key]['#type'] == 'vertical_tabs') {
  1327. $form['redirect']['#group'] = $key;
  1328. $form['redirect']['#attached']['js']['vertical-tabs'] = drupal_get_path('module', 'redirect') . '/redirect.js';
  1329. }
  1330. }
  1331. // We don't have to put our include in $form_state['build_info']['files']
  1332. // since the build array will already be cached.
  1333. module_load_include('inc', 'redirect', 'redirect.admin');
  1334. $redirects = redirect_load_multiple(FALSE, array('redirect' => $uri['path']));
  1335. $header = array('source', 'status_code', 'language', 'count', 'access', 'operations');
  1336. $form['redirect'] += redirect_list_table($redirects, $header);
  1337. $redirect = array(
  1338. 'redirect' => $uri['path'],
  1339. 'redirect_options' => array_diff_key($uri['options'], array('entity_type' => '', 'entity' => '')),
  1340. 'language' => $langcode,
  1341. );
  1342. $form['redirect']['actions'] = array(
  1343. '#theme' => 'links',
  1344. '#links' => array(),
  1345. '#attributes' => array('class' => array('action-links')),
  1346. );
  1347. if (redirect_access('create', 'redirect')) {
  1348. $form['redirect']['actions']['#links']['add'] = array(
  1349. 'title' => t('Add URL redirect to this @entitytype', array('@entitytype' => drupal_strtolower($info['label']))),
  1350. 'href' => 'admin/config/search/redirect/add',
  1351. 'query' => array_filter($redirect) + drupal_get_destination(),
  1352. );
  1353. }
  1354. }
  1355. /**
  1356. * Implements hook_field_extra_fields().
  1357. */
  1358. function redirect_field_extra_fields() {
  1359. $entity_info = entity_get_info();
  1360. foreach (array_keys($entity_info) as $entity_type) {
  1361. if ($entity_type == 'comment') {
  1362. // The comment entity type supports URIs, but they're not real.
  1363. continue;
  1364. }
  1365. foreach (array_keys($entity_info[$entity_type]['bundles']) as $bundle) {
  1366. if (!isset($entity_info[$entity_type]['bundles'][$bundle]['uri callback']) && !isset($entity_info[$entity_type]['uri callback'])) {
  1367. // The bundle or base entity must have an URI callback defined otherwise
  1368. // we cannot use the entity_uri() function to lookup the entity's source
  1369. // path.
  1370. continue;
  1371. }
  1372. $info[$entity_type][$bundle]['form']['redirect'] = array(
  1373. 'label' => t('URL redirects'),
  1374. 'description' => t('Redirect module form elements'),
  1375. 'weight' => 30,
  1376. );
  1377. }
  1378. }
  1379. return $info;
  1380. }
  1381. /**
  1382. * Fetch an array of redirect bulk operations.
  1383. *
  1384. * @see hook_redirect_operations()
  1385. * @see hook_redirect_operations_alter()
  1386. */
  1387. function redirect_get_redirect_operations() {
  1388. $operations = &drupal_static(__FUNCTION__);
  1389. if (!isset($operations)) {
  1390. $operations = module_invoke_all('redirect_operations');
  1391. drupal_alter('redirect_operations', $operations);
  1392. }
  1393. return $operations;
  1394. }
  1395. /**
  1396. * Implements hook_redirect_operations().
  1397. */
  1398. function redirect_redirect_operations() {
  1399. $operations['delete'] = array(
  1400. 'action' => t('Delete'),
  1401. 'action_past' => t('Deleted'),
  1402. 'callback' => 'redirect_delete_multiple',
  1403. 'confirm' => TRUE,
  1404. );
  1405. return $operations;
  1406. }