[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

title

Body

[close]

/wp-includes/ -> canonical.php (source)

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


Generated: Wed Oct 23 08:20:01 2019 Cross-referenced by PHPXref 0.7