[ 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          // Paging and feeds.
 414          if ( get_query_var( 'paged' ) || is_feed() || get_query_var( 'cpage' ) ) {
 415              $paged = get_query_var( 'paged' );
 416              $feed  = get_query_var( 'feed' );
 417              $cpage = get_query_var( 'cpage' );
 418  
 419              while ( preg_match( "#/$wp_rewrite->pagination_base/?[0-9]+?(/+)?$#", $redirect['path'] )
 420                  || preg_match( '#/(comments/?)?(feed|rss2?|rdf|atom)(/+)?$#', $redirect['path'] )
 421                  || preg_match( "#/{$wp_rewrite->comments_pagination_base}-[0-9]+(/+)?$#", $redirect['path'] )
 422              ) {
 423                  // Strip off any existing paging.
 424                  $redirect['path'] = preg_replace( "#/$wp_rewrite->pagination_base/?[0-9]+?(/+)?$#", '/', $redirect['path'] );
 425                  // Strip off feed endings.
 426                  $redirect['path'] = preg_replace( '#/(comments/?)?(feed|rss2?|rdf|atom)(/+|$)#', '/', $redirect['path'] );
 427                  // Strip off any existing comment paging.
 428                  $redirect['path'] = preg_replace( "#/{$wp_rewrite->comments_pagination_base}-[0-9]+?(/+)?$#", '/', $redirect['path'] );
 429              }
 430  
 431              $addl_path    = '';
 432              $default_feed = get_default_feed();
 433  
 434              if ( is_feed() && in_array( $feed, $wp_rewrite->feeds, true ) ) {
 435                  $addl_path = ! empty( $addl_path ) ? trailingslashit( $addl_path ) : '';
 436  
 437                  if ( ! is_singular() && get_query_var( 'withcomments' ) ) {
 438                      $addl_path .= 'comments/';
 439                  }
 440  
 441                  if ( ( 'rss' === $default_feed && 'feed' === $feed ) || 'rss' === $feed ) {
 442                      $format = ( 'rss2' === $default_feed ) ? '' : 'rss2';
 443                  } else {
 444                      $format = ( $default_feed === $feed || 'feed' === $feed ) ? '' : $feed;
 445                  }
 446  
 447                  $addl_path .= user_trailingslashit( 'feed/' . $format, 'feed' );
 448  
 449                  $redirect['query'] = remove_query_arg( 'feed', $redirect['query'] );
 450              } elseif ( is_feed() && 'old' === $feed ) {
 451                  $old_feed_files = array(
 452                      'wp-atom.php'         => 'atom',
 453                      'wp-commentsrss2.php' => 'comments_rss2',
 454                      'wp-feed.php'         => $default_feed,
 455                      'wp-rdf.php'          => 'rdf',
 456                      'wp-rss.php'          => 'rss2',
 457                      'wp-rss2.php'         => 'rss2',
 458                  );
 459  
 460                  if ( isset( $old_feed_files[ basename( $redirect['path'] ) ] ) ) {
 461                      $redirect_url = get_feed_link( $old_feed_files[ basename( $redirect['path'] ) ] );
 462  
 463                      wp_redirect( $redirect_url, 301 );
 464                      die();
 465                  }
 466              }
 467  
 468              if ( $paged > 0 ) {
 469                  $redirect['query'] = remove_query_arg( 'paged', $redirect['query'] );
 470  
 471                  if ( ! is_feed() ) {
 472                      if ( ! is_single() ) {
 473                          $addl_path = ! empty( $addl_path ) ? trailingslashit( $addl_path ) : '';
 474  
 475                          if ( $paged > 1 ) {
 476                              $addl_path .= user_trailingslashit( "$wp_rewrite->pagination_base/$paged", 'paged' );
 477                          }
 478                      }
 479                  } elseif ( $paged > 1 ) {
 480                      $redirect['query'] = add_query_arg( 'paged', $paged, $redirect['query'] );
 481                  }
 482              }
 483  
 484              $default_comments_page = get_option( 'default_comments_page' );
 485  
 486              if ( get_option( 'page_comments' )
 487                  && ( 'newest' === $default_comments_page && $cpage > 0
 488                      || 'newest' !== $default_comments_page && $cpage > 1 )
 489              ) {
 490                  $addl_path  = ( ! empty( $addl_path ) ? trailingslashit( $addl_path ) : '' );
 491                  $addl_path .= user_trailingslashit( $wp_rewrite->comments_pagination_base . '-' . $cpage, 'commentpaged' );
 492  
 493                  $redirect['query'] = remove_query_arg( 'cpage', $redirect['query'] );
 494              }
 495  
 496              // Strip off trailing /index.php/.
 497              $redirect['path'] = preg_replace( '|/' . preg_quote( $wp_rewrite->index, '|' ) . '/?$|', '/', $redirect['path'] );
 498              $redirect['path'] = user_trailingslashit( $redirect['path'] );
 499  
 500              if ( ! empty( $addl_path )
 501                  && $wp_rewrite->using_index_permalinks()
 502                  && strpos( $redirect['path'], '/' . $wp_rewrite->index . '/' ) === false
 503              ) {
 504                  $redirect['path'] = trailingslashit( $redirect['path'] ) . $wp_rewrite->index . '/';
 505              }
 506  
 507              if ( ! empty( $addl_path ) ) {
 508                  $redirect['path'] = trailingslashit( $redirect['path'] ) . $addl_path;
 509              }
 510  
 511              // Remove trailing slash for sitemaps requests.
 512              if ( ! empty( get_query_var( 'sitemap' ) ) ) {
 513                  $redirect['path'] = untrailingslashit( $redirect['path'] );
 514              }
 515  
 516              $redirect_url = $redirect['scheme'] . '://' . $redirect['host'] . $redirect['path'];
 517          }
 518  
 519          if ( 'wp-register.php' === basename( $redirect['path'] ) ) {
 520              if ( is_multisite() ) {
 521                  /** This filter is documented in wp-login.php */
 522                  $redirect_url = apply_filters( 'wp_signup_location', network_site_url( 'wp-signup.php' ) );
 523              } else {
 524                  $redirect_url = wp_registration_url();
 525              }
 526  
 527              wp_redirect( $redirect_url, 301 );
 528              die();
 529          }
 530      }
 531  
 532      $redirect['query'] = preg_replace( '#^\??&*?#', '', $redirect['query'] );
 533  
 534      // Tack on any additional query vars.
 535      if ( $redirect_url && ! empty( $redirect['query'] ) ) {
 536          parse_str( $redirect['query'], $_parsed_query );
 537          $redirect = parse_url( $redirect_url );
 538  
 539          if ( ! empty( $_parsed_query['name'] ) && ! empty( $redirect['query'] ) ) {
 540              parse_str( $redirect['query'], $_parsed_redirect_query );
 541  
 542              if ( empty( $_parsed_redirect_query['name'] ) ) {
 543                  unset( $_parsed_query['name'] );
 544              }
 545          }
 546  
 547          $_parsed_query = array_combine(
 548              rawurlencode_deep( array_keys( $_parsed_query ) ),
 549              rawurlencode_deep( array_values( $_parsed_query ) )
 550          );
 551  
 552          $redirect_url = add_query_arg( $_parsed_query, $redirect_url );
 553      }
 554  
 555      if ( $redirect_url ) {
 556          $redirect = parse_url( $redirect_url );
 557      }
 558  
 559      // www.example.com vs. example.com
 560      $user_home = parse_url( home_url() );
 561  
 562      if ( ! empty( $user_home['host'] ) ) {
 563          $redirect['host'] = $user_home['host'];
 564      }
 565  
 566      if ( empty( $user_home['path'] ) ) {
 567          $user_home['path'] = '/';
 568      }
 569  
 570      // Handle ports.
 571      if ( ! empty( $user_home['port'] ) ) {
 572          $redirect['port'] = $user_home['port'];
 573      } else {
 574          unset( $redirect['port'] );
 575      }
 576  
 577      // Trailing /index.php.
 578      $redirect['path'] = preg_replace( '|/' . preg_quote( $wp_rewrite->index, '|' ) . '/*?$|', '/', $redirect['path'] );
 579  
 580      $punctuation_pattern = implode(
 581          '|',
 582          array_map(
 583              'preg_quote',
 584              array(
 585                  ' ',
 586                  '%20',  // Space.
 587                  '!',
 588                  '%21',  // Exclamation mark.
 589                  '"',
 590                  '%22',  // Double quote.
 591                  "'",
 592                  '%27',  // Single quote.
 593                  '(',
 594                  '%28',  // Opening bracket.
 595                  ')',
 596                  '%29',  // Closing bracket.
 597                  ',',
 598                  '%2C',  // Comma.
 599                  '.',
 600                  '%2E',  // Period.
 601                  ';',
 602                  '%3B',  // Semicolon.
 603                  '{',
 604                  '%7B',  // Opening curly bracket.
 605                  '}',
 606                  '%7D',  // Closing curly bracket.
 607                  '%E2%80%9C', // Opening curly quote.
 608                  '%E2%80%9D', // Closing curly quote.
 609              )
 610          )
 611      );
 612  
 613      // Remove trailing spaces and end punctuation from the path.
 614      $redirect['path'] = preg_replace( "#($punctuation_pattern)+$#", '', $redirect['path'] );
 615  
 616      if ( ! empty( $redirect['query'] ) ) {
 617          // Remove trailing spaces and end punctuation from certain terminating query string args.
 618          $redirect['query'] = preg_replace( "#((^|&)(p|page_id|cat|tag)=[^&]*?)($punctuation_pattern)+$#", '$1', $redirect['query'] );
 619  
 620          // Clean up empty query strings.
 621          $redirect['query'] = trim( preg_replace( '#(^|&)(p|page_id|cat|tag)=?(&|$)#', '&', $redirect['query'] ), '&' );
 622  
 623          // Redirect obsolete feeds.
 624          $redirect['query'] = preg_replace( '#(^|&)feed=rss(&|$)#', '$1feed=rss2$2', $redirect['query'] );
 625  
 626          // Remove redundant leading ampersands.
 627          $redirect['query'] = preg_replace( '#^\??&*?#', '', $redirect['query'] );
 628      }
 629  
 630      // Strip /index.php/ when we're not using PATHINFO permalinks.
 631      if ( ! $wp_rewrite->using_index_permalinks() ) {
 632          $redirect['path'] = str_replace( '/' . $wp_rewrite->index . '/', '/', $redirect['path'] );
 633      }
 634  
 635      // Trailing slashes.
 636      if ( is_object( $wp_rewrite ) && $wp_rewrite->using_permalinks()
 637          && ! is_404() && ( ! is_front_page() || is_front_page() && get_query_var( 'paged' ) > 1 )
 638      ) {
 639          $user_ts_type = '';
 640  
 641          if ( get_query_var( 'paged' ) > 0 ) {
 642              $user_ts_type = 'paged';
 643          } else {
 644              foreach ( array( 'single', 'category', 'page', 'day', 'month', 'year', 'home' ) as $type ) {
 645                  $func = 'is_' . $type;
 646                  if ( call_user_func( $func ) ) {
 647                      $user_ts_type = $type;
 648                      break;
 649                  }
 650              }
 651          }
 652  
 653          $redirect['path'] = user_trailingslashit( $redirect['path'], $user_ts_type );
 654      } elseif ( is_front_page() ) {
 655          $redirect['path'] = trailingslashit( $redirect['path'] );
 656      }
 657  
 658      // Remove trailing slash for robots.txt or sitemap requests.
 659      if ( is_robots()
 660          || ! empty( get_query_var( 'sitemap' ) ) || ! empty( get_query_var( 'sitemap-stylesheet' ) )
 661      ) {
 662          $redirect['path'] = untrailingslashit( $redirect['path'] );
 663      }
 664  
 665      // Strip multiple slashes out of the URL.
 666      if ( strpos( $redirect['path'], '//' ) > -1 ) {
 667          $redirect['path'] = preg_replace( '|/+|', '/', $redirect['path'] );
 668      }
 669  
 670      // Always trailing slash the Front Page URL.
 671      if ( trailingslashit( $redirect['path'] ) === trailingslashit( $user_home['path'] ) ) {
 672          $redirect['path'] = trailingslashit( $redirect['path'] );
 673      }
 674  
 675      $original_host_low = strtolower( $original['host'] );
 676      $redirect_host_low = strtolower( $redirect['host'] );
 677  
 678      // Ignore differences in host capitalization, as this can lead to infinite redirects.
 679      // Only redirect no-www <=> yes-www.
 680      if ( $original_host_low === $redirect_host_low
 681          || ( 'www.' . $original_host_low !== $redirect_host_low
 682              && 'www.' . $redirect_host_low !== $original_host_low )
 683      ) {
 684          $redirect['host'] = $original['host'];
 685      }
 686  
 687      $compare_original = array( $original['host'], $original['path'] );
 688  
 689      if ( ! empty( $original['port'] ) ) {
 690          $compare_original[] = $original['port'];
 691      }
 692  
 693      if ( ! empty( $original['query'] ) ) {
 694          $compare_original[] = $original['query'];
 695      }
 696  
 697      $compare_redirect = array( $redirect['host'], $redirect['path'] );
 698  
 699      if ( ! empty( $redirect['port'] ) ) {
 700          $compare_redirect[] = $redirect['port'];
 701      }
 702  
 703      if ( ! empty( $redirect['query'] ) ) {
 704          $compare_redirect[] = $redirect['query'];
 705      }
 706  
 707      if ( $compare_original !== $compare_redirect ) {
 708          $redirect_url = $redirect['scheme'] . '://' . $redirect['host'];
 709  
 710          if ( ! empty( $redirect['port'] ) ) {
 711              $redirect_url .= ':' . $redirect['port'];
 712          }
 713  
 714          $redirect_url .= $redirect['path'];
 715  
 716          if ( ! empty( $redirect['query'] ) ) {
 717              $redirect_url .= '?' . $redirect['query'];
 718          }
 719      }
 720  
 721      if ( ! $redirect_url || $redirect_url === $requested_url ) {
 722          return;
 723      }
 724  
 725      // Hex encoded octets are case-insensitive.
 726      if ( false !== strpos( $requested_url, '%' ) ) {
 727          if ( ! function_exists( 'lowercase_octets' ) ) {
 728              /**
 729               * Converts the first hex-encoded octet match to lowercase.
 730               *
 731               * @since 3.1.0
 732               * @ignore
 733               *
 734               * @param array $matches Hex-encoded octet matches for the requested URL.
 735               * @return string Lowercased version of the first match.
 736               */
 737  			function lowercase_octets( $matches ) {
 738                  return strtolower( $matches[0] );
 739              }
 740          }
 741  
 742          $requested_url = preg_replace_callback( '|%[a-fA-F0-9][a-fA-F0-9]|', 'lowercase_octets', $requested_url );
 743      }
 744  
 745      /**
 746       * Filters the canonical redirect URL.
 747       *
 748       * Returning false to this filter will cancel the redirect.
 749       *
 750       * @since 2.3.0
 751       *
 752       * @param string $redirect_url  The redirect URL.
 753       * @param string $requested_url The requested URL.
 754       */
 755      $redirect_url = apply_filters( 'redirect_canonical', $redirect_url, $requested_url );
 756  
 757      // Yes, again -- in case the filter aborted the request.
 758      if ( ! $redirect_url || strip_fragment_from_url( $redirect_url ) === strip_fragment_from_url( $requested_url ) ) {
 759          return;
 760      }
 761  
 762      if ( $do_redirect ) {
 763          // Protect against chained redirects.
 764          if ( ! redirect_canonical( $redirect_url, false ) ) {
 765              wp_redirect( $redirect_url, 301 );
 766              exit;
 767          } else {
 768              // Debug.
 769              // die("1: $redirect_url<br />2: " . redirect_canonical( $redirect_url, false ) );
 770              return;
 771          }
 772      } else {
 773          return $redirect_url;
 774      }
 775  }
 776  
 777  /**
 778   * Removes arguments from a query string if they are not present in a URL
 779   * DO NOT use this in plugin code.
 780   *
 781   * @since 3.4.0
 782   * @access private
 783   *
 784   * @param string $query_string
 785   * @param array $args_to_check
 786   * @param string $url
 787   * @return string The altered query string
 788   */
 789  function _remove_qs_args_if_not_in_url( $query_string, array $args_to_check, $url ) {
 790      $parsed_url = parse_url( $url );
 791  
 792      if ( ! empty( $parsed_url['query'] ) ) {
 793          parse_str( $parsed_url['query'], $parsed_query );
 794  
 795          foreach ( $args_to_check as $qv ) {
 796              if ( ! isset( $parsed_query[ $qv ] ) ) {
 797                  $query_string = remove_query_arg( $qv, $query_string );
 798              }
 799          }
 800      } else {
 801          $query_string = remove_query_arg( $args_to_check, $query_string );
 802      }
 803  
 804      return $query_string;
 805  }
 806  
 807  /**
 808   * Strips the #fragment from a URL, if one is present.
 809   *
 810   * @since 4.4.0
 811   *
 812   * @param string $url The URL to strip.
 813   * @return string The altered URL.
 814   */
 815  function strip_fragment_from_url( $url ) {
 816      $parsed_url = parse_url( $url );
 817  
 818      if ( ! empty( $parsed_url['host'] ) ) {
 819          // This mirrors code in redirect_canonical(). It does not handle every case.
 820          $url = $parsed_url['scheme'] . '://' . $parsed_url['host'];
 821          if ( ! empty( $parsed_url['port'] ) ) {
 822              $url .= ':' . $parsed_url['port'];
 823          }
 824  
 825          if ( ! empty( $parsed_url['path'] ) ) {
 826              $url .= $parsed_url['path'];
 827          }
 828  
 829          if ( ! empty( $parsed_url['query'] ) ) {
 830              $url .= '?' . $parsed_url['query'];
 831          }
 832      }
 833  
 834      return $url;
 835  }
 836  
 837  /**
 838   * Attempts to guess the correct URL for a 404 request based on query vars.
 839   *
 840   * @since 2.3.0
 841   *
 842   * @global wpdb $wpdb WordPress database abstraction object.
 843   *
 844   * @return string|false The correct URL if one is found. False on failure.
 845   */
 846  function redirect_guess_404_permalink() {
 847      global $wpdb;
 848  
 849      /**
 850       * Filters whether to attempt to guess a redirect URL for a 404 request.
 851       *
 852       * Returning a false value from the filter will disable the URL guessing
 853       * and return early without performing a redirect.
 854       *
 855       * @since 5.5.0
 856       *
 857       * @param bool $do_redirect_guess Whether to attempt to guess a redirect URL
 858       *                                for a 404 request. Default true.
 859       */
 860      if ( false === apply_filters( 'do_redirect_guess_404_permalink', true ) ) {
 861          return false;
 862      }
 863  
 864      /**
 865       * Short-circuits the redirect URL guessing for 404 requests.
 866       *
 867       * Returning a non-null value from the filter will effectively short-circuit
 868       * the URL guessing, returning the passed value instead.
 869       *
 870       * @since 5.5.0
 871       *
 872       * @param null|string|false $pre Whether to short-circuit guessing the redirect for a 404.
 873       *                               Default null to continue with the URL guessing.
 874       */
 875      $pre = apply_filters( 'pre_redirect_guess_404_permalink', null );
 876      if ( null !== $pre ) {
 877          return $pre;
 878      }
 879  
 880      if ( get_query_var( 'name' ) ) {
 881          /**
 882           * Filters whether to perform a strict guess for a 404 redirect.
 883           *
 884           * Returning a truthy value from the filter will redirect only exact post_name matches.
 885           *
 886           * @since 5.5.0
 887           *
 888           * @param bool $strict_guess Whether to perform a strict guess. Default false (loose guess).
 889           */
 890          $strict_guess = apply_filters( 'strict_redirect_guess_404_permalink', false );
 891  
 892          if ( $strict_guess ) {
 893              $where = $wpdb->prepare( 'post_name = %s', get_query_var( 'name' ) );
 894          } else {
 895              $where = $wpdb->prepare( 'post_name LIKE %s', $wpdb->esc_like( get_query_var( 'name' ) ) . '%' );
 896          }
 897  
 898          // If any of post_type, year, monthnum, or day are set, use them to refine the query.
 899          if ( get_query_var( 'post_type' ) ) {
 900              $where .= $wpdb->prepare( ' AND post_type = %s', get_query_var( 'post_type' ) );
 901          } else {
 902              $where .= " AND post_type IN ('" . implode( "', '", get_post_types( array( 'public' => true ) ) ) . "')";
 903          }
 904  
 905          if ( get_query_var( 'year' ) ) {
 906              $where .= $wpdb->prepare( ' AND YEAR(post_date) = %d', get_query_var( 'year' ) );
 907          }
 908          if ( get_query_var( 'monthnum' ) ) {
 909              $where .= $wpdb->prepare( ' AND MONTH(post_date) = %d', get_query_var( 'monthnum' ) );
 910          }
 911          if ( get_query_var( 'day' ) ) {
 912              $where .= $wpdb->prepare( ' AND DAYOFMONTH(post_date) = %d', get_query_var( 'day' ) );
 913          }
 914  
 915          // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
 916          $post_id = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE $where AND post_status = 'publish'" );
 917  
 918          if ( ! $post_id ) {
 919              return false;
 920          }
 921  
 922          if ( get_query_var( 'feed' ) ) {
 923              return get_post_comments_feed_link( $post_id, get_query_var( 'feed' ) );
 924          } elseif ( get_query_var( 'page' ) > 1 ) {
 925              return trailingslashit( get_permalink( $post_id ) ) . user_trailingslashit( get_query_var( 'page' ), 'single_paged' );
 926          } else {
 927              return get_permalink( $post_id );
 928          }
 929      }
 930  
 931      return false;
 932  }
 933  
 934  /**
 935   * Redirects a variety of shorthand URLs to the admin.
 936   *
 937   * If a user visits example.com/admin, they'll be redirected to /wp-admin.
 938   * Visiting /login redirects to /wp-login.php, and so on.
 939   *
 940   * @since 3.4.0
 941   *
 942   * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
 943   */
 944  function wp_redirect_admin_locations() {
 945      global $wp_rewrite;
 946  
 947      if ( ! ( is_404() && $wp_rewrite->using_permalinks() ) ) {
 948          return;
 949      }
 950  
 951      $admins = array(
 952          home_url( 'wp-admin', 'relative' ),
 953          home_url( 'dashboard', 'relative' ),
 954          home_url( 'admin', 'relative' ),
 955          site_url( 'dashboard', 'relative' ),
 956          site_url( 'admin', 'relative' ),
 957      );
 958  
 959      if ( in_array( untrailingslashit( $_SERVER['REQUEST_URI'] ), $admins, true ) ) {
 960          wp_redirect( admin_url() );
 961          exit;
 962      }
 963  
 964      $logins = array(
 965          home_url( 'wp-login.php', 'relative' ),
 966          home_url( 'login', 'relative' ),
 967          site_url( 'login', 'relative' ),
 968      );
 969  
 970      if ( in_array( untrailingslashit( $_SERVER['REQUEST_URI'] ), $logins, true ) ) {
 971          wp_redirect( wp_login_url() );
 972          exit;
 973      }
 974  }


Generated: Tue Jul 7 01:00:03 2020 Cross-referenced by PHPXref 0.7.1