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');
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 if ( ! get_page_by_path( $matches[ $varmatch[1] ] ) )
217 $this->matched_rule = $match;
223 if ( isset( $this->matched_rule ) ) {
224 // Trim the query of everything up to the '?'.
225 $query = preg_replace("!^.+\?!", '', $query);
227 // Substitute the substring matches into the query.
228 $query = addslashes(WP_MatchesMapRegex::apply($query, $matches));
230 $this->matched_query = $query;
233 parse_str($query, $perma_query_vars);
235 // If we're processing a 404 request, clear the error var since we found something.
236 if ( '404' == $error )
237 unset( $error, $_GET['error'] );
240 // If req_uri is empty or if it is a request for ourself, unset error.
241 if ( empty($request) || $req_uri == $self || strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false ) {
242 unset( $error, $_GET['error'] );
244 if ( isset($perma_query_vars) && strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false )
245 unset( $perma_query_vars );
247 $this->did_permalink = false;
252 * Filter the query variables whitelist before processing.
254 * Allows (publicly allowed) query vars to be added, removed, or changed prior
255 * to executing the query. Needed to allow custom rewrite rules using your own arguments
256 * to work, or any other custom query variables you want to be publicly available.
260 * @param array $public_query_vars The array of whitelisted query variables.
262 $this->public_query_vars = apply_filters( 'query_vars', $this->public_query_vars );
264 foreach ( get_post_types( array(), 'objects' ) as $post_type => $t )
266 $post_type_query_vars[$t->query_var] = $post_type;
268 foreach ( $this->public_query_vars as $wpvar ) {
269 if ( isset( $this->extra_query_vars[$wpvar] ) )
270 $this->query_vars[$wpvar] = $this->extra_query_vars[$wpvar];
271 elseif ( isset( $_POST[$wpvar] ) )
272 $this->query_vars[$wpvar] = $_POST[$wpvar];
273 elseif ( isset( $_GET[$wpvar] ) )
274 $this->query_vars[$wpvar] = $_GET[$wpvar];
275 elseif ( isset( $perma_query_vars[$wpvar] ) )
276 $this->query_vars[$wpvar] = $perma_query_vars[$wpvar];
278 if ( !empty( $this->query_vars[$wpvar] ) ) {
279 if ( ! is_array( $this->query_vars[$wpvar] ) ) {
280 $this->query_vars[$wpvar] = (string) $this->query_vars[$wpvar];
282 foreach ( $this->query_vars[$wpvar] as $vkey => $v ) {
283 if ( !is_object( $v ) ) {
284 $this->query_vars[$wpvar][$vkey] = (string) $v;
289 if ( isset($post_type_query_vars[$wpvar] ) ) {
290 $this->query_vars['post_type'] = $post_type_query_vars[$wpvar];
291 $this->query_vars['name'] = $this->query_vars[$wpvar];
296 // Convert urldecoded spaces back into +
297 foreach ( get_taxonomies( array() , 'objects' ) as $taxonomy => $t )
298 if ( $t->query_var && isset( $this->query_vars[$t->query_var] ) )
299 $this->query_vars[$t->query_var] = str_replace( ' ', '+', $this->query_vars[$t->query_var] );
301 // Limit publicly queried post_types to those that are publicly_queryable
302 if ( isset( $this->query_vars['post_type']) ) {
303 $queryable_post_types = get_post_types( array('publicly_queryable' => true) );
304 if ( ! is_array( $this->query_vars['post_type'] ) ) {
305 if ( ! in_array( $this->query_vars['post_type'], $queryable_post_types ) )
306 unset( $this->query_vars['post_type'] );
308 $this->query_vars['post_type'] = array_intersect( $this->query_vars['post_type'], $queryable_post_types );
312 // Resolve conflicts between posts with numeric slugs and date archive queries.
313 $this->query_vars = wp_resolve_numeric_slug_conflicts( $this->query_vars );
315 foreach ( (array) $this->private_query_vars as $var) {
316 if ( isset($this->extra_query_vars[$var]) )
317 $this->query_vars[$var] = $this->extra_query_vars[$var];
321 $this->query_vars['error'] = $error;
324 * Filter the array of parsed query variables.
328 * @param array $query_vars The array of requested query variables.
330 $this->query_vars = apply_filters( 'request', $this->query_vars );
333 * Fires once all query variables for the current request have been parsed.
337 * @param WP &$this Current WordPress environment instance (passed by reference).
339 do_action_ref_array( 'parse_request', array( &$this ) );
343 * Send additional HTTP headers for caching, content type, etc.
345 * Sets the X-Pingback header, 404 status (if 404), Content-type. If showing
346 * a feed, it will also send last-modified, etag, and 304 status if needed.
350 public function send_headers() {
351 $headers = array('X-Pingback' => get_bloginfo('pingback_url'));
353 $exit_required = false;
355 if ( is_user_logged_in() )
356 $headers = array_merge($headers, wp_get_nocache_headers());
357 if ( ! empty( $this->query_vars['error'] ) ) {
358 $status = (int) $this->query_vars['error'];
359 if ( 404 === $status ) {
360 if ( ! is_user_logged_in() )
361 $headers = array_merge($headers, wp_get_nocache_headers());
362 $headers['Content-Type'] = get_option('html_type') . '; charset=' . get_option('blog_charset');
363 } elseif ( in_array( $status, array( 403, 500, 502, 503 ) ) ) {
364 $exit_required = true;
366 } elseif ( empty( $this->query_vars['feed'] ) ) {
367 $headers['Content-Type'] = get_option('html_type') . '; charset=' . get_option('blog_charset');
369 // We're showing a feed, so WP is indeed the only thing that last changed
370 if ( !empty($this->query_vars['withcomments'])
371 || false !== strpos( $this->query_vars['feed'], 'comments-' )
372 || ( empty($this->query_vars['withoutcomments'])
373 && ( !empty($this->query_vars['p'])
374 || !empty($this->query_vars['name'])
375 || !empty($this->query_vars['page_id'])
376 || !empty($this->query_vars['pagename'])
377 || !empty($this->query_vars['attachment'])
378 || !empty($this->query_vars['attachment_id'])
382 $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastcommentmodified('GMT'), 0).' GMT';
384 $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastpostmodified('GMT'), 0).' GMT';
385 $wp_etag = '"' . md5($wp_last_modified) . '"';
386 $headers['Last-Modified'] = $wp_last_modified;
387 $headers['ETag'] = $wp_etag;
389 // Support for Conditional GET
390 if (isset($_SERVER['HTTP_IF_NONE_MATCH']))
391 $client_etag = wp_unslash( $_SERVER['HTTP_IF_NONE_MATCH'] );
392 else $client_etag = false;
394 $client_last_modified = empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? '' : trim($_SERVER['HTTP_IF_MODIFIED_SINCE']);
395 // If string is empty, return 0. If not, attempt to parse into a timestamp
396 $client_modified_timestamp = $client_last_modified ? strtotime($client_last_modified) : 0;
398 // Make a timestamp for our most recent modification...
399 $wp_modified_timestamp = strtotime($wp_last_modified);
401 if ( ($client_last_modified && $client_etag) ?
402 (($client_modified_timestamp >= $wp_modified_timestamp) && ($client_etag == $wp_etag)) :
403 (($client_modified_timestamp >= $wp_modified_timestamp) || ($client_etag == $wp_etag)) ) {
405 $exit_required = true;
410 * Filter the HTTP headers before they're sent to the browser.
414 * @param array $headers The list of headers to be sent.
415 * @param WP $this Current WordPress environment instance.
417 $headers = apply_filters( 'wp_headers', $headers, $this );
419 if ( ! empty( $status ) )
420 status_header( $status );
422 // If Last-Modified is set to false, it should not be sent (no-cache situation).
423 if ( isset( $headers['Last-Modified'] ) && false === $headers['Last-Modified'] ) {
424 unset( $headers['Last-Modified'] );
426 // In PHP 5.3+, make sure we are not sending a Last-Modified header.
427 if ( function_exists( 'header_remove' ) ) {
428 @header_remove( 'Last-Modified' );
430 // In PHP 5.2, send an empty Last-Modified header, but only as a
431 // last resort to override a header already sent. #WP23021
432 foreach ( headers_list() as $header ) {
433 if ( 0 === stripos( $header, 'Last-Modified' ) ) {
434 $headers['Last-Modified'] = '';
441 foreach( (array) $headers as $name => $field_value )
442 @header("{$name}: {$field_value}");
444 if ( $exit_required )
448 * Fires once the requested HTTP headers for caching, content type, etc. have been sent.
452 * @param WP &$this Current WordPress environment instance (passed by reference).
454 do_action_ref_array( 'send_headers', array( &$this ) );
458 * Sets the query string property based off of the query variable property.
460 * The 'query_string' filter is deprecated, but still works. Plugins should
461 * use the 'request' filter instead.
465 public function build_query_string() {
466 $this->query_string = '';
467 foreach ( (array) array_keys($this->query_vars) as $wpvar) {
468 if ( '' != $this->query_vars[$wpvar] ) {
469 $this->query_string .= (strlen($this->query_string) < 1) ? '' : '&';
470 if ( !is_scalar($this->query_vars[$wpvar]) ) // Discard non-scalars.
472 $this->query_string .= $wpvar . '=' . rawurlencode($this->query_vars[$wpvar]);
476 if ( has_filter( 'query_string' ) ) { // Don't bother filtering and parsing if no plugins are hooked in.
478 * Filter the query string before parsing.
481 * @deprecated 2.1.0 Use 'query_vars' or 'request' filters instead.
483 * @param string $query_string The query string to modify.
485 $this->query_string = apply_filters( 'query_string', $this->query_string );
486 parse_str($this->query_string, $this->query_vars);
491 * Set up the WordPress Globals.
493 * The query_vars property will be extracted to the GLOBALS. So care should
494 * be taken when naming global variables that might interfere with the
495 * WordPress environment.
497 * @global WP_Query $wp_query
498 * @global string $query_string Query string for the loop.
499 * @global array $posts The found posts.
500 * @global WP_Post|null $post The current post, if available.
501 * @global string $request The SQL statement for the request.
502 * @global int $more Only set, if single page or post.
503 * @global int $single If single page or post. Only set, if single page or post.
504 * @global WP_User $authordata Only set, if author archive.
508 public function register_globals() {
511 // Extract updated query vars back into global namespace.
512 foreach ( (array) $wp_query->query_vars as $key => $value ) {
513 $GLOBALS[ $key ] = $value;
516 $GLOBALS['query_string'] = $this->query_string;
517 $GLOBALS['posts'] = & $wp_query->posts;
518 $GLOBALS['post'] = isset( $wp_query->post ) ? $wp_query->post : null;
519 $GLOBALS['request'] = $wp_query->request;
521 if ( $wp_query->is_single() || $wp_query->is_page() ) {
522 $GLOBALS['more'] = 1;
523 $GLOBALS['single'] = 1;
526 if ( $wp_query->is_author() && isset( $wp_query->post ) )
527 $GLOBALS['authordata'] = get_userdata( $wp_query->post->post_author );
531 * Set up the current user.
535 public function init() {
536 wp_get_current_user();
540 * Set up the Loop based on the query variables.
544 * @global WP_Query $wp_the_query
546 public function query_posts() {
547 global $wp_the_query;
548 $this->build_query_string();
549 $wp_the_query->query($this->query_vars);
553 * Set the Headers for 404, if nothing is found for requested URL.
555 * Issue a 404 if a request doesn't match any posts and doesn't match
556 * any object (e.g. an existing-but-empty category, tag, author) and a 404 was not already
557 * issued, and if the request was not a search or the homepage.
559 * Otherwise, issue a 200.
563 * @global WP_Query $wp_query
565 public function handle_404() {
568 // If we've already issued a 404, bail.
572 // Never 404 for the admin, robots, or if we found posts.
573 if ( is_admin() || is_robots() || $wp_query->posts ) {
574 status_header( 200 );
578 // We will 404 for paged queries, as no posts were found.
579 if ( ! is_paged() ) {
581 // Don't 404 for authors without posts as long as they matched an author on this site.
582 $author = get_query_var( 'author' );
583 if ( is_author() && is_numeric( $author ) && $author > 0 && is_user_member_of_blog( $author ) ) {
584 status_header( 200 );
588 // Don't 404 for these queries if they matched an object.
589 if ( ( is_tag() || is_category() || is_tax() || is_post_type_archive() ) && get_queried_object() ) {
590 status_header( 200 );
594 // Don't 404 for these queries either.
595 if ( is_home() || is_search() || is_feed() ) {
596 status_header( 200 );
601 // Guess it's time to 404.
602 $wp_query->set_404();
603 status_header( 404 );
608 * Sets up all of the variables required by the WordPress environment.
610 * The action 'wp' has one parameter that references the WP object. It
611 * allows for accessing the properties and methods to further manipulate the
616 * @param string|array $query_args Passed to {@link parse_request()}
618 public function main($query_args = '') {
620 $this->parse_request($query_args);
621 $this->send_headers();
622 $this->query_posts();
624 $this->register_globals();
627 * Fires once the WordPress environment has been set up.
631 * @param WP &$this Current WordPress environment instance (passed by reference).
633 do_action_ref_array( 'wp', array( &$this ) );
638 * Helper class to remove the need to use eval to replace $matches[] in query strings.
642 class WP_MatchesMapRegex {
652 * store for mapping result
660 * subject to perform mapping on (query string containing $matches[] references
668 * regexp pattern to match $matches[] references
672 public $_pattern = '(\$matches\[[1-9]+[0-9]*\])'; // magic number
677 * @param string $subject subject if regex
678 * @param array $matches data to use in map
680 public function __construct($subject, $matches) {
681 $this->_subject = $subject;
682 $this->_matches = $matches;
683 $this->output = $this->_map();
687 * Substitute substring matches in subject.
689 * static helper function to ease use
694 * @param string $subject subject
695 * @param array $matches data used for substitution
698 public static function apply($subject, $matches) {
699 $oSelf = new WP_MatchesMapRegex($subject, $matches);
700 return $oSelf->output;
704 * do the actual mapping
709 private function _map() {
710 $callback = array($this, 'callback');
711 return preg_replace_callback($this->_pattern, $callback, $this->_subject);
715 * preg_replace_callback hook
718 * @param array $matches preg_replace regexp matches
721 public function callback($matches) {
722 $index = intval(substr($matches[0], 9, -1));
723 return ( isset( $this->_matches[$index] ) ? urlencode($this->_matches[$index]) : '' );