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 * Permalink or requested URI.
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 * Filter 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 $request = $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 )
213 $this->request = $request;
216 $request_match = $request;
217 if ( empty( $request_match ) ) {
218 // An empty request could only match against ^$ regex
219 if ( isset( $rewrite['$'] ) ) {
220 $this->matched_rule = '$';
221 $query = $rewrite['$'];
222 $matches = array('');
225 foreach ( (array) $rewrite as $match => $query ) {
226 // If the requesting file is the anchor of the match, prepend it to the path info.
227 if ( ! empty($req_uri) && strpos($match, $req_uri) === 0 && $req_uri != $request )
228 $request_match = $req_uri . '/' . $request;
230 if ( preg_match("#^$match#", $request_match, $matches) ||
231 preg_match("#^$match#", urldecode($request_match), $matches) ) {
233 if ( $wp_rewrite->use_verbose_page_rules && preg_match( '/pagename=\$matches\[([0-9]+)\]/', $query, $varmatch ) ) {
234 // This is a verbose page match, let's check to be sure about it.
235 $page = get_page_by_path( $matches[ $varmatch[1] ] );
240 $post_status_obj = get_post_status_object( $page->post_status );
241 if ( ! $post_status_obj->public && ! $post_status_obj->protected
242 && ! $post_status_obj->private && $post_status_obj->exclude_from_search ) {
248 $this->matched_rule = $match;
254 if ( isset( $this->matched_rule ) ) {
255 // Trim the query of everything up to the '?'.
256 $query = preg_replace("!^.+\?!", '', $query);
258 // Substitute the substring matches into the query.
259 $query = addslashes(WP_MatchesMapRegex::apply($query, $matches));
261 $this->matched_query = $query;
264 parse_str($query, $perma_query_vars);
266 // If we're processing a 404 request, clear the error var since we found something.
267 if ( '404' == $error )
268 unset( $error, $_GET['error'] );
271 // If req_uri is empty or if it is a request for ourself, unset error.
272 if ( empty($request) || $req_uri == $self || strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false ) {
273 unset( $error, $_GET['error'] );
275 if ( isset($perma_query_vars) && strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false )
276 unset( $perma_query_vars );
278 $this->did_permalink = false;
283 * Filter the query variables whitelist before processing.
285 * Allows (publicly allowed) query vars to be added, removed, or changed prior
286 * to executing the query. Needed to allow custom rewrite rules using your own arguments
287 * to work, or any other custom query variables you want to be publicly available.
291 * @param array $public_query_vars The array of whitelisted query variables.
293 $this->public_query_vars = apply_filters( 'query_vars', $this->public_query_vars );
295 foreach ( get_post_types( array(), 'objects' ) as $post_type => $t ) {
296 if ( is_post_type_viewable( $t ) && $t->query_var ) {
297 $post_type_query_vars[$t->query_var] = $post_type;
301 foreach ( $this->public_query_vars as $wpvar ) {
302 if ( isset( $this->extra_query_vars[$wpvar] ) )
303 $this->query_vars[$wpvar] = $this->extra_query_vars[$wpvar];
304 elseif ( isset( $_POST[$wpvar] ) )
305 $this->query_vars[$wpvar] = $_POST[$wpvar];
306 elseif ( isset( $_GET[$wpvar] ) )
307 $this->query_vars[$wpvar] = $_GET[$wpvar];
308 elseif ( isset( $perma_query_vars[$wpvar] ) )
309 $this->query_vars[$wpvar] = $perma_query_vars[$wpvar];
311 if ( !empty( $this->query_vars[$wpvar] ) ) {
312 if ( ! is_array( $this->query_vars[$wpvar] ) ) {
313 $this->query_vars[$wpvar] = (string) $this->query_vars[$wpvar];
315 foreach ( $this->query_vars[$wpvar] as $vkey => $v ) {
316 if ( !is_object( $v ) ) {
317 $this->query_vars[$wpvar][$vkey] = (string) $v;
322 if ( isset($post_type_query_vars[$wpvar] ) ) {
323 $this->query_vars['post_type'] = $post_type_query_vars[$wpvar];
324 $this->query_vars['name'] = $this->query_vars[$wpvar];
329 // Convert urldecoded spaces back into +
330 foreach ( get_taxonomies( array() , 'objects' ) as $taxonomy => $t )
331 if ( $t->query_var && isset( $this->query_vars[$t->query_var] ) )
332 $this->query_vars[$t->query_var] = str_replace( ' ', '+', $this->query_vars[$t->query_var] );
334 // Don't allow non-publicly queryable taxonomies to be queried from the front end.
335 if ( ! is_admin() ) {
336 foreach ( get_taxonomies( array( 'publicly_queryable' => false ), 'objects' ) as $taxonomy => $t ) {
338 * Disallow when set to the 'taxonomy' query var.
339 * Non-publicly queryable taxonomies cannot register custom query vars. See register_taxonomy().
341 if ( isset( $this->query_vars['taxonomy'] ) && $taxonomy === $this->query_vars['taxonomy'] ) {
342 unset( $this->query_vars['taxonomy'], $this->query_vars['term'] );
347 // Limit publicly queried post_types to those that are publicly_queryable
348 if ( isset( $this->query_vars['post_type']) ) {
349 $queryable_post_types = get_post_types( array('publicly_queryable' => true) );
350 if ( ! is_array( $this->query_vars['post_type'] ) ) {
351 if ( ! in_array( $this->query_vars['post_type'], $queryable_post_types ) )
352 unset( $this->query_vars['post_type'] );
354 $this->query_vars['post_type'] = array_intersect( $this->query_vars['post_type'], $queryable_post_types );
358 // Resolve conflicts between posts with numeric slugs and date archive queries.
359 $this->query_vars = wp_resolve_numeric_slug_conflicts( $this->query_vars );
361 foreach ( (array) $this->private_query_vars as $var) {
362 if ( isset($this->extra_query_vars[$var]) )
363 $this->query_vars[$var] = $this->extra_query_vars[$var];
367 $this->query_vars['error'] = $error;
370 * Filter the array of parsed query variables.
374 * @param array $query_vars The array of requested query variables.
376 $this->query_vars = apply_filters( 'request', $this->query_vars );
379 * Fires once all query variables for the current request have been parsed.
383 * @param WP &$this Current WordPress environment instance (passed by reference).
385 do_action_ref_array( 'parse_request', array( &$this ) );
389 * Sends additional HTTP headers for caching, content type, etc.
391 * Sets the Content-Type header. Sets the 'error' status (if passed) and optionally exits.
392 * If showing a feed, it will also send Last-Modified, ETag, and 304 status if needed.
395 * @since 4.4.0 `X-Pingback` header is added conditionally after posts have been queried in handle_404().
398 public function send_headers() {
401 $exit_required = false;
403 if ( is_user_logged_in() )
404 $headers = array_merge($headers, wp_get_nocache_headers());
405 if ( ! empty( $this->query_vars['error'] ) ) {
406 $status = (int) $this->query_vars['error'];
407 if ( 404 === $status ) {
408 if ( ! is_user_logged_in() )
409 $headers = array_merge($headers, wp_get_nocache_headers());
410 $headers['Content-Type'] = get_option('html_type') . '; charset=' . get_option('blog_charset');
411 } elseif ( in_array( $status, array( 403, 500, 502, 503 ) ) ) {
412 $exit_required = true;
414 } elseif ( empty( $this->query_vars['feed'] ) ) {
415 $headers['Content-Type'] = get_option('html_type') . '; charset=' . get_option('blog_charset');
417 // Set the correct content type for feeds
418 $type = $this->query_vars['feed'];
419 if ( 'feed' == $this->query_vars['feed'] ) {
420 $type = get_default_feed();
422 $headers['Content-Type'] = feed_content_type( $type ) . '; charset=' . get_option( 'blog_charset' );
424 // We're showing a feed, so WP is indeed the only thing that last changed
425 if ( !empty($this->query_vars['withcomments'])
426 || false !== strpos( $this->query_vars['feed'], 'comments-' )
427 || ( empty($this->query_vars['withoutcomments'])
428 && ( !empty($this->query_vars['p'])
429 || !empty($this->query_vars['name'])
430 || !empty($this->query_vars['page_id'])
431 || !empty($this->query_vars['pagename'])
432 || !empty($this->query_vars['attachment'])
433 || !empty($this->query_vars['attachment_id'])
437 $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastcommentmodified('GMT'), 0).' GMT';
439 $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastpostmodified('GMT'), 0).' GMT';
440 $wp_etag = '"' . md5($wp_last_modified) . '"';
441 $headers['Last-Modified'] = $wp_last_modified;
442 $headers['ETag'] = $wp_etag;
444 // Support for Conditional GET
445 if (isset($_SERVER['HTTP_IF_NONE_MATCH']))
446 $client_etag = wp_unslash( $_SERVER['HTTP_IF_NONE_MATCH'] );
447 else $client_etag = false;
449 $client_last_modified = empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? '' : trim($_SERVER['HTTP_IF_MODIFIED_SINCE']);
450 // If string is empty, return 0. If not, attempt to parse into a timestamp
451 $client_modified_timestamp = $client_last_modified ? strtotime($client_last_modified) : 0;
453 // Make a timestamp for our most recent modification...
454 $wp_modified_timestamp = strtotime($wp_last_modified);
456 if ( ($client_last_modified && $client_etag) ?
457 (($client_modified_timestamp >= $wp_modified_timestamp) && ($client_etag == $wp_etag)) :
458 (($client_modified_timestamp >= $wp_modified_timestamp) || ($client_etag == $wp_etag)) ) {
460 $exit_required = true;
465 * Filter the HTTP headers before they're sent to the browser.
469 * @param array $headers The list of headers to be sent.
470 * @param WP $this Current WordPress environment instance.
472 $headers = apply_filters( 'wp_headers', $headers, $this );
474 if ( ! empty( $status ) )
475 status_header( $status );
477 // If Last-Modified is set to false, it should not be sent (no-cache situation).
478 if ( isset( $headers['Last-Modified'] ) && false === $headers['Last-Modified'] ) {
479 unset( $headers['Last-Modified'] );
481 // In PHP 5.3+, make sure we are not sending a Last-Modified header.
482 if ( function_exists( 'header_remove' ) ) {
483 @header_remove( 'Last-Modified' );
485 // In PHP 5.2, send an empty Last-Modified header, but only as a
486 // last resort to override a header already sent. #WP23021
487 foreach ( headers_list() as $header ) {
488 if ( 0 === stripos( $header, 'Last-Modified' ) ) {
489 $headers['Last-Modified'] = '';
496 foreach ( (array) $headers as $name => $field_value )
497 @header("{$name}: {$field_value}");
499 if ( $exit_required )
503 * Fires once the requested HTTP headers for caching, content type, etc. have been sent.
507 * @param WP &$this Current WordPress environment instance (passed by reference).
509 do_action_ref_array( 'send_headers', array( &$this ) );
513 * Sets the query string property based off of the query variable property.
515 * The 'query_string' filter is deprecated, but still works. Plugins should
516 * use the 'request' filter instead.
521 public function build_query_string() {
522 $this->query_string = '';
523 foreach ( (array) array_keys($this->query_vars) as $wpvar) {
524 if ( '' != $this->query_vars[$wpvar] ) {
525 $this->query_string .= (strlen($this->query_string) < 1) ? '' : '&';
526 if ( !is_scalar($this->query_vars[$wpvar]) ) // Discard non-scalars.
528 $this->query_string .= $wpvar . '=' . rawurlencode($this->query_vars[$wpvar]);
532 if ( has_filter( 'query_string' ) ) { // Don't bother filtering and parsing if no plugins are hooked in.
534 * Filter the query string before parsing.
537 * @deprecated 2.1.0 Use 'query_vars' or 'request' filters instead.
539 * @param string $query_string The query string to modify.
541 $this->query_string = apply_filters( 'query_string', $this->query_string );
542 parse_str($this->query_string, $this->query_vars);
547 * Set up the WordPress Globals.
549 * The query_vars property will be extracted to the GLOBALS. So care should
550 * be taken when naming global variables that might interfere with the
551 * WordPress environment.
556 * @global WP_Query $wp_query
557 * @global string $query_string Query string for the loop.
558 * @global array $posts The found posts.
559 * @global WP_Post|null $post The current post, if available.
560 * @global string $request The SQL statement for the request.
561 * @global int $more Only set, if single page or post.
562 * @global int $single If single page or post. Only set, if single page or post.
563 * @global WP_User $authordata Only set, if author archive.
565 public function register_globals() {
568 // Extract updated query vars back into global namespace.
569 foreach ( (array) $wp_query->query_vars as $key => $value ) {
570 $GLOBALS[ $key ] = $value;
573 $GLOBALS['query_string'] = $this->query_string;
574 $GLOBALS['posts'] = & $wp_query->posts;
575 $GLOBALS['post'] = isset( $wp_query->post ) ? $wp_query->post : null;
576 $GLOBALS['request'] = $wp_query->request;
578 if ( $wp_query->is_single() || $wp_query->is_page() ) {
579 $GLOBALS['more'] = 1;
580 $GLOBALS['single'] = 1;
583 if ( $wp_query->is_author() && isset( $wp_query->post ) )
584 $GLOBALS['authordata'] = get_userdata( $wp_query->post->post_author );
588 * Set up the current user.
593 public function init() {
594 wp_get_current_user();
598 * Set up the Loop based on the query variables.
603 * @global WP_Query $wp_the_query
605 public function query_posts() {
606 global $wp_the_query;
607 $this->build_query_string();
608 $wp_the_query->query($this->query_vars);
612 * Set the Headers for 404, if nothing is found for requested URL.
614 * Issue a 404 if a request doesn't match any posts and doesn't match
615 * any object (e.g. an existing-but-empty category, tag, author) and a 404 was not already
616 * issued, and if the request was not a search or the homepage.
618 * Otherwise, issue a 200.
620 * This sets headers after posts have been queried. handle_404() really means "handle status."
621 * By inspecting the result of querying posts, seemingly successful requests can be switched to
622 * a 404 so that canonical redirection logic can kick in.
627 * @global WP_Query $wp_query
629 public function handle_404() {
633 * Filter whether to short-circuit default header status handling.
635 * Returning a non-false value from the filter will short-circuit the handling
640 * @param bool $preempt Whether to short-circuit default header status handling. Default false.
641 * @param WP_Query $wp_query WordPress Query object.
643 if ( false !== apply_filters( 'pre_handle_404', false, $wp_query ) ) {
647 // If we've already issued a 404, bail.
651 // Never 404 for the admin, robots, or if we found posts.
652 if ( is_admin() || is_robots() || $wp_query->posts ) {
655 if ( is_singular() ) {
658 if ( $wp_query->post instanceof WP_Post ) {
659 $p = clone $wp_query->post;
662 // Only set X-Pingback for single posts that allow pings.
663 if ( $p && pings_open( $p ) ) {
664 @header( 'X-Pingback: ' . get_bloginfo( 'pingback_url' ) );
667 // check for paged content that exceeds the max number of pages
668 $next = '<!--nextpage-->';
669 if ( $p && false !== strpos( $p->post_content, $next ) && ! empty( $this->query_vars['page'] ) ) {
670 $page = trim( $this->query_vars['page'], '/' );
671 $success = (int) $page <= ( substr_count( $p->post_content, $next ) + 1 );
676 status_header( 200 );
681 // We will 404 for paged queries, as no posts were found.
682 if ( ! is_paged() ) {
684 // Don't 404 for authors without posts as long as they matched an author on this site.
685 $author = get_query_var( 'author' );
686 if ( is_author() && is_numeric( $author ) && $author > 0 && is_user_member_of_blog( $author ) ) {
687 status_header( 200 );
691 // Don't 404 for these queries if they matched an object.
692 if ( ( is_tag() || is_category() || is_tax() || is_post_type_archive() ) && get_queried_object() ) {
693 status_header( 200 );
697 // Don't 404 for these queries either.
698 if ( is_home() || is_search() || is_feed() ) {
699 status_header( 200 );
704 // Guess it's time to 404.
705 $wp_query->set_404();
706 status_header( 404 );
711 * Sets up all of the variables required by the WordPress environment.
713 * The action 'wp' has one parameter that references the WP object. It
714 * allows for accessing the properties and methods to further manipulate the
720 * @param string|array $query_args Passed to {@link parse_request()}
722 public function main($query_args = '') {
724 $this->parse_request($query_args);
725 $this->send_headers();
726 $this->query_posts();
728 $this->register_globals();
731 * Fires once the WordPress environment has been set up.
735 * @param WP &$this Current WordPress environment instance (passed by reference).
737 do_action_ref_array( 'wp', array( &$this ) );
742 * Helper class to remove the need to use eval to replace $matches[] in query strings.
746 class WP_MatchesMapRegex {
756 * store for mapping result
764 * subject to perform mapping on (query string containing $matches[] references
772 * regexp pattern to match $matches[] references
776 public $_pattern = '(\$matches\[[1-9]+[0-9]*\])'; // magic number
781 * @param string $subject subject if regex
782 * @param array $matches data to use in map
784 public function __construct($subject, $matches) {
785 $this->_subject = $subject;
786 $this->_matches = $matches;
787 $this->output = $this->_map();
791 * Substitute substring matches in subject.
793 * static helper function to ease use
798 * @param string $subject subject
799 * @param array $matches data used for substitution
802 public static function apply($subject, $matches) {
803 $oSelf = new WP_MatchesMapRegex($subject, $matches);
804 return $oSelf->output;
808 * do the actual mapping
813 private function _map() {
814 $callback = array($this, 'callback');
815 return preg_replace_callback($this->_pattern, $callback, $this->_subject);
819 * preg_replace_callback hook
822 * @param array $matches preg_replace regexp matches
825 public function callback($matches) {
826 $index = intval(substr($matches[0], 9, -1));
827 return ( isset( $this->_matches[$index] ) ? urlencode($this->_matches[$index]) : '' );