canonical.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  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, searches, or on POST
  22. * 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
  31. * @global bool $is_IIS
  32. * @global WP_Query $wp_query
  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' ) ) ) {
  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. $wp_query->is_preview = false;
  53. }
  54. }
  55. if ( is_trackback() || is_search() || is_admin() || is_preview() || is_robots() || ( $is_IIS && !iis7_supports_permalinks() ) ) {
  56. return;
  57. }
  58. if ( ! $requested_url && isset( $_SERVER['HTTP_HOST'] ) ) {
  59. // build the URL in the address bar
  60. $requested_url = is_ssl() ? 'https://' : 'http://';
  61. $requested_url .= $_SERVER['HTTP_HOST'];
  62. $requested_url .= $_SERVER['REQUEST_URI'];
  63. }
  64. $original = @parse_url($requested_url);
  65. if ( false === $original ) {
  66. return;
  67. }
  68. $redirect = $original;
  69. $redirect_url = false;
  70. // Notice fixing
  71. if ( !isset($redirect['path']) )
  72. $redirect['path'] = '';
  73. if ( !isset($redirect['query']) )
  74. $redirect['query'] = '';
  75. // If the original URL ended with non-breaking spaces, they were almost
  76. // certainly inserted by accident. Let's remove them, so the reader doesn't
  77. // see a 404 error with no obvious cause.
  78. $redirect['path'] = preg_replace( '|(%C2%A0)+$|i', '', $redirect['path'] );
  79. // It's not a preview, so remove it from URL
  80. if ( get_query_var( 'preview' ) ) {
  81. $redirect['query'] = remove_query_arg( 'preview', $redirect['query'] );
  82. }
  83. if ( is_feed() && ( $id = get_query_var( 'p' ) ) ) {
  84. if ( $redirect_url = get_post_comments_feed_link( $id, get_query_var( 'feed' ) ) ) {
  85. $redirect['query'] = _remove_qs_args_if_not_in_url( $redirect['query'], array( 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type', 'feed'), $redirect_url );
  86. $redirect['path'] = parse_url( $redirect_url, PHP_URL_PATH );
  87. }
  88. }
  89. if ( is_singular() && 1 > $wp_query->post_count && ($id = get_query_var('p')) ) {
  90. $vars = $wpdb->get_results( $wpdb->prepare("SELECT post_type, post_parent FROM $wpdb->posts WHERE ID = %d", $id) );
  91. if ( isset($vars[0]) && $vars = $vars[0] ) {
  92. if ( 'revision' == $vars->post_type && $vars->post_parent > 0 )
  93. $id = $vars->post_parent;
  94. if ( $redirect_url = get_permalink($id) )
  95. $redirect['query'] = _remove_qs_args_if_not_in_url( $redirect['query'], array( 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type' ), $redirect_url );
  96. }
  97. }
  98. // These tests give us a WP-generated permalink
  99. if ( is_404() ) {
  100. // Redirect ?page_id, ?p=, ?attachment_id= to their respective url's
  101. $id = max( get_query_var('p'), get_query_var('page_id'), get_query_var('attachment_id') );
  102. if ( $id && $redirect_post = get_post($id) ) {
  103. $post_type_obj = get_post_type_object($redirect_post->post_type);
  104. if ( $post_type_obj->public && 'auto-draft' != $redirect_post->post_status ) {
  105. $redirect_url = get_permalink($redirect_post);
  106. $redirect['query'] = _remove_qs_args_if_not_in_url( $redirect['query'], array( 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type' ), $redirect_url );
  107. }
  108. }
  109. if ( get_query_var( 'day' ) && get_query_var( 'monthnum' ) && get_query_var( 'year' ) ) {
  110. $year = get_query_var( 'year' );
  111. $month = get_query_var( 'monthnum' );
  112. $day = get_query_var( 'day' );
  113. $date = sprintf( '%04d-%02d-%02d', $year, $month, $day );
  114. if ( ! wp_checkdate( $month, $day, $year, $date ) ) {
  115. $redirect_url = get_month_link( $year, $month );
  116. $redirect['query'] = _remove_qs_args_if_not_in_url( $redirect['query'], array( 'year', 'monthnum', 'day' ), $redirect_url );
  117. }
  118. } elseif ( get_query_var( 'monthnum' ) && get_query_var( 'year' ) && 12 < get_query_var( 'monthnum' ) ) {
  119. $redirect_url = get_year_link( get_query_var( 'year' ) );
  120. $redirect['query'] = _remove_qs_args_if_not_in_url( $redirect['query'], array( 'year', 'monthnum' ), $redirect_url );
  121. }
  122. if ( ! $redirect_url ) {
  123. if ( $redirect_url = redirect_guess_404_permalink() ) {
  124. $redirect['query'] = _remove_qs_args_if_not_in_url( $redirect['query'], array( 'page', 'feed', 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type' ), $redirect_url );
  125. }
  126. }
  127. if ( get_query_var( 'page' ) && $wp_query->post &&
  128. false !== strpos( $wp_query->post->post_content, '<!--nextpage-->' ) ) {
  129. $redirect['path'] = rtrim( $redirect['path'], (int) get_query_var( 'page' ) . '/' );
  130. $redirect['query'] = remove_query_arg( 'page', $redirect['query'] );
  131. $redirect_url = get_permalink( $wp_query->post->ID );
  132. }
  133. } elseif ( is_object($wp_rewrite) && $wp_rewrite->using_permalinks() ) {
  134. // rewriting of old ?p=X, ?m=2004, ?m=200401, ?m=20040101
  135. if ( is_attachment() &&
  136. ! array_diff( array_keys( $wp->query_vars ), array( 'attachment', 'attachment_id' ) ) &&
  137. ! $redirect_url ) {
  138. if ( ! empty( $_GET['attachment_id'] ) ) {
  139. $redirect_url = get_attachment_link( get_query_var( 'attachment_id' ) );
  140. if ( $redirect_url ) {
  141. $redirect['query'] = remove_query_arg( 'attachment_id', $redirect['query'] );
  142. }
  143. } else {
  144. $redirect_url = get_attachment_link();
  145. }
  146. } elseif ( is_single() && !empty($_GET['p']) && ! $redirect_url ) {
  147. if ( $redirect_url = get_permalink(get_query_var('p')) )
  148. $redirect['query'] = remove_query_arg(array('p', 'post_type'), $redirect['query']);
  149. } elseif ( is_single() && !empty($_GET['name']) && ! $redirect_url ) {
  150. if ( $redirect_url = get_permalink( $wp_query->get_queried_object_id() ) )
  151. $redirect['query'] = remove_query_arg('name', $redirect['query']);
  152. } elseif ( is_page() && !empty($_GET['page_id']) && ! $redirect_url ) {
  153. if ( $redirect_url = get_permalink(get_query_var('page_id')) )
  154. $redirect['query'] = remove_query_arg('page_id', $redirect['query']);
  155. } elseif ( is_page() && !is_feed() && 'page' == get_option('show_on_front') && get_queried_object_id() == get_option('page_on_front') && ! $redirect_url ) {
  156. $redirect_url = home_url('/');
  157. } elseif ( is_home() && !empty($_GET['page_id']) && 'page' == get_option('show_on_front') && get_query_var('page_id') == get_option('page_for_posts') && ! $redirect_url ) {
  158. if ( $redirect_url = get_permalink(get_option('page_for_posts')) )
  159. $redirect['query'] = remove_query_arg('page_id', $redirect['query']);
  160. } elseif ( !empty($_GET['m']) && ( is_year() || is_month() || is_day() ) ) {
  161. $m = get_query_var('m');
  162. switch ( strlen($m) ) {
  163. case 4: // Yearly
  164. $redirect_url = get_year_link($m);
  165. break;
  166. case 6: // Monthly
  167. $redirect_url = get_month_link( substr($m, 0, 4), substr($m, 4, 2) );
  168. break;
  169. case 8: // Daily
  170. $redirect_url = get_day_link(substr($m, 0, 4), substr($m, 4, 2), substr($m, 6, 2));
  171. break;
  172. }
  173. if ( $redirect_url )
  174. $redirect['query'] = remove_query_arg('m', $redirect['query']);
  175. // now moving on to non ?m=X year/month/day links
  176. } elseif ( is_day() && get_query_var('year') && get_query_var('monthnum') && !empty($_GET['day']) ) {
  177. if ( $redirect_url = get_day_link(get_query_var('year'), get_query_var('monthnum'), get_query_var('day')) )
  178. $redirect['query'] = remove_query_arg(array('year', 'monthnum', 'day'), $redirect['query']);
  179. } elseif ( is_month() && get_query_var('year') && !empty($_GET['monthnum']) ) {
  180. if ( $redirect_url = get_month_link(get_query_var('year'), get_query_var('monthnum')) )
  181. $redirect['query'] = remove_query_arg(array('year', 'monthnum'), $redirect['query']);
  182. } elseif ( is_year() && !empty($_GET['year']) ) {
  183. if ( $redirect_url = get_year_link(get_query_var('year')) )
  184. $redirect['query'] = remove_query_arg('year', $redirect['query']);
  185. } elseif ( is_author() && !empty($_GET['author']) && preg_match( '|^[0-9]+$|', $_GET['author'] ) ) {
  186. $author = get_userdata(get_query_var('author'));
  187. if ( ( false !== $author ) && $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 ) ) ) {
  188. if ( $redirect_url = get_author_posts_url($author->ID, $author->user_nicename) )
  189. $redirect['query'] = remove_query_arg('author', $redirect['query']);
  190. }
  191. } elseif ( is_category() || is_tag() || is_tax() ) { // Terms (Tags/categories)
  192. $term_count = 0;
  193. foreach ( $wp_query->tax_query->queried_terms as $tax_query )
  194. $term_count += count( $tax_query['terms'] );
  195. $obj = $wp_query->get_queried_object();
  196. if ( $term_count <= 1 && !empty($obj->term_id) && ( $tax_url = get_term_link((int)$obj->term_id, $obj->taxonomy) ) && !is_wp_error($tax_url) ) {
  197. if ( !empty($redirect['query']) ) {
  198. // Strip taxonomy query vars off the url.
  199. $qv_remove = array( 'term', 'taxonomy');
  200. if ( is_category() ) {
  201. $qv_remove[] = 'category_name';
  202. $qv_remove[] = 'cat';
  203. } elseif ( is_tag() ) {
  204. $qv_remove[] = 'tag';
  205. $qv_remove[] = 'tag_id';
  206. } else { // Custom taxonomies will have a custom query var, remove those too:
  207. $tax_obj = get_taxonomy( $obj->taxonomy );
  208. if ( false !== $tax_obj->query_var )
  209. $qv_remove[] = $tax_obj->query_var;
  210. }
  211. $rewrite_vars = array_diff( array_keys($wp_query->query), array_keys($_GET) );
  212. if ( !array_diff($rewrite_vars, array_keys($_GET)) ) { // Check to see if all the Query vars are coming from the rewrite, none are set via $_GET
  213. $redirect['query'] = remove_query_arg($qv_remove, $redirect['query']); //Remove all of the per-tax qv's
  214. // Create the destination url for this taxonomy
  215. $tax_url = parse_url($tax_url);
  216. if ( ! empty($tax_url['query']) ) { // Taxonomy accessible via ?taxonomy=..&term=.. or any custom qv..
  217. parse_str($tax_url['query'], $query_vars);
  218. $redirect['query'] = add_query_arg($query_vars, $redirect['query']);
  219. } else { // Taxonomy is accessible via a "pretty-URL"
  220. $redirect['path'] = $tax_url['path'];
  221. }
  222. } else { // Some query vars are set via $_GET. Unset those from $_GET that exist via the rewrite
  223. foreach ( $qv_remove as $_qv ) {
  224. if ( isset($rewrite_vars[$_qv]) )
  225. $redirect['query'] = remove_query_arg($_qv, $redirect['query']);
  226. }
  227. }
  228. }
  229. }
  230. } elseif ( is_single() && strpos($wp_rewrite->permalink_structure, '%category%') !== false && $cat = get_query_var( 'category_name' ) ) {
  231. $category = get_category_by_path( $cat );
  232. if ( ( ! $category || is_wp_error( $category ) ) || ! has_term( $category->term_id, 'category', $wp_query->get_queried_object_id() ) ) {
  233. $redirect_url = get_permalink($wp_query->get_queried_object_id());
  234. }
  235. }
  236. // Post Paging
  237. if ( is_singular() && get_query_var('page') ) {
  238. if ( !$redirect_url )
  239. $redirect_url = get_permalink( get_queried_object_id() );
  240. $page = get_query_var( 'page' );
  241. if ( $page > 1 ) {
  242. if ( is_front_page() ) {
  243. $redirect_url = trailingslashit( $redirect_url ) . user_trailingslashit( "$wp_rewrite->pagination_base/$page", 'paged' );
  244. } else {
  245. $redirect_url = trailingslashit( $redirect_url ) . user_trailingslashit( $page, 'single_paged' );
  246. }
  247. }
  248. $redirect['query'] = remove_query_arg( 'page', $redirect['query'] );
  249. }
  250. // paging and feeds
  251. if ( get_query_var('paged') || is_feed() || get_query_var('cpage') ) {
  252. while ( preg_match( "#/$wp_rewrite->pagination_base/?[0-9]+?(/+)?$#", $redirect['path'] ) || preg_match( '#/(comments/?)?(feed|rss|rdf|atom|rss2)(/+)?$#', $redirect['path'] ) || preg_match( "#/{$wp_rewrite->comments_pagination_base}-[0-9]+(/+)?$#", $redirect['path'] ) ) {
  253. // Strip off paging and feed
  254. $redirect['path'] = preg_replace("#/$wp_rewrite->pagination_base/?[0-9]+?(/+)?$#", '/', $redirect['path']); // strip off any existing paging
  255. $redirect['path'] = preg_replace('#/(comments/?)?(feed|rss2?|rdf|atom)(/+|$)#', '/', $redirect['path']); // strip off feed endings
  256. $redirect['path'] = preg_replace("#/{$wp_rewrite->comments_pagination_base}-[0-9]+?(/+)?$#", '/', $redirect['path']); // strip off any existing comment paging
  257. }
  258. $addl_path = '';
  259. if ( is_feed() && in_array( get_query_var('feed'), $wp_rewrite->feeds ) ) {
  260. $addl_path = !empty( $addl_path ) ? trailingslashit($addl_path) : '';
  261. if ( !is_singular() && get_query_var( 'withcomments' ) )
  262. $addl_path .= 'comments/';
  263. if ( ( 'rss' == get_default_feed() && 'feed' == get_query_var('feed') ) || 'rss' == get_query_var('feed') )
  264. $addl_path .= user_trailingslashit( 'feed/' . ( ( get_default_feed() == 'rss2' ) ? '' : 'rss2' ), 'feed' );
  265. else
  266. $addl_path .= user_trailingslashit( 'feed/' . ( ( get_default_feed() == get_query_var('feed') || 'feed' == get_query_var('feed') ) ? '' : get_query_var('feed') ), 'feed' );
  267. $redirect['query'] = remove_query_arg( 'feed', $redirect['query'] );
  268. } elseif ( is_feed() && 'old' == get_query_var('feed') ) {
  269. $old_feed_files = array(
  270. 'wp-atom.php' => 'atom',
  271. 'wp-commentsrss2.php' => 'comments_rss2',
  272. 'wp-feed.php' => get_default_feed(),
  273. 'wp-rdf.php' => 'rdf',
  274. 'wp-rss.php' => 'rss2',
  275. 'wp-rss2.php' => 'rss2',
  276. );
  277. if ( isset( $old_feed_files[ basename( $redirect['path'] ) ] ) ) {
  278. $redirect_url = get_feed_link( $old_feed_files[ basename( $redirect['path'] ) ] );
  279. wp_redirect( $redirect_url, 301 );
  280. die();
  281. }
  282. }
  283. if ( get_query_var('paged') > 0 ) {
  284. $paged = get_query_var('paged');
  285. $redirect['query'] = remove_query_arg( 'paged', $redirect['query'] );
  286. if ( !is_feed() ) {
  287. if ( $paged > 1 && !is_single() ) {
  288. $addl_path = ( !empty( $addl_path ) ? trailingslashit($addl_path) : '' ) . user_trailingslashit("$wp_rewrite->pagination_base/$paged", 'paged');
  289. } elseif ( !is_single() ) {
  290. $addl_path = !empty( $addl_path ) ? trailingslashit($addl_path) : '';
  291. }
  292. } elseif ( $paged > 1 ) {
  293. $redirect['query'] = add_query_arg( 'paged', $paged, $redirect['query'] );
  294. }
  295. }
  296. if ( get_option( 'page_comments' ) && (
  297. ( 'newest' == get_option( 'default_comments_page' ) && get_query_var( 'cpage' ) > 0 ) ||
  298. ( 'newest' != get_option( 'default_comments_page' ) && get_query_var( 'cpage' ) > 1 )
  299. ) ) {
  300. $addl_path = ( !empty( $addl_path ) ? trailingslashit($addl_path) : '' ) . user_trailingslashit( $wp_rewrite->comments_pagination_base . '-' . get_query_var('cpage'), 'commentpaged' );
  301. $redirect['query'] = remove_query_arg( 'cpage', $redirect['query'] );
  302. }
  303. $redirect['path'] = user_trailingslashit( preg_replace('|/' . preg_quote( $wp_rewrite->index, '|' ) . '/?$|', '/', $redirect['path']) ); // strip off trailing /index.php/
  304. if ( !empty( $addl_path ) && $wp_rewrite->using_index_permalinks() && strpos($redirect['path'], '/' . $wp_rewrite->index . '/') === false )
  305. $redirect['path'] = trailingslashit($redirect['path']) . $wp_rewrite->index . '/';
  306. if ( !empty( $addl_path ) )
  307. $redirect['path'] = trailingslashit($redirect['path']) . $addl_path;
  308. $redirect_url = $redirect['scheme'] . '://' . $redirect['host'] . $redirect['path'];
  309. }
  310. if ( 'wp-register.php' == basename( $redirect['path'] ) ) {
  311. if ( is_multisite() ) {
  312. /** This filter is documented in wp-login.php */
  313. $redirect_url = apply_filters( 'wp_signup_location', network_site_url( 'wp-signup.php' ) );
  314. } else {
  315. $redirect_url = wp_registration_url();
  316. }
  317. wp_redirect( $redirect_url, 301 );
  318. die();
  319. }
  320. }
  321. // tack on any additional query vars
  322. $redirect['query'] = preg_replace( '#^\??&*?#', '', $redirect['query'] );
  323. if ( $redirect_url && !empty($redirect['query']) ) {
  324. parse_str( $redirect['query'], $_parsed_query );
  325. $redirect = @parse_url($redirect_url);
  326. if ( ! empty( $_parsed_query['name'] ) && ! empty( $redirect['query'] ) ) {
  327. parse_str( $redirect['query'], $_parsed_redirect_query );
  328. if ( empty( $_parsed_redirect_query['name'] ) )
  329. unset( $_parsed_query['name'] );
  330. }
  331. $_parsed_query = rawurlencode_deep( $_parsed_query );
  332. $redirect_url = add_query_arg( $_parsed_query, $redirect_url );
  333. }
  334. if ( $redirect_url )
  335. $redirect = @parse_url($redirect_url);
  336. // www.example.com vs example.com
  337. $user_home = @parse_url(home_url());
  338. if ( !empty($user_home['host']) )
  339. $redirect['host'] = $user_home['host'];
  340. if ( empty($user_home['path']) )
  341. $user_home['path'] = '/';
  342. // Handle ports
  343. if ( !empty($user_home['port']) )
  344. $redirect['port'] = $user_home['port'];
  345. else
  346. unset($redirect['port']);
  347. // trailing /index.php
  348. $redirect['path'] = preg_replace('|/' . preg_quote( $wp_rewrite->index, '|' ) . '/*?$|', '/', $redirect['path']);
  349. $punctuation_pattern = implode( '|', array_map( 'preg_quote', array(
  350. ' ', '%20', // space
  351. '!', '%21', // exclamation mark
  352. '"', '%22', // double quote
  353. "'", '%27', // single quote
  354. '(', '%28', // opening bracket
  355. ')', '%29', // closing bracket
  356. ',', '%2C', // comma
  357. '.', '%2E', // period
  358. ';', '%3B', // semicolon
  359. '{', '%7B', // opening curly bracket
  360. '}', '%7D', // closing curly bracket
  361. '%E2%80%9C', // opening curly quote
  362. '%E2%80%9D', // closing curly quote
  363. ) ) );
  364. // Remove trailing spaces and end punctuation from the path.
  365. $redirect['path'] = preg_replace( "#($punctuation_pattern)+$#", '', $redirect['path'] );
  366. if ( !empty( $redirect['query'] ) ) {
  367. // Remove trailing spaces and end punctuation from certain terminating query string args.
  368. $redirect['query'] = preg_replace( "#((p|page_id|cat|tag)=[^&]*?)($punctuation_pattern)+$#", '$1', $redirect['query'] );
  369. // Clean up empty query strings
  370. $redirect['query'] = trim(preg_replace( '#(^|&)(p|page_id|cat|tag)=?(&|$)#', '&', $redirect['query']), '&');
  371. // Redirect obsolete feeds
  372. $redirect['query'] = preg_replace( '#(^|&)feed=rss(&|$)#', '$1feed=rss2$2', $redirect['query'] );
  373. // Remove redundant leading ampersands
  374. $redirect['query'] = preg_replace( '#^\??&*?#', '', $redirect['query'] );
  375. }
  376. // strip /index.php/ when we're not using PATHINFO permalinks
  377. if ( !$wp_rewrite->using_index_permalinks() )
  378. $redirect['path'] = str_replace( '/' . $wp_rewrite->index . '/', '/', $redirect['path'] );
  379. // trailing slashes
  380. if ( is_object($wp_rewrite) && $wp_rewrite->using_permalinks() && !is_404() && (!is_front_page() || ( is_front_page() && (get_query_var('paged') > 1) ) ) ) {
  381. $user_ts_type = '';
  382. if ( get_query_var('paged') > 0 ) {
  383. $user_ts_type = 'paged';
  384. } else {
  385. foreach ( array('single', 'category', 'page', 'day', 'month', 'year', 'home') as $type ) {
  386. $func = 'is_' . $type;
  387. if ( call_user_func($func) ) {
  388. $user_ts_type = $type;
  389. break;
  390. }
  391. }
  392. }
  393. $redirect['path'] = user_trailingslashit($redirect['path'], $user_ts_type);
  394. } elseif ( is_front_page() ) {
  395. $redirect['path'] = trailingslashit($redirect['path']);
  396. }
  397. // Strip multiple slashes out of the URL
  398. if ( strpos($redirect['path'], '//') > -1 )
  399. $redirect['path'] = preg_replace('|/+|', '/', $redirect['path']);
  400. // Always trailing slash the Front Page URL
  401. if ( trailingslashit( $redirect['path'] ) == trailingslashit( $user_home['path'] ) )
  402. $redirect['path'] = trailingslashit($redirect['path']);
  403. // Ignore differences in host capitalization, as this can lead to infinite redirects
  404. // Only redirect no-www <=> yes-www
  405. if ( strtolower($original['host']) == strtolower($redirect['host']) ||
  406. ( strtolower($original['host']) != 'www.' . strtolower($redirect['host']) && 'www.' . strtolower($original['host']) != strtolower($redirect['host']) ) )
  407. $redirect['host'] = $original['host'];
  408. $compare_original = array( $original['host'], $original['path'] );
  409. if ( !empty( $original['port'] ) )
  410. $compare_original[] = $original['port'];
  411. if ( !empty( $original['query'] ) )
  412. $compare_original[] = $original['query'];
  413. $compare_redirect = array( $redirect['host'], $redirect['path'] );
  414. if ( !empty( $redirect['port'] ) )
  415. $compare_redirect[] = $redirect['port'];
  416. if ( !empty( $redirect['query'] ) )
  417. $compare_redirect[] = $redirect['query'];
  418. if ( $compare_original !== $compare_redirect ) {
  419. $redirect_url = $redirect['scheme'] . '://' . $redirect['host'];
  420. if ( !empty($redirect['port']) )
  421. $redirect_url .= ':' . $redirect['port'];
  422. $redirect_url .= $redirect['path'];
  423. if ( !empty($redirect['query']) )
  424. $redirect_url .= '?' . $redirect['query'];
  425. }
  426. if ( ! $redirect_url || $redirect_url == $requested_url ) {
  427. return;
  428. }
  429. // Hex encoded octets are case-insensitive.
  430. if ( false !== strpos($requested_url, '%') ) {
  431. if ( !function_exists('lowercase_octets') ) {
  432. /**
  433. * Converts the first hex-encoded octet match to lowercase.
  434. *
  435. * @since 3.1.0
  436. * @ignore
  437. *
  438. * @param array $matches Hex-encoded octet matches for the requested URL.
  439. * @return string Lowercased version of the first match.
  440. */
  441. function lowercase_octets($matches) {
  442. return strtolower( $matches[0] );
  443. }
  444. }
  445. $requested_url = preg_replace_callback('|%[a-fA-F0-9][a-fA-F0-9]|', 'lowercase_octets', $requested_url);
  446. }
  447. /**
  448. * Filters the canonical redirect URL.
  449. *
  450. * Returning false to this filter will cancel the redirect.
  451. *
  452. * @since 2.3.0
  453. *
  454. * @param string $redirect_url The redirect URL.
  455. * @param string $requested_url The requested URL.
  456. */
  457. $redirect_url = apply_filters( 'redirect_canonical', $redirect_url, $requested_url );
  458. // yes, again -- in case the filter aborted the request
  459. if ( ! $redirect_url || strip_fragment_from_url( $redirect_url ) == strip_fragment_from_url( $requested_url ) ) {
  460. return;
  461. }
  462. if ( $do_redirect ) {
  463. // protect against chained redirects
  464. if ( !redirect_canonical($redirect_url, false) ) {
  465. wp_redirect($redirect_url, 301);
  466. exit();
  467. } else {
  468. // Debug
  469. // die("1: $redirect_url<br />2: " . redirect_canonical( $redirect_url, false ) );
  470. return;
  471. }
  472. } else {
  473. return $redirect_url;
  474. }
  475. }
  476. /**
  477. * Removes arguments from a query string if they are not present in a URL
  478. * DO NOT use this in plugin code.
  479. *
  480. * @since 3.4.0
  481. * @access private
  482. *
  483. * @param string $query_string
  484. * @param array $args_to_check
  485. * @param string $url
  486. * @return string The altered query string
  487. */
  488. function _remove_qs_args_if_not_in_url( $query_string, Array $args_to_check, $url ) {
  489. $parsed_url = @parse_url( $url );
  490. if ( ! empty( $parsed_url['query'] ) ) {
  491. parse_str( $parsed_url['query'], $parsed_query );
  492. foreach ( $args_to_check as $qv ) {
  493. if ( !isset( $parsed_query[$qv] ) )
  494. $query_string = remove_query_arg( $qv, $query_string );
  495. }
  496. } else {
  497. $query_string = remove_query_arg( $args_to_check, $query_string );
  498. }
  499. return $query_string;
  500. }
  501. /**
  502. * Strips the #fragment from a URL, if one is present.
  503. *
  504. * @since 4.4.0
  505. *
  506. * @param string $url The URL to strip.
  507. * @return string The altered URL.
  508. */
  509. function strip_fragment_from_url( $url ) {
  510. $parsed_url = @parse_url( $url );
  511. if ( ! empty( $parsed_url['host'] ) ) {
  512. // This mirrors code in redirect_canonical(). It does not handle every case.
  513. $url = $parsed_url['scheme'] . '://' . $parsed_url['host'];
  514. if ( ! empty( $parsed_url['port'] ) ) {
  515. $url .= ':' . $parsed_url['port'];
  516. }
  517. if ( ! empty( $parsed_url['path'] ) ) {
  518. $url .= $parsed_url['path'];
  519. }
  520. if ( ! empty( $parsed_url['query'] ) ) {
  521. $url .= '?' . $parsed_url['query'];
  522. }
  523. }
  524. return $url;
  525. }
  526. /**
  527. * Attempts to guess the correct URL based on query vars
  528. *
  529. * @since 2.3.0
  530. *
  531. * @global wpdb $wpdb WordPress database abstraction object.
  532. *
  533. * @return false|string The correct URL if one is found. False on failure.
  534. */
  535. function redirect_guess_404_permalink() {
  536. global $wpdb;
  537. if ( get_query_var('name') ) {
  538. $where = $wpdb->prepare("post_name LIKE %s", $wpdb->esc_like( get_query_var('name') ) . '%');
  539. // if any of post_type, year, monthnum, or day are set, use them to refine the query
  540. if ( get_query_var('post_type') )
  541. $where .= $wpdb->prepare(" AND post_type = %s", get_query_var('post_type'));
  542. else
  543. $where .= " AND post_type IN ('" . implode( "', '", get_post_types( array( 'public' => true ) ) ) . "')";
  544. if ( get_query_var('year') )
  545. $where .= $wpdb->prepare(" AND YEAR(post_date) = %d", get_query_var('year'));
  546. if ( get_query_var('monthnum') )
  547. $where .= $wpdb->prepare(" AND MONTH(post_date) = %d", get_query_var('monthnum'));
  548. if ( get_query_var('day') )
  549. $where .= $wpdb->prepare(" AND DAYOFMONTH(post_date) = %d", get_query_var('day'));
  550. $post_id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE $where AND post_status = 'publish'");
  551. if ( ! $post_id )
  552. return false;
  553. if ( get_query_var( 'feed' ) )
  554. return get_post_comments_feed_link( $post_id, get_query_var( 'feed' ) );
  555. elseif ( get_query_var( 'page' ) && 1 < get_query_var( 'page' ) )
  556. return trailingslashit( get_permalink( $post_id ) ) . user_trailingslashit( get_query_var( 'page' ), 'single_paged' );
  557. else
  558. return get_permalink( $post_id );
  559. }
  560. return false;
  561. }
  562. /**
  563. * Redirects a variety of shorthand URLs to the admin.
  564. *
  565. * If a user visits example.com/admin, they'll be redirected to /wp-admin.
  566. * Visiting /login redirects to /wp-login.php, and so on.
  567. *
  568. * @since 3.4.0
  569. *
  570. * @global WP_Rewrite $wp_rewrite
  571. */
  572. function wp_redirect_admin_locations() {
  573. global $wp_rewrite;
  574. if ( ! ( is_404() && $wp_rewrite->using_permalinks() ) )
  575. return;
  576. $admins = array(
  577. home_url( 'wp-admin', 'relative' ),
  578. home_url( 'dashboard', 'relative' ),
  579. home_url( 'admin', 'relative' ),
  580. site_url( 'dashboard', 'relative' ),
  581. site_url( 'admin', 'relative' ),
  582. );
  583. if ( in_array( untrailingslashit( $_SERVER['REQUEST_URI'] ), $admins ) ) {
  584. wp_redirect( admin_url() );
  585. exit;
  586. }
  587. $logins = array(
  588. home_url( 'wp-login.php', 'relative' ),
  589. home_url( 'login', 'relative' ),
  590. site_url( 'login', 'relative' ),
  591. );
  592. if ( in_array( untrailingslashit( $_SERVER['REQUEST_URI'] ), $logins ) ) {
  593. wp_redirect( wp_login_url() );
  594. exit;
  595. }
  596. }