[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

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


Generated : Tue Mar 19 08:20:01 2024 Cross-referenced by PHPXref