Нема описа

canonical.php 32KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  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() || is_favicon()
  57. || ( $is_IIS && ! iis7_supports_permalinks() )
  58. ) {
  59. return;
  60. }
  61. if ( ! $requested_url && isset( $_SERVER['HTTP_HOST'] ) ) {
  62. // Build the URL in the address bar.
  63. $requested_url = is_ssl() ? 'https://' : 'http://';
  64. $requested_url .= $_SERVER['HTTP_HOST'];
  65. $requested_url .= $_SERVER['REQUEST_URI'];
  66. }
  67. $original = parse_url( $requested_url );
  68. if ( false === $original ) {
  69. return;
  70. }
  71. $redirect = $original;
  72. $redirect_url = false;
  73. $redirect_obj = 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. $redirect_obj = get_post( $post_id );
  95. if ( $redirect_url ) {
  96. $redirect['query'] = _remove_qs_args_if_not_in_url(
  97. $redirect['query'],
  98. array( 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type', 'feed' ),
  99. $redirect_url
  100. );
  101. $redirect['path'] = parse_url( $redirect_url, PHP_URL_PATH );
  102. }
  103. }
  104. if ( is_singular() && $wp_query->post_count < 1 && $post_id ) {
  105. $vars = $wpdb->get_results( $wpdb->prepare( "SELECT post_type, post_parent FROM $wpdb->posts WHERE ID = %d", $post_id ) );
  106. if ( ! empty( $vars[0] ) ) {
  107. $vars = $vars[0];
  108. if ( 'revision' === $vars->post_type && $vars->post_parent > 0 ) {
  109. $post_id = $vars->post_parent;
  110. }
  111. $redirect_url = get_permalink( $post_id );
  112. $redirect_obj = get_post( $post_id );
  113. if ( $redirect_url ) {
  114. $redirect['query'] = _remove_qs_args_if_not_in_url(
  115. $redirect['query'],
  116. array( 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type' ),
  117. $redirect_url
  118. );
  119. }
  120. }
  121. }
  122. // These tests give us a WP-generated permalink.
  123. if ( is_404() ) {
  124. // Redirect ?page_id, ?p=, ?attachment_id= to their respective URLs.
  125. $post_id = max( get_query_var( 'p' ), get_query_var( 'page_id' ), get_query_var( 'attachment_id' ) );
  126. $redirect_post = $post_id ? get_post( $post_id ) : false;
  127. if ( $redirect_post ) {
  128. $post_type_obj = get_post_type_object( $redirect_post->post_type );
  129. if ( $post_type_obj && $post_type_obj->public && 'auto-draft' !== $redirect_post->post_status ) {
  130. $redirect_url = get_permalink( $redirect_post );
  131. $redirect_obj = get_post( $redirect_post );
  132. $redirect['query'] = _remove_qs_args_if_not_in_url(
  133. $redirect['query'],
  134. array( 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type' ),
  135. $redirect_url
  136. );
  137. }
  138. }
  139. $year = get_query_var( 'year' );
  140. $month = get_query_var( 'monthnum' );
  141. $day = get_query_var( 'day' );
  142. if ( $year && $month && $day ) {
  143. $date = sprintf( '%04d-%02d-%02d', $year, $month, $day );
  144. if ( ! wp_checkdate( $month, $day, $year, $date ) ) {
  145. $redirect_url = get_month_link( $year, $month );
  146. $redirect['query'] = _remove_qs_args_if_not_in_url(
  147. $redirect['query'],
  148. array( 'year', 'monthnum', 'day' ),
  149. $redirect_url
  150. );
  151. }
  152. } elseif ( $year && $month && $month > 12 ) {
  153. $redirect_url = get_year_link( $year );
  154. $redirect['query'] = _remove_qs_args_if_not_in_url(
  155. $redirect['query'],
  156. array( 'year', 'monthnum' ),
  157. $redirect_url
  158. );
  159. }
  160. // Strip off non-existing <!--nextpage--> links from single posts or pages.
  161. if ( get_query_var( 'page' ) ) {
  162. $post_id = 0;
  163. if ( $wp_query->queried_object instanceof WP_Post ) {
  164. $post_id = $wp_query->queried_object->ID;
  165. } elseif ( $wp_query->post ) {
  166. $post_id = $wp_query->post->ID;
  167. }
  168. if ( $post_id ) {
  169. $redirect_url = get_permalink( $post_id );
  170. $redirect_obj = get_post( $post_id );
  171. $redirect['path'] = rtrim( $redirect['path'], (int) get_query_var( 'page' ) . '/' );
  172. $redirect['query'] = remove_query_arg( 'page', $redirect['query'] );
  173. }
  174. }
  175. if ( ! $redirect_url ) {
  176. $redirect_url = redirect_guess_404_permalink();
  177. if ( $redirect_url ) {
  178. $redirect['query'] = _remove_qs_args_if_not_in_url(
  179. $redirect['query'],
  180. array( 'page', 'feed', 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type' ),
  181. $redirect_url
  182. );
  183. }
  184. }
  185. } elseif ( is_object( $wp_rewrite ) && $wp_rewrite->using_permalinks() ) {
  186. // Rewriting of old ?p=X, ?m=2004, ?m=200401, ?m=20040101.
  187. if ( is_attachment()
  188. && ! array_diff( array_keys( $wp->query_vars ), array( 'attachment', 'attachment_id' ) )
  189. && ! $redirect_url
  190. ) {
  191. if ( ! empty( $_GET['attachment_id'] ) ) {
  192. $redirect_url = get_attachment_link( get_query_var( 'attachment_id' ) );
  193. $redirect_obj = get_post( get_query_var( 'attachment_id' ) );
  194. if ( $redirect_url ) {
  195. $redirect['query'] = remove_query_arg( 'attachment_id', $redirect['query'] );
  196. }
  197. } else {
  198. $redirect_url = get_attachment_link();
  199. $redirect_obj = get_post();
  200. }
  201. } elseif ( is_single() && ! empty( $_GET['p'] ) && ! $redirect_url ) {
  202. $redirect_url = get_permalink( get_query_var( 'p' ) );
  203. $redirect_obj = get_post( get_query_var( 'p' ) );
  204. if ( $redirect_url ) {
  205. $redirect['query'] = remove_query_arg( array( 'p', 'post_type' ), $redirect['query'] );
  206. }
  207. } elseif ( is_single() && ! empty( $_GET['name'] ) && ! $redirect_url ) {
  208. $redirect_url = get_permalink( $wp_query->get_queried_object_id() );
  209. $redirect_obj = get_post( $wp_query->get_queried_object_id() );
  210. if ( $redirect_url ) {
  211. $redirect['query'] = remove_query_arg( 'name', $redirect['query'] );
  212. }
  213. } elseif ( is_page() && ! empty( $_GET['page_id'] ) && ! $redirect_url ) {
  214. $redirect_url = get_permalink( get_query_var( 'page_id' ) );
  215. $redirect_obj = get_post( get_query_var( 'page_id' ) );
  216. if ( $redirect_url ) {
  217. $redirect['query'] = remove_query_arg( 'page_id', $redirect['query'] );
  218. }
  219. } elseif ( is_page() && ! is_feed() && ! $redirect_url
  220. && 'page' === get_option( 'show_on_front' ) && get_queried_object_id() === (int) get_option( 'page_on_front' )
  221. ) {
  222. $redirect_url = home_url( '/' );
  223. } elseif ( is_home() && ! empty( $_GET['page_id'] ) && ! $redirect_url
  224. && 'page' === get_option( 'show_on_front' ) && get_query_var( 'page_id' ) === (int) get_option( 'page_for_posts' )
  225. ) {
  226. $redirect_url = get_permalink( get_option( 'page_for_posts' ) );
  227. $redirect_obj = get_post( get_option( 'page_for_posts' ) );
  228. if ( $redirect_url ) {
  229. $redirect['query'] = remove_query_arg( 'page_id', $redirect['query'] );
  230. }
  231. } elseif ( ! empty( $_GET['m'] ) && ( is_year() || is_month() || is_day() ) ) {
  232. $m = get_query_var( 'm' );
  233. switch ( strlen( $m ) ) {
  234. case 4: // Yearly.
  235. $redirect_url = get_year_link( $m );
  236. break;
  237. case 6: // Monthly.
  238. $redirect_url = get_month_link( substr( $m, 0, 4 ), substr( $m, 4, 2 ) );
  239. break;
  240. case 8: // Daily.
  241. $redirect_url = get_day_link( substr( $m, 0, 4 ), substr( $m, 4, 2 ), substr( $m, 6, 2 ) );
  242. break;
  243. }
  244. if ( $redirect_url ) {
  245. $redirect['query'] = remove_query_arg( 'm', $redirect['query'] );
  246. }
  247. // Now moving on to non ?m=X year/month/day links.
  248. } elseif ( is_date() ) {
  249. $year = get_query_var( 'year' );
  250. $month = get_query_var( 'monthnum' );
  251. $day = get_query_var( 'day' );
  252. if ( is_day() && $year && $month && ! empty( $_GET['day'] ) ) {
  253. $redirect_url = get_day_link( $year, $month, $day );
  254. if ( $redirect_url ) {
  255. $redirect['query'] = remove_query_arg( array( 'year', 'monthnum', 'day' ), $redirect['query'] );
  256. }
  257. } elseif ( is_month() && $year && ! empty( $_GET['monthnum'] ) ) {
  258. $redirect_url = get_month_link( $year, $month );
  259. if ( $redirect_url ) {
  260. $redirect['query'] = remove_query_arg( array( 'year', 'monthnum' ), $redirect['query'] );
  261. }
  262. } elseif ( is_year() && ! empty( $_GET['year'] ) ) {
  263. $redirect_url = get_year_link( $year );
  264. if ( $redirect_url ) {
  265. $redirect['query'] = remove_query_arg( 'year', $redirect['query'] );
  266. }
  267. }
  268. } elseif ( is_author() && ! empty( $_GET['author'] ) && preg_match( '|^[0-9]+$|', $_GET['author'] ) ) {
  269. $author = get_userdata( get_query_var( 'author' ) );
  270. if ( false !== $author
  271. && $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 ) )
  272. ) {
  273. $redirect_url = get_author_posts_url( $author->ID, $author->user_nicename );
  274. $redirect_obj = $author;
  275. if ( $redirect_url ) {
  276. $redirect['query'] = remove_query_arg( 'author', $redirect['query'] );
  277. }
  278. }
  279. } elseif ( is_category() || is_tag() || is_tax() ) { // Terms (tags/categories).
  280. $term_count = 0;
  281. foreach ( $wp_query->tax_query->queried_terms as $tax_query ) {
  282. $term_count += count( $tax_query['terms'] );
  283. }
  284. $obj = $wp_query->get_queried_object();
  285. if ( $term_count <= 1 && ! empty( $obj->term_id ) ) {
  286. $tax_url = get_term_link( (int) $obj->term_id, $obj->taxonomy );
  287. if ( $tax_url && ! is_wp_error( $tax_url ) ) {
  288. if ( ! empty( $redirect['query'] ) ) {
  289. // Strip taxonomy query vars off the URL.
  290. $qv_remove = array( 'term', 'taxonomy' );
  291. if ( is_category() ) {
  292. $qv_remove[] = 'category_name';
  293. $qv_remove[] = 'cat';
  294. } elseif ( is_tag() ) {
  295. $qv_remove[] = 'tag';
  296. $qv_remove[] = 'tag_id';
  297. } else {
  298. // Custom taxonomies will have a custom query var, remove those too.
  299. $tax_obj = get_taxonomy( $obj->taxonomy );
  300. if ( false !== $tax_obj->query_var ) {
  301. $qv_remove[] = $tax_obj->query_var;
  302. }
  303. }
  304. $rewrite_vars = array_diff( array_keys( $wp_query->query ), array_keys( $_GET ) );
  305. // Check to see if all the query vars are coming from the rewrite, none are set via $_GET.
  306. if ( ! array_diff( $rewrite_vars, array_keys( $_GET ) ) ) {
  307. // Remove all of the per-tax query vars.
  308. $redirect['query'] = remove_query_arg( $qv_remove, $redirect['query'] );
  309. // Create the destination URL for this taxonomy.
  310. $tax_url = parse_url( $tax_url );
  311. if ( ! empty( $tax_url['query'] ) ) {
  312. // Taxonomy accessible via ?taxonomy=...&term=... or any custom query var.
  313. parse_str( $tax_url['query'], $query_vars );
  314. $redirect['query'] = add_query_arg( $query_vars, $redirect['query'] );
  315. } else {
  316. // Taxonomy is accessible via a "pretty URL".
  317. $redirect['path'] = $tax_url['path'];
  318. }
  319. } else {
  320. // Some query vars are set via $_GET. Unset those from $_GET that exist via the rewrite.
  321. foreach ( $qv_remove as $_qv ) {
  322. if ( isset( $rewrite_vars[ $_qv ] ) ) {
  323. $redirect['query'] = remove_query_arg( $_qv, $redirect['query'] );
  324. }
  325. }
  326. }
  327. }
  328. }
  329. }
  330. } elseif ( is_single() && strpos( $wp_rewrite->permalink_structure, '%category%' ) !== false ) {
  331. $category_name = get_query_var( 'category_name' );
  332. if ( $category_name ) {
  333. $category = get_category_by_path( $category_name );
  334. if ( ! $category || is_wp_error( $category )
  335. || ! has_term( $category->term_id, 'category', $wp_query->get_queried_object_id() )
  336. ) {
  337. $redirect_url = get_permalink( $wp_query->get_queried_object_id() );
  338. $redirect_obj = get_post( $wp_query->get_queried_object_id() );
  339. }
  340. }
  341. }
  342. // Post paging.
  343. if ( is_singular() && get_query_var( 'page' ) ) {
  344. $page = get_query_var( 'page' );
  345. if ( ! $redirect_url ) {
  346. $redirect_url = get_permalink( get_queried_object_id() );
  347. $redirect_obj = get_post( get_queried_object_id() );
  348. }
  349. if ( $page > 1 ) {
  350. $redirect_url = trailingslashit( $redirect_url );
  351. if ( is_front_page() ) {
  352. $redirect_url .= user_trailingslashit( "$wp_rewrite->pagination_base/$page", 'paged' );
  353. } else {
  354. $redirect_url .= user_trailingslashit( $page, 'single_paged' );
  355. }
  356. }
  357. $redirect['query'] = remove_query_arg( 'page', $redirect['query'] );
  358. }
  359. if ( get_query_var( 'sitemap' ) ) {
  360. $redirect_url = get_sitemap_url( get_query_var( 'sitemap' ), get_query_var( 'sitemap-subtype' ), get_query_var( 'paged' ) );
  361. $redirect['query'] = remove_query_arg( array( 'sitemap', 'sitemap-subtype', 'paged' ), $redirect['query'] );
  362. } elseif ( get_query_var( 'paged' ) || is_feed() || get_query_var( 'cpage' ) ) {
  363. // Paging and feeds.
  364. $paged = get_query_var( 'paged' );
  365. $feed = get_query_var( 'feed' );
  366. $cpage = get_query_var( 'cpage' );
  367. while ( preg_match( "#/$wp_rewrite->pagination_base/?[0-9]+?(/+)?$#", $redirect['path'] )
  368. || preg_match( '#/(comments/?)?(feed|rss2?|rdf|atom)(/+)?$#', $redirect['path'] )
  369. || preg_match( "#/{$wp_rewrite->comments_pagination_base}-[0-9]+(/+)?$#", $redirect['path'] )
  370. ) {
  371. // Strip off any existing paging.
  372. $redirect['path'] = preg_replace( "#/$wp_rewrite->pagination_base/?[0-9]+?(/+)?$#", '/', $redirect['path'] );
  373. // Strip off feed endings.
  374. $redirect['path'] = preg_replace( '#/(comments/?)?(feed|rss2?|rdf|atom)(/+|$)#', '/', $redirect['path'] );
  375. // Strip off any existing comment paging.
  376. $redirect['path'] = preg_replace( "#/{$wp_rewrite->comments_pagination_base}-[0-9]+?(/+)?$#", '/', $redirect['path'] );
  377. }
  378. $addl_path = '';
  379. $default_feed = get_default_feed();
  380. if ( is_feed() && in_array( $feed, $wp_rewrite->feeds, true ) ) {
  381. $addl_path = ! empty( $addl_path ) ? trailingslashit( $addl_path ) : '';
  382. if ( ! is_singular() && get_query_var( 'withcomments' ) ) {
  383. $addl_path .= 'comments/';
  384. }
  385. if ( ( 'rss' === $default_feed && 'feed' === $feed ) || 'rss' === $feed ) {
  386. $format = ( 'rss2' === $default_feed ) ? '' : 'rss2';
  387. } else {
  388. $format = ( $default_feed === $feed || 'feed' === $feed ) ? '' : $feed;
  389. }
  390. $addl_path .= user_trailingslashit( 'feed/' . $format, 'feed' );
  391. $redirect['query'] = remove_query_arg( 'feed', $redirect['query'] );
  392. } elseif ( is_feed() && 'old' === $feed ) {
  393. $old_feed_files = array(
  394. 'wp-atom.php' => 'atom',
  395. 'wp-commentsrss2.php' => 'comments_rss2',
  396. 'wp-feed.php' => $default_feed,
  397. 'wp-rdf.php' => 'rdf',
  398. 'wp-rss.php' => 'rss2',
  399. 'wp-rss2.php' => 'rss2',
  400. );
  401. if ( isset( $old_feed_files[ basename( $redirect['path'] ) ] ) ) {
  402. $redirect_url = get_feed_link( $old_feed_files[ basename( $redirect['path'] ) ] );
  403. wp_redirect( $redirect_url, 301 );
  404. die();
  405. }
  406. }
  407. if ( $paged > 0 ) {
  408. $redirect['query'] = remove_query_arg( 'paged', $redirect['query'] );
  409. if ( ! is_feed() ) {
  410. if ( ! is_single() ) {
  411. $addl_path = ! empty( $addl_path ) ? trailingslashit( $addl_path ) : '';
  412. if ( $paged > 1 ) {
  413. $addl_path .= user_trailingslashit( "$wp_rewrite->pagination_base/$paged", 'paged' );
  414. }
  415. }
  416. } elseif ( $paged > 1 ) {
  417. $redirect['query'] = add_query_arg( 'paged', $paged, $redirect['query'] );
  418. }
  419. }
  420. $default_comments_page = get_option( 'default_comments_page' );
  421. if ( get_option( 'page_comments' )
  422. && ( 'newest' === $default_comments_page && $cpage > 0
  423. || 'newest' !== $default_comments_page && $cpage > 1 )
  424. ) {
  425. $addl_path = ( ! empty( $addl_path ) ? trailingslashit( $addl_path ) : '' );
  426. $addl_path .= user_trailingslashit( $wp_rewrite->comments_pagination_base . '-' . $cpage, 'commentpaged' );
  427. $redirect['query'] = remove_query_arg( 'cpage', $redirect['query'] );
  428. }
  429. // Strip off trailing /index.php/.
  430. $redirect['path'] = preg_replace( '|/' . preg_quote( $wp_rewrite->index, '|' ) . '/?$|', '/', $redirect['path'] );
  431. $redirect['path'] = user_trailingslashit( $redirect['path'] );
  432. if ( ! empty( $addl_path )
  433. && $wp_rewrite->using_index_permalinks()
  434. && strpos( $redirect['path'], '/' . $wp_rewrite->index . '/' ) === false
  435. ) {
  436. $redirect['path'] = trailingslashit( $redirect['path'] ) . $wp_rewrite->index . '/';
  437. }
  438. if ( ! empty( $addl_path ) ) {
  439. $redirect['path'] = trailingslashit( $redirect['path'] ) . $addl_path;
  440. }
  441. $redirect_url = $redirect['scheme'] . '://' . $redirect['host'] . $redirect['path'];
  442. }
  443. if ( 'wp-register.php' === basename( $redirect['path'] ) ) {
  444. if ( is_multisite() ) {
  445. /** This filter is documented in wp-login.php */
  446. $redirect_url = apply_filters( 'wp_signup_location', network_site_url( 'wp-signup.php' ) );
  447. } else {
  448. $redirect_url = wp_registration_url();
  449. }
  450. wp_redirect( $redirect_url, 301 );
  451. die();
  452. }
  453. }
  454. $redirect['query'] = preg_replace( '#^\??&*?#', '', $redirect['query'] );
  455. // Tack on any additional query vars.
  456. if ( $redirect_url && ! empty( $redirect['query'] ) ) {
  457. parse_str( $redirect['query'], $_parsed_query );
  458. $redirect = parse_url( $redirect_url );
  459. if ( ! empty( $_parsed_query['name'] ) && ! empty( $redirect['query'] ) ) {
  460. parse_str( $redirect['query'], $_parsed_redirect_query );
  461. if ( empty( $_parsed_redirect_query['name'] ) ) {
  462. unset( $_parsed_query['name'] );
  463. }
  464. }
  465. $_parsed_query = array_combine(
  466. rawurlencode_deep( array_keys( $_parsed_query ) ),
  467. rawurlencode_deep( array_values( $_parsed_query ) )
  468. );
  469. $redirect_url = add_query_arg( $_parsed_query, $redirect_url );
  470. }
  471. if ( $redirect_url ) {
  472. $redirect = parse_url( $redirect_url );
  473. }
  474. // www.example.com vs. example.com
  475. $user_home = parse_url( home_url() );
  476. if ( ! empty( $user_home['host'] ) ) {
  477. $redirect['host'] = $user_home['host'];
  478. }
  479. if ( empty( $user_home['path'] ) ) {
  480. $user_home['path'] = '/';
  481. }
  482. // Handle ports.
  483. if ( ! empty( $user_home['port'] ) ) {
  484. $redirect['port'] = $user_home['port'];
  485. } else {
  486. unset( $redirect['port'] );
  487. }
  488. // Trailing /index.php.
  489. $redirect['path'] = preg_replace( '|/' . preg_quote( $wp_rewrite->index, '|' ) . '/*?$|', '/', $redirect['path'] );
  490. $punctuation_pattern = implode(
  491. '|',
  492. array_map(
  493. 'preg_quote',
  494. array(
  495. ' ',
  496. '%20', // Space.
  497. '!',
  498. '%21', // Exclamation mark.
  499. '"',
  500. '%22', // Double quote.
  501. "'",
  502. '%27', // Single quote.
  503. '(',
  504. '%28', // Opening bracket.
  505. ')',
  506. '%29', // Closing bracket.
  507. ',',
  508. '%2C', // Comma.
  509. '.',
  510. '%2E', // Period.
  511. ';',
  512. '%3B', // Semicolon.
  513. '{',
  514. '%7B', // Opening curly bracket.
  515. '}',
  516. '%7D', // Closing curly bracket.
  517. '%E2%80%9C', // Opening curly quote.
  518. '%E2%80%9D', // Closing curly quote.
  519. )
  520. )
  521. );
  522. // Remove trailing spaces and end punctuation from the path.
  523. $redirect['path'] = preg_replace( "#($punctuation_pattern)+$#", '', $redirect['path'] );
  524. if ( ! empty( $redirect['query'] ) ) {
  525. // Remove trailing spaces and end punctuation from certain terminating query string args.
  526. $redirect['query'] = preg_replace( "#((^|&)(p|page_id|cat|tag)=[^&]*?)($punctuation_pattern)+$#", '$1', $redirect['query'] );
  527. // Clean up empty query strings.
  528. $redirect['query'] = trim( preg_replace( '#(^|&)(p|page_id|cat|tag)=?(&|$)#', '&', $redirect['query'] ), '&' );
  529. // Redirect obsolete feeds.
  530. $redirect['query'] = preg_replace( '#(^|&)feed=rss(&|$)#', '$1feed=rss2$2', $redirect['query'] );
  531. // Remove redundant leading ampersands.
  532. $redirect['query'] = preg_replace( '#^\??&*?#', '', $redirect['query'] );
  533. }
  534. // Strip /index.php/ when we're not using PATHINFO permalinks.
  535. if ( ! $wp_rewrite->using_index_permalinks() ) {
  536. $redirect['path'] = str_replace( '/' . $wp_rewrite->index . '/', '/', $redirect['path'] );
  537. }
  538. // Trailing slashes.
  539. if ( is_object( $wp_rewrite ) && $wp_rewrite->using_permalinks()
  540. && ! is_404() && ( ! is_front_page() || is_front_page() && get_query_var( 'paged' ) > 1 )
  541. ) {
  542. $user_ts_type = '';
  543. if ( get_query_var( 'paged' ) > 0 ) {
  544. $user_ts_type = 'paged';
  545. } else {
  546. foreach ( array( 'single', 'category', 'page', 'day', 'month', 'year', 'home' ) as $type ) {
  547. $func = 'is_' . $type;
  548. if ( call_user_func( $func ) ) {
  549. $user_ts_type = $type;
  550. break;
  551. }
  552. }
  553. }
  554. $redirect['path'] = user_trailingslashit( $redirect['path'], $user_ts_type );
  555. } elseif ( is_front_page() ) {
  556. $redirect['path'] = trailingslashit( $redirect['path'] );
  557. }
  558. // Remove trailing slash for robots.txt or sitemap requests.
  559. if ( is_robots()
  560. || ! empty( get_query_var( 'sitemap' ) ) || ! empty( get_query_var( 'sitemap-stylesheet' ) )
  561. ) {
  562. $redirect['path'] = untrailingslashit( $redirect['path'] );
  563. }
  564. // Strip multiple slashes out of the URL.
  565. if ( strpos( $redirect['path'], '//' ) > -1 ) {
  566. $redirect['path'] = preg_replace( '|/+|', '/', $redirect['path'] );
  567. }
  568. // Always trailing slash the Front Page URL.
  569. if ( trailingslashit( $redirect['path'] ) === trailingslashit( $user_home['path'] ) ) {
  570. $redirect['path'] = trailingslashit( $redirect['path'] );
  571. }
  572. $original_host_low = strtolower( $original['host'] );
  573. $redirect_host_low = strtolower( $redirect['host'] );
  574. // Ignore differences in host capitalization, as this can lead to infinite redirects.
  575. // Only redirect no-www <=> yes-www.
  576. if ( $original_host_low === $redirect_host_low
  577. || ( 'www.' . $original_host_low !== $redirect_host_low
  578. && 'www.' . $redirect_host_low !== $original_host_low )
  579. ) {
  580. $redirect['host'] = $original['host'];
  581. }
  582. $compare_original = array( $original['host'], $original['path'] );
  583. if ( ! empty( $original['port'] ) ) {
  584. $compare_original[] = $original['port'];
  585. }
  586. if ( ! empty( $original['query'] ) ) {
  587. $compare_original[] = $original['query'];
  588. }
  589. $compare_redirect = array( $redirect['host'], $redirect['path'] );
  590. if ( ! empty( $redirect['port'] ) ) {
  591. $compare_redirect[] = $redirect['port'];
  592. }
  593. if ( ! empty( $redirect['query'] ) ) {
  594. $compare_redirect[] = $redirect['query'];
  595. }
  596. if ( $compare_original !== $compare_redirect ) {
  597. $redirect_url = $redirect['scheme'] . '://' . $redirect['host'];
  598. if ( ! empty( $redirect['port'] ) ) {
  599. $redirect_url .= ':' . $redirect['port'];
  600. }
  601. $redirect_url .= $redirect['path'];
  602. if ( ! empty( $redirect['query'] ) ) {
  603. $redirect_url .= '?' . $redirect['query'];
  604. }
  605. }
  606. if ( ! $redirect_url || $redirect_url === $requested_url ) {
  607. return;
  608. }
  609. // Hex encoded octets are case-insensitive.
  610. if ( false !== strpos( $requested_url, '%' ) ) {
  611. if ( ! function_exists( 'lowercase_octets' ) ) {
  612. /**
  613. * Converts the first hex-encoded octet match to lowercase.
  614. *
  615. * @since 3.1.0
  616. * @ignore
  617. *
  618. * @param array $matches Hex-encoded octet matches for the requested URL.
  619. * @return string Lowercased version of the first match.
  620. */
  621. function lowercase_octets( $matches ) {
  622. return strtolower( $matches[0] );
  623. }
  624. }
  625. $requested_url = preg_replace_callback( '|%[a-fA-F0-9][a-fA-F0-9]|', 'lowercase_octets', $requested_url );
  626. }
  627. if ( $redirect_obj instanceof WP_Post ) {
  628. $post_status_obj = get_post_status_object( get_post_status( $redirect_obj ) );
  629. /*
  630. * Unset the redirect object and URL if they are not readable by the user.
  631. * This condition is a little confusing as the condition needs to pass if
  632. * the post is not readable by the user. That's why there are ! (not) conditions
  633. * throughout.
  634. */
  635. if (
  636. // Private post statuses only redirect if the user can read them.
  637. ! (
  638. $post_status_obj->private &&
  639. current_user_can( 'read_post', $redirect_obj->ID )
  640. ) &&
  641. // For other posts, only redirect if publicly viewable.
  642. ! is_post_publicly_viewable( $redirect_obj )
  643. ) {
  644. $redirect_obj = false;
  645. $redirect_url = false;
  646. }
  647. }
  648. /**
  649. * Filters the canonical redirect URL.
  650. *
  651. * Returning false to this filter will cancel the redirect.
  652. *
  653. * @since 2.3.0
  654. *
  655. * @param string $redirect_url The redirect URL.
  656. * @param string $requested_url The requested URL.
  657. */
  658. $redirect_url = apply_filters( 'redirect_canonical', $redirect_url, $requested_url );
  659. // Yes, again -- in case the filter aborted the request.
  660. if ( ! $redirect_url || strip_fragment_from_url( $redirect_url ) === strip_fragment_from_url( $requested_url ) ) {
  661. return;
  662. }
  663. if ( $do_redirect ) {
  664. // Protect against chained redirects.
  665. if ( ! redirect_canonical( $redirect_url, false ) ) {
  666. wp_redirect( $redirect_url, 301 );
  667. exit;
  668. } else {
  669. // Debug.
  670. // die("1: $redirect_url<br />2: " . redirect_canonical( $redirect_url, false ) );
  671. return;
  672. }
  673. } else {
  674. return $redirect_url;
  675. }
  676. }
  677. /**
  678. * Removes arguments from a query string if they are not present in a URL
  679. * DO NOT use this in plugin code.
  680. *
  681. * @since 3.4.0
  682. * @access private
  683. *
  684. * @param string $query_string
  685. * @param array $args_to_check
  686. * @param string $url
  687. * @return string The altered query string
  688. */
  689. function _remove_qs_args_if_not_in_url( $query_string, array $args_to_check, $url ) {
  690. $parsed_url = parse_url( $url );
  691. if ( ! empty( $parsed_url['query'] ) ) {
  692. parse_str( $parsed_url['query'], $parsed_query );
  693. foreach ( $args_to_check as $qv ) {
  694. if ( ! isset( $parsed_query[ $qv ] ) ) {
  695. $query_string = remove_query_arg( $qv, $query_string );
  696. }
  697. }
  698. } else {
  699. $query_string = remove_query_arg( $args_to_check, $query_string );
  700. }
  701. return $query_string;
  702. }
  703. /**
  704. * Strips the #fragment from a URL, if one is present.
  705. *
  706. * @since 4.4.0
  707. *
  708. * @param string $url The URL to strip.
  709. * @return string The altered URL.
  710. */
  711. function strip_fragment_from_url( $url ) {
  712. $parsed_url = parse_url( $url );
  713. if ( ! empty( $parsed_url['host'] ) ) {
  714. // This mirrors code in redirect_canonical(). It does not handle every case.
  715. $url = $parsed_url['scheme'] . '://' . $parsed_url['host'];
  716. if ( ! empty( $parsed_url['port'] ) ) {
  717. $url .= ':' . $parsed_url['port'];
  718. }
  719. if ( ! empty( $parsed_url['path'] ) ) {
  720. $url .= $parsed_url['path'];
  721. }
  722. if ( ! empty( $parsed_url['query'] ) ) {
  723. $url .= '?' . $parsed_url['query'];
  724. }
  725. }
  726. return $url;
  727. }
  728. /**
  729. * Attempts to guess the correct URL for a 404 request based on query vars.
  730. *
  731. * @since 2.3.0
  732. *
  733. * @global wpdb $wpdb WordPress database abstraction object.
  734. *
  735. * @return string|false The correct URL if one is found. False on failure.
  736. */
  737. function redirect_guess_404_permalink() {
  738. global $wpdb;
  739. /**
  740. * Filters whether to attempt to guess a redirect URL for a 404 request.
  741. *
  742. * Returning a false value from the filter will disable the URL guessing
  743. * and return early without performing a redirect.
  744. *
  745. * @since 5.5.0
  746. *
  747. * @param bool $do_redirect_guess Whether to attempt to guess a redirect URL
  748. * for a 404 request. Default true.
  749. */
  750. if ( false === apply_filters( 'do_redirect_guess_404_permalink', true ) ) {
  751. return false;
  752. }
  753. /**
  754. * Short-circuits the redirect URL guessing for 404 requests.
  755. *
  756. * Returning a non-null value from the filter will effectively short-circuit
  757. * the URL guessing, returning the passed value instead.
  758. *
  759. * @since 5.5.0
  760. *
  761. * @param null|string|false $pre Whether to short-circuit guessing the redirect for a 404.
  762. * Default null to continue with the URL guessing.
  763. */
  764. $pre = apply_filters( 'pre_redirect_guess_404_permalink', null );
  765. if ( null !== $pre ) {
  766. return $pre;
  767. }
  768. if ( get_query_var( 'name' ) ) {
  769. /**
  770. * Filters whether to perform a strict guess for a 404 redirect.
  771. *
  772. * Returning a truthy value from the filter will redirect only exact post_name matches.
  773. *
  774. * @since 5.5.0
  775. *
  776. * @param bool $strict_guess Whether to perform a strict guess. Default false (loose guess).
  777. */
  778. $strict_guess = apply_filters( 'strict_redirect_guess_404_permalink', false );
  779. if ( $strict_guess ) {
  780. $where = $wpdb->prepare( 'post_name = %s', get_query_var( 'name' ) );
  781. } else {
  782. $where = $wpdb->prepare( 'post_name LIKE %s', $wpdb->esc_like( get_query_var( 'name' ) ) . '%' );
  783. }
  784. // If any of post_type, year, monthnum, or day are set, use them to refine the query.
  785. if ( get_query_var( 'post_type' ) ) {
  786. if ( is_array( get_query_var( 'post_type' ) ) ) {
  787. // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
  788. $where .= " AND post_type IN ('" . join( "', '", esc_sql( get_query_var( 'post_type' ) ) ) . "')";
  789. } else {
  790. $where .= $wpdb->prepare( ' AND post_type = %s', get_query_var( 'post_type' ) );
  791. }
  792. } else {
  793. $where .= " AND post_type IN ('" . implode( "', '", get_post_types( array( 'public' => true ) ) ) . "')";
  794. }
  795. if ( get_query_var( 'year' ) ) {
  796. $where .= $wpdb->prepare( ' AND YEAR(post_date) = %d', get_query_var( 'year' ) );
  797. }
  798. if ( get_query_var( 'monthnum' ) ) {
  799. $where .= $wpdb->prepare( ' AND MONTH(post_date) = %d', get_query_var( 'monthnum' ) );
  800. }
  801. if ( get_query_var( 'day' ) ) {
  802. $where .= $wpdb->prepare( ' AND DAYOFMONTH(post_date) = %d', get_query_var( 'day' ) );
  803. }
  804. // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
  805. $post_id = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE $where AND post_status = 'publish'" );
  806. if ( ! $post_id ) {
  807. return false;
  808. }
  809. if ( get_query_var( 'feed' ) ) {
  810. return get_post_comments_feed_link( $post_id, get_query_var( 'feed' ) );
  811. } elseif ( get_query_var( 'page' ) > 1 ) {
  812. return trailingslashit( get_permalink( $post_id ) ) . user_trailingslashit( get_query_var( 'page' ), 'single_paged' );
  813. } else {
  814. return get_permalink( $post_id );
  815. }
  816. }
  817. return false;
  818. }
  819. /**
  820. * Redirects a variety of shorthand URLs to the admin.
  821. *
  822. * If a user visits example.com/admin, they'll be redirected to /wp-admin.
  823. * Visiting /login redirects to /wp-login.php, and so on.
  824. *
  825. * @since 3.4.0
  826. *
  827. * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
  828. */
  829. function wp_redirect_admin_locations() {
  830. global $wp_rewrite;
  831. if ( ! ( is_404() && $wp_rewrite->using_permalinks() ) ) {
  832. return;
  833. }
  834. $admins = array(
  835. home_url( 'wp-admin', 'relative' ),
  836. home_url( 'dashboard', 'relative' ),
  837. home_url( 'admin', 'relative' ),
  838. site_url( 'dashboard', 'relative' ),
  839. site_url( 'admin', 'relative' ),
  840. );
  841. if ( in_array( untrailingslashit( $_SERVER['REQUEST_URI'] ), $admins, true ) ) {
  842. wp_redirect( admin_url() );
  843. exit;
  844. }
  845. $logins = array(
  846. home_url( 'wp-login.php', 'relative' ),
  847. home_url( 'login', 'relative' ),
  848. site_url( 'login', 'relative' ),
  849. );
  850. if ( in_array( untrailingslashit( $_SERVER['REQUEST_URI'] ), $logins, true ) ) {
  851. wp_redirect( wp_login_url() );
  852. exit;
  853. }
  854. }