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', 'comments_popup', 'attachment', 'attachment_id', 'subpost', 'subpost_id', 'preview', 'robots', 'taxonomy', 'term', 'cpage', 'post_type', 'title', 'embed' );
21 * Private query variables.
23 * Long list of private query variables.
28 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' );
31 * Extra query variables set by the user.
36 public $extra_query_vars = array();
39 * Query variables for setting up the WordPress Query Loop.
47 * String parsed to set the query variables.
55 * Permalink or requested URI.
63 * Rewrite rule the request matched.
71 * Rewrite query the request matched.
76 public $matched_query;
79 * Whether already did the permalink.
84 public $did_permalink = false;
87 * Add name to list of public query variables.
91 * @param string $qv Query variable name.
93 public function add_query_var($qv) {
94 if ( !in_array($qv, $this->public_query_vars) )
95 $this->public_query_vars[] = $qv;
99 * Set the value of a query variable.
103 * @param string $key Query variable name.
104 * @param mixed $value Query variable value.
106 public function set_query_var($key, $value) {
107 $this->query_vars[$key] = $value;
111 * Parse request to find correct WordPress query.
113 * Sets up the query variables based on the request. There are also many
114 * filters and actions that can be used to further manipulate the result.
118 * @global WP_Rewrite $wp_rewrite
120 * @param array|string $extra_query_vars Set the extra query variables.
122 public function parse_request($extra_query_vars = '') {
126 * Filter whether to parse the request.
130 * @param bool $bool Whether or not to parse the request. Default true.
131 * @param WP $this Current WordPress environment instance.
132 * @param array|string $extra_query_vars Extra passed query variables.
134 if ( ! apply_filters( 'do_parse_request', true, $this, $extra_query_vars ) )
137 $this->query_vars = array();
138 $post_type_query_vars = array();
140 if ( is_array( $extra_query_vars ) ) {
141 $this->extra_query_vars = & $extra_query_vars;
142 } elseif ( ! empty( $extra_query_vars ) ) {
143 parse_str( $extra_query_vars, $this->extra_query_vars );
145 // Process PATH_INFO, REQUEST_URI, and 404 for permalinks.
147 // Fetch the rewrite rules.
148 $rewrite = $wp_rewrite->wp_rewrite_rules();
150 if ( ! empty($rewrite) ) {
151 // If we match a rewrite rule, this will be cleared.
153 $this->did_permalink = true;
155 $pathinfo = isset( $_SERVER['PATH_INFO'] ) ? $_SERVER['PATH_INFO'] : '';
156 list( $pathinfo ) = explode( '?', $pathinfo );
157 $pathinfo = str_replace( "%", "%25", $pathinfo );
159 list( $req_uri ) = explode( '?', $_SERVER['REQUEST_URI'] );
160 $self = $_SERVER['PHP_SELF'];
161 $home_path = trim( parse_url( home_url(), PHP_URL_PATH ), '/' );
162 $home_path_regex = sprintf( '|^%s|i', preg_quote( $home_path, '|' ) );
164 // Trim path info from the end and the leading home path from the
165 // front. For path info requests, this leaves us with the requesting
166 // filename, if any. For 404 requests, this leaves us with the
167 // requested permalink.
168 $req_uri = str_replace($pathinfo, '', $req_uri);
169 $req_uri = trim($req_uri, '/');
170 $req_uri = preg_replace( $home_path_regex, '', $req_uri );
171 $req_uri = trim($req_uri, '/');
172 $pathinfo = trim($pathinfo, '/');
173 $pathinfo = preg_replace( $home_path_regex, '', $pathinfo );
174 $pathinfo = trim($pathinfo, '/');
175 $self = trim($self, '/');
176 $self = preg_replace( $home_path_regex, '', $self );
177 $self = trim($self, '/');
179 // The requested permalink is in $pathinfo for path info requests and
180 // $req_uri for other requests.
181 if ( ! empty($pathinfo) && !preg_match('|^.*' . $wp_rewrite->index . '$|', $pathinfo) ) {
182 $request = $pathinfo;
184 // If the request uri is the index, blank it out so that we don't try to match it against a rule.
185 if ( $req_uri == $wp_rewrite->index )
190 $this->request = $request;
193 $request_match = $request;
194 if ( empty( $request_match ) ) {
195 // An empty request could only match against ^$ regex
196 if ( isset( $rewrite['$'] ) ) {
197 $this->matched_rule = '$';
198 $query = $rewrite['$'];
199 $matches = array('');
202 foreach ( (array) $rewrite as $match => $query ) {
203 // If the requesting file is the anchor of the match, prepend it to the path info.
204 if ( ! empty($req_uri) && strpos($match, $req_uri) === 0 && $req_uri != $request )
205 $request_match = $req_uri . '/' . $request;
207 if ( preg_match("#^$match#", $request_match, $matches) ||
208 preg_match("#^$match#", urldecode($request_match), $matches) ) {
210 if ( $wp_rewrite->use_verbose_page_rules && preg_match( '/pagename=\$matches\[([0-9]+)\]/', $query, $varmatch ) ) {
211 // This is a verbose page match, let's check to be sure about it.
212 $page = get_page_by_path( $matches[ $varmatch[1] ] );
217 $post_status_obj = get_post_status_object( $page->post_status );
218 if ( ! $post_status_obj->public && ! $post_status_obj->protected
219 && ! $post_status_obj->private && $post_status_obj->exclude_from_search ) {
225 $this->matched_rule = $match;
231 if ( isset( $this->matched_rule ) ) {
232 // Trim the query of everything up to the '?'.
233 $query = preg_replace("!^.+\?!", '', $query);
235 // Substitute the substring matches into the query.
236 $query = addslashes(WP_MatchesMapRegex::apply($query, $matches));
238 $this->matched_query = $query;
241 parse_str($query, $perma_query_vars);
243 // If we're processing a 404 request, clear the error var since we found something.
244 if ( '404' == $error )
245 unset( $error, $_GET['error'] );
248 // If req_uri is empty or if it is a request for ourself, unset error.
249 if ( empty($request) || $req_uri == $self || strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false ) {
250 unset( $error, $_GET['error'] );
252 if ( isset($perma_query_vars) && strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false )
253 unset( $perma_query_vars );
255 $this->did_permalink = false;
260 * Filter the query variables whitelist before processing.
262 * Allows (publicly allowed) query vars to be added, removed, or changed prior
263 * to executing the query. Needed to allow custom rewrite rules using your own arguments
264 * to work, or any other custom query variables you want to be publicly available.
268 * @param array $public_query_vars The array of whitelisted query variables.
270 $this->public_query_vars = apply_filters( 'query_vars', $this->public_query_vars );
272 foreach ( get_post_types( array(), 'objects' ) as $post_type => $t ) {
273 if ( is_post_type_viewable( $t ) && $t->query_var ) {
274 $post_type_query_vars[$t->query_var] = $post_type;
278 foreach ( $this->public_query_vars as $wpvar ) {
279 if ( isset( $this->extra_query_vars[$wpvar] ) )
280 $this->query_vars[$wpvar] = $this->extra_query_vars[$wpvar];
281 elseif ( isset( $_POST[$wpvar] ) )
282 $this->query_vars[$wpvar] = $_POST[$wpvar];
283 elseif ( isset( $_GET[$wpvar] ) )
284 $this->query_vars[$wpvar] = $_GET[$wpvar];
285 elseif ( isset( $perma_query_vars[$wpvar] ) )
286 $this->query_vars[$wpvar] = $perma_query_vars[$wpvar];
288 if ( !empty( $this->query_vars[$wpvar] ) ) {
289 if ( ! is_array( $this->query_vars[$wpvar] ) ) {
290 $this->query_vars[$wpvar] = (string) $this->query_vars[$wpvar];
292 foreach ( $this->query_vars[$wpvar] as $vkey => $v ) {
293 if ( !is_object( $v ) ) {
294 $this->query_vars[$wpvar][$vkey] = (string) $v;
299 if ( isset($post_type_query_vars[$wpvar] ) ) {
300 $this->query_vars['post_type'] = $post_type_query_vars[$wpvar];
301 $this->query_vars['name'] = $this->query_vars[$wpvar];
306 // Convert urldecoded spaces back into +
307 foreach ( get_taxonomies( array() , 'objects' ) as $taxonomy => $t )
308 if ( $t->query_var && isset( $this->query_vars[$t->query_var] ) )
309 $this->query_vars[$t->query_var] = str_replace( ' ', '+', $this->query_vars[$t->query_var] );
311 // Don't allow non-public taxonomies to be queried from the front-end.
312 if ( ! is_admin() ) {
313 foreach ( get_taxonomies( array( 'public' => false ), 'objects' ) as $taxonomy => $t ) {
315 * Disallow when set to the 'taxonomy' query var.
316 * Non-public taxonomies cannot register custom query vars. See register_taxonomy().
318 if ( isset( $this->query_vars['taxonomy'] ) && $taxonomy === $this->query_vars['taxonomy'] ) {
319 unset( $this->query_vars['taxonomy'], $this->query_vars['term'] );
324 // Limit publicly queried post_types to those that are publicly_queryable
325 if ( isset( $this->query_vars['post_type']) ) {
326 $queryable_post_types = get_post_types( array('publicly_queryable' => true) );
327 if ( ! is_array( $this->query_vars['post_type'] ) ) {
328 if ( ! in_array( $this->query_vars['post_type'], $queryable_post_types ) )
329 unset( $this->query_vars['post_type'] );
331 $this->query_vars['post_type'] = array_intersect( $this->query_vars['post_type'], $queryable_post_types );
335 // Resolve conflicts between posts with numeric slugs and date archive queries.
336 $this->query_vars = wp_resolve_numeric_slug_conflicts( $this->query_vars );
338 foreach ( (array) $this->private_query_vars as $var) {
339 if ( isset($this->extra_query_vars[$var]) )
340 $this->query_vars[$var] = $this->extra_query_vars[$var];
344 $this->query_vars['error'] = $error;
347 * Filter the array of parsed query variables.
351 * @param array $query_vars The array of requested query variables.
353 $this->query_vars = apply_filters( 'request', $this->query_vars );
356 * Fires once all query variables for the current request have been parsed.
360 * @param WP &$this Current WordPress environment instance (passed by reference).
362 do_action_ref_array( 'parse_request', array( &$this ) );
366 * Sends additional HTTP headers for caching, content type, etc.
368 * Sets the Content-Type header. Sets the 'error' status (if passed) and optionally exits.
369 * If showing a feed, it will also send Last-Modified, ETag, and 304 status if needed.
372 * @since 4.4.0 `X-Pingback` header is added conditionally after posts have been queried in handle_404().
374 public function send_headers() {
377 $exit_required = false;
379 if ( is_user_logged_in() )
380 $headers = array_merge($headers, wp_get_nocache_headers());
381 if ( ! empty( $this->query_vars['error'] ) ) {
382 $status = (int) $this->query_vars['error'];
383 if ( 404 === $status ) {
384 if ( ! is_user_logged_in() )
385 $headers = array_merge($headers, wp_get_nocache_headers());
386 $headers['Content-Type'] = get_option('html_type') . '; charset=' . get_option('blog_charset');
387 } elseif ( in_array( $status, array( 403, 500, 502, 503 ) ) ) {
388 $exit_required = true;
390 } elseif ( empty( $this->query_vars['feed'] ) ) {
391 $headers['Content-Type'] = get_option('html_type') . '; charset=' . get_option('blog_charset');
393 // Set the correct content type for feeds
394 $type = $this->query_vars['feed'];
395 if ( 'feed' == $this->query_vars['feed'] ) {
396 $type = get_default_feed();
398 $headers['Content-Type'] = feed_content_type( $type ) . '; charset=' . get_option( 'blog_charset' );
400 // We're showing a feed, so WP is indeed the only thing that last changed
401 if ( !empty($this->query_vars['withcomments'])
402 || false !== strpos( $this->query_vars['feed'], 'comments-' )
403 || ( empty($this->query_vars['withoutcomments'])
404 && ( !empty($this->query_vars['p'])
405 || !empty($this->query_vars['name'])
406 || !empty($this->query_vars['page_id'])
407 || !empty($this->query_vars['pagename'])
408 || !empty($this->query_vars['attachment'])
409 || !empty($this->query_vars['attachment_id'])
413 $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastcommentmodified('GMT'), 0).' GMT';
415 $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastpostmodified('GMT'), 0).' GMT';
416 $wp_etag = '"' . md5($wp_last_modified) . '"';
417 $headers['Last-Modified'] = $wp_last_modified;
418 $headers['ETag'] = $wp_etag;
420 // Support for Conditional GET
421 if (isset($_SERVER['HTTP_IF_NONE_MATCH']))
422 $client_etag = wp_unslash( $_SERVER['HTTP_IF_NONE_MATCH'] );
423 else $client_etag = false;
425 $client_last_modified = empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? '' : trim($_SERVER['HTTP_IF_MODIFIED_SINCE']);
426 // If string is empty, return 0. If not, attempt to parse into a timestamp
427 $client_modified_timestamp = $client_last_modified ? strtotime($client_last_modified) : 0;
429 // Make a timestamp for our most recent modification...
430 $wp_modified_timestamp = strtotime($wp_last_modified);
432 if ( ($client_last_modified && $client_etag) ?
433 (($client_modified_timestamp >= $wp_modified_timestamp) && ($client_etag == $wp_etag)) :
434 (($client_modified_timestamp >= $wp_modified_timestamp) || ($client_etag == $wp_etag)) ) {
436 $exit_required = true;
441 * Filter the HTTP headers before they're sent to the browser.
445 * @param array $headers The list of headers to be sent.
446 * @param WP $this Current WordPress environment instance.
448 $headers = apply_filters( 'wp_headers', $headers, $this );
450 if ( ! empty( $status ) )
451 status_header( $status );
453 // If Last-Modified is set to false, it should not be sent (no-cache situation).
454 if ( isset( $headers['Last-Modified'] ) && false === $headers['Last-Modified'] ) {
455 unset( $headers['Last-Modified'] );
457 // In PHP 5.3+, make sure we are not sending a Last-Modified header.
458 if ( function_exists( 'header_remove' ) ) {
459 @header_remove( 'Last-Modified' );
461 // In PHP 5.2, send an empty Last-Modified header, but only as a
462 // last resort to override a header already sent. #WP23021
463 foreach ( headers_list() as $header ) {
464 if ( 0 === stripos( $header, 'Last-Modified' ) ) {
465 $headers['Last-Modified'] = '';
472 foreach ( (array) $headers as $name => $field_value )
473 @header("{$name}: {$field_value}");
475 if ( $exit_required )
479 * Fires once the requested HTTP headers for caching, content type, etc. have been sent.
483 * @param WP &$this Current WordPress environment instance (passed by reference).
485 do_action_ref_array( 'send_headers', array( &$this ) );
489 * Sets the query string property based off of the query variable property.
491 * The 'query_string' filter is deprecated, but still works. Plugins should
492 * use the 'request' filter instead.
496 public function build_query_string() {
497 $this->query_string = '';
498 foreach ( (array) array_keys($this->query_vars) as $wpvar) {
499 if ( '' != $this->query_vars[$wpvar] ) {
500 $this->query_string .= (strlen($this->query_string) < 1) ? '' : '&';
501 if ( !is_scalar($this->query_vars[$wpvar]) ) // Discard non-scalars.
503 $this->query_string .= $wpvar . '=' . rawurlencode($this->query_vars[$wpvar]);
507 if ( has_filter( 'query_string' ) ) { // Don't bother filtering and parsing if no plugins are hooked in.
509 * Filter the query string before parsing.
512 * @deprecated 2.1.0 Use 'query_vars' or 'request' filters instead.
514 * @param string $query_string The query string to modify.
516 $this->query_string = apply_filters( 'query_string', $this->query_string );
517 parse_str($this->query_string, $this->query_vars);
522 * Set up the WordPress Globals.
524 * The query_vars property will be extracted to the GLOBALS. So care should
525 * be taken when naming global variables that might interfere with the
526 * WordPress environment.
528 * @global WP_Query $wp_query
529 * @global string $query_string Query string for the loop.
530 * @global array $posts The found posts.
531 * @global WP_Post|null $post The current post, if available.
532 * @global string $request The SQL statement for the request.
533 * @global int $more Only set, if single page or post.
534 * @global int $single If single page or post. Only set, if single page or post.
535 * @global WP_User $authordata Only set, if author archive.
539 public function register_globals() {
542 // Extract updated query vars back into global namespace.
543 foreach ( (array) $wp_query->query_vars as $key => $value ) {
544 $GLOBALS[ $key ] = $value;
547 $GLOBALS['query_string'] = $this->query_string;
548 $GLOBALS['posts'] = & $wp_query->posts;
549 $GLOBALS['post'] = isset( $wp_query->post ) ? $wp_query->post : null;
550 $GLOBALS['request'] = $wp_query->request;
552 if ( $wp_query->is_single() || $wp_query->is_page() ) {
553 $GLOBALS['more'] = 1;
554 $GLOBALS['single'] = 1;
557 if ( $wp_query->is_author() && isset( $wp_query->post ) )
558 $GLOBALS['authordata'] = get_userdata( $wp_query->post->post_author );
562 * Set up the current user.
566 public function init() {
567 wp_get_current_user();
571 * Set up the Loop based on the query variables.
575 * @global WP_Query $wp_the_query
577 public function query_posts() {
578 global $wp_the_query;
579 $this->build_query_string();
580 $wp_the_query->query($this->query_vars);
584 * Set the Headers for 404, if nothing is found for requested URL.
586 * Issue a 404 if a request doesn't match any posts and doesn't match
587 * any object (e.g. an existing-but-empty category, tag, author) and a 404 was not already
588 * issued, and if the request was not a search or the homepage.
590 * Otherwise, issue a 200.
592 * This sets headers after posts have been queried. handle_404() really means "handle status."
593 * By inspecting the result of querying posts, seemingly successful requests can be switched to
594 * a 404 so that canonical redirection logic can kick in.
598 * @global WP_Query $wp_query
600 public function handle_404() {
603 // If we've already issued a 404, bail.
607 // Never 404 for the admin, robots, or if we found posts.
608 if ( is_admin() || is_robots() || $wp_query->posts ) {
611 if ( is_singular() ) {
612 $p = clone $wp_query->post;
613 // Only set X-Pingback for single posts that allow pings.
614 if ( $p && pings_open( $p ) ) {
615 @header( 'X-Pingback: ' . get_bloginfo( 'pingback_url' ) );
618 // check for paged content that exceeds the max number of pages
619 $next = '<!--nextpage-->';
620 if ( $p && false !== strpos( $p->post_content, $next ) && ! empty( $this->query_vars['page'] ) ) {
621 $page = trim( $this->query_vars['page'], '/' );
622 $success = (int) $page <= ( substr_count( $p->post_content, $next ) + 1 );
627 status_header( 200 );
632 // We will 404 for paged queries, as no posts were found.
633 if ( ! is_paged() ) {
635 // Don't 404 for authors without posts as long as they matched an author on this site.
636 $author = get_query_var( 'author' );
637 if ( is_author() && is_numeric( $author ) && $author > 0 && is_user_member_of_blog( $author ) ) {
638 status_header( 200 );
642 // Don't 404 for these queries if they matched an object.
643 if ( ( is_tag() || is_category() || is_tax() || is_post_type_archive() ) && get_queried_object() ) {
644 status_header( 200 );
648 // Don't 404 for these queries either.
649 if ( is_home() || is_search() || is_feed() ) {
650 status_header( 200 );
655 // Guess it's time to 404.
656 $wp_query->set_404();
657 status_header( 404 );
662 * Sets up all of the variables required by the WordPress environment.
664 * The action 'wp' has one parameter that references the WP object. It
665 * allows for accessing the properties and methods to further manipulate the
670 * @param string|array $query_args Passed to {@link parse_request()}
672 public function main($query_args = '') {
674 $this->parse_request($query_args);
675 $this->send_headers();
676 $this->query_posts();
678 $this->register_globals();
681 * Fires once the WordPress environment has been set up.
685 * @param WP &$this Current WordPress environment instance (passed by reference).
687 do_action_ref_array( 'wp', array( &$this ) );
692 * Helper class to remove the need to use eval to replace $matches[] in query strings.
696 class WP_MatchesMapRegex {
706 * store for mapping result
714 * subject to perform mapping on (query string containing $matches[] references
722 * regexp pattern to match $matches[] references
726 public $_pattern = '(\$matches\[[1-9]+[0-9]*\])'; // magic number
731 * @param string $subject subject if regex
732 * @param array $matches data to use in map
734 public function __construct($subject, $matches) {
735 $this->_subject = $subject;
736 $this->_matches = $matches;
737 $this->output = $this->_map();
741 * Substitute substring matches in subject.
743 * static helper function to ease use
748 * @param string $subject subject
749 * @param array $matches data used for substitution
752 public static function apply($subject, $matches) {
753 $oSelf = new WP_MatchesMapRegex($subject, $matches);
754 return $oSelf->output;
758 * do the actual mapping
763 private function _map() {
764 $callback = array($this, 'callback');
765 return preg_replace_callback($this->_pattern, $callback, $this->_subject);
769 * preg_replace_callback hook
772 * @param array $matches preg_replace regexp matches
775 public function callback($matches) {
776 $index = intval(substr($matches[0], 9, -1));
777 return ( isset( $this->_matches[$index] ) ? urlencode($this->_matches[$index]) : '' );