canonical.php 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022
  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. if ( isset( $tax_query['terms'] ) && is_countable( $tax_query['terms'] ) ) {
  283. $term_count += count( $tax_query['terms'] );
  284. }
  285. }
  286. $obj = $wp_query->get_queried_object();
  287. if ( $term_count <= 1 && ! empty( $obj->term_id ) ) {
  288. $tax_url = get_term_link( (int) $obj->term_id, $obj->taxonomy );
  289. if ( $tax_url && ! is_wp_error( $tax_url ) ) {
  290. if ( ! empty( $redirect['query'] ) ) {
  291. // Strip taxonomy query vars off the URL.
  292. $qv_remove = array( 'term', 'taxonomy' );
  293. if ( is_category() ) {
  294. $qv_remove[] = 'category_name';
  295. $qv_remove[] = 'cat';
  296. } elseif ( is_tag() ) {
  297. $qv_remove[] = 'tag';
  298. $qv_remove[] = 'tag_id';
  299. } else {
  300. // Custom taxonomies will have a custom query var, remove those too.
  301. $tax_obj = get_taxonomy( $obj->taxonomy );
  302. if ( false !== $tax_obj->query_var ) {
  303. $qv_remove[] = $tax_obj->query_var;
  304. }
  305. }
  306. $rewrite_vars = array_diff( array_keys( $wp_query->query ), array_keys( $_GET ) );
  307. // Check to see if all the query vars are coming from the rewrite, none are set via $_GET.
  308. if ( ! array_diff( $rewrite_vars, array_keys( $_GET ) ) ) {
  309. // Remove all of the per-tax query vars.
  310. $redirect['query'] = remove_query_arg( $qv_remove, $redirect['query'] );
  311. // Create the destination URL for this taxonomy.
  312. $tax_url = parse_url( $tax_url );
  313. if ( ! empty( $tax_url['query'] ) ) {
  314. // Taxonomy accessible via ?taxonomy=...&term=... or any custom query var.
  315. parse_str( $tax_url['query'], $query_vars );
  316. $redirect['query'] = add_query_arg( $query_vars, $redirect['query'] );
  317. } else {
  318. // Taxonomy is accessible via a "pretty URL".
  319. $redirect['path'] = $tax_url['path'];
  320. }
  321. } else {
  322. // Some query vars are set via $_GET. Unset those from $_GET that exist via the rewrite.
  323. foreach ( $qv_remove as $_qv ) {
  324. if ( isset( $rewrite_vars[ $_qv ] ) ) {
  325. $redirect['query'] = remove_query_arg( $_qv, $redirect['query'] );
  326. }
  327. }
  328. }
  329. }
  330. }
  331. }
  332. } elseif ( is_single() && strpos( $wp_rewrite->permalink_structure, '%category%' ) !== false ) {
  333. $category_name = get_query_var( 'category_name' );
  334. if ( $category_name ) {
  335. $category = get_category_by_path( $category_name );
  336. if ( ! $category || is_wp_error( $category )
  337. || ! has_term( $category->term_id, 'category', $wp_query->get_queried_object_id() )
  338. ) {
  339. $redirect_url = get_permalink( $wp_query->get_queried_object_id() );
  340. $redirect_obj = get_post( $wp_query->get_queried_object_id() );
  341. }
  342. }
  343. }
  344. // Post paging.
  345. if ( is_singular() && get_query_var( 'page' ) ) {
  346. $page = get_query_var( 'page' );
  347. if ( ! $redirect_url ) {
  348. $redirect_url = get_permalink( get_queried_object_id() );
  349. $redirect_obj = get_post( get_queried_object_id() );
  350. }
  351. if ( $page > 1 ) {
  352. $redirect_url = trailingslashit( $redirect_url );
  353. if ( is_front_page() ) {
  354. $redirect_url .= user_trailingslashit( "$wp_rewrite->pagination_base/$page", 'paged' );
  355. } else {
  356. $redirect_url .= user_trailingslashit( $page, 'single_paged' );
  357. }
  358. }
  359. $redirect['query'] = remove_query_arg( 'page', $redirect['query'] );
  360. }
  361. if ( get_query_var( 'sitemap' ) ) {
  362. $redirect_url = get_sitemap_url( get_query_var( 'sitemap' ), get_query_var( 'sitemap-subtype' ), get_query_var( 'paged' ) );
  363. $redirect['query'] = remove_query_arg( array( 'sitemap', 'sitemap-subtype', 'paged' ), $redirect['query'] );
  364. } elseif ( get_query_var( 'paged' ) || is_feed() || get_query_var( 'cpage' ) ) {
  365. // Paging and feeds.
  366. $paged = get_query_var( 'paged' );
  367. $feed = get_query_var( 'feed' );
  368. $cpage = get_query_var( 'cpage' );
  369. while ( preg_match( "#/$wp_rewrite->pagination_base/?[0-9]+?(/+)?$#", $redirect['path'] )
  370. || preg_match( '#/(comments/?)?(feed|rss2?|rdf|atom)(/+)?$#', $redirect['path'] )
  371. || preg_match( "#/{$wp_rewrite->comments_pagination_base}-[0-9]+(/+)?$#", $redirect['path'] )
  372. ) {
  373. // Strip off any existing paging.
  374. $redirect['path'] = preg_replace( "#/$wp_rewrite->pagination_base/?[0-9]+?(/+)?$#", '/', $redirect['path'] );
  375. // Strip off feed endings.
  376. $redirect['path'] = preg_replace( '#/(comments/?)?(feed|rss2?|rdf|atom)(/+|$)#', '/', $redirect['path'] );
  377. // Strip off any existing comment paging.
  378. $redirect['path'] = preg_replace( "#/{$wp_rewrite->comments_pagination_base}-[0-9]+?(/+)?$#", '/', $redirect['path'] );
  379. }
  380. $addl_path = '';
  381. $default_feed = get_default_feed();
  382. if ( is_feed() && in_array( $feed, $wp_rewrite->feeds, true ) ) {
  383. $addl_path = ! empty( $addl_path ) ? trailingslashit( $addl_path ) : '';
  384. if ( ! is_singular() && get_query_var( 'withcomments' ) ) {
  385. $addl_path .= 'comments/';
  386. }
  387. if ( ( 'rss' === $default_feed && 'feed' === $feed ) || 'rss' === $feed ) {
  388. $format = ( 'rss2' === $default_feed ) ? '' : 'rss2';
  389. } else {
  390. $format = ( $default_feed === $feed || 'feed' === $feed ) ? '' : $feed;
  391. }
  392. $addl_path .= user_trailingslashit( 'feed/' . $format, 'feed' );
  393. $redirect['query'] = remove_query_arg( 'feed', $redirect['query'] );
  394. } elseif ( is_feed() && 'old' === $feed ) {
  395. $old_feed_files = array(
  396. 'wp-atom.php' => 'atom',
  397. 'wp-commentsrss2.php' => 'comments_rss2',
  398. 'wp-feed.php' => $default_feed,
  399. 'wp-rdf.php' => 'rdf',
  400. 'wp-rss.php' => 'rss2',
  401. 'wp-rss2.php' => 'rss2',
  402. );
  403. if ( isset( $old_feed_files[ basename( $redirect['path'] ) ] ) ) {
  404. $redirect_url = get_feed_link( $old_feed_files[ basename( $redirect['path'] ) ] );
  405. wp_redirect( $redirect_url, 301 );
  406. die();
  407. }
  408. }
  409. if ( $paged > 0 ) {
  410. $redirect['query'] = remove_query_arg( 'paged', $redirect['query'] );
  411. if ( ! is_feed() ) {
  412. if ( ! is_single() ) {
  413. $addl_path = ! empty( $addl_path ) ? trailingslashit( $addl_path ) : '';
  414. if ( $paged > 1 ) {
  415. $addl_path .= user_trailingslashit( "$wp_rewrite->pagination_base/$paged", 'paged' );
  416. }
  417. }
  418. } elseif ( $paged > 1 ) {
  419. $redirect['query'] = add_query_arg( 'paged', $paged, $redirect['query'] );
  420. }
  421. }
  422. $default_comments_page = get_option( 'default_comments_page' );
  423. if ( get_option( 'page_comments' )
  424. && ( 'newest' === $default_comments_page && $cpage > 0
  425. || 'newest' !== $default_comments_page && $cpage > 1 )
  426. ) {
  427. $addl_path = ( ! empty( $addl_path ) ? trailingslashit( $addl_path ) : '' );
  428. $addl_path .= user_trailingslashit( $wp_rewrite->comments_pagination_base . '-' . $cpage, 'commentpaged' );
  429. $redirect['query'] = remove_query_arg( 'cpage', $redirect['query'] );
  430. }
  431. // Strip off trailing /index.php/.
  432. $redirect['path'] = preg_replace( '|/' . preg_quote( $wp_rewrite->index, '|' ) . '/?$|', '/', $redirect['path'] );
  433. $redirect['path'] = user_trailingslashit( $redirect['path'] );
  434. if ( ! empty( $addl_path )
  435. && $wp_rewrite->using_index_permalinks()
  436. && strpos( $redirect['path'], '/' . $wp_rewrite->index . '/' ) === false
  437. ) {
  438. $redirect['path'] = trailingslashit( $redirect['path'] ) . $wp_rewrite->index . '/';
  439. }
  440. if ( ! empty( $addl_path ) ) {
  441. $redirect['path'] = trailingslashit( $redirect['path'] ) . $addl_path;
  442. }
  443. $redirect_url = $redirect['scheme'] . '://' . $redirect['host'] . $redirect['path'];
  444. }
  445. if ( 'wp-register.php' === basename( $redirect['path'] ) ) {
  446. if ( is_multisite() ) {
  447. /** This filter is documented in wp-login.php */
  448. $redirect_url = apply_filters( 'wp_signup_location', network_site_url( 'wp-signup.php' ) );
  449. } else {
  450. $redirect_url = wp_registration_url();
  451. }
  452. wp_redirect( $redirect_url, 301 );
  453. die();
  454. }
  455. }
  456. $redirect['query'] = preg_replace( '#^\??&*?#', '', $redirect['query'] );
  457. // Tack on any additional query vars.
  458. if ( $redirect_url && ! empty( $redirect['query'] ) ) {
  459. parse_str( $redirect['query'], $_parsed_query );
  460. $redirect = parse_url( $redirect_url );
  461. if ( ! empty( $_parsed_query['name'] ) && ! empty( $redirect['query'] ) ) {
  462. parse_str( $redirect['query'], $_parsed_redirect_query );
  463. if ( empty( $_parsed_redirect_query['name'] ) ) {
  464. unset( $_parsed_query['name'] );
  465. }
  466. }
  467. $_parsed_query = array_combine(
  468. rawurlencode_deep( array_keys( $_parsed_query ) ),
  469. rawurlencode_deep( array_values( $_parsed_query ) )
  470. );
  471. $redirect_url = add_query_arg( $_parsed_query, $redirect_url );
  472. }
  473. if ( $redirect_url ) {
  474. $redirect = parse_url( $redirect_url );
  475. }
  476. // www.example.com vs. example.com
  477. $user_home = parse_url( home_url() );
  478. if ( ! empty( $user_home['host'] ) ) {
  479. $redirect['host'] = $user_home['host'];
  480. }
  481. if ( empty( $user_home['path'] ) ) {
  482. $user_home['path'] = '/';
  483. }
  484. // Handle ports.
  485. if ( ! empty( $user_home['port'] ) ) {
  486. $redirect['port'] = $user_home['port'];
  487. } else {
  488. unset( $redirect['port'] );
  489. }
  490. // Trailing /index.php.
  491. $redirect['path'] = preg_replace( '|/' . preg_quote( $wp_rewrite->index, '|' ) . '/*?$|', '/', $redirect['path'] );
  492. $punctuation_pattern = implode(
  493. '|',
  494. array_map(
  495. 'preg_quote',
  496. array(
  497. ' ',
  498. '%20', // Space.
  499. '!',
  500. '%21', // Exclamation mark.
  501. '"',
  502. '%22', // Double quote.
  503. "'",
  504. '%27', // Single quote.
  505. '(',
  506. '%28', // Opening bracket.
  507. ')',
  508. '%29', // Closing bracket.
  509. ',',
  510. '%2C', // Comma.
  511. '.',
  512. '%2E', // Period.
  513. ';',
  514. '%3B', // Semicolon.
  515. '{',
  516. '%7B', // Opening curly bracket.
  517. '}',
  518. '%7D', // Closing curly bracket.
  519. '%E2%80%9C', // Opening curly quote.
  520. '%E2%80%9D', // Closing curly quote.
  521. )
  522. )
  523. );
  524. // Remove trailing spaces and end punctuation from the path.
  525. $redirect['path'] = preg_replace( "#($punctuation_pattern)+$#", '', $redirect['path'] );
  526. if ( ! empty( $redirect['query'] ) ) {
  527. // Remove trailing spaces and end punctuation from certain terminating query string args.
  528. $redirect['query'] = preg_replace( "#((^|&)(p|page_id|cat|tag)=[^&]*?)($punctuation_pattern)+$#", '$1', $redirect['query'] );
  529. // Clean up empty query strings.
  530. $redirect['query'] = trim( preg_replace( '#(^|&)(p|page_id|cat|tag)=?(&|$)#', '&', $redirect['query'] ), '&' );
  531. // Redirect obsolete feeds.
  532. $redirect['query'] = preg_replace( '#(^|&)feed=rss(&|$)#', '$1feed=rss2$2', $redirect['query'] );
  533. // Remove redundant leading ampersands.
  534. $redirect['query'] = preg_replace( '#^\??&*?#', '', $redirect['query'] );
  535. }
  536. // Strip /index.php/ when we're not using PATHINFO permalinks.
  537. if ( ! $wp_rewrite->using_index_permalinks() ) {
  538. $redirect['path'] = str_replace( '/' . $wp_rewrite->index . '/', '/', $redirect['path'] );
  539. }
  540. // Trailing slashes.
  541. if ( is_object( $wp_rewrite ) && $wp_rewrite->using_permalinks()
  542. && ! is_404() && ( ! is_front_page() || is_front_page() && get_query_var( 'paged' ) > 1 )
  543. ) {
  544. $user_ts_type = '';
  545. if ( get_query_var( 'paged' ) > 0 ) {
  546. $user_ts_type = 'paged';
  547. } else {
  548. foreach ( array( 'single', 'category', 'page', 'day', 'month', 'year', 'home' ) as $type ) {
  549. $func = 'is_' . $type;
  550. if ( call_user_func( $func ) ) {
  551. $user_ts_type = $type;
  552. break;
  553. }
  554. }
  555. }
  556. $redirect['path'] = user_trailingslashit( $redirect['path'], $user_ts_type );
  557. } elseif ( is_front_page() ) {
  558. $redirect['path'] = trailingslashit( $redirect['path'] );
  559. }
  560. // Remove trailing slash for robots.txt or sitemap requests.
  561. if ( is_robots()
  562. || ! empty( get_query_var( 'sitemap' ) ) || ! empty( get_query_var( 'sitemap-stylesheet' ) )
  563. ) {
  564. $redirect['path'] = untrailingslashit( $redirect['path'] );
  565. }
  566. // Strip multiple slashes out of the URL.
  567. if ( strpos( $redirect['path'], '//' ) > -1 ) {
  568. $redirect['path'] = preg_replace( '|/+|', '/', $redirect['path'] );
  569. }
  570. // Always trailing slash the Front Page URL.
  571. if ( trailingslashit( $redirect['path'] ) === trailingslashit( $user_home['path'] ) ) {
  572. $redirect['path'] = trailingslashit( $redirect['path'] );
  573. }
  574. $original_host_low = strtolower( $original['host'] );
  575. $redirect_host_low = strtolower( $redirect['host'] );
  576. // Ignore differences in host capitalization, as this can lead to infinite redirects.
  577. // Only redirect no-www <=> yes-www.
  578. if ( $original_host_low === $redirect_host_low
  579. || ( 'www.' . $original_host_low !== $redirect_host_low
  580. && 'www.' . $redirect_host_low !== $original_host_low )
  581. ) {
  582. $redirect['host'] = $original['host'];
  583. }
  584. $compare_original = array( $original['host'], $original['path'] );
  585. if ( ! empty( $original['port'] ) ) {
  586. $compare_original[] = $original['port'];
  587. }
  588. if ( ! empty( $original['query'] ) ) {
  589. $compare_original[] = $original['query'];
  590. }
  591. $compare_redirect = array( $redirect['host'], $redirect['path'] );
  592. if ( ! empty( $redirect['port'] ) ) {
  593. $compare_redirect[] = $redirect['port'];
  594. }
  595. if ( ! empty( $redirect['query'] ) ) {
  596. $compare_redirect[] = $redirect['query'];
  597. }
  598. if ( $compare_original !== $compare_redirect ) {
  599. $redirect_url = $redirect['scheme'] . '://' . $redirect['host'];
  600. if ( ! empty( $redirect['port'] ) ) {
  601. $redirect_url .= ':' . $redirect['port'];
  602. }
  603. $redirect_url .= $redirect['path'];
  604. if ( ! empty( $redirect['query'] ) ) {
  605. $redirect_url .= '?' . $redirect['query'];
  606. }
  607. }
  608. if ( ! $redirect_url || $redirect_url === $requested_url ) {
  609. return;
  610. }
  611. // Hex encoded octets are case-insensitive.
  612. if ( false !== strpos( $requested_url, '%' ) ) {
  613. if ( ! function_exists( 'lowercase_octets' ) ) {
  614. /**
  615. * Converts the first hex-encoded octet match to lowercase.
  616. *
  617. * @since 3.1.0
  618. * @ignore
  619. *
  620. * @param array $matches Hex-encoded octet matches for the requested URL.
  621. * @return string Lowercased version of the first match.
  622. */
  623. function lowercase_octets( $matches ) {
  624. return strtolower( $matches[0] );
  625. }
  626. }
  627. $requested_url = preg_replace_callback( '|%[a-fA-F0-9][a-fA-F0-9]|', 'lowercase_octets', $requested_url );
  628. }
  629. if ( $redirect_obj instanceof WP_Post ) {
  630. $post_status_obj = get_post_status_object( get_post_status( $redirect_obj ) );
  631. /*
  632. * Unset the redirect object and URL if they are not readable by the user.
  633. * This condition is a little confusing as the condition needs to pass if
  634. * the post is not readable by the user. That's why there are ! (not) conditions
  635. * throughout.
  636. */
  637. if (
  638. // Private post statuses only redirect if the user can read them.
  639. ! (
  640. $post_status_obj->private &&
  641. current_user_can( 'read_post', $redirect_obj->ID )
  642. ) &&
  643. // For other posts, only redirect if publicly viewable.
  644. ! is_post_publicly_viewable( $redirect_obj )
  645. ) {
  646. $redirect_obj = false;
  647. $redirect_url = false;
  648. }
  649. }
  650. /**
  651. * Filters the canonical redirect URL.
  652. *
  653. * Returning false to this filter will cancel the redirect.
  654. *
  655. * @since 2.3.0
  656. *
  657. * @param string $redirect_url The redirect URL.
  658. * @param string $requested_url The requested URL.
  659. */
  660. $redirect_url = apply_filters( 'redirect_canonical', $redirect_url, $requested_url );
  661. // Yes, again -- in case the filter aborted the request.
  662. if ( ! $redirect_url || strip_fragment_from_url( $redirect_url ) === strip_fragment_from_url( $requested_url ) ) {
  663. return;
  664. }
  665. if ( $do_redirect ) {
  666. // Protect against chained redirects.
  667. if ( ! redirect_canonical( $redirect_url, false ) ) {
  668. wp_redirect( $redirect_url, 301 );
  669. exit;
  670. } else {
  671. // Debug.
  672. // die("1: $redirect_url<br />2: " . redirect_canonical( $redirect_url, false ) );
  673. return;
  674. }
  675. } else {
  676. return $redirect_url;
  677. }
  678. }
  679. /**
  680. * Removes arguments from a query string if they are not present in a URL
  681. * DO NOT use this in plugin code.
  682. *
  683. * @since 3.4.0
  684. * @access private
  685. *
  686. * @param string $query_string
  687. * @param array $args_to_check
  688. * @param string $url
  689. * @return string The altered query string
  690. */
  691. function _remove_qs_args_if_not_in_url( $query_string, array $args_to_check, $url ) {
  692. $parsed_url = parse_url( $url );
  693. if ( ! empty( $parsed_url['query'] ) ) {
  694. parse_str( $parsed_url['query'], $parsed_query );
  695. foreach ( $args_to_check as $qv ) {
  696. if ( ! isset( $parsed_query[ $qv ] ) ) {
  697. $query_string = remove_query_arg( $qv, $query_string );
  698. }
  699. }
  700. } else {
  701. $query_string = remove_query_arg( $args_to_check, $query_string );
  702. }
  703. return $query_string;
  704. }
  705. /**
  706. * Strips the #fragment from a URL, if one is present.
  707. *
  708. * @since 4.4.0
  709. *
  710. * @param string $url The URL to strip.
  711. * @return string The altered URL.
  712. */
  713. function strip_fragment_from_url( $url ) {
  714. $parsed_url = wp_parse_url( $url );
  715. if ( ! empty( $parsed_url['host'] ) ) {
  716. $url = '';
  717. if ( ! empty( $parsed_url['scheme'] ) ) {
  718. $url = $parsed_url['scheme'] . ':';
  719. }
  720. $url .= '//' . $parsed_url['host'];
  721. if ( ! empty( $parsed_url['port'] ) ) {
  722. $url .= ':' . $parsed_url['port'];
  723. }
  724. if ( ! empty( $parsed_url['path'] ) ) {
  725. $url .= $parsed_url['path'];
  726. }
  727. if ( ! empty( $parsed_url['query'] ) ) {
  728. $url .= '?' . $parsed_url['query'];
  729. }
  730. }
  731. return $url;
  732. }
  733. /**
  734. * Attempts to guess the correct URL for a 404 request based on query vars.
  735. *
  736. * @since 2.3.0
  737. *
  738. * @global wpdb $wpdb WordPress database abstraction object.
  739. *
  740. * @return string|false The correct URL if one is found. False on failure.
  741. */
  742. function redirect_guess_404_permalink() {
  743. global $wpdb;
  744. /**
  745. * Filters whether to attempt to guess a redirect URL for a 404 request.
  746. *
  747. * Returning a false value from the filter will disable the URL guessing
  748. * and return early without performing a redirect.
  749. *
  750. * @since 5.5.0
  751. *
  752. * @param bool $do_redirect_guess Whether to attempt to guess a redirect URL
  753. * for a 404 request. Default true.
  754. */
  755. if ( false === apply_filters( 'do_redirect_guess_404_permalink', true ) ) {
  756. return false;
  757. }
  758. /**
  759. * Short-circuits the redirect URL guessing for 404 requests.
  760. *
  761. * Returning a non-null value from the filter will effectively short-circuit
  762. * the URL guessing, returning the passed value instead.
  763. *
  764. * @since 5.5.0
  765. *
  766. * @param null|string|false $pre Whether to short-circuit guessing the redirect for a 404.
  767. * Default null to continue with the URL guessing.
  768. */
  769. $pre = apply_filters( 'pre_redirect_guess_404_permalink', null );
  770. if ( null !== $pre ) {
  771. return $pre;
  772. }
  773. if ( get_query_var( 'name' ) ) {
  774. /**
  775. * Filters whether to perform a strict guess for a 404 redirect.
  776. *
  777. * Returning a truthy value from the filter will redirect only exact post_name matches.
  778. *
  779. * @since 5.5.0
  780. *
  781. * @param bool $strict_guess Whether to perform a strict guess. Default false (loose guess).
  782. */
  783. $strict_guess = apply_filters( 'strict_redirect_guess_404_permalink', false );
  784. if ( $strict_guess ) {
  785. $where = $wpdb->prepare( 'post_name = %s', get_query_var( 'name' ) );
  786. } else {
  787. $where = $wpdb->prepare( 'post_name LIKE %s', $wpdb->esc_like( get_query_var( 'name' ) ) . '%' );
  788. }
  789. // If any of post_type, year, monthnum, or day are set, use them to refine the query.
  790. if ( get_query_var( 'post_type' ) ) {
  791. if ( is_array( get_query_var( 'post_type' ) ) ) {
  792. // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
  793. $where .= " AND post_type IN ('" . join( "', '", esc_sql( get_query_var( 'post_type' ) ) ) . "')";
  794. } else {
  795. $where .= $wpdb->prepare( ' AND post_type = %s', get_query_var( 'post_type' ) );
  796. }
  797. } else {
  798. $where .= " AND post_type IN ('" . implode( "', '", get_post_types( array( 'public' => true ) ) ) . "')";
  799. }
  800. if ( get_query_var( 'year' ) ) {
  801. $where .= $wpdb->prepare( ' AND YEAR(post_date) = %d', get_query_var( 'year' ) );
  802. }
  803. if ( get_query_var( 'monthnum' ) ) {
  804. $where .= $wpdb->prepare( ' AND MONTH(post_date) = %d', get_query_var( 'monthnum' ) );
  805. }
  806. if ( get_query_var( 'day' ) ) {
  807. $where .= $wpdb->prepare( ' AND DAYOFMONTH(post_date) = %d', get_query_var( 'day' ) );
  808. }
  809. $publicly_viewable_statuses = array_filter( get_post_stati(), 'is_post_status_viewable' );
  810. // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
  811. $post_id = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE $where AND post_status IN ('" . implode( "', '", esc_sql( $publicly_viewable_statuses ) ) . "')" );
  812. if ( ! $post_id ) {
  813. return false;
  814. }
  815. if ( get_query_var( 'feed' ) ) {
  816. return get_post_comments_feed_link( $post_id, get_query_var( 'feed' ) );
  817. } elseif ( get_query_var( 'page' ) > 1 ) {
  818. return trailingslashit( get_permalink( $post_id ) ) . user_trailingslashit( get_query_var( 'page' ), 'single_paged' );
  819. } else {
  820. return get_permalink( $post_id );
  821. }
  822. }
  823. return false;
  824. }
  825. /**
  826. * Redirects a variety of shorthand URLs to the admin.
  827. *
  828. * If a user visits example.com/admin, they'll be redirected to /wp-admin.
  829. * Visiting /login redirects to /wp-login.php, and so on.
  830. *
  831. * @since 3.4.0
  832. *
  833. * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
  834. */
  835. function wp_redirect_admin_locations() {
  836. global $wp_rewrite;
  837. if ( ! ( is_404() && $wp_rewrite->using_permalinks() ) ) {
  838. return;
  839. }
  840. $admins = array(
  841. home_url( 'wp-admin', 'relative' ),
  842. home_url( 'dashboard', 'relative' ),
  843. home_url( 'admin', 'relative' ),
  844. site_url( 'dashboard', 'relative' ),
  845. site_url( 'admin', 'relative' ),
  846. );
  847. if ( in_array( untrailingslashit( $_SERVER['REQUEST_URI'] ), $admins, true ) ) {
  848. wp_redirect( admin_url() );
  849. exit;
  850. }
  851. $logins = array(
  852. home_url( 'wp-login.php', 'relative' ),
  853. home_url( 'login', 'relative' ),
  854. site_url( 'login', 'relative' ),
  855. );
  856. if ( in_array( untrailingslashit( $_SERVER['REQUEST_URI'] ), $logins, true ) ) {
  857. wp_redirect( wp_login_url() );
  858. exit;
  859. }
  860. }