[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

title

Body

[close]

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

   1  <?php
   2  /**
   3   * WordPress Rewrite API
   4   *
   5   * @package WordPress
   6   * @subpackage Rewrite
   7   */
   8  
   9  /**
  10   * Endpoint Mask for default, which is nothing.
  11   *
  12   * @since 2.1.0
  13   */
  14  define( 'EP_NONE', 0 );
  15  
  16  /**
  17   * Endpoint Mask for Permalink.
  18   *
  19   * @since 2.1.0
  20   */
  21  define( 'EP_PERMALINK', 1 );
  22  
  23  /**
  24   * Endpoint Mask for Attachment.
  25   *
  26   * @since 2.1.0
  27   */
  28  define( 'EP_ATTACHMENT', 2 );
  29  
  30  /**
  31   * Endpoint Mask for date.
  32   *
  33   * @since 2.1.0
  34   */
  35  define( 'EP_DATE', 4 );
  36  
  37  /**
  38   * Endpoint Mask for year
  39   *
  40   * @since 2.1.0
  41   */
  42  define( 'EP_YEAR', 8 );
  43  
  44  /**
  45   * Endpoint Mask for month.
  46   *
  47   * @since 2.1.0
  48   */
  49  define( 'EP_MONTH', 16 );
  50  
  51  /**
  52   * Endpoint Mask for day.
  53   *
  54   * @since 2.1.0
  55   */
  56  define( 'EP_DAY', 32 );
  57  
  58  /**
  59   * Endpoint Mask for root.
  60   *
  61   * @since 2.1.0
  62   */
  63  define( 'EP_ROOT', 64 );
  64  
  65  /**
  66   * Endpoint Mask for comments.
  67   *
  68   * @since 2.1.0
  69   */
  70  define( 'EP_COMMENTS', 128 );
  71  
  72  /**
  73   * Endpoint Mask for searches.
  74   *
  75   * @since 2.1.0
  76   */
  77  define( 'EP_SEARCH', 256 );
  78  
  79  /**
  80   * Endpoint Mask for categories.
  81   *
  82   * @since 2.1.0
  83   */
  84  define( 'EP_CATEGORIES', 512 );
  85  
  86  /**
  87   * Endpoint Mask for tags.
  88   *
  89   * @since 2.3.0
  90   */
  91  define( 'EP_TAGS', 1024 );
  92  
  93  /**
  94   * Endpoint Mask for authors.
  95   *
  96   * @since 2.1.0
  97   */
  98  define( 'EP_AUTHORS', 2048 );
  99  
 100  /**
 101   * Endpoint Mask for pages.
 102   *
 103   * @since 2.1.0
 104   */
 105  define( 'EP_PAGES', 4096 );
 106  
 107  /**
 108   * Endpoint Mask for all archive views.
 109   *
 110   * @since 3.7.0
 111   */
 112  define( 'EP_ALL_ARCHIVES', EP_DATE | EP_YEAR | EP_MONTH | EP_DAY | EP_CATEGORIES | EP_TAGS | EP_AUTHORS );
 113  
 114  /**
 115   * Endpoint Mask for everything.
 116   *
 117   * @since 2.1.0
 118   */
 119  define( 'EP_ALL', EP_PERMALINK | EP_ATTACHMENT | EP_ROOT | EP_COMMENTS | EP_SEARCH | EP_PAGES | EP_ALL_ARCHIVES );
 120  
 121  /**
 122   * Adds a rewrite rule that transforms a URL structure to a set of query vars.
 123   *
 124   * Any value in the $after parameter that isn't 'bottom' will result in the rule
 125   * being placed at the top of the rewrite rules.
 126   *
 127   * @since 2.1.0
 128   * @since 4.4.0 Array support was added to the `$query` parameter.
 129   *
 130   * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
 131   *
 132   * @param string       $regex Regular expression to match request against.
 133   * @param string|array $query The corresponding query vars for this rewrite rule.
 134   * @param string       $after Optional. Priority of the new rule. Accepts 'top'
 135   *                            or 'bottom'. Default 'bottom'.
 136   */
 137  function add_rewrite_rule( $regex, $query, $after = 'bottom' ) {
 138      global $wp_rewrite;
 139  
 140      $wp_rewrite->add_rule( $regex, $query, $after );
 141  }
 142  
 143  /**
 144   * Add a new rewrite tag (like %postname%).
 145   *
 146   * The $query parameter is optional. If it is omitted you must ensure that
 147   * you call this on, or before, the {@see 'init'} hook. This is because $query defaults
 148   * to "$tag=", and for this to work a new query var has to be added.
 149   *
 150   * @since 2.1.0
 151   *
 152   * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
 153   * @global WP         $wp         Current WordPress environment instance.
 154   *
 155   * @param string $tag   Name of the new rewrite tag.
 156   * @param string $regex Regular expression to substitute the tag for in rewrite rules.
 157   * @param string $query Optional. String to append to the rewritten query. Must end in '='. Default empty.
 158   */
 159  function add_rewrite_tag( $tag, $regex, $query = '' ) {
 160      // validate the tag's name
 161      if ( strlen( $tag ) < 3 || $tag[0] != '%' || $tag[ strlen( $tag ) - 1 ] != '%' ) {
 162          return;
 163      }
 164  
 165      global $wp_rewrite, $wp;
 166  
 167      if ( empty( $query ) ) {
 168          $qv = trim( $tag, '%' );
 169          $wp->add_query_var( $qv );
 170          $query = $qv . '=';
 171      }
 172  
 173      $wp_rewrite->add_rewrite_tag( $tag, $regex, $query );
 174  }
 175  
 176  /**
 177   * Removes an existing rewrite tag (like %postname%).
 178   *
 179   * @since 4.5.0
 180   *
 181   * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
 182   *
 183   * @param string $tag Name of the rewrite tag.
 184   */
 185  function remove_rewrite_tag( $tag ) {
 186      global $wp_rewrite;
 187      $wp_rewrite->remove_rewrite_tag( $tag );
 188  }
 189  
 190  /**
 191   * Add permalink structure.
 192   *
 193   * @since 3.0.0
 194   *
 195   * @see WP_Rewrite::add_permastruct()
 196   * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
 197   *
 198   * @param string $name   Name for permalink structure.
 199   * @param string $struct Permalink structure.
 200   * @param array  $args   Optional. Arguments for building the rules from the permalink structure,
 201   *                       see WP_Rewrite::add_permastruct() for full details. Default empty array.
 202   */
 203  function add_permastruct( $name, $struct, $args = array() ) {
 204      global $wp_rewrite;
 205  
 206      // Back-compat for the old parameters: $with_front and $ep_mask.
 207      if ( ! is_array( $args ) ) {
 208          $args = array( 'with_front' => $args );
 209      }
 210      if ( func_num_args() == 4 ) {
 211          $args['ep_mask'] = func_get_arg( 3 );
 212      }
 213  
 214      $wp_rewrite->add_permastruct( $name, $struct, $args );
 215  }
 216  
 217  /**
 218   * Removes a permalink structure.
 219   *
 220   * Can only be used to remove permastructs that were added using add_permastruct().
 221   * Built-in permastructs cannot be removed.
 222   *
 223   * @since 4.5.0
 224   *
 225   * @see WP_Rewrite::remove_permastruct()
 226   * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
 227   *
 228   * @param string $name Name for permalink structure.
 229   */
 230  function remove_permastruct( $name ) {
 231      global $wp_rewrite;
 232  
 233      $wp_rewrite->remove_permastruct( $name );
 234  }
 235  
 236  /**
 237   * Add a new feed type like /atom1/.
 238   *
 239   * @since 2.1.0
 240   *
 241   * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
 242   *
 243   * @param string   $feedname Feed name.
 244   * @param callable $function Callback to run on feed display.
 245   * @return string Feed action name.
 246   */
 247  function add_feed( $feedname, $function ) {
 248      global $wp_rewrite;
 249  
 250      if ( ! in_array( $feedname, $wp_rewrite->feeds ) ) {
 251          $wp_rewrite->feeds[] = $feedname;
 252      }
 253  
 254      $hook = 'do_feed_' . $feedname;
 255  
 256      // Remove default function hook
 257      remove_action( $hook, $hook );
 258  
 259      add_action( $hook, $function, 10, 2 );
 260  
 261      return $hook;
 262  }
 263  
 264  /**
 265   * Remove rewrite rules and then recreate rewrite rules.
 266   *
 267   * @since 3.0.0
 268   *
 269   * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
 270   *
 271   * @param bool $hard Whether to update .htaccess (hard flush) or just update
 272   *                   rewrite_rules transient (soft flush). Default is true (hard).
 273   */
 274  function flush_rewrite_rules( $hard = true ) {
 275      global $wp_rewrite;
 276  
 277      if ( is_callable( array( $wp_rewrite, 'flush_rules' ) ) ) {
 278          $wp_rewrite->flush_rules( $hard );
 279      }
 280  }
 281  
 282  /**
 283   * Add an endpoint, like /trackback/.
 284   *
 285   * Adding an endpoint creates extra rewrite rules for each of the matching
 286   * places specified by the provided bitmask. For example:
 287   *
 288   *     add_rewrite_endpoint( 'json', EP_PERMALINK | EP_PAGES );
 289   *
 290   * will add a new rewrite rule ending with "json(/(.*))?/?$" for every permastruct
 291   * that describes a permalink (post) or page. This is rewritten to "json=$match"
 292   * where $match is the part of the URL matched by the endpoint regex (e.g. "foo" in
 293   * "[permalink]/json/foo/").
 294   *
 295   * A new query var with the same name as the endpoint will also be created.
 296   *
 297   * When specifying $places ensure that you are using the EP_* constants (or a
 298   * combination of them using the bitwise OR operator) as their values are not
 299   * guaranteed to remain static (especially `EP_ALL`).
 300   *
 301   * Be sure to flush the rewrite rules - see flush_rewrite_rules() - when your plugin gets
 302   * activated and deactivated.
 303   *
 304   * @since 2.1.0
 305   * @since 4.3.0 Added support for skipping query var registration by passing `false` to `$query_var`.
 306   *
 307   * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
 308   *
 309   * @param string      $name      Name of the endpoint.
 310   * @param int         $places    Endpoint mask describing the places the endpoint should be added.
 311   * @param string|bool $query_var Name of the corresponding query variable. Pass `false` to skip registering a query_var
 312   *                               for this endpoint. Defaults to the value of `$name`.
 313   */
 314  function add_rewrite_endpoint( $name, $places, $query_var = true ) {
 315      global $wp_rewrite;
 316      $wp_rewrite->add_endpoint( $name, $places, $query_var );
 317  }
 318  
 319  /**
 320   * Filters the URL base for taxonomies.
 321   *
 322   * To remove any manually prepended /index.php/.
 323   *
 324   * @access private
 325   * @since 2.6.0
 326   *
 327   * @param string $base The taxonomy base that we're going to filter
 328   * @return string
 329   */
 330  function _wp_filter_taxonomy_base( $base ) {
 331      if ( ! empty( $base ) ) {
 332          $base = preg_replace( '|^/index\.php/|', '', $base );
 333          $base = trim( $base, '/' );
 334      }
 335      return $base;
 336  }
 337  
 338  
 339  /**
 340   * Resolve numeric slugs that collide with date permalinks.
 341   *
 342   * Permalinks of posts with numeric slugs can sometimes look to WP_Query::parse_query()
 343   * like a date archive, as when your permalink structure is `/%year%/%postname%/` and
 344   * a post with post_name '05' has the URL `/2015/05/`.
 345   *
 346   * This function detects conflicts of this type and resolves them in favor of the
 347   * post permalink.
 348   *
 349   * Note that, since 4.3.0, wp_unique_post_slug() prevents the creation of post slugs
 350   * that would result in a date archive conflict. The resolution performed in this
 351   * function is primarily for legacy content, as well as cases when the admin has changed
 352   * the site's permalink structure in a way that introduces URL conflicts.
 353   *
 354   * @since 4.3.0
 355   *
 356   * @param array $query_vars Optional. Query variables for setting up the loop, as determined in
 357   *                          WP::parse_request(). Default empty array.
 358   * @return array Returns the original array of query vars, with date/post conflicts resolved.
 359   */
 360  function wp_resolve_numeric_slug_conflicts( $query_vars = array() ) {
 361      if ( ! isset( $query_vars['year'] ) && ! isset( $query_vars['monthnum'] ) && ! isset( $query_vars['day'] ) ) {
 362          return $query_vars;
 363      }
 364  
 365      // Identify the 'postname' position in the permastruct array.
 366      $permastructs   = array_values( array_filter( explode( '/', get_option( 'permalink_structure' ) ) ) );
 367      $postname_index = array_search( '%postname%', $permastructs );
 368  
 369      if ( false === $postname_index ) {
 370          return $query_vars;
 371      }
 372  
 373      /*
 374       * A numeric slug could be confused with a year, month, or day, depending on position. To account for
 375       * the possibility of post pagination (eg 2015/2 for the second page of a post called '2015'), our
 376       * `is_*` checks are generous: check for year-slug clashes when `is_year` *or* `is_month`, and check
 377       * for month-slug clashes when `is_month` *or* `is_day`.
 378       */
 379      $compare = '';
 380      if ( 0 === $postname_index && ( isset( $query_vars['year'] ) || isset( $query_vars['monthnum'] ) ) ) {
 381          $compare = 'year';
 382      } elseif ( $postname_index && '%year%' === $permastructs[ $postname_index - 1 ] && ( isset( $query_vars['monthnum'] ) || isset( $query_vars['day'] ) ) ) {
 383          $compare = 'monthnum';
 384      } elseif ( $postname_index && '%monthnum%' === $permastructs[ $postname_index - 1 ] && isset( $query_vars['day'] ) ) {
 385          $compare = 'day';
 386      }
 387  
 388      if ( ! $compare ) {
 389          return $query_vars;
 390      }
 391  
 392      // This is the potentially clashing slug.
 393      $value = $query_vars[ $compare ];
 394  
 395      $post = get_page_by_path( $value, OBJECT, 'post' );
 396      if ( ! ( $post instanceof WP_Post ) ) {
 397          return $query_vars;
 398      }
 399  
 400      // If the date of the post doesn't match the date specified in the URL, resolve to the date archive.
 401      if ( preg_match( '/^([0-9]{4})\-([0-9]{2})/', $post->post_date, $matches ) && isset( $query_vars['year'] ) && ( 'monthnum' === $compare || 'day' === $compare ) ) {
 402          // $matches[1] is the year the post was published.
 403          if ( intval( $query_vars['year'] ) !== intval( $matches[1] ) ) {
 404              return $query_vars;
 405          }
 406  
 407          // $matches[2] is the month the post was published.
 408          if ( 'day' === $compare && isset( $query_vars['monthnum'] ) && intval( $query_vars['monthnum'] ) !== intval( $matches[2] ) ) {
 409              return $query_vars;
 410          }
 411      }
 412  
 413      /*
 414       * If the located post contains nextpage pagination, then the URL chunk following postname may be
 415       * intended as the page number. Verify that it's a valid page before resolving to it.
 416       */
 417      $maybe_page = '';
 418      if ( 'year' === $compare && isset( $query_vars['monthnum'] ) ) {
 419          $maybe_page = $query_vars['monthnum'];
 420      } elseif ( 'monthnum' === $compare && isset( $query_vars['day'] ) ) {
 421          $maybe_page = $query_vars['day'];
 422      }
 423      // Bug found in #11694 - 'page' was returning '/4'
 424      $maybe_page = (int) trim( $maybe_page, '/' );
 425  
 426      $post_page_count = substr_count( $post->post_content, '<!--nextpage-->' ) + 1;
 427  
 428      // If the post doesn't have multiple pages, but a 'page' candidate is found, resolve to the date archive.
 429      if ( 1 === $post_page_count && $maybe_page ) {
 430          return $query_vars;
 431      }
 432  
 433      // If the post has multiple pages and the 'page' number isn't valid, resolve to the date archive.
 434      if ( $post_page_count > 1 && $maybe_page > $post_page_count ) {
 435          return $query_vars;
 436      }
 437  
 438      // If we've gotten to this point, we have a slug/date clash. First, adjust for nextpage.
 439      if ( '' !== $maybe_page ) {
 440          $query_vars['page'] = intval( $maybe_page );
 441      }
 442  
 443      // Next, unset autodetected date-related query vars.
 444      unset( $query_vars['year'] );
 445      unset( $query_vars['monthnum'] );
 446      unset( $query_vars['day'] );
 447  
 448      // Then, set the identified post.
 449      $query_vars['name'] = $post->post_name;
 450  
 451      // Finally, return the modified query vars.
 452      return $query_vars;
 453  }
 454  
 455  /**
 456   * Examine a URL and try to determine the post ID it represents.
 457   *
 458   * Checks are supposedly from the hosted site blog.
 459   *
 460   * @since 1.0.0
 461   *
 462   * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
 463   * @global WP         $wp         Current WordPress environment instance.
 464   *
 465   * @param string $url Permalink to check.
 466   * @return int Post ID, or 0 on failure.
 467   */
 468  function url_to_postid( $url ) {
 469      global $wp_rewrite;
 470  
 471      /**
 472       * Filters the URL to derive the post ID from.
 473       *
 474       * @since 2.2.0
 475       *
 476       * @param string $url The URL to derive the post ID from.
 477       */
 478      $url = apply_filters( 'url_to_postid', $url );
 479  
 480      $url_host      = str_replace( 'www.', '', parse_url( $url, PHP_URL_HOST ) );
 481      $home_url_host = str_replace( 'www.', '', parse_url( home_url(), PHP_URL_HOST ) );
 482  
 483      // Bail early if the URL does not belong to this site.
 484      if ( $url_host && $url_host !== $home_url_host ) {
 485          return 0;
 486      }
 487  
 488      // First, check to see if there is a 'p=N' or 'page_id=N' to match against
 489      if ( preg_match( '#[?&](p|page_id|attachment_id)=(\d+)#', $url, $values ) ) {
 490          $id = absint( $values[2] );
 491          if ( $id ) {
 492              return $id;
 493          }
 494      }
 495  
 496      // Get rid of the #anchor
 497      $url_split = explode( '#', $url );
 498      $url       = $url_split[0];
 499  
 500      // Get rid of URL ?query=string
 501      $url_split = explode( '?', $url );
 502      $url       = $url_split[0];
 503  
 504      // Set the correct URL scheme.
 505      $scheme = parse_url( home_url(), PHP_URL_SCHEME );
 506      $url    = set_url_scheme( $url, $scheme );
 507  
 508      // Add 'www.' if it is absent and should be there
 509      if ( false !== strpos( home_url(), '://www.' ) && false === strpos( $url, '://www.' ) ) {
 510          $url = str_replace( '://', '://www.', $url );
 511      }
 512  
 513      // Strip 'www.' if it is present and shouldn't be
 514      if ( false === strpos( home_url(), '://www.' ) ) {
 515          $url = str_replace( '://www.', '://', $url );
 516      }
 517  
 518      if ( trim( $url, '/' ) === home_url() && 'page' == get_option( 'show_on_front' ) ) {
 519          $page_on_front = get_option( 'page_on_front' );
 520  
 521          if ( $page_on_front && get_post( $page_on_front ) instanceof WP_Post ) {
 522              return (int) $page_on_front;
 523          }
 524      }
 525  
 526      // Check to see if we are using rewrite rules
 527      $rewrite = $wp_rewrite->wp_rewrite_rules();
 528  
 529      // Not using rewrite rules, and 'p=N' and 'page_id=N' methods failed, so we're out of options
 530      if ( empty( $rewrite ) ) {
 531          return 0;
 532      }
 533  
 534      // Strip 'index.php/' if we're not using path info permalinks
 535      if ( ! $wp_rewrite->using_index_permalinks() ) {
 536          $url = str_replace( $wp_rewrite->index . '/', '', $url );
 537      }
 538  
 539      if ( false !== strpos( trailingslashit( $url ), home_url( '/' ) ) ) {
 540          // Chop off http://domain.com/[path]
 541          $url = str_replace( home_url(), '', $url );
 542      } else {
 543          // Chop off /path/to/blog
 544          $home_path = parse_url( home_url( '/' ) );
 545          $home_path = isset( $home_path['path'] ) ? $home_path['path'] : '';
 546          $url       = preg_replace( sprintf( '#^%s#', preg_quote( $home_path ) ), '', trailingslashit( $url ) );
 547      }
 548  
 549      // Trim leading and lagging slashes
 550      $url = trim( $url, '/' );
 551  
 552      $request              = $url;
 553      $post_type_query_vars = array();
 554  
 555      foreach ( get_post_types( array(), 'objects' ) as $post_type => $t ) {
 556          if ( ! empty( $t->query_var ) ) {
 557              $post_type_query_vars[ $t->query_var ] = $post_type;
 558          }
 559      }
 560  
 561      // Look for matches.
 562      $request_match = $request;
 563      foreach ( (array) $rewrite as $match => $query ) {
 564  
 565          // If the requesting file is the anchor of the match, prepend it
 566          // to the path info.
 567          if ( ! empty( $url ) && ( $url != $request ) && ( strpos( $match, $url ) === 0 ) ) {
 568              $request_match = $url . '/' . $request;
 569          }
 570  
 571          if ( preg_match( "#^$match#", $request_match, $matches ) ) {
 572  
 573              if ( $wp_rewrite->use_verbose_page_rules && preg_match( '/pagename=\$matches\[([0-9]+)\]/', $query, $varmatch ) ) {
 574                  // This is a verbose page match, let's check to be sure about it.
 575                  $page = get_page_by_path( $matches[ $varmatch[1] ] );
 576                  if ( ! $page ) {
 577                      continue;
 578                  }
 579  
 580                  $post_status_obj = get_post_status_object( $page->post_status );
 581                  if ( ! $post_status_obj->public && ! $post_status_obj->protected
 582                      && ! $post_status_obj->private && $post_status_obj->exclude_from_search ) {
 583                      continue;
 584                  }
 585              }
 586  
 587              // Got a match.
 588              // Trim the query of everything up to the '?'.
 589              $query = preg_replace( '!^.+\?!', '', $query );
 590  
 591              // Substitute the substring matches into the query.
 592              $query = addslashes( WP_MatchesMapRegex::apply( $query, $matches ) );
 593  
 594              // Filter out non-public query vars
 595              global $wp;
 596              parse_str( $query, $query_vars );
 597              $query = array();
 598              foreach ( (array) $query_vars as $key => $value ) {
 599                  if ( in_array( $key, $wp->public_query_vars ) ) {
 600                      $query[ $key ] = $value;
 601                      if ( isset( $post_type_query_vars[ $key ] ) ) {
 602                          $query['post_type'] = $post_type_query_vars[ $key ];
 603                          $query['name']      = $value;
 604                      }
 605                  }
 606              }
 607  
 608              // Resolve conflicts between posts with numeric slugs and date archive queries.
 609              $query = wp_resolve_numeric_slug_conflicts( $query );
 610  
 611              // Do the query
 612              $query = new WP_Query( $query );
 613              if ( ! empty( $query->posts ) && $query->is_singular ) {
 614                  return $query->post->ID;
 615              } else {
 616                  return 0;
 617              }
 618          }
 619      }
 620      return 0;
 621  }


Generated: Tue Sep 24 08:20:01 2019 Cross-referenced by PHPXref 0.7