canonical.php 28 KB

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