3 * WordPress environment setup class.
10 * Public query variables.
12 * Long list of public query variables.
18 public $public_query_vars = array('m', 'p', 'posts', 'w', 'cat', 'withcomments', 'withoutcomments', 's', 'search', 'exact', 'sentence', 'calendar', 'page', 'paged', 'more', 'tb', 'pb', 'author', 'order', 'orderby', 'year', 'monthnum', 'day', 'hour', 'minute', 'second', 'name', 'category_name', 'tag', 'feed', 'author_name', 'static', 'pagename', 'page_id', 'error', 'attachment', 'attachment_id', 'subpost', 'subpost_id', 'preview', 'robots', 'taxonomy', 'term', 'cpage', 'post_type', 'embed' );
21 * Private query variables.
23 * Long list of private query variables.
29 public $private_query_vars = array( 'offset', 'posts_per_page', 'posts_per_archive_page', 'showposts', 'nopaging', 'post_type', 'post_status', 'category__in', 'category__not_in', 'category__and', 'tag__in', 'tag__not_in', 'tag__and', 'tag_slug__in', 'tag_slug__and', 'tag_id', 'post_mime_type', 'perm', 'comments_per_page', 'post__in', 'post__not_in', 'post_parent', 'post_parent__in', 'post_parent__not_in', 'title' );
32 * Extra query variables set by the user.
38 public $extra_query_vars = array();
41 * Query variables for setting up the WordPress Query Loop.
50 * String parsed to set the query variables.
59 * The request path, e.g. 2015/05/06.
68 * Rewrite rule the request matched.
77 * Rewrite query the request matched.
83 public $matched_query;
86 * Whether already did the permalink.
92 public $did_permalink = false;
95 * Add name to list of public query variables.
100 * @param string $qv Query variable name.
102 public function add_query_var($qv) {
103 if ( !in_array($qv, $this->public_query_vars) )
104 $this->public_query_vars[] = $qv;
108 * Removes a query variable from a list of public query variables.
113 * @param string $name Query variable name.
115 public function remove_query_var( $name ) {
116 $this->public_query_vars = array_diff( $this->public_query_vars, array( $name ) );
120 * Set the value of a query variable.
125 * @param string $key Query variable name.
126 * @param mixed $value Query variable value.
128 public function set_query_var($key, $value) {
129 $this->query_vars[$key] = $value;
133 * Parse request to find correct WordPress query.
135 * Sets up the query variables based on the request. There are also many
136 * filters and actions that can be used to further manipulate the result.
141 * @global WP_Rewrite $wp_rewrite
143 * @param array|string $extra_query_vars Set the extra query variables.
145 public function parse_request($extra_query_vars = '') {
149 * Filters whether to parse the request.
153 * @param bool $bool Whether or not to parse the request. Default true.
154 * @param WP $this Current WordPress environment instance.
155 * @param array|string $extra_query_vars Extra passed query variables.
157 if ( ! apply_filters( 'do_parse_request', true, $this, $extra_query_vars ) )
160 $this->query_vars = array();
161 $post_type_query_vars = array();
163 if ( is_array( $extra_query_vars ) ) {
164 $this->extra_query_vars = & $extra_query_vars;
165 } elseif ( ! empty( $extra_query_vars ) ) {
166 parse_str( $extra_query_vars, $this->extra_query_vars );
168 // Process PATH_INFO, REQUEST_URI, and 404 for permalinks.
170 // Fetch the rewrite rules.
171 $rewrite = $wp_rewrite->wp_rewrite_rules();
173 if ( ! empty($rewrite) ) {
174 // If we match a rewrite rule, this will be cleared.
176 $this->did_permalink = true;
178 $pathinfo = isset( $_SERVER['PATH_INFO'] ) ? $_SERVER['PATH_INFO'] : '';
179 list( $pathinfo ) = explode( '?', $pathinfo );
180 $pathinfo = str_replace( "%", "%25", $pathinfo );
182 list( $req_uri ) = explode( '?', $_SERVER['REQUEST_URI'] );
183 $self = $_SERVER['PHP_SELF'];
184 $home_path = trim( parse_url( home_url(), PHP_URL_PATH ), '/' );
185 $home_path_regex = sprintf( '|^%s|i', preg_quote( $home_path, '|' ) );
187 // Trim path info from the end and the leading home path from the
188 // front. For path info requests, this leaves us with the requesting
189 // filename, if any. For 404 requests, this leaves us with the
190 // requested permalink.
191 $req_uri = str_replace($pathinfo, '', $req_uri);
192 $req_uri = trim($req_uri, '/');
193 $req_uri = preg_replace( $home_path_regex, '', $req_uri );
194 $req_uri = trim($req_uri, '/');
195 $pathinfo = trim($pathinfo, '/');
196 $pathinfo = preg_replace( $home_path_regex, '', $pathinfo );
197 $pathinfo = trim($pathinfo, '/');
198 $self = trim($self, '/');
199 $self = preg_replace( $home_path_regex, '', $self );
200 $self = trim($self, '/');
202 // The requested permalink is in $pathinfo for path info requests and
203 // $req_uri for other requests.
204 if ( ! empty($pathinfo) && !preg_match('|^.*' . $wp_rewrite->index . '$|', $pathinfo) ) {
205 $requested_path = $pathinfo;
207 // If the request uri is the index, blank it out so that we don't try to match it against a rule.
208 if ( $req_uri == $wp_rewrite->index )
210 $requested_path = $req_uri;
212 $requested_file = $req_uri;
214 $this->request = $requested_path;
217 $request_match = $requested_path;
218 if ( empty( $request_match ) ) {
219 // An empty request could only match against ^$ regex
220 if ( isset( $rewrite['$'] ) ) {
221 $this->matched_rule = '$';
222 $query = $rewrite['$'];
223 $matches = array('');
226 foreach ( (array) $rewrite as $match => $query ) {
227 // If the requested file is the anchor of the match, prepend it to the path info.
228 if ( ! empty($requested_file) && strpos($match, $requested_file) === 0 && $requested_file != $requested_path )
229 $request_match = $requested_file . '/' . $requested_path;
231 if ( preg_match("#^$match#", $request_match, $matches) ||
232 preg_match("#^$match#", urldecode($request_match), $matches) ) {
234 if ( $wp_rewrite->use_verbose_page_rules && preg_match( '/pagename=\$matches\[([0-9]+)\]/', $query, $varmatch ) ) {
235 // This is a verbose page match, let's check to be sure about it.
236 $page = get_page_by_path( $matches[ $varmatch[1] ] );
241 $post_status_obj = get_post_status_object( $page->post_status );
242 if ( ! $post_status_obj->public && ! $post_status_obj->protected
243 && ! $post_status_obj->private && $post_status_obj->exclude_from_search ) {
249 $this->matched_rule = $match;
255 if ( isset( $this->matched_rule ) ) {
256 // Trim the query of everything up to the '?'.
257 $query = preg_replace("!^.+\?!", '', $query);
259 // Substitute the substring matches into the query.
260 $query = addslashes(WP_MatchesMapRegex::apply($query, $matches));
262 $this->matched_query = $query;
265 parse_str($query, $perma_query_vars);
267 // If we're processing a 404 request, clear the error var since we found something.
268 if ( '404' == $error )
269 unset( $error, $_GET['error'] );
272 // If req_uri is empty or if it is a request for ourself, unset error.
273 if ( empty($requested_path) || $requested_file == $self || strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false ) {
274 unset( $error, $_GET['error'] );
276 if ( isset($perma_query_vars) && strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false )
277 unset( $perma_query_vars );
279 $this->did_permalink = false;
284 * Filters the query variables whitelist before processing.
286 * Allows (publicly allowed) query vars to be added, removed, or changed prior
287 * to executing the query. Needed to allow custom rewrite rules using your own arguments
288 * to work, or any other custom query variables you want to be publicly available.
292 * @param array $public_query_vars The array of whitelisted query variables.
294 $this->public_query_vars = apply_filters( 'query_vars', $this->public_query_vars );
296 foreach ( get_post_types( array(), 'objects' ) as $post_type => $t ) {
297 if ( is_post_type_viewable( $t ) && $t->query_var ) {
298 $post_type_query_vars[$t->query_var] = $post_type;
302 foreach ( $this->public_query_vars as $wpvar ) {
303 if ( isset( $this->extra_query_vars[$wpvar] ) )
304 $this->query_vars[$wpvar] = $this->extra_query_vars[$wpvar];
305 elseif ( isset( $_POST[$wpvar] ) )
306 $this->query_vars[$wpvar] = $_POST[$wpvar];
307 elseif ( isset( $_GET[$wpvar] ) )
308 $this->query_vars[$wpvar] = $_GET[$wpvar];
309 elseif ( isset( $perma_query_vars[$wpvar] ) )
310 $this->query_vars[$wpvar] = $perma_query_vars[$wpvar];
312 if ( !empty( $this->query_vars[$wpvar] ) ) {
313 if ( ! is_array( $this->query_vars[$wpvar] ) ) {
314 $this->query_vars[$wpvar] = (string) $this->query_vars[$wpvar];
316 foreach ( $this->query_vars[$wpvar] as $vkey => $v ) {
317 if ( !is_object( $v ) ) {
318 $this->query_vars[$wpvar][$vkey] = (string) $v;
323 if ( isset($post_type_query_vars[$wpvar] ) ) {
324 $this->query_vars['post_type'] = $post_type_query_vars[$wpvar];
325 $this->query_vars['name'] = $this->query_vars[$wpvar];
330 // Convert urldecoded spaces back into +
331 foreach ( get_taxonomies( array() , 'objects' ) as $taxonomy => $t )
332 if ( $t->query_var && isset( $this->query_vars[$t->query_var] ) )
333 $this->query_vars[$t->query_var] = str_replace( ' ', '+', $this->query_vars[$t->query_var] );
335 // Don't allow non-publicly queryable taxonomies to be queried from the front end.
336 if ( ! is_admin() ) {
337 foreach ( get_taxonomies( array( 'publicly_queryable' => false ), 'objects' ) as $taxonomy => $t ) {
339 * Disallow when set to the 'taxonomy' query var.
340 * Non-publicly queryable taxonomies cannot register custom query vars. See register_taxonomy().
342 if ( isset( $this->query_vars['taxonomy'] ) && $taxonomy === $this->query_vars['taxonomy'] ) {
343 unset( $this->query_vars['taxonomy'], $this->query_vars['term'] );
348 // Limit publicly queried post_types to those that are publicly_queryable
349 if ( isset( $this->query_vars['post_type']) ) {
350 $queryable_post_types = get_post_types( array('publicly_queryable' => true) );
351 if ( ! is_array( $this->query_vars['post_type'] ) ) {
352 if ( ! in_array( $this->query_vars['post_type'], $queryable_post_types ) )
353 unset( $this->query_vars['post_type'] );
355 $this->query_vars['post_type'] = array_intersect( $this->query_vars['post_type'], $queryable_post_types );
359 // Resolve conflicts between posts with numeric slugs and date archive queries.
360 $this->query_vars = wp_resolve_numeric_slug_conflicts( $this->query_vars );
362 foreach ( (array) $this->private_query_vars as $var) {
363 if ( isset($this->extra_query_vars[$var]) )
364 $this->query_vars[$var] = $this->extra_query_vars[$var];
368 $this->query_vars['error'] = $error;
371 * Filters the array of parsed query variables.
375 * @param array $query_vars The array of requested query variables.
377 $this->query_vars = apply_filters( 'request', $this->query_vars );
380 * Fires once all query variables for the current request have been parsed.
384 * @param WP &$this Current WordPress environment instance (passed by reference).
386 do_action_ref_array( 'parse_request', array( &$this ) );
390 * Sends additional HTTP headers for caching, content type, etc.
392 * Sets the Content-Type header. Sets the 'error' status (if passed) and optionally exits.
393 * If showing a feed, it will also send Last-Modified, ETag, and 304 status if needed.
396 * @since 4.4.0 `X-Pingback` header is added conditionally after posts have been queried in handle_404().
399 public function send_headers() {
402 $exit_required = false;
404 if ( is_user_logged_in() )
405 $headers = array_merge($headers, wp_get_nocache_headers());
406 if ( ! empty( $this->query_vars['error'] ) ) {
407 $status = (int) $this->query_vars['error'];
408 if ( 404 === $status ) {
409 if ( ! is_user_logged_in() )
410 $headers = array_merge($headers, wp_get_nocache_headers());
411 $headers['Content-Type'] = get_option('html_type') . '; charset=' . get_option('blog_charset');
412 } elseif ( in_array( $status, array( 403, 500, 502, 503 ) ) ) {
413 $exit_required = true;
415 } elseif ( empty( $this->query_vars['feed'] ) ) {
416 $headers['Content-Type'] = get_option('html_type') . '; charset=' . get_option('blog_charset');
418 // Set the correct content type for feeds
419 $type = $this->query_vars['feed'];
420 if ( 'feed' == $this->query_vars['feed'] ) {
421 $type = get_default_feed();
423 $headers['Content-Type'] = feed_content_type( $type ) . '; charset=' . get_option( 'blog_charset' );
425 // We're showing a feed, so WP is indeed the only thing that last changed
426 if ( !empty($this->query_vars['withcomments'])
427 || false !== strpos( $this->query_vars['feed'], 'comments-' )
428 || ( empty($this->query_vars['withoutcomments'])
429 && ( !empty($this->query_vars['p'])
430 || !empty($this->query_vars['name'])
431 || !empty($this->query_vars['page_id'])
432 || !empty($this->query_vars['pagename'])
433 || !empty($this->query_vars['attachment'])
434 || !empty($this->query_vars['attachment_id'])
438 $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastcommentmodified('GMT'), 0).' GMT';
440 $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastpostmodified('GMT'), 0).' GMT';
441 $wp_etag = '"' . md5($wp_last_modified) . '"';
442 $headers['Last-Modified'] = $wp_last_modified;
443 $headers['ETag'] = $wp_etag;
445 // Support for Conditional GET
446 if (isset($_SERVER['HTTP_IF_NONE_MATCH']))
447 $client_etag = wp_unslash( $_SERVER['HTTP_IF_NONE_MATCH'] );
448 else $client_etag = false;
450 $client_last_modified = empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? '' : trim($_SERVER['HTTP_IF_MODIFIED_SINCE']);
451 // If string is empty, return 0. If not, attempt to parse into a timestamp
452 $client_modified_timestamp = $client_last_modified ? strtotime($client_last_modified) : 0;
454 // Make a timestamp for our most recent modification...
455 $wp_modified_timestamp = strtotime($wp_last_modified);
457 if ( ($client_last_modified && $client_etag) ?
458 (($client_modified_timestamp >= $wp_modified_timestamp) && ($client_etag == $wp_etag)) :
459 (($client_modified_timestamp >= $wp_modified_timestamp) || ($client_etag == $wp_etag)) ) {
461 $exit_required = true;
466 * Filters the HTTP headers before they're sent to the browser.
470 * @param array $headers The list of headers to be sent.
471 * @param WP $this Current WordPress environment instance.
473 $headers = apply_filters( 'wp_headers', $headers, $this );
475 if ( ! empty( $status ) )
476 status_header( $status );
478 // If Last-Modified is set to false, it should not be sent (no-cache situation).
479 if ( isset( $headers['Last-Modified'] ) && false === $headers['Last-Modified'] ) {
480 unset( $headers['Last-Modified'] );
482 // In PHP 5.3+, make sure we are not sending a Last-Modified header.
483 if ( function_exists( 'header_remove' ) ) {
484 @header_remove( 'Last-Modified' );
486 // In PHP 5.2, send an empty Last-Modified header, but only as a
487 // last resort to override a header already sent. #WP23021
488 foreach ( headers_list() as $header ) {
489 if ( 0 === stripos( $header, 'Last-Modified' ) ) {
490 $headers['Last-Modified'] = '';
497 foreach ( (array) $headers as $name => $field_value )
498 @header("{$name}: {$field_value}");
500 if ( $exit_required )
504 * Fires once the requested HTTP headers for caching, content type, etc. have been sent.
508 * @param WP &$this Current WordPress environment instance (passed by reference).
510 do_action_ref_array( 'send_headers', array( &$this ) );
514 * Sets the query string property based off of the query variable property.
516 * The {@see 'query_string'} filter is deprecated, but still works. Plugins should
517 * use the {@see 'request'} filter instead.
522 public function build_query_string() {
523 $this->query_string = '';
524 foreach ( (array) array_keys($this->query_vars) as $wpvar) {
525 if ( '' != $this->query_vars[$wpvar] ) {
526 $this->query_string .= (strlen($this->query_string) < 1) ? '' : '&';
527 if ( !is_scalar($this->query_vars[$wpvar]) ) // Discard non-scalars.
529 $this->query_string .= $wpvar . '=' . rawurlencode($this->query_vars[$wpvar]);
533 if ( has_filter( 'query_string' ) ) { // Don't bother filtering and parsing if no plugins are hooked in.
535 * Filters the query string before parsing.
538 * @deprecated 2.1.0 Use 'query_vars' or 'request' filters instead.
540 * @param string $query_string The query string to modify.
542 $this->query_string = apply_filters( 'query_string', $this->query_string );
543 parse_str($this->query_string, $this->query_vars);
548 * Set up the WordPress Globals.
550 * The query_vars property will be extracted to the GLOBALS. So care should
551 * be taken when naming global variables that might interfere with the
552 * WordPress environment.
557 * @global WP_Query $wp_query
558 * @global string $query_string Query string for the loop.
559 * @global array $posts The found posts.
560 * @global WP_Post|null $post The current post, if available.
561 * @global string $request The SQL statement for the request.
562 * @global int $more Only set, if single page or post.
563 * @global int $single If single page or post. Only set, if single page or post.
564 * @global WP_User $authordata Only set, if author archive.
566 public function register_globals() {
569 // Extract updated query vars back into global namespace.
570 foreach ( (array) $wp_query->query_vars as $key => $value ) {
571 $GLOBALS[ $key ] = $value;
574 $GLOBALS['query_string'] = $this->query_string;
575 $GLOBALS['posts'] = & $wp_query->posts;
576 $GLOBALS['post'] = isset( $wp_query->post ) ? $wp_query->post : null;
577 $GLOBALS['request'] = $wp_query->request;
579 if ( $wp_query->is_single() || $wp_query->is_page() ) {
580 $GLOBALS['more'] = 1;
581 $GLOBALS['single'] = 1;
584 if ( $wp_query->is_author() && isset( $wp_query->post ) )
585 $GLOBALS['authordata'] = get_userdata( $wp_query->post->post_author );
589 * Set up the current user.
594 public function init() {
595 wp_get_current_user();
599 * Set up the Loop based on the query variables.
604 * @global WP_Query $wp_the_query
606 public function query_posts() {
607 global $wp_the_query;
608 $this->build_query_string();
609 $wp_the_query->query($this->query_vars);
613 * Set the Headers for 404, if nothing is found for requested URL.
615 * Issue a 404 if a request doesn't match any posts and doesn't match
616 * any object (e.g. an existing-but-empty category, tag, author) and a 404 was not already
617 * issued, and if the request was not a search or the homepage.
619 * Otherwise, issue a 200.
621 * This sets headers after posts have been queried. handle_404() really means "handle status."
622 * By inspecting the result of querying posts, seemingly successful requests can be switched to
623 * a 404 so that canonical redirection logic can kick in.
628 * @global WP_Query $wp_query
630 public function handle_404() {
634 * Filters whether to short-circuit default header status handling.
636 * Returning a non-false value from the filter will short-circuit the handling
641 * @param bool $preempt Whether to short-circuit default header status handling. Default false.
642 * @param WP_Query $wp_query WordPress Query object.
644 if ( false !== apply_filters( 'pre_handle_404', false, $wp_query ) ) {
648 // If we've already issued a 404, bail.
652 // Never 404 for the admin, robots, or if we found posts.
653 if ( is_admin() || is_robots() || $wp_query->posts ) {
656 if ( is_singular() ) {
659 if ( $wp_query->post instanceof WP_Post ) {
660 $p = clone $wp_query->post;
663 // Only set X-Pingback for single posts that allow pings.
664 if ( $p && pings_open( $p ) ) {
665 @header( 'X-Pingback: ' . get_bloginfo( 'pingback_url' ) );
668 // check for paged content that exceeds the max number of pages
669 $next = '<!--nextpage-->';
670 if ( $p && false !== strpos( $p->post_content, $next ) && ! empty( $this->query_vars['page'] ) ) {
671 $page = trim( $this->query_vars['page'], '/' );
672 $success = (int) $page <= ( substr_count( $p->post_content, $next ) + 1 );
677 status_header( 200 );
682 // We will 404 for paged queries, as no posts were found.
683 if ( ! is_paged() ) {
685 // Don't 404 for authors without posts as long as they matched an author on this site.
686 $author = get_query_var( 'author' );
687 if ( is_author() && is_numeric( $author ) && $author > 0 && is_user_member_of_blog( $author ) ) {
688 status_header( 200 );
692 // Don't 404 for these queries if they matched an object.
693 if ( ( is_tag() || is_category() || is_tax() || is_post_type_archive() ) && get_queried_object() ) {
694 status_header( 200 );
698 // Don't 404 for these queries either.
699 if ( is_home() || is_search() || is_feed() ) {
700 status_header( 200 );
705 // Guess it's time to 404.
706 $wp_query->set_404();
707 status_header( 404 );
712 * Sets up all of the variables required by the WordPress environment.
714 * The action {@see 'wp'} has one parameter that references the WP object. It
715 * allows for accessing the properties and methods to further manipulate the
721 * @param string|array $query_args Passed to parse_request().
723 public function main($query_args = '') {
725 $this->parse_request($query_args);
726 $this->send_headers();
727 $this->query_posts();
729 $this->register_globals();
732 * Fires once the WordPress environment has been set up.
736 * @param WP &$this Current WordPress environment instance (passed by reference).
738 do_action_ref_array( 'wp', array( &$this ) );
743 * Helper class to remove the need to use eval to replace $matches[] in query strings.
747 class WP_MatchesMapRegex {
757 * store for mapping result
765 * subject to perform mapping on (query string containing $matches[] references
773 * regexp pattern to match $matches[] references
777 public $_pattern = '(\$matches\[[1-9]+[0-9]*\])'; // magic number
782 * @param string $subject subject if regex
783 * @param array $matches data to use in map
785 public function __construct($subject, $matches) {
786 $this->_subject = $subject;
787 $this->_matches = $matches;
788 $this->output = $this->_map();
792 * Substitute substring matches in subject.
794 * static helper function to ease use
799 * @param string $subject subject
800 * @param array $matches data used for substitution
803 public static function apply($subject, $matches) {
804 $oSelf = new WP_MatchesMapRegex($subject, $matches);
805 return $oSelf->output;
809 * do the actual mapping
814 private function _map() {
815 $callback = array($this, 'callback');
816 return preg_replace_callback($this->_pattern, $callback, $this->_subject);
820 * preg_replace_callback hook
823 * @param array $matches preg_replace regexp matches
826 public function callback($matches) {
827 $index = intval(substr($matches[0], 9, -1));
828 return ( isset( $this->_matches[$index] ) ? urlencode($this->_matches[$index]) : '' );