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 * @param array|string $extra_query_vars Set the extra query variables.
120 public function parse_request($extra_query_vars = '') {
124 * Filter whether to parse the request.
128 * @param bool $bool Whether or not to parse the request. Default true.
129 * @param WP $this Current WordPress environment instance.
130 * @param array|string $extra_query_vars Extra passed query variables.
132 if ( ! apply_filters( 'do_parse_request', true, $this, $extra_query_vars ) )
135 $this->query_vars = array();
136 $post_type_query_vars = array();
138 if ( is_array($extra_query_vars) )
139 $this->extra_query_vars = & $extra_query_vars;
140 else if (! empty($extra_query_vars))
141 parse_str($extra_query_vars, $this->extra_query_vars);
143 // Process PATH_INFO, REQUEST_URI, and 404 for permalinks.
145 // Fetch the rewrite rules.
146 $rewrite = $wp_rewrite->wp_rewrite_rules();
148 if ( ! empty($rewrite) ) {
149 // If we match a rewrite rule, this will be cleared.
151 $this->did_permalink = true;
153 $pathinfo = isset( $_SERVER['PATH_INFO'] ) ? $_SERVER['PATH_INFO'] : '';
154 list( $pathinfo ) = explode( '?', $pathinfo );
155 $pathinfo = str_replace( "%", "%25", $pathinfo );
157 list( $req_uri ) = explode( '?', $_SERVER['REQUEST_URI'] );
158 $self = $_SERVER['PHP_SELF'];
159 $home_path = trim( parse_url( home_url(), PHP_URL_PATH ), '/' );
161 // Trim path info from the end and the leading home path from the
162 // front. For path info requests, this leaves us with the requesting
163 // filename, if any. For 404 requests, this leaves us with the
164 // requested permalink.
165 $req_uri = str_replace($pathinfo, '', $req_uri);
166 $req_uri = trim($req_uri, '/');
167 $req_uri = preg_replace("|^$home_path|i", '', $req_uri);
168 $req_uri = trim($req_uri, '/');
169 $pathinfo = trim($pathinfo, '/');
170 $pathinfo = preg_replace("|^$home_path|i", '', $pathinfo);
171 $pathinfo = trim($pathinfo, '/');
172 $self = trim($self, '/');
173 $self = preg_replace("|^$home_path|i", '', $self);
174 $self = trim($self, '/');
176 // The requested permalink is in $pathinfo for path info requests and
177 // $req_uri for other requests.
178 if ( ! empty($pathinfo) && !preg_match('|^.*' . $wp_rewrite->index . '$|', $pathinfo) ) {
179 $request = $pathinfo;
181 // If the request uri is the index, blank it out so that we don't try to match it against a rule.
182 if ( $req_uri == $wp_rewrite->index )
187 $this->request = $request;
190 $request_match = $request;
191 if ( empty( $request_match ) ) {
192 // An empty request could only match against ^$ regex
193 if ( isset( $rewrite['$'] ) ) {
194 $this->matched_rule = '$';
195 $query = $rewrite['$'];
196 $matches = array('');
199 foreach ( (array) $rewrite as $match => $query ) {
200 // If the requesting file is the anchor of the match, prepend it to the path info.
201 if ( ! empty($req_uri) && strpos($match, $req_uri) === 0 && $req_uri != $request )
202 $request_match = $req_uri . '/' . $request;
204 if ( preg_match("#^$match#", $request_match, $matches) ||
205 preg_match("#^$match#", urldecode($request_match), $matches) ) {
207 if ( $wp_rewrite->use_verbose_page_rules && preg_match( '/pagename=\$matches\[([0-9]+)\]/', $query, $varmatch ) ) {
208 // This is a verbose page match, let's check to be sure about it.
209 if ( ! get_page_by_path( $matches[ $varmatch[1] ] ) )
214 $this->matched_rule = $match;
220 if ( isset( $this->matched_rule ) ) {
221 // Trim the query of everything up to the '?'.
222 $query = preg_replace("!^.+\?!", '', $query);
224 // Substitute the substring matches into the query.
225 $query = addslashes(WP_MatchesMapRegex::apply($query, $matches));
227 $this->matched_query = $query;
230 parse_str($query, $perma_query_vars);
232 // If we're processing a 404 request, clear the error var since we found something.
233 if ( '404' == $error )
234 unset( $error, $_GET['error'] );
237 // If req_uri is empty or if it is a request for ourself, unset error.
238 if ( empty($request) || $req_uri == $self || strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false ) {
239 unset( $error, $_GET['error'] );
241 if ( isset($perma_query_vars) && strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false )
242 unset( $perma_query_vars );
244 $this->did_permalink = false;
249 * Filter the query variables whitelist before processing.
251 * Allows (publicly allowed) query vars to be added, removed, or changed prior
252 * to executing the query. Needed to allow custom rewrite rules using your own arguments
253 * to work, or any other custom query variables you want to be publicly available.
257 * @param array $public_query_vars The array of whitelisted query variables.
259 $this->public_query_vars = apply_filters( 'query_vars', $this->public_query_vars );
261 foreach ( get_post_types( array(), 'objects' ) as $post_type => $t )
263 $post_type_query_vars[$t->query_var] = $post_type;
265 foreach ( $this->public_query_vars as $wpvar ) {
266 if ( isset( $this->extra_query_vars[$wpvar] ) )
267 $this->query_vars[$wpvar] = $this->extra_query_vars[$wpvar];
268 elseif ( isset( $_POST[$wpvar] ) )
269 $this->query_vars[$wpvar] = $_POST[$wpvar];
270 elseif ( isset( $_GET[$wpvar] ) )
271 $this->query_vars[$wpvar] = $_GET[$wpvar];
272 elseif ( isset( $perma_query_vars[$wpvar] ) )
273 $this->query_vars[$wpvar] = $perma_query_vars[$wpvar];
275 if ( !empty( $this->query_vars[$wpvar] ) ) {
276 if ( ! is_array( $this->query_vars[$wpvar] ) ) {
277 $this->query_vars[$wpvar] = (string) $this->query_vars[$wpvar];
279 foreach ( $this->query_vars[$wpvar] as $vkey => $v ) {
280 if ( !is_object( $v ) ) {
281 $this->query_vars[$wpvar][$vkey] = (string) $v;
286 if ( isset($post_type_query_vars[$wpvar] ) ) {
287 $this->query_vars['post_type'] = $post_type_query_vars[$wpvar];
288 $this->query_vars['name'] = $this->query_vars[$wpvar];
293 // Convert urldecoded spaces back into +
294 foreach ( get_taxonomies( array() , 'objects' ) as $taxonomy => $t )
295 if ( $t->query_var && isset( $this->query_vars[$t->query_var] ) )
296 $this->query_vars[$t->query_var] = str_replace( ' ', '+', $this->query_vars[$t->query_var] );
298 // Limit publicly queried post_types to those that are publicly_queryable
299 if ( isset( $this->query_vars['post_type']) ) {
300 $queryable_post_types = get_post_types( array('publicly_queryable' => true) );
301 if ( ! is_array( $this->query_vars['post_type'] ) ) {
302 if ( ! in_array( $this->query_vars['post_type'], $queryable_post_types ) )
303 unset( $this->query_vars['post_type'] );
305 $this->query_vars['post_type'] = array_intersect( $this->query_vars['post_type'], $queryable_post_types );
309 foreach ( (array) $this->private_query_vars as $var) {
310 if ( isset($this->extra_query_vars[$var]) )
311 $this->query_vars[$var] = $this->extra_query_vars[$var];
315 $this->query_vars['error'] = $error;
318 * Filter the array of parsed query variables.
322 * @param array $query_vars The array of requested query variables.
324 $this->query_vars = apply_filters( 'request', $this->query_vars );
327 * Fires once all query variables for the current request have been parsed.
331 * @param WP &$this Current WordPress environment instance (passed by reference).
333 do_action_ref_array( 'parse_request', array( &$this ) );
337 * Send additional HTTP headers for caching, content type, etc.
339 * Sets the X-Pingback header, 404 status (if 404), Content-type. If showing
340 * a feed, it will also send last-modified, etag, and 304 status if needed.
344 public function send_headers() {
345 $headers = array('X-Pingback' => get_bloginfo('pingback_url'));
347 $exit_required = false;
349 if ( is_user_logged_in() )
350 $headers = array_merge($headers, wp_get_nocache_headers());
351 if ( ! empty( $this->query_vars['error'] ) ) {
352 $status = (int) $this->query_vars['error'];
353 if ( 404 === $status ) {
354 if ( ! is_user_logged_in() )
355 $headers = array_merge($headers, wp_get_nocache_headers());
356 $headers['Content-Type'] = get_option('html_type') . '; charset=' . get_option('blog_charset');
357 } elseif ( in_array( $status, array( 403, 500, 502, 503 ) ) ) {
358 $exit_required = true;
360 } else if ( empty($this->query_vars['feed']) ) {
361 $headers['Content-Type'] = get_option('html_type') . '; charset=' . get_option('blog_charset');
363 // We're showing a feed, so WP is indeed the only thing that last changed
364 if ( !empty($this->query_vars['withcomments'])
365 || false !== strpos( $this->query_vars['feed'], 'comments-' )
366 || ( empty($this->query_vars['withoutcomments'])
367 && ( !empty($this->query_vars['p'])
368 || !empty($this->query_vars['name'])
369 || !empty($this->query_vars['page_id'])
370 || !empty($this->query_vars['pagename'])
371 || !empty($this->query_vars['attachment'])
372 || !empty($this->query_vars['attachment_id'])
376 $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastcommentmodified('GMT'), 0).' GMT';
378 $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastpostmodified('GMT'), 0).' GMT';
379 $wp_etag = '"' . md5($wp_last_modified) . '"';
380 $headers['Last-Modified'] = $wp_last_modified;
381 $headers['ETag'] = $wp_etag;
383 // Support for Conditional GET
384 if (isset($_SERVER['HTTP_IF_NONE_MATCH']))
385 $client_etag = wp_unslash( $_SERVER['HTTP_IF_NONE_MATCH'] );
386 else $client_etag = false;
388 $client_last_modified = empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? '' : trim($_SERVER['HTTP_IF_MODIFIED_SINCE']);
389 // If string is empty, return 0. If not, attempt to parse into a timestamp
390 $client_modified_timestamp = $client_last_modified ? strtotime($client_last_modified) : 0;
392 // Make a timestamp for our most recent modification...
393 $wp_modified_timestamp = strtotime($wp_last_modified);
395 if ( ($client_last_modified && $client_etag) ?
396 (($client_modified_timestamp >= $wp_modified_timestamp) && ($client_etag == $wp_etag)) :
397 (($client_modified_timestamp >= $wp_modified_timestamp) || ($client_etag == $wp_etag)) ) {
399 $exit_required = true;
404 * Filter the HTTP headers before they're sent to the browser.
408 * @param array $headers The list of headers to be sent.
409 * @param WP $this Current WordPress environment instance.
411 $headers = apply_filters( 'wp_headers', $headers, $this );
413 if ( ! empty( $status ) )
414 status_header( $status );
416 // If Last-Modified is set to false, it should not be sent (no-cache situation).
417 if ( isset( $headers['Last-Modified'] ) && false === $headers['Last-Modified'] ) {
418 unset( $headers['Last-Modified'] );
420 // In PHP 5.3+, make sure we are not sending a Last-Modified header.
421 if ( function_exists( 'header_remove' ) ) {
422 @header_remove( 'Last-Modified' );
424 // In PHP 5.2, send an empty Last-Modified header, but only as a
425 // last resort to override a header already sent. #WP23021
426 foreach ( headers_list() as $header ) {
427 if ( 0 === stripos( $header, 'Last-Modified' ) ) {
428 $headers['Last-Modified'] = '';
435 foreach( (array) $headers as $name => $field_value )
436 @header("{$name}: {$field_value}");
438 if ( $exit_required )
442 * Fires once the requested HTTP headers for caching, content type, etc. have been sent.
446 * @param WP &$this Current WordPress environment instance (passed by reference).
448 do_action_ref_array( 'send_headers', array( &$this ) );
452 * Sets the query string property based off of the query variable property.
454 * The 'query_string' filter is deprecated, but still works. Plugins should
455 * use the 'request' filter instead.
459 public function build_query_string() {
460 $this->query_string = '';
461 foreach ( (array) array_keys($this->query_vars) as $wpvar) {
462 if ( '' != $this->query_vars[$wpvar] ) {
463 $this->query_string .= (strlen($this->query_string) < 1) ? '' : '&';
464 if ( !is_scalar($this->query_vars[$wpvar]) ) // Discard non-scalars.
466 $this->query_string .= $wpvar . '=' . rawurlencode($this->query_vars[$wpvar]);
470 if ( has_filter( 'query_string' ) ) { // Don't bother filtering and parsing if no plugins are hooked in.
472 * Filter the query string before parsing.
475 * @deprecated 2.1.0 Use 'query_vars' or 'request' filters instead.
477 * @param string $query_string The query string to modify.
479 $this->query_string = apply_filters( 'query_string', $this->query_string );
480 parse_str($this->query_string, $this->query_vars);
485 * Set up the WordPress Globals.
487 * The query_vars property will be extracted to the GLOBALS. So care should
488 * be taken when naming global variables that might interfere with the
489 * WordPress environment.
491 * @global string $query_string Query string for the loop.
492 * @global array $posts The found posts.
493 * @global WP_Post|null $post The current post, if available.
494 * @global string $request The SQL statement for the request.
495 * @global int $more Only set, if single page or post.
496 * @global int $single If single page or post. Only set, if single page or post.
497 * @global WP_User $authordata Only set, if author archive.
501 public function register_globals() {
504 // Extract updated query vars back into global namespace.
505 foreach ( (array) $wp_query->query_vars as $key => $value ) {
506 $GLOBALS[ $key ] = $value;
509 $GLOBALS['query_string'] = $this->query_string;
510 $GLOBALS['posts'] = & $wp_query->posts;
511 $GLOBALS['post'] = isset( $wp_query->post ) ? $wp_query->post : null;
512 $GLOBALS['request'] = $wp_query->request;
514 if ( $wp_query->is_single() || $wp_query->is_page() ) {
515 $GLOBALS['more'] = 1;
516 $GLOBALS['single'] = 1;
519 if ( $wp_query->is_author() && isset( $wp_query->post ) )
520 $GLOBALS['authordata'] = get_userdata( $wp_query->post->post_author );
524 * Set up the current user.
528 public function init() {
529 wp_get_current_user();
533 * Set up the Loop based on the query variables.
537 public function query_posts() {
538 global $wp_the_query;
539 $this->build_query_string();
540 $wp_the_query->query($this->query_vars);
544 * Set the Headers for 404, if nothing is found for requested URL.
546 * Issue a 404 if a request doesn't match any posts and doesn't match
547 * any object (e.g. an existing-but-empty category, tag, author) and a 404 was not already
548 * issued, and if the request was not a search or the homepage.
550 * Otherwise, issue a 200.
554 public function handle_404() {
557 // If we've already issued a 404, bail.
561 // Never 404 for the admin, robots, or if we found posts.
562 if ( is_admin() || is_robots() || $wp_query->posts ) {
563 status_header( 200 );
567 // We will 404 for paged queries, as no posts were found.
568 if ( ! is_paged() ) {
570 // Don't 404 for authors without posts as long as they matched an author on this site.
571 $author = get_query_var( 'author' );
572 if ( is_author() && is_numeric( $author ) && $author > 0 && is_user_member_of_blog( $author ) ) {
573 status_header( 200 );
577 // Don't 404 for these queries if they matched an object.
578 if ( ( is_tag() || is_category() || is_tax() || is_post_type_archive() ) && get_queried_object() ) {
579 status_header( 200 );
583 // Don't 404 for these queries either.
584 if ( is_home() || is_search() || is_feed() ) {
585 status_header( 200 );
590 // Guess it's time to 404.
591 $wp_query->set_404();
592 status_header( 404 );
597 * Sets up all of the variables required by the WordPress environment.
599 * The action 'wp' has one parameter that references the WP object. It
600 * allows for accessing the properties and methods to further manipulate the
605 * @param string|array $query_args Passed to {@link parse_request()}
607 public function main($query_args = '') {
609 $this->parse_request($query_args);
610 $this->send_headers();
611 $this->query_posts();
613 $this->register_globals();
616 * Fires once the WordPress environment has been set up.
620 * @param WP &$this Current WordPress environment instance (passed by reference).
622 do_action_ref_array( 'wp', array( &$this ) );
628 * Helper class to remove the need to use eval to replace $matches[] in query strings.
632 class WP_MatchesMapRegex {
642 * store for mapping result
650 * subject to perform mapping on (query string containing $matches[] references
658 * regexp pattern to match $matches[] references
662 public $_pattern = '(\$matches\[[1-9]+[0-9]*\])'; // magic number
665 * Make private properties readable for backwards compatibility.
670 * @param string $name Property to get.
671 * @return mixed Property.
673 public function __get( $name ) {
678 * Make private properties settable for backwards compatibility.
683 * @param string $name Property to set.
684 * @param mixed $value Property value.
685 * @return mixed Newly-set property.
687 public function __set( $name, $value ) {
688 return $this->$name = $value;
692 * Make private properties checkable for backwards compatibility.
697 * @param string $name Property to check if set.
698 * @return bool Whether the property is set.
700 public function __isset( $name ) {
701 return isset( $this->$name );
705 * Make private properties un-settable for backwards compatibility.
710 * @param string $name Property to unset.
712 public function __unset( $name ) {
713 unset( $this->$name );
717 * Make private/protected methods readable for backwards compatibility.
722 * @param callable $name Method to call.
723 * @param array $arguments Arguments to pass when calling.
724 * @return mixed|bool Return value of the callback, false otherwise.
726 public function __call( $name, $arguments ) {
727 return call_user_func_array( array( $this, $name ), $arguments );
733 * @param string $subject subject if regex
734 * @param array $matches data to use in map
737 public function WP_MatchesMapRegex($subject, $matches) {
738 $this->_subject = $subject;
739 $this->_matches = $matches;
740 $this->output = $this->_map();
744 * Substitute substring matches in subject.
746 * static helper function to ease use
749 * @param string $subject subject
750 * @param array $matches data used for substitution
753 public static function apply($subject, $matches) {
754 $oSelf = new WP_MatchesMapRegex($subject, $matches);
755 return $oSelf->output;
759 * do the actual mapping
764 private function _map() {
765 $callback = array($this, 'callback');
766 return preg_replace_callback($this->_pattern, $callback, $this->_subject);
770 * preg_replace_callback hook
773 * @param array $matches preg_replace regexp matches
776 public function callback($matches) {
777 $index = intval(substr($matches[0], 9, -1));
778 return ( isset( $this->_matches[$index] ) ? urlencode($this->_matches[$index]) : '' );