]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/class-wp.php
WordPress 4.5.2
[autoinstalls/wordpress.git] / wp-includes / class-wp.php
1 <?php
2 /**
3  * WordPress environment setup class.
4  *
5  * @package WordPress
6  * @since 2.0.0
7  */
8 class WP {
9         /**
10          * Public query variables.
11          *
12          * Long list of public query variables.
13          *
14          * @since 2.0.0
15          * @access public
16          * @var array
17          */
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' );
19
20         /**
21          * Private query variables.
22          *
23          * Long list of private query variables.
24          *
25          * @since 2.0.0
26          * @access public
27          * @var array
28          */
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' );
30
31         /**
32          * Extra query variables set by the user.
33          *
34          * @since 2.1.0
35          * @access public
36          * @var array
37          */
38         public $extra_query_vars = array();
39
40         /**
41          * Query variables for setting up the WordPress Query Loop.
42          *
43          * @since 2.0.0
44          * @access public
45          * @var array
46          */
47         public $query_vars;
48
49         /**
50          * String parsed to set the query variables.
51          *
52          * @since 2.0.0
53          * @access public
54          * @var string
55          */
56         public $query_string;
57
58         /**
59          * Permalink or requested URI.
60          *
61          * @since 2.0.0
62          * @access public
63          * @var string
64          */
65         public $request;
66
67         /**
68          * Rewrite rule the request matched.
69          *
70          * @since 2.0.0
71          * @access public
72          * @var string
73          */
74         public $matched_rule;
75
76         /**
77          * Rewrite query the request matched.
78          *
79          * @since 2.0.0
80          * @access public
81          * @var string
82          */
83         public $matched_query;
84
85         /**
86          * Whether already did the permalink.
87          *
88          * @since 2.0.0
89          * @access public
90          * @var bool
91          */
92         public $did_permalink = false;
93
94         /**
95          * Add name to list of public query variables.
96          *
97          * @since 2.1.0
98          * @access public
99          *
100          * @param string $qv Query variable name.
101          */
102         public function add_query_var($qv) {
103                 if ( !in_array($qv, $this->public_query_vars) )
104                         $this->public_query_vars[] = $qv;
105         }
106
107         /**
108          * Removes a query variable from a list of public query variables.
109          *
110          * @since 4.5.0
111          * @access public
112          *
113          * @param string $name Query variable name.
114          */
115         public function remove_query_var( $name ) {
116                 $this->public_query_vars = array_diff( $this->public_query_vars, array( $name ) );
117         }
118
119         /**
120          * Set the value of a query variable.
121          *
122          * @since 2.3.0
123          * @access public
124          *
125          * @param string $key Query variable name.
126          * @param mixed $value Query variable value.
127          */
128         public function set_query_var($key, $value) {
129                 $this->query_vars[$key] = $value;
130         }
131
132         /**
133          * Parse request to find correct WordPress query.
134          *
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.
137          *
138          * @since 2.0.0
139          * @access public
140          *
141          * @global WP_Rewrite $wp_rewrite
142          *
143          * @param array|string $extra_query_vars Set the extra query variables.
144          */
145         public function parse_request($extra_query_vars = '') {
146                 global $wp_rewrite;
147
148                 /**
149                  * Filter whether to parse the request.
150                  *
151                  * @since 3.5.0
152                  *
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.
156                  */
157                 if ( ! apply_filters( 'do_parse_request', true, $this, $extra_query_vars ) )
158                         return;
159
160                 $this->query_vars = array();
161                 $post_type_query_vars = array();
162
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 );
167                 }
168                 // Process PATH_INFO, REQUEST_URI, and 404 for permalinks.
169
170                 // Fetch the rewrite rules.
171                 $rewrite = $wp_rewrite->wp_rewrite_rules();
172
173                 if ( ! empty($rewrite) ) {
174                         // If we match a rewrite rule, this will be cleared.
175                         $error = '404';
176                         $this->did_permalink = true;
177
178                         $pathinfo = isset( $_SERVER['PATH_INFO'] ) ? $_SERVER['PATH_INFO'] : '';
179                         list( $pathinfo ) = explode( '?', $pathinfo );
180                         $pathinfo = str_replace( "%", "%25", $pathinfo );
181
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, '|' ) );
186
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, '/');
201
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;
206                         } else {
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 )
209                                         $req_uri = '';
210                                 $request = $req_uri;
211                         }
212
213                         $this->request = $request;
214
215                         // Look for matches.
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('');
223                                 }
224                         } else {
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;
229
230                                         if ( preg_match("#^$match#", $request_match, $matches) ||
231                                                 preg_match("#^$match#", urldecode($request_match), $matches) ) {
232
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] ] );
236                                                         if ( ! $page ) {
237                                                                 continue;
238                                                         }
239
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 ) {
243                                                                 continue;
244                                                         }
245                                                 }
246
247                                                 // Got a match.
248                                                 $this->matched_rule = $match;
249                                                 break;
250                                         }
251                                 }
252                         }
253
254                         if ( isset( $this->matched_rule ) ) {
255                                 // Trim the query of everything up to the '?'.
256                                 $query = preg_replace("!^.+\?!", '', $query);
257
258                                 // Substitute the substring matches into the query.
259                                 $query = addslashes(WP_MatchesMapRegex::apply($query, $matches));
260
261                                 $this->matched_query = $query;
262
263                                 // Parse the query.
264                                 parse_str($query, $perma_query_vars);
265
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'] );
269                         }
270
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'] );
274
275                                 if ( isset($perma_query_vars) && strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false )
276                                         unset( $perma_query_vars );
277
278                                 $this->did_permalink = false;
279                         }
280                 }
281
282                 /**
283                  * Filter the query variables whitelist before processing.
284                  *
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.
288                  *
289                  * @since 1.5.0
290                  *
291                  * @param array $public_query_vars The array of whitelisted query variables.
292                  */
293                 $this->public_query_vars = apply_filters( 'query_vars', $this->public_query_vars );
294
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;
298                         }
299                 }
300
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];
310
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];
314                                 } else {
315                                         foreach ( $this->query_vars[$wpvar] as $vkey => $v ) {
316                                                 if ( !is_object( $v ) ) {
317                                                         $this->query_vars[$wpvar][$vkey] = (string) $v;
318                                                 }
319                                         }
320                                 }
321
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];
325                                 }
326                         }
327                 }
328
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] );
333
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 ) {
337                                 /*
338                                  * Disallow when set to the 'taxonomy' query var.
339                                  * Non-publicly queryable taxonomies cannot register custom query vars. See register_taxonomy().
340                                  */
341                                 if ( isset( $this->query_vars['taxonomy'] ) && $taxonomy === $this->query_vars['taxonomy'] ) {
342                                         unset( $this->query_vars['taxonomy'], $this->query_vars['term'] );
343                                 }
344                         }
345                 }
346
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'] );
353                         } else {
354                                 $this->query_vars['post_type'] = array_intersect( $this->query_vars['post_type'], $queryable_post_types );
355                         }
356                 }
357
358                 // Resolve conflicts between posts with numeric slugs and date archive queries.
359                 $this->query_vars = wp_resolve_numeric_slug_conflicts( $this->query_vars );
360
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];
364                 }
365
366                 if ( isset($error) )
367                         $this->query_vars['error'] = $error;
368
369                 /**
370                  * Filter the array of parsed query variables.
371                  *
372                  * @since 2.1.0
373                  *
374                  * @param array $query_vars The array of requested query variables.
375                  */
376                 $this->query_vars = apply_filters( 'request', $this->query_vars );
377
378                 /**
379                  * Fires once all query variables for the current request have been parsed.
380                  *
381                  * @since 2.1.0
382                  *
383                  * @param WP &$this Current WordPress environment instance (passed by reference).
384                  */
385                 do_action_ref_array( 'parse_request', array( &$this ) );
386         }
387
388         /**
389          * Sends additional HTTP headers for caching, content type, etc.
390          *
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.
393          *
394          * @since 2.0.0
395          * @since 4.4.0 `X-Pingback` header is added conditionally after posts have been queried in handle_404().
396          * @access public
397          */
398         public function send_headers() {
399                 $headers = array();
400                 $status = null;
401                 $exit_required = false;
402
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;
413                         }
414                 } elseif ( empty( $this->query_vars['feed'] ) ) {
415                         $headers['Content-Type'] = get_option('html_type') . '; charset=' . get_option('blog_charset');
416                 } else {
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();
421                         }
422                         $headers['Content-Type'] = feed_content_type( $type ) . '; charset=' . get_option( 'blog_charset' );
423
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'])
434                                         )
435                                 )
436                         )
437                                 $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastcommentmodified('GMT'), 0).' GMT';
438                         else
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;
443
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;
448
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;
452
453                         // Make a timestamp for our most recent modification...
454                         $wp_modified_timestamp = strtotime($wp_last_modified);
455
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)) ) {
459                                 $status = 304;
460                                 $exit_required = true;
461                         }
462                 }
463
464                 /**
465                  * Filter the HTTP headers before they're sent to the browser.
466                  *
467                  * @since 2.8.0
468                  *
469                  * @param array $headers The list of headers to be sent.
470                  * @param WP    $this    Current WordPress environment instance.
471                  */
472                 $headers = apply_filters( 'wp_headers', $headers, $this );
473
474                 if ( ! empty( $status ) )
475                         status_header( $status );
476
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'] );
480
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' );
484                         } else {
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'] = '';
490                                                 break;
491                                         }
492                                 }
493                         }
494                 }
495
496                 foreach ( (array) $headers as $name => $field_value )
497                         @header("{$name}: {$field_value}");
498
499                 if ( $exit_required )
500                         exit();
501
502                 /**
503                  * Fires once the requested HTTP headers for caching, content type, etc. have been sent.
504                  *
505                  * @since 2.1.0
506                  *
507                  * @param WP &$this Current WordPress environment instance (passed by reference).
508                  */
509                 do_action_ref_array( 'send_headers', array( &$this ) );
510         }
511
512         /**
513          * Sets the query string property based off of the query variable property.
514          *
515          * The 'query_string' filter is deprecated, but still works. Plugins should
516          * use the 'request' filter instead.
517          *
518          * @since 2.0.0
519          * @access public
520          */
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.
527                                         continue;
528                                 $this->query_string .= $wpvar . '=' . rawurlencode($this->query_vars[$wpvar]);
529                         }
530                 }
531
532                 if ( has_filter( 'query_string' ) ) {  // Don't bother filtering and parsing if no plugins are hooked in.
533                         /**
534                          * Filter the query string before parsing.
535                          *
536                          * @since 1.5.0
537                          * @deprecated 2.1.0 Use 'query_vars' or 'request' filters instead.
538                          *
539                          * @param string $query_string The query string to modify.
540                          */
541                         $this->query_string = apply_filters( 'query_string', $this->query_string );
542                         parse_str($this->query_string, $this->query_vars);
543                 }
544         }
545
546         /**
547          * Set up the WordPress Globals.
548          *
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.
552          *
553          * @since 2.0.0
554          * @access public
555          *
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.
564          */
565         public function register_globals() {
566                 global $wp_query;
567
568                 // Extract updated query vars back into global namespace.
569                 foreach ( (array) $wp_query->query_vars as $key => $value ) {
570                         $GLOBALS[ $key ] = $value;
571                 }
572
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;
577
578                 if ( $wp_query->is_single() || $wp_query->is_page() ) {
579                         $GLOBALS['more']   = 1;
580                         $GLOBALS['single'] = 1;
581                 }
582
583                 if ( $wp_query->is_author() && isset( $wp_query->post ) )
584                         $GLOBALS['authordata'] = get_userdata( $wp_query->post->post_author );
585         }
586
587         /**
588          * Set up the current user.
589          *
590          * @since 2.0.0
591          * @access public
592          */
593         public function init() {
594                 wp_get_current_user();
595         }
596
597         /**
598          * Set up the Loop based on the query variables.
599          *
600          * @since 2.0.0
601          * @access public
602          *
603          * @global WP_Query $wp_the_query
604          */
605         public function query_posts() {
606                 global $wp_the_query;
607                 $this->build_query_string();
608                 $wp_the_query->query($this->query_vars);
609         }
610
611         /**
612          * Set the Headers for 404, if nothing is found for requested URL.
613          *
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.
617          *
618          * Otherwise, issue a 200.
619          *
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.
623          *
624          * @since 2.0.0
625      * @access public
626          *
627          * @global WP_Query $wp_query
628          */
629         public function handle_404() {
630                 global $wp_query;
631
632                 /**
633                  * Filter whether to short-circuit default header status handling.
634                  *
635                  * Returning a non-false value from the filter will short-circuit the handling
636                  * and return early.
637                  *
638                  * @since 4.5.0
639                  *
640                  * @param bool     $preempt  Whether to short-circuit default header status handling. Default false.
641                  * @param WP_Query $wp_query WordPress Query object.
642                  */
643                 if ( false !== apply_filters( 'pre_handle_404', false, $wp_query ) ) {
644                         return;
645                 }
646
647                 // If we've already issued a 404, bail.
648                 if ( is_404() )
649                         return;
650
651                 // Never 404 for the admin, robots, or if we found posts.
652                 if ( is_admin() || is_robots() || $wp_query->posts ) {
653
654                         $success = true;
655                         if ( is_singular() ) {
656                                 $p = false;
657
658                                 if ( $wp_query->post instanceof WP_Post ) {
659                                         $p = clone $wp_query->post;
660                                 }
661
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' ) );
665                                 }
666
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 );
672                                 }
673                         }
674
675                         if ( $success ) {
676                                 status_header( 200 );
677                                 return;
678                         }
679                 }
680
681                 // We will 404 for paged queries, as no posts were found.
682                 if ( ! is_paged() ) {
683
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 );
688                                 return;
689                         }
690
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 );
694                                 return;
695                         }
696
697                         // Don't 404 for these queries either.
698                         if ( is_home() || is_search() || is_feed() ) {
699                                 status_header( 200 );
700                                 return;
701                         }
702                 }
703
704                 // Guess it's time to 404.
705                 $wp_query->set_404();
706                 status_header( 404 );
707                 nocache_headers();
708         }
709
710         /**
711          * Sets up all of the variables required by the WordPress environment.
712          *
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
715          * object.
716          *
717          * @since 2.0.0
718          * @access public
719          *
720          * @param string|array $query_args Passed to {@link parse_request()}
721          */
722         public function main($query_args = '') {
723                 $this->init();
724                 $this->parse_request($query_args);
725                 $this->send_headers();
726                 $this->query_posts();
727                 $this->handle_404();
728                 $this->register_globals();
729
730                 /**
731                  * Fires once the WordPress environment has been set up.
732                  *
733                  * @since 2.1.0
734                  *
735                  * @param WP &$this Current WordPress environment instance (passed by reference).
736                  */
737                 do_action_ref_array( 'wp', array( &$this ) );
738         }
739 }
740
741 /**
742  * Helper class to remove the need to use eval to replace $matches[] in query strings.
743  *
744  * @since 2.9.0
745  */
746 class WP_MatchesMapRegex {
747         /**
748          * store for matches
749          *
750          * @access private
751          * @var array
752          */
753         private $_matches;
754
755         /**
756          * store for mapping result
757          *
758          * @access public
759          * @var string
760          */
761         public $output;
762
763         /**
764          * subject to perform mapping on (query string containing $matches[] references
765          *
766          * @access private
767          * @var string
768          */
769         private $_subject;
770
771         /**
772          * regexp pattern to match $matches[] references
773          *
774          * @var string
775          */
776         public $_pattern = '(\$matches\[[1-9]+[0-9]*\])'; // magic number
777
778         /**
779          * constructor
780          *
781          * @param string $subject subject if regex
782          * @param array  $matches data to use in map
783          */
784         public function __construct($subject, $matches) {
785                 $this->_subject = $subject;
786                 $this->_matches = $matches;
787                 $this->output = $this->_map();
788         }
789
790         /**
791          * Substitute substring matches in subject.
792          *
793          * static helper function to ease use
794          *
795          * @static
796          * @access public
797          *
798          * @param string $subject subject
799          * @param array  $matches data used for substitution
800          * @return string
801          */
802         public static function apply($subject, $matches) {
803                 $oSelf = new WP_MatchesMapRegex($subject, $matches);
804                 return $oSelf->output;
805         }
806
807         /**
808          * do the actual mapping
809          *
810          * @access private
811          * @return string
812          */
813         private function _map() {
814                 $callback = array($this, 'callback');
815                 return preg_replace_callback($this->_pattern, $callback, $this->_subject);
816         }
817
818         /**
819          * preg_replace_callback hook
820          *
821          * @access public
822          * @param  array $matches preg_replace regexp matches
823          * @return string
824          */
825         public function callback($matches) {
826                 $index = intval(substr($matches[0], 9, -1));
827                 return ( isset( $this->_matches[$index] ) ? urlencode($this->_matches[$index]) : '' );
828         }
829 }