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