Make WordPress Core


Ignore:
Timestamp:
08/26/2015 04:41:29 AM (9 years ago)
Author:
wonderboymusic
Message:

Rewrite: move WP_Rewrite into its own file. rewrite.php loads the new files, so this is 100% BC if someone is loading rewrite.php directly. New files created using svn cp.

The rewrite functions have all kinds of cross-dependencies (like WP_Query), so loading the file by itself would have been bizarre (and still is).

Creates:
rewrite-constants.php
rewrite-functions.php
class-wp-rewrite.php

rewrite.php contains only top-level code. Class file only contains the class. Functions file only contains functions.

See #33413.

File:
1 copied

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/class-wp-rewrite.php

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