Make WordPress Core

Ticket #43539: canonical.php

File canonical.php, 27.1 KB (added by satantime, 5 years ago)

Possible fix

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