[ Index ]

PHP Cross Reference of WordPress

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, favicon.ico, searches,
  23   * or on POST 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' ), true ) ) {
  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          ) {
  56              $wp_query->is_preview = false;
  57          }
  58      }
  59  
  60      if ( is_admin() || is_search() || is_preview() || is_trackback() || is_favicon()
  61          || ( $is_IIS && ! iis7_supports_permalinks() )
  62      ) {
  63          return;
  64      }
  65  
  66      if ( ! $requested_url && isset( $_SERVER['HTTP_HOST'] ) ) {
  67          // Build the URL in the address bar.
  68          $requested_url  = is_ssl() ? 'https://' : 'http://';
  69          $requested_url .= $_SERVER['HTTP_HOST'];
  70          $requested_url .= $_SERVER['REQUEST_URI'];
  71      }
  72  
  73      $original = parse_url( $requested_url );
  74      if ( false === $original ) {
  75          return;
  76      }
  77  
  78      $redirect     = $original;
  79      $redirect_url = false;
  80  
  81      // Notice fixing.
  82      if ( ! isset( $redirect['path'] ) ) {
  83          $redirect['path'] = '';
  84      }
  85      if ( ! isset( $redirect['query'] ) ) {
  86          $redirect['query'] = '';
  87      }
  88  
  89      /*
  90       * If the original URL ended with non-breaking spaces, they were almost
  91       * certainly inserted by accident. Let's remove them, so the reader doesn't
  92       * see a 404 error with no obvious cause.
  93       */
  94      $redirect['path'] = preg_replace( '|(%C2%A0)+$|i', '', $redirect['path'] );
  95  
  96      // It's not a preview, so remove it from URL.
  97      if ( get_query_var( 'preview' ) ) {
  98          $redirect['query'] = remove_query_arg( 'preview', $redirect['query'] );
  99      }
 100  
 101      $post_id = get_query_var( 'p' );
 102  
 103      if ( is_feed() && $post_id ) {
 104          $redirect_url = get_post_comments_feed_link( $post_id, get_query_var( 'feed' ) );
 105  
 106          if ( $redirect_url ) {
 107              $redirect['query'] = _remove_qs_args_if_not_in_url(
 108                  $redirect['query'],
 109                  array( 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type', 'feed' ),
 110                  $redirect_url
 111              );
 112  
 113              $redirect['path'] = parse_url( $redirect_url, PHP_URL_PATH );
 114          }
 115      }
 116  
 117      if ( is_singular() && $wp_query->post_count < 1 && $post_id ) {
 118  
 119          $vars = $wpdb->get_results( $wpdb->prepare( "SELECT post_type, post_parent FROM $wpdb->posts WHERE ID = %d", $post_id ) );
 120  
 121          if ( ! empty( $vars[0] ) ) {
 122              $vars = $vars[0];
 123  
 124              if ( 'revision' === $vars->post_type && $vars->post_parent > 0 ) {
 125                  $post_id = $vars->post_parent;
 126              }
 127  
 128              $redirect_url = get_permalink( $post_id );
 129  
 130              if ( $redirect_url ) {
 131                  $redirect['query'] = _remove_qs_args_if_not_in_url(
 132                      $redirect['query'],
 133                      array( 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type' ),
 134                      $redirect_url
 135                  );
 136              }
 137          }
 138      }
 139  
 140      // These tests give us a WP-generated permalink.
 141      if ( is_404() ) {
 142  
 143          // Redirect ?page_id, ?p=, ?attachment_id= to their respective URLs.
 144          $post_id = max( get_query_var( 'p' ), get_query_var( 'page_id' ), get_query_var( 'attachment_id' ) );
 145  
 146          $redirect_post = $post_id ? get_post( $post_id ) : false;
 147  
 148          if ( $redirect_post ) {
 149              $post_type_obj = get_post_type_object( $redirect_post->post_type );
 150  
 151              if ( $post_type_obj->public && 'auto-draft' !== $redirect_post->post_status ) {
 152                  $redirect_url = get_permalink( $redirect_post );
 153  
 154                  $redirect['query'] = _remove_qs_args_if_not_in_url(
 155                      $redirect['query'],
 156                      array( 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type' ),
 157                      $redirect_url
 158                  );
 159              }
 160          }
 161  
 162          $year  = get_query_var( 'year' );
 163          $month = get_query_var( 'monthnum' );
 164          $day   = get_query_var( 'day' );
 165  
 166          if ( $year && $month && $day ) {
 167              $date = sprintf( '%04d-%02d-%02d', $year, $month, $day );
 168  
 169              if ( ! wp_checkdate( $month, $day, $year, $date ) ) {
 170                  $redirect_url = get_month_link( $year, $month );
 171  
 172                  $redirect['query'] = _remove_qs_args_if_not_in_url(
 173                      $redirect['query'],
 174                      array( 'year', 'monthnum', 'day' ),
 175                      $redirect_url
 176                  );
 177              }
 178          } elseif ( $year && $month && $month > 12 ) {
 179              $redirect_url = get_year_link( $year );
 180  
 181              $redirect['query'] = _remove_qs_args_if_not_in_url(
 182                  $redirect['query'],
 183                  array( 'year', 'monthnum' ),
 184                  $redirect_url
 185              );
 186          }
 187  
 188          // Strip off non-existing <!--nextpage--> links from single posts or pages.
 189          if ( get_query_var( 'page' ) ) {
 190              $post_id = 0;
 191  
 192              if ( $wp_query->queried_object instanceof WP_Post ) {
 193                  $post_id = $wp_query->queried_object->ID;
 194              } elseif ( $wp_query->post ) {
 195                  $post_id = $wp_query->post->ID;
 196              }
 197  
 198              if ( $post_id ) {
 199                  $redirect_url = get_permalink( $post_id );
 200  
 201                  $redirect['path']  = rtrim( $redirect['path'], (int) get_query_var( 'page' ) . '/' );
 202                  $redirect['query'] = remove_query_arg( 'page', $redirect['query'] );
 203              }
 204          }
 205  
 206          if ( ! $redirect_url ) {
 207              $redirect_url = redirect_guess_404_permalink();
 208  
 209              if ( $redirect_url ) {
 210                  $redirect['query'] = _remove_qs_args_if_not_in_url(
 211                      $redirect['query'],
 212                      array( 'page', 'feed', 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type' ),
 213                      $redirect_url
 214                  );
 215              }
 216          }
 217      } elseif ( is_object( $wp_rewrite ) && $wp_rewrite->using_permalinks() ) {
 218  
 219          // Rewriting of old ?p=X, ?m=2004, ?m=200401, ?m=20040101.
 220          if ( is_attachment()
 221              && ! array_diff( array_keys( $wp->query_vars ), array( 'attachment', 'attachment_id' ) )
 222              && ! $redirect_url
 223          ) {
 224              if ( ! empty( $_GET['attachment_id'] ) ) {
 225                  $redirect_url = get_attachment_link( get_query_var( 'attachment_id' ) );
 226  
 227                  if ( $redirect_url ) {
 228                      $redirect['query'] = remove_query_arg( 'attachment_id', $redirect['query'] );
 229                  }
 230              } else {
 231                  $redirect_url = get_attachment_link();
 232              }
 233          } elseif ( is_single() && ! empty( $_GET['p'] ) && ! $redirect_url ) {
 234              $redirect_url = get_permalink( get_query_var( 'p' ) );
 235  
 236              if ( $redirect_url ) {
 237                  $redirect['query'] = remove_query_arg( array( 'p', 'post_type' ), $redirect['query'] );
 238              }
 239          } elseif ( is_single() && ! empty( $_GET['name'] ) && ! $redirect_url ) {
 240              $redirect_url = get_permalink( $wp_query->get_queried_object_id() );
 241  
 242              if ( $redirect_url ) {
 243                  $redirect['query'] = remove_query_arg( 'name', $redirect['query'] );
 244              }
 245          } elseif ( is_page() && ! empty( $_GET['page_id'] ) && ! $redirect_url ) {
 246              $redirect_url = get_permalink( get_query_var( 'page_id' ) );
 247  
 248              if ( $redirect_url ) {
 249                  $redirect['query'] = remove_query_arg( 'page_id', $redirect['query'] );
 250              }
 251          } elseif ( is_page() && ! is_feed() && ! $redirect_url
 252              && 'page' === get_option( 'show_on_front' ) && get_queried_object_id() === (int) get_option( 'page_on_front' )
 253          ) {
 254              $redirect_url = home_url( '/' );
 255          } elseif ( is_home() && ! empty( $_GET['page_id'] ) && ! $redirect_url
 256              && 'page' === get_option( 'show_on_front' ) && get_query_var( 'page_id' ) === (int) get_option( 'page_for_posts' )
 257          ) {
 258              $redirect_url = get_permalink( get_option( 'page_for_posts' ) );
 259  
 260              if ( $redirect_url ) {
 261                  $redirect['query'] = remove_query_arg( 'page_id', $redirect['query'] );
 262              }
 263          } elseif ( ! empty( $_GET['m'] ) && ( is_year() || is_month() || is_day() ) ) {
 264              $m = get_query_var( 'm' );
 265  
 266              switch ( strlen( $m ) ) {
 267                  case 4: // Yearly.
 268                      $redirect_url = get_year_link( $m );
 269                      break;
 270                  case 6: // Monthly.
 271                      $redirect_url = get_month_link( substr( $m, 0, 4 ), substr( $m, 4, 2 ) );
 272                      break;
 273                  case 8: // Daily.
 274                      $redirect_url = get_day_link( substr( $m, 0, 4 ), substr( $m, 4, 2 ), substr( $m, 6, 2 ) );
 275                      break;
 276              }
 277  
 278              if ( $redirect_url ) {
 279                  $redirect['query'] = remove_query_arg( 'm', $redirect['query'] );
 280              }
 281              // Now moving on to non ?m=X year/month/day links.
 282          } elseif ( is_date() ) {
 283              $year  = get_query_var( 'year' );
 284              $month = get_query_var( 'monthnum' );
 285              $day   = get_query_var( 'day' );
 286  
 287              if ( is_day() && $year && $month && ! empty( $_GET['day'] ) ) {
 288                  $redirect_url = get_day_link( $year, $month, $day );
 289  
 290                  if ( $redirect_url ) {
 291                      $redirect['query'] = remove_query_arg( array( 'year', 'monthnum', 'day' ), $redirect['query'] );
 292                  }
 293              } elseif ( is_month() && $year && ! empty( $_GET['monthnum'] ) ) {
 294                  $redirect_url = get_month_link( $year, $month );
 295  
 296                  if ( $redirect_url ) {
 297                      $redirect['query'] = remove_query_arg( array( 'year', 'monthnum' ), $redirect['query'] );
 298                  }
 299              } elseif ( is_year() && ! empty( $_GET['year'] ) ) {
 300                  $redirect_url = get_year_link( $year );
 301  
 302                  if ( $redirect_url ) {
 303                      $redirect['query'] = remove_query_arg( 'year', $redirect['query'] );
 304                  }
 305              }
 306          } elseif ( is_author() && ! empty( $_GET['author'] ) && preg_match( '|^[0-9]+$|', $_GET['author'] ) ) {
 307              $author = get_userdata( get_query_var( 'author' ) );
 308  
 309              if ( false !== $author
 310                  && $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 ) )
 311              ) {
 312                  $redirect_url = get_author_posts_url( $author->ID, $author->user_nicename );
 313  
 314                  if ( $redirect_url ) {
 315                      $redirect['query'] = remove_query_arg( 'author', $redirect['query'] );
 316                  }
 317              }
 318          } elseif ( is_category() || is_tag() || is_tax() ) { // Terms (tags/categories).
 319              $term_count = 0;
 320  
 321              foreach ( $wp_query->tax_query->queried_terms as $tax_query ) {
 322                  $term_count += count( $tax_query['terms'] );
 323              }
 324  
 325              $obj = $wp_query->get_queried_object();
 326  
 327              if ( $term_count <= 1 && ! empty( $obj->term_id ) ) {
 328                  $tax_url = get_term_link( (int) $obj->term_id, $obj->taxonomy );
 329  
 330                  if ( $tax_url && ! is_wp_error( $tax_url ) ) {
 331                      if ( ! empty( $redirect['query'] ) ) {
 332                          // Strip taxonomy query vars off the URL.
 333                          $qv_remove = array( 'term', 'taxonomy' );
 334  
 335                          if ( is_category() ) {
 336                              $qv_remove[] = 'category_name';
 337                              $qv_remove[] = 'cat';
 338                          } elseif ( is_tag() ) {
 339                              $qv_remove[] = 'tag';
 340                              $qv_remove[] = 'tag_id';
 341                          } else {
 342                              // Custom taxonomies will have a custom query var, remove those too.
 343                              $tax_obj = get_taxonomy( $obj->taxonomy );
 344                              if ( false !== $tax_obj->query_var ) {
 345                                  $qv_remove[] = $tax_obj->query_var;
 346                              }
 347                          }
 348  
 349                          $rewrite_vars = array_diff( array_keys( $wp_query->query ), array_keys( $_GET ) );
 350  
 351                          // Check to see if all the query vars are coming from the rewrite, none are set via $_GET.
 352                          if ( ! array_diff( $rewrite_vars, array_keys( $_GET ) ) ) {
 353                              // Remove all of the per-tax query vars.
 354                              $redirect['query'] = remove_query_arg( $qv_remove, $redirect['query'] );
 355  
 356                              // Create the destination URL for this taxonomy.
 357                              $tax_url = parse_url( $tax_url );
 358  
 359                              if ( ! empty( $tax_url['query'] ) ) {
 360                                  // Taxonomy accessible via ?taxonomy=...&term=... or any custom query var.
 361                                  parse_str( $tax_url['query'], $query_vars );
 362                                  $redirect['query'] = add_query_arg( $query_vars, $redirect['query'] );
 363                              } else {
 364                                  // Taxonomy is accessible via a "pretty URL".
 365                                  $redirect['path'] = $tax_url['path'];
 366                              }
 367                          } else {
 368                              // Some query vars are set via $_GET. Unset those from $_GET that exist via the rewrite.
 369                              foreach ( $qv_remove as $_qv ) {
 370                                  if ( isset( $rewrite_vars[ $_qv ] ) ) {
 371                                      $redirect['query'] = remove_query_arg( $_qv, $redirect['query'] );
 372                                  }
 373                              }
 374                          }
 375                      }
 376                  }
 377              }
 378          } elseif ( is_single() && strpos( $wp_rewrite->permalink_structure, '%category%' ) !== false ) {
 379              $category_name = get_query_var( 'category_name' );
 380  
 381              if ( $category_name ) {
 382                  $category = get_category_by_path( $category_name );
 383  
 384                  if ( ! $category || is_wp_error( $category )
 385                      || ! has_term( $category->term_id, 'category', $wp_query->get_queried_object_id() )
 386                  ) {
 387                      $redirect_url = get_permalink( $wp_query->get_queried_object_id() );
 388                  }
 389              }
 390          }
 391  
 392          // Post paging.
 393          if ( is_singular() && get_query_var( 'page' ) ) {
 394              $page = get_query_var( 'page' );
 395  
 396              if ( ! $redirect_url ) {
 397                  $redirect_url = get_permalink( get_queried_object_id() );
 398              }
 399  
 400              if ( $page > 1 ) {
 401                  $redirect_url = trailingslashit( $redirect_url );
 402  
 403                  if ( is_front_page() ) {
 404                      $redirect_url .= user_trailingslashit( "$wp_rewrite->pagination_base/$page", 'paged' );
 405                  } else {
 406                      $redirect_url .= user_trailingslashit( $page, 'single_paged' );
 407                  }
 408              }
 409  
 410              $redirect['query'] = remove_query_arg( 'page', $redirect['query'] );
 411          }
 412  
 413          if ( get_query_var( 'sitemap' ) ) {
 414              $redirect_url      = get_sitemap_url( get_query_var( 'sitemap' ), get_query_var( 'sitemap-subtype' ), get_query_var( 'paged' ) );
 415              $redirect['query'] = remove_query_arg( array( 'sitemap', 'sitemap-subtype', 'paged' ), $redirect['query'] );
 416          } elseif ( get_query_var( 'paged' ) || is_feed() || get_query_var( 'cpage' ) ) {
 417              // Paging and feeds.
 418              $paged = get_query_var( 'paged' );
 419              $feed  = get_query_var( 'feed' );
 420              $cpage = get_query_var( 'cpage' );
 421  
 422              while ( preg_match( "#/$wp_rewrite->pagination_base/?[0-9]+?(/+)?$#", $redirect['path'] )
 423                  || preg_match( '#/(comments/?)?(feed|rss2?|rdf|atom)(/+)?$#', $redirect['path'] )
 424                  || preg_match( "#/{$wp_rewrite->comments_pagination_base}-[0-9]+(/+)?$#", $redirect['path'] )
 425              ) {
 426                  // Strip off any existing paging.
 427                  $redirect['path'] = preg_replace( "#/$wp_rewrite->pagination_base/?[0-9]+?(/+)?$#", '/', $redirect['path'] );
 428                  // Strip off feed endings.
 429                  $redirect['path'] = preg_replace( '#/(comments/?)?(feed|rss2?|rdf|atom)(/+|$)#', '/', $redirect['path'] );
 430                  // Strip off any existing comment paging.
 431                  $redirect['path'] = preg_replace( "#/{$wp_rewrite->comments_pagination_base}-[0-9]+?(/+)?$#", '/', $redirect['path'] );
 432              }
 433  
 434              $addl_path    = '';
 435              $default_feed = get_default_feed();
 436  
 437              if ( is_feed() && in_array( $feed, $wp_rewrite->feeds, true ) ) {
 438                  $addl_path = ! empty( $addl_path ) ? trailingslashit( $addl_path ) : '';
 439  
 440                  if ( ! is_singular() && get_query_var( 'withcomments' ) ) {
 441                      $addl_path .= 'comments/';
 442                  }
 443  
 444                  if ( ( 'rss' === $default_feed && 'feed' === $feed ) || 'rss' === $feed ) {
 445                      $format = ( 'rss2' === $default_feed ) ? '' : 'rss2';
 446                  } else {
 447                      $format = ( $default_feed === $feed || 'feed' === $feed ) ? '' : $feed;
 448                  }
 449  
 450                  $addl_path .= user_trailingslashit( 'feed/' . $format, 'feed' );
 451  
 452                  $redirect['query'] = remove_query_arg( 'feed', $redirect['query'] );
 453              } elseif ( is_feed() && 'old' === $feed ) {
 454                  $old_feed_files = array(
 455                      'wp-atom.php'         => 'atom',
 456                      'wp-commentsrss2.php' => 'comments_rss2',
 457                      'wp-feed.php'         => $default_feed,
 458                      'wp-rdf.php'          => 'rdf',
 459                      'wp-rss.php'          => 'rss2',
 460                      'wp-rss2.php'         => 'rss2',
 461                  );
 462  
 463                  if ( isset( $old_feed_files[ basename( $redirect['path'] ) ] ) ) {
 464                      $redirect_url = get_feed_link( $old_feed_files[ basename( $redirect['path'] ) ] );
 465  
 466                      wp_redirect( $redirect_url, 301 );
 467                      die();
 468                  }
 469              }
 470  
 471              if ( $paged > 0 ) {
 472                  $redirect['query'] = remove_query_arg( 'paged', $redirect['query'] );
 473  
 474                  if ( ! is_feed() ) {
 475                      if ( ! is_single() ) {
 476                          $addl_path = ! empty( $addl_path ) ? trailingslashit( $addl_path ) : '';
 477  
 478                          if ( $paged > 1 ) {
 479                              $addl_path .= user_trailingslashit( "$wp_rewrite->pagination_base/$paged", 'paged' );
 480                          }
 481                      }
 482                  } elseif ( $paged > 1 ) {
 483                      $redirect['query'] = add_query_arg( 'paged', $paged, $redirect['query'] );
 484                  }
 485              }
 486  
 487              $default_comments_page = get_option( 'default_comments_page' );
 488  
 489              if ( get_option( 'page_comments' )
 490                  && ( 'newest' === $default_comments_page && $cpage > 0
 491                      || 'newest' !== $default_comments_page && $cpage > 1 )
 492              ) {
 493                  $addl_path  = ( ! empty( $addl_path ) ? trailingslashit( $addl_path ) : '' );
 494                  $addl_path .= user_trailingslashit( $wp_rewrite->comments_pagination_base . '-' . $cpage, 'commentpaged' );
 495  
 496                  $redirect['query'] = remove_query_arg( 'cpage', $redirect['query'] );
 497              }
 498  
 499              // Strip off trailing /index.php/.
 500              $redirect['path'] = preg_replace( '|/' . preg_quote( $wp_rewrite->index, '|' ) . '/?$|', '/', $redirect['path'] );
 501              $redirect['path'] = user_trailingslashit( $redirect['path'] );
 502  
 503              if ( ! empty( $addl_path )
 504                  && $wp_rewrite->using_index_permalinks()
 505                  && strpos( $redirect['path'], '/' . $wp_rewrite->index . '/' ) === false
 506              ) {
 507                  $redirect['path'] = trailingslashit( $redirect['path'] ) . $wp_rewrite->index . '/';
 508              }
 509  
 510              if ( ! empty( $addl_path ) ) {
 511                  $redirect['path'] = trailingslashit( $redirect['path'] ) . $addl_path;
 512              }
 513  
 514              $redirect_url = $redirect['scheme'] . '://' . $redirect['host'] . $redirect['path'];
 515          }
 516  
 517          if ( 'wp-register.php' === basename( $redirect['path'] ) ) {
 518              if ( is_multisite() ) {
 519                  /** This filter is documented in wp-login.php */
 520                  $redirect_url = apply_filters( 'wp_signup_location', network_site_url( 'wp-signup.php' ) );
 521              } else {
 522                  $redirect_url = wp_registration_url();
 523              }
 524  
 525              wp_redirect( $redirect_url, 301 );
 526              die();
 527          }
 528      }
 529  
 530      $redirect['query'] = preg_replace( '#^\??&*?#', '', $redirect['query'] );
 531  
 532      // Tack on any additional query vars.
 533      if ( $redirect_url && ! empty( $redirect['query'] ) ) {
 534          parse_str( $redirect['query'], $_parsed_query );
 535          $redirect = parse_url( $redirect_url );
 536  
 537          if ( ! empty( $_parsed_query['name'] ) && ! empty( $redirect['query'] ) ) {
 538              parse_str( $redirect['query'], $_parsed_redirect_query );
 539  
 540              if ( empty( $_parsed_redirect_query['name'] ) ) {
 541                  unset( $_parsed_query['name'] );
 542              }
 543          }
 544  
 545          $_parsed_query = array_combine(
 546              rawurlencode_deep( array_keys( $_parsed_query ) ),
 547              rawurlencode_deep( array_values( $_parsed_query ) )
 548          );
 549  
 550          $redirect_url = add_query_arg( $_parsed_query, $redirect_url );
 551      }
 552  
 553      if ( $redirect_url ) {
 554          $redirect = parse_url( $redirect_url );
 555      }
 556  
 557      // www.example.com vs. example.com
 558      $user_home = parse_url( home_url() );
 559  
 560      if ( ! empty( $user_home['host'] ) ) {
 561          $redirect['host'] = $user_home['host'];
 562      }
 563  
 564      if ( empty( $user_home['path'] ) ) {
 565          $user_home['path'] = '/';
 566      }
 567  
 568      // Handle ports.
 569      if ( ! empty( $user_home['port'] ) ) {
 570          $redirect['port'] = $user_home['port'];
 571      } else {
 572          unset( $redirect['port'] );
 573      }
 574  
 575      // Trailing /index.php.
 576      $redirect['path'] = preg_replace( '|/' . preg_quote( $wp_rewrite->index, '|' ) . '/*?$|', '/', $redirect['path'] );
 577  
 578      $punctuation_pattern = implode(
 579          '|',
 580          array_map(
 581              'preg_quote',
 582              array(
 583                  ' ',
 584                  '%20',  // Space.
 585                  '!',
 586                  '%21',  // Exclamation mark.
 587                  '"',
 588                  '%22',  // Double quote.
 589                  "'",
 590                  '%27',  // Single quote.
 591                  '(',
 592                  '%28',  // Opening bracket.
 593                  ')',
 594                  '%29',  // Closing bracket.
 595                  ',',
 596                  '%2C',  // Comma.
 597                  '.',
 598                  '%2E',  // Period.
 599                  ';',
 600                  '%3B',  // Semicolon.
 601                  '{',
 602                  '%7B',  // Opening curly bracket.
 603                  '}',
 604                  '%7D',  // Closing curly bracket.
 605                  '%E2%80%9C', // Opening curly quote.
 606                  '%E2%80%9D', // Closing curly quote.
 607              )
 608          )
 609      );
 610  
 611      // Remove trailing spaces and end punctuation from the path.
 612      $redirect['path'] = preg_replace( "#($punctuation_pattern)+$#", '', $redirect['path'] );
 613  
 614      if ( ! empty( $redirect['query'] ) ) {
 615          // Remove trailing spaces and end punctuation from certain terminating query string args.
 616          $redirect['query'] = preg_replace( "#((^|&)(p|page_id|cat|tag)=[^&]*?)($punctuation_pattern)+$#", '$1', $redirect['query'] );
 617  
 618          // Clean up empty query strings.
 619          $redirect['query'] = trim( preg_replace( '#(^|&)(p|page_id|cat|tag)=?(&|$)#', '&', $redirect['query'] ), '&' );
 620  
 621          // Redirect obsolete feeds.
 622          $redirect['query'] = preg_replace( '#(^|&)feed=rss(&|$)#', '$1feed=rss2$2', $redirect['query'] );
 623  
 624          // Remove redundant leading ampersands.
 625          $redirect['query'] = preg_replace( '#^\??&*?#', '', $redirect['query'] );
 626      }
 627  
 628      // Strip /index.php/ when we're not using PATHINFO permalinks.
 629      if ( ! $wp_rewrite->using_index_permalinks() ) {
 630          $redirect['path'] = str_replace( '/' . $wp_rewrite->index . '/', '/', $redirect['path'] );
 631      }
 632  
 633      // Trailing slashes.
 634      if ( is_object( $wp_rewrite ) && $wp_rewrite->using_permalinks()
 635          && ! is_404() && ( ! is_front_page() || is_front_page() && get_query_var( 'paged' ) > 1 )
 636      ) {
 637          $user_ts_type = '';
 638  
 639          if ( get_query_var( 'paged' ) > 0 ) {
 640              $user_ts_type = 'paged';
 641          } else {
 642              foreach ( array( 'single', 'category', 'page', 'day', 'month', 'year', 'home' ) as $type ) {
 643                  $func = 'is_' . $type;
 644                  if ( call_user_func( $func ) ) {
 645                      $user_ts_type = $type;
 646                      break;
 647                  }
 648              }
 649          }
 650  
 651          $redirect['path'] = user_trailingslashit( $redirect['path'], $user_ts_type );
 652      } elseif ( is_front_page() ) {
 653          $redirect['path'] = trailingslashit( $redirect['path'] );
 654      }
 655  
 656      // Remove trailing slash for robots.txt or sitemap requests.
 657      if ( is_robots()
 658          || ! empty( get_query_var( 'sitemap' ) ) || ! empty( get_query_var( 'sitemap-stylesheet' ) )
 659      ) {
 660          $redirect['path'] = untrailingslashit( $redirect['path'] );
 661      }
 662  
 663      // Strip multiple slashes out of the URL.
 664      if ( strpos( $redirect['path'], '//' ) > -1 ) {
 665          $redirect['path'] = preg_replace( '|/+|', '/', $redirect['path'] );
 666      }
 667  
 668      // Always trailing slash the Front Page URL.
 669      if ( trailingslashit( $redirect['path'] ) === trailingslashit( $user_home['path'] ) ) {
 670          $redirect['path'] = trailingslashit( $redirect['path'] );
 671      }
 672  
 673      $original_host_low = strtolower( $original['host'] );
 674      $redirect_host_low = strtolower( $redirect['host'] );
 675  
 676      // Ignore differences in host capitalization, as this can lead to infinite redirects.
 677      // Only redirect no-www <=> yes-www.
 678      if ( $original_host_low === $redirect_host_low
 679          || ( 'www.' . $original_host_low !== $redirect_host_low
 680              && 'www.' . $redirect_host_low !== $original_host_low )
 681      ) {
 682          $redirect['host'] = $original['host'];
 683      }
 684  
 685      $compare_original = array( $original['host'], $original['path'] );
 686  
 687      if ( ! empty( $original['port'] ) ) {
 688          $compare_original[] = $original['port'];
 689      }
 690  
 691      if ( ! empty( $original['query'] ) ) {
 692          $compare_original[] = $original['query'];
 693      }
 694  
 695      $compare_redirect = array( $redirect['host'], $redirect['path'] );
 696  
 697      if ( ! empty( $redirect['port'] ) ) {
 698          $compare_redirect[] = $redirect['port'];
 699      }
 700  
 701      if ( ! empty( $redirect['query'] ) ) {
 702          $compare_redirect[] = $redirect['query'];
 703      }
 704  
 705      if ( $compare_original !== $compare_redirect ) {
 706          $redirect_url = $redirect['scheme'] . '://' . $redirect['host'];
 707  
 708          if ( ! empty( $redirect['port'] ) ) {
 709              $redirect_url .= ':' . $redirect['port'];
 710          }
 711  
 712          $redirect_url .= $redirect['path'];
 713  
 714          if ( ! empty( $redirect['query'] ) ) {
 715              $redirect_url .= '?' . $redirect['query'];
 716          }
 717      }
 718  
 719      if ( ! $redirect_url || $redirect_url === $requested_url ) {
 720          return;
 721      }
 722  
 723      // Hex encoded octets are case-insensitive.
 724      if ( false !== strpos( $requested_url, '%' ) ) {
 725          if ( ! function_exists( 'lowercase_octets' ) ) {
 726              /**
 727               * Converts the first hex-encoded octet match to lowercase.
 728               *
 729               * @since 3.1.0
 730               * @ignore
 731               *
 732               * @param array $matches Hex-encoded octet matches for the requested URL.
 733               * @return string Lowercased version of the first match.
 734               */
 735  			function lowercase_octets( $matches ) {
 736                  return strtolower( $matches[0] );
 737              }
 738          }
 739  
 740          $requested_url = preg_replace_callback( '|%[a-fA-F0-9][a-fA-F0-9]|', 'lowercase_octets', $requested_url );
 741      }
 742  
 743      /**
 744       * Filters the canonical redirect URL.
 745       *
 746       * Returning false to this filter will cancel the redirect.
 747       *
 748       * @since 2.3.0
 749       *
 750       * @param string $redirect_url  The redirect URL.
 751       * @param string $requested_url The requested URL.
 752       */
 753      $redirect_url = apply_filters( 'redirect_canonical', $redirect_url, $requested_url );
 754  
 755      // Yes, again -- in case the filter aborted the request.
 756      if ( ! $redirect_url || strip_fragment_from_url( $redirect_url ) === strip_fragment_from_url( $requested_url ) ) {
 757          return;
 758      }
 759  
 760      if ( $do_redirect ) {
 761          // Protect against chained redirects.
 762          if ( ! redirect_canonical( $redirect_url, false ) ) {
 763              wp_redirect( $redirect_url, 301 );
 764              exit;
 765          } else {
 766              // Debug.
 767              // die("1: $redirect_url<br />2: " . redirect_canonical( $redirect_url, false ) );
 768              return;
 769          }
 770      } else {
 771          return $redirect_url;
 772      }
 773  }
 774  
 775  /**
 776   * Removes arguments from a query string if they are not present in a URL
 777   * DO NOT use this in plugin code.
 778   *
 779   * @since 3.4.0
 780   * @access private
 781   *
 782   * @param string $query_string
 783   * @param array  $args_to_check
 784   * @param string $url
 785   * @return string The altered query string
 786   */
 787  function _remove_qs_args_if_not_in_url( $query_string, array $args_to_check, $url ) {
 788      $parsed_url = parse_url( $url );
 789  
 790      if ( ! empty( $parsed_url['query'] ) ) {
 791          parse_str( $parsed_url['query'], $parsed_query );
 792  
 793          foreach ( $args_to_check as $qv ) {
 794              if ( ! isset( $parsed_query[ $qv ] ) ) {
 795                  $query_string = remove_query_arg( $qv, $query_string );
 796              }
 797          }
 798      } else {
 799          $query_string = remove_query_arg( $args_to_check, $query_string );
 800      }
 801  
 802      return $query_string;
 803  }
 804  
 805  /**
 806   * Strips the #fragment from a URL, if one is present.
 807   *
 808   * @since 4.4.0
 809   *
 810   * @param string $url The URL to strip.
 811   * @return string The altered URL.
 812   */
 813  function strip_fragment_from_url( $url ) {
 814      $parsed_url = parse_url( $url );
 815  
 816      if ( ! empty( $parsed_url['host'] ) ) {
 817          // This mirrors code in redirect_canonical(). It does not handle every case.
 818          $url = $parsed_url['scheme'] . '://' . $parsed_url['host'];
 819          if ( ! empty( $parsed_url['port'] ) ) {
 820              $url .= ':' . $parsed_url['port'];
 821          }
 822  
 823          if ( ! empty( $parsed_url['path'] ) ) {
 824              $url .= $parsed_url['path'];
 825          }
 826  
 827          if ( ! empty( $parsed_url['query'] ) ) {
 828              $url .= '?' . $parsed_url['query'];
 829          }
 830      }
 831  
 832      return $url;
 833  }
 834  
 835  /**
 836   * Attempts to guess the correct URL for a 404 request based on query vars.
 837   *
 838   * @since 2.3.0
 839   *
 840   * @global wpdb $wpdb WordPress database abstraction object.
 841   *
 842   * @return string|false The correct URL if one is found. False on failure.
 843   */
 844  function redirect_guess_404_permalink() {
 845      global $wpdb;
 846  
 847      /**
 848       * Filters whether to attempt to guess a redirect URL for a 404 request.
 849       *
 850       * Returning a false value from the filter will disable the URL guessing
 851       * and return early without performing a redirect.
 852       *
 853       * @since 5.5.0
 854       *
 855       * @param bool $do_redirect_guess Whether to attempt to guess a redirect URL
 856       *                                for a 404 request. Default true.
 857       */
 858      if ( false === apply_filters( 'do_redirect_guess_404_permalink', true ) ) {
 859          return false;
 860      }
 861  
 862      /**
 863       * Short-circuits the redirect URL guessing for 404 requests.
 864       *
 865       * Returning a non-null value from the filter will effectively short-circuit
 866       * the URL guessing, returning the passed value instead.
 867       *
 868       * @since 5.5.0
 869       *
 870       * @param null|string|false $pre Whether to short-circuit guessing the redirect for a 404.
 871       *                               Default null to continue with the URL guessing.
 872       */
 873      $pre = apply_filters( 'pre_redirect_guess_404_permalink', null );
 874      if ( null !== $pre ) {
 875          return $pre;
 876      }
 877  
 878      if ( get_query_var( 'name' ) ) {
 879          /**
 880           * Filters whether to perform a strict guess for a 404 redirect.
 881           *
 882           * Returning a truthy value from the filter will redirect only exact post_name matches.
 883           *
 884           * @since 5.5.0
 885           *
 886           * @param bool $strict_guess Whether to perform a strict guess. Default false (loose guess).
 887           */
 888          $strict_guess = apply_filters( 'strict_redirect_guess_404_permalink', false );
 889  
 890          if ( $strict_guess ) {
 891              $where = $wpdb->prepare( 'post_name = %s', get_query_var( 'name' ) );
 892          } else {
 893              $where = $wpdb->prepare( 'post_name LIKE %s', $wpdb->esc_like( get_query_var( 'name' ) ) . '%' );
 894          }
 895  
 896          // If any of post_type, year, monthnum, or day are set, use them to refine the query.
 897          if ( get_query_var( 'post_type' ) ) {
 898              if ( is_array( get_query_var( 'post_type' ) ) ) {
 899                  // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
 900                  $where .= " AND post_type IN ('" . join( "', '", esc_sql( get_query_var( 'post_type' ) ) ) . "')";
 901              } else {
 902                  $where .= $wpdb->prepare( ' AND post_type = %s', get_query_var( 'post_type' ) );
 903              }
 904          } else {
 905              $where .= " AND post_type IN ('" . implode( "', '", get_post_types( array( 'public' => true ) ) ) . "')";
 906          }
 907  
 908          if ( get_query_var( 'year' ) ) {
 909              $where .= $wpdb->prepare( ' AND YEAR(post_date) = %d', get_query_var( 'year' ) );
 910          }
 911          if ( get_query_var( 'monthnum' ) ) {
 912              $where .= $wpdb->prepare( ' AND MONTH(post_date) = %d', get_query_var( 'monthnum' ) );
 913          }
 914          if ( get_query_var( 'day' ) ) {
 915              $where .= $wpdb->prepare( ' AND DAYOFMONTH(post_date) = %d', get_query_var( 'day' ) );
 916          }
 917  
 918          // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
 919          $post_id = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE $where AND post_status = 'publish'" );
 920  
 921          if ( ! $post_id ) {
 922              return false;
 923          }
 924  
 925          if ( get_query_var( 'feed' ) ) {
 926              return get_post_comments_feed_link( $post_id, get_query_var( 'feed' ) );
 927          } elseif ( get_query_var( 'page' ) > 1 ) {
 928              return trailingslashit( get_permalink( $post_id ) ) . user_trailingslashit( get_query_var( 'page' ), 'single_paged' );
 929          } else {
 930              return get_permalink( $post_id );
 931          }
 932      }
 933  
 934      return false;
 935  }
 936  
 937  /**
 938   * Redirects a variety of shorthand URLs to the admin.
 939   *
 940   * If a user visits example.com/admin, they'll be redirected to /wp-admin.
 941   * Visiting /login redirects to /wp-login.php, and so on.
 942   *
 943   * @since 3.4.0
 944   *
 945   * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
 946   */
 947  function wp_redirect_admin_locations() {
 948      global $wp_rewrite;
 949  
 950      if ( ! ( is_404() && $wp_rewrite->using_permalinks() ) ) {
 951          return;
 952      }
 953  
 954      $admins = array(
 955          home_url( 'wp-admin', 'relative' ),
 956          home_url( 'dashboard', 'relative' ),
 957          home_url( 'admin', 'relative' ),
 958          site_url( 'dashboard', 'relative' ),
 959          site_url( 'admin', 'relative' ),
 960      );
 961  
 962      if ( in_array( untrailingslashit( $_SERVER['REQUEST_URI'] ), $admins, true ) ) {
 963          wp_redirect( admin_url() );
 964          exit;
 965      }
 966  
 967      $logins = array(
 968          home_url( 'wp-login.php', 'relative' ),
 969          home_url( 'login', 'relative' ),
 970          site_url( 'login', 'relative' ),
 971      );
 972  
 973      if ( in_array( untrailingslashit( $_SERVER['REQUEST_URI'] ), $logins, true ) ) {
 974          wp_redirect( wp_login_url() );
 975          exit;
 976      }
 977  }


Generated: Sat Nov 28 01:00:03 2020 Cross-referenced by PHPXref 0.7.1