PageRenderTime 180ms CodeModel.GetById 144ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-includes/canonical.php

http://github.com/wordpress/wordpress
PHP | 917 lines | 619 code | 151 blank | 147 comment | 213 complexity | 7e956e43f970bcdfe616894cf33370f1 MD5 | raw file
Possible License(s): 0BSD
  1. <?php
  2. /**
  3. * Canonical API to handle WordPress Redirecting
  4. *
  5. * Based on "Permalink Redirect" from Scott Yang and "Enforce www. Preference"
  6. * by Mark Jaquith
  7. *
  8. * @package WordPress
  9. * @since 2.3.0
  10. */
  11. /**
  12. * Redirects incoming links to the proper URL based on the site url.
  13. *
  14. * Search engines consider www.somedomain.com and somedomain.com to be two
  15. * different URLs when they both go to the same location. This SEO enhancement
  16. * prevents penalty for duplicate content by redirecting all incoming links to
  17. * one or the other.
  18. *
  19. * Prevents redirection for feeds, trackbacks, searches, and
  20. * admin URLs. Does not redirect on non-pretty-permalink-supporting IIS 7+,
  21. * page/post previews, WP admin, Trackbacks, robots.txt, favicon.ico, searches,
  22. * or on POST requests.
  23. *
  24. * Will also attempt to find the correct link when a user enters a URL that does
  25. * not exist based on exact WordPress query. Will instead try to parse the URL
  26. * or query in an attempt to figure the correct page to go to.
  27. *
  28. * @since 2.3.0
  29. *
  30. * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
  31. * @global bool $is_IIS
  32. * @global WP_Query $wp_query WordPress Query object.
  33. * @global wpdb $wpdb WordPress database abstraction object.
  34. * @global WP $wp Current WordPress environment instance.
  35. *
  36. * @param string $requested_url Optional. The URL that was requested, used to
  37. * figure if redirect is needed.
  38. * @param bool $do_redirect Optional. Redirect to the new URL.
  39. * @return string|void The string of the URL, if redirect needed.
  40. */
  41. function redirect_canonical( $requested_url = null, $do_redirect = true ) {
  42. global $wp_rewrite, $is_IIS, $wp_query, $wpdb, $wp;
  43. if ( isset( $_SERVER['REQUEST_METHOD'] ) && ! in_array( strtoupper( $_SERVER['REQUEST_METHOD'] ), array( 'GET', 'HEAD' ), true ) ) {
  44. return;
  45. }
  46. // If we're not in wp-admin and the post has been published and preview nonce
  47. // is non-existent or invalid then no need for preview in query.
  48. if ( is_preview() && get_query_var( 'p' ) && 'publish' === get_post_status( get_query_var( 'p' ) ) ) {
  49. if ( ! isset( $_GET['preview_id'] )
  50. || ! isset( $_GET['preview_nonce'] )
  51. || ! wp_verify_nonce( $_GET['preview_nonce'], 'post_preview_' . (int) $_GET['preview_id'] )
  52. ) {
  53. $wp_query->is_preview = false;
  54. }
  55. }
  56. if ( is_admin() || is_search() || is_preview() || is_trackback()
  57. || is_robots() || is_favicon()
  58. || ( $is_IIS && ! iis7_supports_permalinks() )
  59. ) {
  60. return;
  61. }
  62. if ( ! $requested_url && isset( $_SERVER['HTTP_HOST'] ) ) {
  63. // Build the URL in the address bar.
  64. $requested_url = is_ssl() ? 'https://' : 'http://';
  65. $requested_url .= $_SERVER['HTTP_HOST'];
  66. $requested_url .= $_SERVER['REQUEST_URI'];
  67. }
  68. $original = parse_url( $requested_url );
  69. if ( false === $original ) {
  70. return;
  71. }
  72. $redirect = $original;
  73. $redirect_url = false;
  74. // Notice fixing.
  75. if ( ! isset( $redirect['path'] ) ) {
  76. $redirect['path'] = '';
  77. }
  78. if ( ! isset( $redirect['query'] ) ) {
  79. $redirect['query'] = '';
  80. }
  81. /*
  82. * If the original URL ended with non-breaking spaces, they were almost
  83. * certainly inserted by accident. Let's remove them, so the reader doesn't
  84. * see a 404 error with no obvious cause.
  85. */
  86. $redirect['path'] = preg_replace( '|(%C2%A0)+$|i', '', $redirect['path'] );
  87. // It's not a preview, so remove it from URL.
  88. if ( get_query_var( 'preview' ) ) {
  89. $redirect['query'] = remove_query_arg( 'preview', $redirect['query'] );
  90. }
  91. $post_id = get_query_var( 'p' );
  92. if ( is_feed() && $post_id ) {
  93. $redirect_url = get_post_comments_feed_link( $post_id, get_query_var( 'feed' ) );
  94. if ( $redirect_url ) {
  95. $redirect['query'] = _remove_qs_args_if_not_in_url(
  96. $redirect['query'],
  97. array( 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type', 'feed' ),
  98. $redirect_url
  99. );
  100. $redirect['path'] = parse_url( $redirect_url, PHP_URL_PATH );
  101. }
  102. }
  103. if ( is_singular() && $wp_query->post_count < 1 && $post_id ) {
  104. $vars = $wpdb->get_results( $wpdb->prepare( "SELECT post_type, post_parent FROM $wpdb->posts WHERE ID = %d", $post_id ) );
  105. if ( ! empty( $vars[0] ) ) {
  106. $vars = $vars[0];
  107. if ( 'revision' === $vars->post_type && $vars->post_parent > 0 ) {
  108. $post_id = $vars->post_parent;
  109. }
  110. $redirect_url = get_permalink( $post_id );
  111. if ( $redirect_url ) {
  112. $redirect['query'] = _remove_qs_args_if_not_in_url(
  113. $redirect['query'],
  114. array( 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type' ),
  115. $redirect_url
  116. );
  117. }
  118. }
  119. }
  120. // These tests give us a WP-generated permalink.
  121. if ( is_404() ) {
  122. // Redirect ?page_id, ?p=, ?attachment_id= to their respective URLs.
  123. $post_id = max( get_query_var( 'p' ), get_query_var( 'page_id' ), get_query_var( 'attachment_id' ) );
  124. $redirect_post = $post_id ? get_post( $post_id ) : false;
  125. if ( $redirect_post ) {
  126. $post_type_obj = get_post_type_object( $redirect_post->post_type );
  127. if ( $post_type_obj->public && 'auto-draft' !== $redirect_post->post_status ) {
  128. $redirect_url = get_permalink( $redirect_post );
  129. $redirect['query'] = _remove_qs_args_if_not_in_url(
  130. $redirect['query'],
  131. array( 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type' ),
  132. $redirect_url
  133. );
  134. }
  135. }
  136. $year = get_query_var( 'year' );
  137. $month = get_query_var( 'monthnum' );
  138. $day = get_query_var( 'day' );
  139. if ( $year && $month && $day ) {
  140. $date = sprintf( '%04d-%02d-%02d', $year, $month, $day );
  141. if ( ! wp_checkdate( $month, $day, $year, $date ) ) {
  142. $redirect_url = get_month_link( $year, $month );
  143. $redirect['query'] = _remove_qs_args_if_not_in_url(
  144. $redirect['query'],
  145. array( 'year', 'monthnum', 'day' ),
  146. $redirect_url
  147. );
  148. }
  149. } elseif ( $year && $month && $month > 12 ) {
  150. $redirect_url = get_year_link( $year );
  151. $redirect['query'] = _remove_qs_args_if_not_in_url(
  152. $redirect['query'],
  153. array( 'year', 'monthnum' ),
  154. $redirect_url
  155. );
  156. }
  157. // Strip off non-existing <!--nextpage--> links from single posts or pages.
  158. if ( get_query_var( 'page' ) ) {
  159. $post_id = 0;
  160. if ( $wp_query->queried_object instanceof WP_Post ) {
  161. $post_id = $wp_query->queried_object->ID;
  162. } elseif ( $wp_query->post ) {
  163. $post_id = $wp_query->post->ID;
  164. }
  165. if ( $post_id ) {
  166. $redirect_url = get_permalink( $post_id );
  167. $redirect['path'] = rtrim( $redirect['path'], (int) get_query_var( 'page' ) . '/' );
  168. $redirect['query'] = remove_query_arg( 'page', $redirect['query'] );
  169. }
  170. }
  171. if ( ! $redirect_url ) {
  172. $redirect_url = redirect_guess_404_permalink();
  173. if ( $redirect_url ) {
  174. $redirect['query'] = _remove_qs_args_if_not_in_url(
  175. $redirect['query'],
  176. array( 'page', 'feed', 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type' ),
  177. $redirect_url
  178. );
  179. }
  180. }
  181. } elseif ( is_object( $wp_rewrite ) && $wp_rewrite->using_permalinks() ) {
  182. // Rewriting of old ?p=X, ?m=2004, ?m=200401, ?m=20040101.
  183. if ( is_attachment()
  184. && ! array_diff( array_keys( $wp->query_vars ), array( 'attachment', 'attachment_id' ) )
  185. && ! $redirect_url
  186. ) {
  187. if ( ! empty( $_GET['attachment_id'] ) ) {
  188. $redirect_url = get_attachment_link( get_query_var( 'attachment_id' ) );
  189. if ( $redirect_url ) {
  190. $redirect['query'] = remove_query_arg( 'attachment_id', $redirect['query'] );
  191. }
  192. } else {
  193. $redirect_url = get_attachment_link();
  194. }
  195. } elseif ( is_single() && ! empty( $_GET['p'] ) && ! $redirect_url ) {
  196. $redirect_url = get_permalink( get_query_var( 'p' ) );
  197. if ( $redirect_url ) {
  198. $redirect['query'] = remove_query_arg( array( 'p', 'post_type' ), $redirect['query'] );
  199. }
  200. } elseif ( is_single() && ! empty( $_GET['name'] ) && ! $redirect_url ) {
  201. $redirect_url = get_permalink( $wp_query->get_queried_object_id() );
  202. if ( $redirect_url ) {
  203. $redirect['query'] = remove_query_arg( 'name', $redirect['query'] );
  204. }
  205. } elseif ( is_page() && ! empty( $_GET['page_id'] ) && ! $redirect_url ) {
  206. $redirect_url = get_permalink( get_query_var( 'page_id' ) );
  207. if ( $redirect_url ) {
  208. $redirect['query'] = remove_query_arg( 'page_id', $redirect['query'] );
  209. }
  210. } elseif ( is_page() && ! is_feed() && ! $redirect_url
  211. && 'page' === get_option( 'show_on_front' ) && get_queried_object_id() === (int) get_option( 'page_on_front' )
  212. ) {
  213. $redirect_url = home_url( '/' );
  214. } elseif ( is_home() && ! empty( $_GET['page_id'] ) && ! $redirect_url
  215. && 'page' === get_option( 'show_on_front' ) && get_query_var( 'page_id' ) === (int) get_option( 'page_for_posts' )
  216. ) {
  217. $redirect_url = get_permalink( get_option( 'page_for_posts' ) );
  218. if ( $redirect_url ) {
  219. $redirect['query'] = remove_query_arg( 'page_id', $redirect['query'] );
  220. }
  221. } elseif ( ! empty( $_GET['m'] ) && ( is_year() || is_month() || is_day() ) ) {
  222. $m = get_query_var( 'm' );
  223. switch ( strlen( $m ) ) {
  224. case 4: // Yearly.
  225. $redirect_url = get_year_link( $m );
  226. break;
  227. case 6: // Monthly.
  228. $redirect_url = get_month_link( substr( $m, 0, 4 ), substr( $m, 4, 2 ) );
  229. break;
  230. case 8: // Daily.
  231. $redirect_url = get_day_link( substr( $m, 0, 4 ), substr( $m, 4, 2 ), substr( $m, 6, 2 ) );
  232. break;
  233. }
  234. if ( $redirect_url ) {
  235. $redirect['query'] = remove_query_arg( 'm', $redirect['query'] );
  236. }
  237. // Now moving on to non ?m=X year/month/day links.
  238. } elseif ( is_date() ) {
  239. $year = get_query_var( 'year' );
  240. $month = get_query_var( 'monthnum' );
  241. $day = get_query_var( 'day' );
  242. if ( is_day() && $year && $month && ! empty( $_GET['day'] ) ) {
  243. $redirect_url = get_day_link( $year, $month, $day );
  244. if ( $redirect_url ) {
  245. $redirect['query'] = remove_query_arg( array( 'year', 'monthnum', 'day' ), $redirect['query'] );
  246. }
  247. } elseif ( is_month() && $year && ! empty( $_GET['monthnum'] ) ) {
  248. $redirect_url = get_month_link( $year, $month );
  249. if ( $redirect_url ) {
  250. $redirect['query'] = remove_query_arg( array( 'year', 'monthnum' ), $redirect['query'] );
  251. }
  252. } elseif ( is_year() && ! empty( $_GET['year'] ) ) {
  253. $redirect_url = get_year_link( $year );
  254. if ( $redirect_url ) {
  255. $redirect['query'] = remove_query_arg( 'year', $redirect['query'] );
  256. }
  257. }
  258. } elseif ( is_author() && ! empty( $_GET['author'] ) && preg_match( '|^[0-9]+$|', $_GET['author'] ) ) {
  259. $author = get_userdata( get_query_var( 'author' ) );
  260. if ( false !== $author
  261. && $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE $wpdb->posts.post_author = %d AND $wpdb->posts.post_status = 'publish' LIMIT 1", $author->ID ) )
  262. ) {
  263. $redirect_url = get_author_posts_url( $author->ID, $author->user_nicename );
  264. if ( $redirect_url ) {
  265. $redirect['query'] = remove_query_arg( 'author', $redirect['query'] );
  266. }
  267. }
  268. } elseif ( is_category() || is_tag() || is_tax() ) { // Terms (tags/categories).
  269. $term_count = 0;
  270. foreach ( $wp_query->tax_query->queried_terms as $tax_query ) {
  271. $term_count += count( $tax_query['terms'] );
  272. }
  273. $obj = $wp_query->get_queried_object();
  274. if ( $term_count <= 1 && ! empty( $obj->term_id ) ) {
  275. $tax_url = get_term_link( (int) $obj->term_id, $obj->taxonomy );
  276. if ( $tax_url && ! is_wp_error( $tax_url ) ) {
  277. if ( ! empty( $redirect['query'] ) ) {
  278. // Strip taxonomy query vars off the URL.
  279. $qv_remove = array( 'term', 'taxonomy' );
  280. if ( is_category() ) {
  281. $qv_remove[] = 'category_name';
  282. $qv_remove[] = 'cat';
  283. } elseif ( is_tag() ) {
  284. $qv_remove[] = 'tag';
  285. $qv_remove[] = 'tag_id';
  286. } else {
  287. // Custom taxonomies will have a custom query var, remove those too.
  288. $tax_obj = get_taxonomy( $obj->taxonomy );
  289. if ( false !== $tax_obj->query_var ) {
  290. $qv_remove[] = $tax_obj->query_var;
  291. }
  292. }
  293. $rewrite_vars = array_diff( array_keys( $wp_query->query ), array_keys( $_GET ) );
  294. // Check to see if all the query vars are coming from the rewrite, none are set via $_GET.
  295. if ( ! array_diff( $rewrite_vars, array_keys( $_GET ) ) ) {
  296. // Remove all of the per-tax query vars.
  297. $redirect['query'] = remove_query_arg( $qv_remove, $redirect['query'] );
  298. // Create the destination URL for this taxonomy.
  299. $tax_url = parse_url( $tax_url );
  300. if ( ! empty( $tax_url['query'] ) ) {
  301. // Taxonomy accessible via ?taxonomy=...&term=... or any custom query var.
  302. parse_str( $tax_url['query'], $query_vars );
  303. $redirect['query'] = add_query_arg( $query_vars, $redirect['query'] );
  304. } else {
  305. // Taxonomy is accessible via a "pretty URL".
  306. $redirect['path'] = $tax_url['path'];
  307. }
  308. } else {
  309. // Some query vars are set via $_GET. Unset those from $_GET that exist via the rewrite.
  310. foreach ( $qv_remove as $_qv ) {
  311. if ( isset( $rewrite_vars[ $_qv ] ) ) {
  312. $redirect['query'] = remove_query_arg( $_qv, $redirect['query'] );
  313. }
  314. }
  315. }
  316. }
  317. }
  318. }
  319. } elseif ( is_single() && strpos( $wp_rewrite->permalink_structure, '%category%' ) !== false ) {
  320. $category_name = get_query_var( 'category_name' );
  321. if ( $category_name ) {
  322. $category = get_category_by_path( $category_name );
  323. if ( ! $category || is_wp_error( $category )
  324. || ! has_term( $category->term_id, 'category', $wp_query->get_queried_object_id() )
  325. ) {
  326. $redirect_url = get_permalink( $wp_query->get_queried_object_id() );
  327. }
  328. }
  329. }
  330. // Post paging.
  331. if ( is_singular() && get_query_var( 'page' ) ) {
  332. $page = get_query_var( 'page' );
  333. if ( ! $redirect_url ) {
  334. $redirect_url = get_permalink( get_queried_object_id() );
  335. }
  336. if ( $page > 1 ) {
  337. $redirect_url = trailingslashit( $redirect_url );
  338. if ( is_front_page() ) {
  339. $redirect_url .= user_trailingslashit( "$wp_rewrite->pagination_base/$page", 'paged' );
  340. } else {
  341. $redirect_url .= user_trailingslashit( $page, 'single_paged' );
  342. }
  343. }
  344. $redirect['query'] = remove_query_arg( 'page', $redirect['query'] );
  345. }
  346. // Paging and feeds.
  347. if ( get_query_var( 'paged' ) || is_feed() || get_query_var( 'cpage' ) ) {
  348. $paged = get_query_var( 'paged' );
  349. $feed = get_query_var( 'feed' );
  350. $cpage = get_query_var( 'cpage' );
  351. while ( preg_match( "#/$wp_rewrite->pagination_base/?[0-9]+?(/+)?$#", $redirect['path'] )
  352. || preg_match( '#/(comments/?)?(feed|rss2?|rdf|atom)(/+)?$#', $redirect['path'] )
  353. || preg_match( "#/{$wp_rewrite->comments_pagination_base}-[0-9]+(/+)?$#", $redirect['path'] )
  354. ) {
  355. // Strip off any existing paging.
  356. $redirect['path'] = preg_replace( "#/$wp_rewrite->pagination_base/?[0-9]+?(/+)?$#", '/', $redirect['path'] );
  357. // Strip off feed endings.
  358. $redirect['path'] = preg_replace( '#/(comments/?)?(feed|rss2?|rdf|atom)(/+|$)#', '/', $redirect['path'] );
  359. // Strip off any existing comment paging.
  360. $redirect['path'] = preg_replace( "#/{$wp_rewrite->comments_pagination_base}-[0-9]+?(/+)?$#", '/', $redirect['path'] );
  361. }
  362. $addl_path = '';
  363. $default_feed = get_default_feed();
  364. if ( is_feed() && in_array( $feed, $wp_rewrite->feeds, true ) ) {
  365. $addl_path = ! empty( $addl_path ) ? trailingslashit( $addl_path ) : '';
  366. if ( ! is_singular() && get_query_var( 'withcomments' ) ) {
  367. $addl_path .= 'comments/';
  368. }
  369. if ( ( 'rss' === $default_feed && 'feed' === $feed ) || 'rss' === $feed ) {
  370. $format = ( 'rss2' === $default_feed ) ? '' : 'rss2';
  371. } else {
  372. $format = ( $default_feed === $feed || 'feed' === $feed ) ? '' : $feed;
  373. }
  374. $addl_path .= user_trailingslashit( 'feed/' . $format, 'feed' );
  375. $redirect['query'] = remove_query_arg( 'feed', $redirect['query'] );
  376. } elseif ( is_feed() && 'old' === $feed ) {
  377. $old_feed_files = array(
  378. 'wp-atom.php' => 'atom',
  379. 'wp-commentsrss2.php' => 'comments_rss2',
  380. 'wp-feed.php' => $default_feed,
  381. 'wp-rdf.php' => 'rdf',
  382. 'wp-rss.php' => 'rss2',
  383. 'wp-rss2.php' => 'rss2',
  384. );
  385. if ( isset( $old_feed_files[ basename( $redirect['path'] ) ] ) ) {
  386. $redirect_url = get_feed_link( $old_feed_files[ basename( $redirect['path'] ) ] );
  387. wp_redirect( $redirect_url, 301 );
  388. die();
  389. }
  390. }
  391. if ( $paged > 0 ) {
  392. $redirect['query'] = remove_query_arg( 'paged', $redirect['query'] );
  393. if ( ! is_feed() ) {
  394. if ( ! is_single() ) {
  395. $addl_path = ! empty( $addl_path ) ? trailingslashit( $addl_path ) : '';
  396. if ( $paged > 1 ) {
  397. $addl_path .= user_trailingslashit( "$wp_rewrite->pagination_base/$paged", 'paged' );
  398. }
  399. }
  400. } elseif ( $paged > 1 ) {
  401. $redirect['query'] = add_query_arg( 'paged', $paged, $redirect['query'] );
  402. }
  403. }
  404. $default_comments_page = get_option( 'default_comments_page' );
  405. if ( get_option( 'page_comments' )
  406. && ( 'newest' === $default_comments_page && $cpage > 0
  407. || 'newest' !== $default_comments_page && $cpage > 1 )
  408. ) {
  409. $addl_path = ( ! empty( $addl_path ) ? trailingslashit( $addl_path ) : '' );
  410. $addl_path .= user_trailingslashit( $wp_rewrite->comments_pagination_base . '-' . $cpage, 'commentpaged' );
  411. $redirect['query'] = remove_query_arg( 'cpage', $redirect['query'] );
  412. }
  413. // Strip off trailing /index.php/.
  414. $redirect['path'] = preg_replace( '|/' . preg_quote( $wp_rewrite->index, '|' ) . '/?$|', '/', $redirect['path'] );
  415. $redirect['path'] = user_trailingslashit( $redirect['path'] );
  416. if ( ! empty( $addl_path )
  417. && $wp_rewrite->using_index_permalinks()
  418. && strpos( $redirect['path'], '/' . $wp_rewrite->index . '/' ) === false
  419. ) {
  420. $redirect['path'] = trailingslashit( $redirect['path'] ) . $wp_rewrite->index . '/';
  421. }
  422. if ( ! empty( $addl_path ) ) {
  423. $redirect['path'] = trailingslashit( $redirect['path'] ) . $addl_path;
  424. }
  425. $redirect_url = $redirect['scheme'] . '://' . $redirect['host'] . $redirect['path'];
  426. }
  427. if ( 'wp-register.php' === basename( $redirect['path'] ) ) {
  428. if ( is_multisite() ) {
  429. /** This filter is documented in wp-login.php */
  430. $redirect_url = apply_filters( 'wp_signup_location', network_site_url( 'wp-signup.php' ) );
  431. } else {
  432. $redirect_url = wp_registration_url();
  433. }
  434. wp_redirect( $redirect_url, 301 );
  435. die();
  436. }
  437. }
  438. $redirect['query'] = preg_replace( '#^\??&*?#', '', $redirect['query'] );
  439. // Tack on any additional query vars.
  440. if ( $redirect_url && ! empty( $redirect['query'] ) ) {
  441. parse_str( $redirect['query'], $_parsed_query );
  442. $redirect = parse_url( $redirect_url );
  443. if ( ! empty( $_parsed_query['name'] ) && ! empty( $redirect['query'] ) ) {
  444. parse_str( $redirect['query'], $_parsed_redirect_query );
  445. if ( empty( $_parsed_redirect_query['name'] ) ) {
  446. unset( $_parsed_query['name'] );
  447. }
  448. }
  449. $_parsed_query = array_combine(
  450. rawurlencode_deep( array_keys( $_parsed_query ) ),
  451. rawurlencode_deep( array_values( $_parsed_query ) )
  452. );
  453. $redirect_url = add_query_arg( $_parsed_query, $redirect_url );
  454. }
  455. if ( $redirect_url ) {
  456. $redirect = parse_url( $redirect_url );
  457. }
  458. // www.example.com vs. example.com
  459. $user_home = parse_url( home_url() );
  460. if ( ! empty( $user_home['host'] ) ) {
  461. $redirect['host'] = $user_home['host'];
  462. }
  463. if ( empty( $user_home['path'] ) ) {
  464. $user_home['path'] = '/';
  465. }
  466. // Handle ports.
  467. if ( ! empty( $user_home['port'] ) ) {
  468. $redirect['port'] = $user_home['port'];
  469. } else {
  470. unset( $redirect['port'] );
  471. }
  472. // Trailing /index.php.
  473. $redirect['path'] = preg_replace( '|/' . preg_quote( $wp_rewrite->index, '|' ) . '/*?$|', '/', $redirect['path'] );
  474. $punctuation_pattern = implode(
  475. '|',
  476. array_map(
  477. 'preg_quote',
  478. array(
  479. ' ',
  480. '%20', // Space.
  481. '!',
  482. '%21', // Exclamation mark.
  483. '"',
  484. '%22', // Double quote.
  485. "'",
  486. '%27', // Single quote.
  487. '(',
  488. '%28', // Opening bracket.
  489. ')',
  490. '%29', // Closing bracket.
  491. ',',
  492. '%2C', // Comma.
  493. '.',
  494. '%2E', // Period.
  495. ';',
  496. '%3B', // Semicolon.
  497. '{',
  498. '%7B', // Opening curly bracket.
  499. '}',
  500. '%7D', // Closing curly bracket.
  501. '%E2%80%9C', // Opening curly quote.
  502. '%E2%80%9D', // Closing curly quote.
  503. )
  504. )
  505. );
  506. // Remove trailing spaces and end punctuation from the path.
  507. $redirect['path'] = preg_replace( "#($punctuation_pattern)+$#", '', $redirect['path'] );
  508. if ( ! empty( $redirect['query'] ) ) {
  509. // Remove trailing spaces and end punctuation from certain terminating query string args.
  510. $redirect['query'] = preg_replace( "#((^|&)(p|page_id|cat|tag)=[^&]*?)($punctuation_pattern)+$#", '$1', $redirect['query'] );
  511. // Clean up empty query strings.
  512. $redirect['query'] = trim( preg_replace( '#(^|&)(p|page_id|cat|tag)=?(&|$)#', '&', $redirect['query'] ), '&' );
  513. // Redirect obsolete feeds.
  514. $redirect['query'] = preg_replace( '#(^|&)feed=rss(&|$)#', '$1feed=rss2$2', $redirect['query'] );
  515. // Remove redundant leading ampersands.
  516. $redirect['query'] = preg_replace( '#^\??&*?#', '', $redirect['query'] );
  517. }
  518. // Strip /index.php/ when we're not using PATHINFO permalinks.
  519. if ( ! $wp_rewrite->using_index_permalinks() ) {
  520. $redirect['path'] = str_replace( '/' . $wp_rewrite->index . '/', '/', $redirect['path'] );
  521. }
  522. // Trailing slashes.
  523. if ( is_object( $wp_rewrite ) && $wp_rewrite->using_permalinks()
  524. && ! is_404() && ( ! is_front_page() || is_front_page() && get_query_var( 'paged' ) > 1 )
  525. ) {
  526. $user_ts_type = '';
  527. if ( get_query_var( 'paged' ) > 0 ) {
  528. $user_ts_type = 'paged';
  529. } else {
  530. foreach ( array( 'single', 'category', 'page', 'day', 'month', 'year', 'home' ) as $type ) {
  531. $func = 'is_' . $type;
  532. if ( call_user_func( $func ) ) {
  533. $user_ts_type = $type;
  534. break;
  535. }
  536. }
  537. }
  538. $redirect['path'] = user_trailingslashit( $redirect['path'], $user_ts_type );
  539. } elseif ( is_front_page() ) {
  540. $redirect['path'] = trailingslashit( $redirect['path'] );
  541. }
  542. // Strip multiple slashes out of the URL.
  543. if ( strpos( $redirect['path'], '//' ) > -1 ) {
  544. $redirect['path'] = preg_replace( '|/+|', '/', $redirect['path'] );
  545. }
  546. // Always trailing slash the Front Page URL.
  547. if ( trailingslashit( $redirect['path'] ) === trailingslashit( $user_home['path'] ) ) {
  548. $redirect['path'] = trailingslashit( $redirect['path'] );
  549. }
  550. $original_host_low = strtolower( $original['host'] );
  551. $redirect_host_low = strtolower( $redirect['host'] );
  552. // Ignore differences in host capitalization, as this can lead to infinite redirects.
  553. // Only redirect no-www <=> yes-www.
  554. if ( $original_host_low === $redirect_host_low
  555. || ( 'www.' . $original_host_low !== $redirect_host_low
  556. && 'www.' . $redirect_host_low !== $original_host_low )
  557. ) {
  558. $redirect['host'] = $original['host'];
  559. }
  560. $compare_original = array( $original['host'], $original['path'] );
  561. if ( ! empty( $original['port'] ) ) {
  562. $compare_original[] = $original['port'];
  563. }
  564. if ( ! empty( $original['query'] ) ) {
  565. $compare_original[] = $original['query'];
  566. }
  567. $compare_redirect = array( $redirect['host'], $redirect['path'] );
  568. if ( ! empty( $redirect['port'] ) ) {
  569. $compare_redirect[] = $redirect['port'];
  570. }
  571. if ( ! empty( $redirect['query'] ) ) {
  572. $compare_redirect[] = $redirect['query'];
  573. }
  574. if ( $compare_original !== $compare_redirect ) {
  575. $redirect_url = $redirect['scheme'] . '://' . $redirect['host'];
  576. if ( ! empty( $redirect['port'] ) ) {
  577. $redirect_url .= ':' . $redirect['port'];
  578. }
  579. $redirect_url .= $redirect['path'];
  580. if ( ! empty( $redirect['query'] ) ) {
  581. $redirect_url .= '?' . $redirect['query'];
  582. }
  583. }
  584. if ( ! $redirect_url || $redirect_url === $requested_url ) {
  585. return;
  586. }
  587. // Hex encoded octets are case-insensitive.
  588. if ( false !== strpos( $requested_url, '%' ) ) {
  589. if ( ! function_exists( 'lowercase_octets' ) ) {
  590. /**
  591. * Converts the first hex-encoded octet match to lowercase.
  592. *
  593. * @since 3.1.0
  594. * @ignore
  595. *
  596. * @param array $matches Hex-encoded octet matches for the requested URL.
  597. * @return string Lowercased version of the first match.
  598. */
  599. function lowercase_octets( $matches ) {
  600. return strtolower( $matches[0] );
  601. }
  602. }
  603. $requested_url = preg_replace_callback( '|%[a-fA-F0-9][a-fA-F0-9]|', 'lowercase_octets', $requested_url );
  604. }
  605. /**
  606. * Filters the canonical redirect URL.
  607. *
  608. * Returning false to this filter will cancel the redirect.
  609. *
  610. * @since 2.3.0
  611. *
  612. * @param string $redirect_url The redirect URL.
  613. * @param string $requested_url The requested URL.
  614. */
  615. $redirect_url = apply_filters( 'redirect_canonical', $redirect_url, $requested_url );
  616. // Yes, again -- in case the filter aborted the request.
  617. if ( ! $redirect_url || strip_fragment_from_url( $redirect_url ) === strip_fragment_from_url( $requested_url ) ) {
  618. return;
  619. }
  620. if ( $do_redirect ) {
  621. // Protect against chained redirects.
  622. if ( ! redirect_canonical( $redirect_url, false ) ) {
  623. wp_redirect( $redirect_url, 301 );
  624. exit();
  625. } else {
  626. // Debug.
  627. // die("1: $redirect_url<br />2: " . redirect_canonical( $redirect_url, false ) );
  628. return;
  629. }
  630. } else {
  631. return $redirect_url;
  632. }
  633. }
  634. /**
  635. * Removes arguments from a query string if they are not present in a URL
  636. * DO NOT use this in plugin code.
  637. *
  638. * @since 3.4.0
  639. * @access private
  640. *
  641. * @param string $query_string
  642. * @param array $args_to_check
  643. * @param string $url
  644. * @return string The altered query string
  645. */
  646. function _remove_qs_args_if_not_in_url( $query_string, array $args_to_check, $url ) {
  647. $parsed_url = parse_url( $url );
  648. if ( ! empty( $parsed_url['query'] ) ) {
  649. parse_str( $parsed_url['query'], $parsed_query );
  650. foreach ( $args_to_check as $qv ) {
  651. if ( ! isset( $parsed_query[ $qv ] ) ) {
  652. $query_string = remove_query_arg( $qv, $query_string );
  653. }
  654. }
  655. } else {
  656. $query_string = remove_query_arg( $args_to_check, $query_string );
  657. }
  658. return $query_string;
  659. }
  660. /**
  661. * Strips the #fragment from a URL, if one is present.
  662. *
  663. * @since 4.4.0
  664. *
  665. * @param string $url The URL to strip.
  666. * @return string The altered URL.
  667. */
  668. function strip_fragment_from_url( $url ) {
  669. $parsed_url = parse_url( $url );
  670. if ( ! empty( $parsed_url['host'] ) ) {
  671. // This mirrors code in redirect_canonical(). It does not handle every case.
  672. $url = $parsed_url['scheme'] . '://' . $parsed_url['host'];
  673. if ( ! empty( $parsed_url['port'] ) ) {
  674. $url .= ':' . $parsed_url['port'];
  675. }
  676. if ( ! empty( $parsed_url['path'] ) ) {
  677. $url .= $parsed_url['path'];
  678. }
  679. if ( ! empty( $parsed_url['query'] ) ) {
  680. $url .= '?' . $parsed_url['query'];
  681. }
  682. }
  683. return $url;
  684. }
  685. /**
  686. * Attempts to guess the correct URL based on query vars
  687. *
  688. * @since 2.3.0
  689. *
  690. * @global wpdb $wpdb WordPress database abstraction object.
  691. *
  692. * @return string|false The correct URL if one is found. False on failure.
  693. */
  694. function redirect_guess_404_permalink() {
  695. global $wpdb;
  696. if ( get_query_var( 'name' ) ) {
  697. $where = $wpdb->prepare( 'post_name LIKE %s', $wpdb->esc_like( get_query_var( 'name' ) ) . '%' );
  698. // If any of post_type, year, monthnum, or day are set, use them to refine the query.
  699. if ( get_query_var( 'post_type' ) ) {
  700. $where .= $wpdb->prepare( ' AND post_type = %s', get_query_var( 'post_type' ) );
  701. } else {
  702. $where .= " AND post_type IN ('" . implode( "', '", get_post_types( array( 'public' => true ) ) ) . "')";
  703. }
  704. if ( get_query_var( 'year' ) ) {
  705. $where .= $wpdb->prepare( ' AND YEAR(post_date) = %d', get_query_var( 'year' ) );
  706. }
  707. if ( get_query_var( 'monthnum' ) ) {
  708. $where .= $wpdb->prepare( ' AND MONTH(post_date) = %d', get_query_var( 'monthnum' ) );
  709. }
  710. if ( get_query_var( 'day' ) ) {
  711. $where .= $wpdb->prepare( ' AND DAYOFMONTH(post_date) = %d', get_query_var( 'day' ) );
  712. }
  713. // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
  714. $post_id = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE $where AND post_status = 'publish'" );
  715. if ( ! $post_id ) {
  716. return false;
  717. }
  718. if ( get_query_var( 'feed' ) ) {
  719. return get_post_comments_feed_link( $post_id, get_query_var( 'feed' ) );
  720. } elseif ( get_query_var( 'page' ) > 1 ) {
  721. return trailingslashit( get_permalink( $post_id ) ) . user_trailingslashit( get_query_var( 'page' ), 'single_paged' );
  722. } else {
  723. return get_permalink( $post_id );
  724. }
  725. }
  726. return false;
  727. }
  728. /**
  729. * Redirects a variety of shorthand URLs to the admin.
  730. *
  731. * If a user visits example.com/admin, they'll be redirected to /wp-admin.
  732. * Visiting /login redirects to /wp-login.php, and so on.
  733. *
  734. * @since 3.4.0
  735. *
  736. * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
  737. */
  738. function wp_redirect_admin_locations() {
  739. global $wp_rewrite;
  740. if ( ! ( is_404() && $wp_rewrite->using_permalinks() ) ) {
  741. return;
  742. }
  743. $admins = array(
  744. home_url( 'wp-admin', 'relative' ),
  745. home_url( 'dashboard', 'relative' ),
  746. home_url( 'admin', 'relative' ),
  747. site_url( 'dashboard', 'relative' ),
  748. site_url( 'admin', 'relative' ),
  749. );
  750. if ( in_array( untrailingslashit( $_SERVER['REQUEST_URI'] ), $admins, true ) ) {
  751. wp_redirect( admin_url() );
  752. exit;
  753. }
  754. $logins = array(
  755. home_url( 'wp-login.php', 'relative' ),
  756. home_url( 'login', 'relative' ),
  757. site_url( 'login', 'relative' ),
  758. );
  759. if ( in_array( untrailingslashit( $_SERVER['REQUEST_URI'] ), $logins, true ) ) {
  760. wp_redirect( wp_login_url() );
  761. exit;
  762. }
  763. }