Make WordPress Core

Ticket #34353: canonical.php

File canonical.php, 24.9 KB (added by theamila, 11 years ago)

canonical.php file

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