~canonical-sysadmins/wordpress/4.7.2

« back to all changes in this revision

Viewing changes to wp-includes/canonical.php

  • Committer: Jacek Nykis
  • Date: 2015-01-05 16:17:05 UTC
  • Revision ID: jacek.nykis@canonical.com-20150105161705-w544l1h5mcg7u4w9
Initial commit

Show diffs side-by-side

added added

removed removed

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