| [ Index ] |
PHP Cross Reference of WordPress Trunk (Updated Daily) |
[Summary view] [Print] [Text view]
1 <?php 2 /** 3 * WordPress environment setup class. 4 * 5 * @package WordPress 6 * @since 2.0.0 7 */ 8 #[AllowDynamicProperties] 9 class WP { 10 /** 11 * Public query variables. 12 * 13 * Long list of public query variables. 14 * 15 * @since 2.0.0 16 * @since 7.2.0 Added the `random` query variable. 17 * @var string[] 18 */ 19 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', 'pagename', 'page_id', 'error', 'attachment', 'attachment_id', 'subpost', 'subpost_id', 'preview', 'robots', 'favicon', 'taxonomy', 'term', 'cpage', 'post_type', 'embed', 'random' ); 20 21 /** 22 * Private query variables. 23 * 24 * Long list of private query variables. 25 * 26 * @since 2.0.0 27 * @var string[] 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', 'fields' ); 30 31 /** 32 * Extra query variables set by the user. 33 * 34 * @since 2.1.0 35 * @var array 36 */ 37 public $extra_query_vars = array(); 38 39 /** 40 * Query variables for setting up the WordPress Query Loop. 41 * 42 * @since 2.0.0 43 * @var array 44 */ 45 public $query_vars = array(); 46 47 /** 48 * String parsed to set the query variables. 49 * 50 * @since 2.0.0 51 * @var string 52 */ 53 public $query_string = ''; 54 55 /** 56 * The request path, e.g. 2015/05/06. 57 * 58 * @since 2.0.0 59 * @var string 60 */ 61 public $request = ''; 62 63 /** 64 * Rewrite rule the request matched. 65 * 66 * @since 2.0.0 67 * @var string 68 */ 69 public $matched_rule = ''; 70 71 /** 72 * Rewrite query the request matched. 73 * 74 * @since 2.0.0 75 * @var string 76 */ 77 public $matched_query = ''; 78 79 /** 80 * Whether already did the permalink. 81 * 82 * @since 2.0.0 83 * @var bool 84 */ 85 public $did_permalink = false; 86 87 /** 88 * Adds a query variable to the list of public query variables. 89 * 90 * @since 2.1.0 91 * 92 * @param string $qv Query variable name. 93 */ 94 public function add_query_var( $qv ) { 95 if ( ! in_array( $qv, $this->public_query_vars, true ) ) { 96 $this->public_query_vars[] = $qv; 97 } 98 } 99 100 /** 101 * Removes a query variable from a list of public query variables. 102 * 103 * @since 4.5.0 104 * 105 * @param string $name Query variable name. 106 */ 107 public function remove_query_var( $name ) { 108 $this->public_query_vars = array_diff( $this->public_query_vars, array( $name ) ); 109 } 110 111 /** 112 * Sets the value of a query variable. 113 * 114 * @since 2.3.0 115 * 116 * @param string $key Query variable name. 117 * @param mixed $value Query variable value. 118 */ 119 public function set_query_var( $key, $value ) { 120 $this->query_vars[ $key ] = $value; 121 } 122 123 /** 124 * Parses the request to find the correct WordPress query. 125 * 126 * Sets up the query variables based on the request. There are also many 127 * filters and actions that can be used to further manipulate the result. 128 * 129 * @since 2.0.0 130 * @since 6.0.0 A return value was added. 131 * 132 * @global WP_Rewrite $wp_rewrite WordPress rewrite component. 133 * 134 * @param array|string $extra_query_vars Set the extra query variables. 135 * @return bool Whether the request was parsed. 136 */ 137 public function parse_request( $extra_query_vars = '' ) { 138 global $wp_rewrite; 139 140 /** 141 * Filters whether to parse the request. 142 * 143 * @since 3.5.0 144 * 145 * @param bool $bool Whether or not to parse the request. Default true. 146 * @param WP $wp Current WordPress environment instance. 147 * @param array|string $extra_query_vars Extra passed query variables. 148 */ 149 if ( ! apply_filters( 'do_parse_request', true, $this, $extra_query_vars ) ) { 150 return false; 151 } 152 153 $this->query_vars = array(); 154 $post_type_query_vars = array(); 155 156 if ( is_array( $extra_query_vars ) ) { 157 $this->extra_query_vars = & $extra_query_vars; 158 } elseif ( ! empty( $extra_query_vars ) ) { 159 parse_str( $extra_query_vars, $this->extra_query_vars ); 160 } 161 // Process PATH_INFO, REQUEST_URI, and 404 for permalinks. 162 163 // Fetch the rewrite rules. 164 $rewrite = $wp_rewrite->wp_rewrite_rules(); 165 166 if ( ! empty( $rewrite ) ) { 167 // If we match a rewrite rule, this will be cleared. 168 $error = '404'; 169 $this->did_permalink = true; 170 171 $pathinfo = $_SERVER['PATH_INFO'] ?? ''; 172 list( $pathinfo ) = explode( '?', $pathinfo ); 173 $pathinfo = str_replace( '%', '%25', $pathinfo ); 174 175 list( $req_uri ) = explode( '?', $_SERVER['REQUEST_URI'] ); 176 $self = $_SERVER['PHP_SELF']; 177 178 $home_path = parse_url( home_url(), PHP_URL_PATH ); 179 $home_path_regex = ''; 180 if ( is_string( $home_path ) && '' !== $home_path ) { 181 $home_path = trim( $home_path, '/' ); 182 $home_path_regex = sprintf( '|^%s|i', preg_quote( $home_path, '|' ) ); 183 } 184 185 /* 186 * Trim path info from the end and the leading home path from the front. 187 * For path info requests, this leaves us with the requesting filename, if any. 188 * For 404 requests, this leaves us with the requested permalink. 189 */ 190 $req_uri = str_replace( $pathinfo, '', $req_uri ); 191 $req_uri = trim( $req_uri, '/' ); 192 $pathinfo = trim( $pathinfo, '/' ); 193 $self = trim( $self, '/' ); 194 195 if ( ! empty( $home_path_regex ) ) { 196 $req_uri = preg_replace( $home_path_regex, '', $req_uri ); 197 $req_uri = trim( $req_uri, '/' ); 198 $pathinfo = preg_replace( $home_path_regex, '', $pathinfo ); 199 $pathinfo = trim( $pathinfo, '/' ); 200 $self = preg_replace( $home_path_regex, '', $self ); 201 $self = trim( $self, '/' ); 202 } 203 204 // The requested permalink is in $pathinfo for path info requests and $req_uri for other requests. 205 if ( ! empty( $pathinfo ) && ! preg_match( '|^.*' . $wp_rewrite->index . '$|', $pathinfo ) ) { 206 $requested_path = $pathinfo; 207 } else { 208 // If the request uri is the index, blank it out so that we don't try to match it against a rule. 209 if ( $req_uri === $wp_rewrite->index ) { 210 $req_uri = ''; 211 } 212 213 $requested_path = $req_uri; 214 } 215 216 $requested_file = $req_uri; 217 218 $this->request = $requested_path; 219 220 // Look for matches. 221 $request_match = $requested_path; 222 if ( empty( $request_match ) ) { 223 // An empty request could only match against ^$ regex. 224 if ( isset( $rewrite['$'] ) ) { 225 $this->matched_rule = '$'; 226 $query = $rewrite['$']; 227 $matches = array( '' ); 228 } 229 } else { 230 foreach ( (array) $rewrite as $match => $query ) { 231 // If the requested file is the anchor of the match, prepend it to the path info. 232 if ( ! empty( $requested_file ) 233 && str_starts_with( $match, $requested_file ) 234 && $requested_file !== $requested_path 235 ) { 236 $request_match = $requested_file . '/' . $requested_path; 237 } 238 239 if ( preg_match( "#^$match#", $request_match, $matches ) 240 || preg_match( "#^$match#", urldecode( $request_match ), $matches ) 241 ) { 242 243 if ( $wp_rewrite->use_verbose_page_rules 244 && preg_match( '/pagename=\$matches\[([0-9]+)\]/', $query, $varmatch ) 245 ) { 246 // This is a verbose page match, let's check to be sure about it. 247 $page = get_page_by_path( $matches[ $varmatch[1] ] ); 248 249 if ( ! $page ) { 250 continue; 251 } 252 253 $post_status_obj = get_post_status_object( $page->post_status ); 254 255 if ( ! $post_status_obj->public && ! $post_status_obj->protected 256 && ! $post_status_obj->private && $post_status_obj->exclude_from_search 257 ) { 258 continue; 259 } 260 } 261 262 // Got a match. 263 $this->matched_rule = $match; 264 break; 265 } 266 } 267 } 268 269 if ( ! empty( $this->matched_rule ) ) { 270 // Trim the query of everything up to the '?'. 271 $query = preg_replace( '!^.+\?!', '', $query ); 272 273 // Substitute the substring matches into the query. 274 $query = addslashes( WP_MatchesMapRegex::apply( $query, $matches ) ); 275 276 $this->matched_query = $query; 277 278 // Parse the query. 279 parse_str( $query, $perma_query_vars ); 280 281 // Clear the 404 error var since we found something. 282 unset( $error, $_GET['error'] ); 283 } 284 285 // If req_uri is empty or if it is a request for ourself, unset error. 286 if ( empty( $requested_path ) || $requested_file === $self 287 || str_contains( $_SERVER['PHP_SELF'], 'wp-admin/' ) 288 ) { 289 unset( $error, $_GET['error'] ); 290 291 if ( isset( $perma_query_vars ) && str_contains( $_SERVER['PHP_SELF'], 'wp-admin/' ) ) { 292 unset( $perma_query_vars ); 293 } 294 295 $this->did_permalink = false; 296 } 297 } 298 299 /** 300 * Filters the query variables allowed before processing. 301 * 302 * Allows (publicly allowed) query vars to be added, removed, or changed prior 303 * to executing the query. Needed to allow custom rewrite rules using your own arguments 304 * to work, or any other custom query variables you want to be publicly available. 305 * 306 * @since 1.5.0 307 * 308 * @param string[] $public_query_vars The array of allowed query variable names. 309 */ 310 $this->public_query_vars = apply_filters( 'query_vars', $this->public_query_vars ); 311 312 foreach ( get_post_types( array(), 'objects' ) as $post_type => $t ) { 313 if ( is_post_type_viewable( $t ) && $t->query_var ) { 314 $post_type_query_vars[ $t->query_var ] = $post_type; 315 } 316 } 317 318 foreach ( $this->public_query_vars as $wpvar ) { 319 if ( isset( $this->extra_query_vars[ $wpvar ] ) ) { 320 $this->query_vars[ $wpvar ] = $this->extra_query_vars[ $wpvar ]; 321 } elseif ( isset( $_GET[ $wpvar ] ) && isset( $_POST[ $wpvar ] ) 322 && $_GET[ $wpvar ] !== $_POST[ $wpvar ] 323 ) { 324 wp_die( 325 __( 'A variable mismatch has been detected.' ), 326 __( 'Sorry, you are not allowed to view this item.' ), 327 400 328 ); 329 } elseif ( isset( $_POST[ $wpvar ] ) ) { 330 $this->query_vars[ $wpvar ] = $_POST[ $wpvar ]; 331 } elseif ( isset( $_GET[ $wpvar ] ) ) { 332 $this->query_vars[ $wpvar ] = $_GET[ $wpvar ]; 333 } elseif ( isset( $perma_query_vars[ $wpvar ] ) ) { 334 $this->query_vars[ $wpvar ] = $perma_query_vars[ $wpvar ]; 335 } 336 337 if ( ! empty( $this->query_vars[ $wpvar ] ) ) { 338 if ( ! is_array( $this->query_vars[ $wpvar ] ) ) { 339 $this->query_vars[ $wpvar ] = (string) $this->query_vars[ $wpvar ]; 340 } else { 341 foreach ( $this->query_vars[ $wpvar ] as $vkey => $v ) { 342 if ( is_scalar( $v ) ) { 343 $this->query_vars[ $wpvar ][ $vkey ] = (string) $v; 344 } 345 } 346 } 347 348 if ( isset( $post_type_query_vars[ $wpvar ] ) ) { 349 $this->query_vars['post_type'] = $post_type_query_vars[ $wpvar ]; 350 $this->query_vars['name'] = $this->query_vars[ $wpvar ]; 351 } 352 } 353 } 354 355 // Convert urldecoded spaces back into '+'. 356 foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy => $t ) { 357 if ( $t->query_var && isset( $this->query_vars[ $t->query_var ] ) ) { 358 $this->query_vars[ $t->query_var ] = str_replace( ' ', '+', $this->query_vars[ $t->query_var ] ); 359 } 360 } 361 362 // Don't allow non-publicly queryable taxonomies to be queried from the front end. 363 if ( ! is_admin() ) { 364 foreach ( get_taxonomies( array( 'publicly_queryable' => false ), 'objects' ) as $taxonomy => $t ) { 365 /* 366 * Disallow when set to the 'taxonomy' query var. 367 * Non-publicly queryable taxonomies cannot register custom query vars. See register_taxonomy(). 368 */ 369 if ( isset( $this->query_vars['taxonomy'] ) && $taxonomy === $this->query_vars['taxonomy'] ) { 370 unset( $this->query_vars['taxonomy'], $this->query_vars['term'] ); 371 } 372 } 373 } 374 375 // Limit publicly queried post_types to those that are 'publicly_queryable'. 376 if ( isset( $this->query_vars['post_type'] ) ) { 377 $queryable_post_types = get_post_types( array( 'publicly_queryable' => true ) ); 378 379 if ( ! is_array( $this->query_vars['post_type'] ) ) { 380 if ( ! in_array( $this->query_vars['post_type'], $queryable_post_types, true ) ) { 381 unset( $this->query_vars['post_type'] ); 382 } 383 } else { 384 $this->query_vars['post_type'] = array_intersect( $this->query_vars['post_type'], $queryable_post_types ); 385 } 386 } 387 388 // Resolve conflicts between posts with numeric slugs and date archive queries. 389 $this->query_vars = wp_resolve_numeric_slug_conflicts( $this->query_vars ); 390 391 foreach ( (array) $this->private_query_vars as $var ) { 392 if ( isset( $this->extra_query_vars[ $var ] ) ) { 393 $this->query_vars[ $var ] = $this->extra_query_vars[ $var ]; 394 } 395 } 396 397 if ( isset( $error ) ) { 398 $this->query_vars['error'] = $error; 399 } 400 401 /** 402 * Filters the array of parsed query variables. 403 * 404 * @since 2.1.0 405 * 406 * @param array $query_vars The array of requested query variables. 407 */ 408 $this->query_vars = apply_filters( 'request', $this->query_vars ); 409 410 /** 411 * Fires once all query variables for the current request have been parsed. 412 * 413 * @since 2.1.0 414 * 415 * @param WP $wp Current WordPress environment instance (passed by reference). 416 */ 417 do_action_ref_array( 'parse_request', array( &$this ) ); 418 419 return true; 420 } 421 422 /** 423 * Sends additional HTTP headers for caching, content type, etc. 424 * 425 * Sets the Content-Type header. Sets the 'error' status (if passed) and optionally exits. 426 * If showing a feed, it will also send Last-Modified, ETag, and 304 status if needed. 427 * 428 * @since 2.0.0 429 * @since 4.4.0 `X-Pingback` header is added conditionally for single posts that allow pings. 430 * @since 6.1.0 Runs after posts have been queried. 431 * 432 * @global WP_Query $wp_query WordPress Query object. 433 */ 434 public function send_headers() { 435 global $wp_query; 436 437 $headers = array(); 438 $status = null; 439 $exit_required = false; 440 $date_format = 'D, d M Y H:i:s'; 441 442 if ( is_user_logged_in() ) { 443 $headers = array_merge( $headers, wp_get_nocache_headers() ); 444 } elseif ( ! empty( $_GET['unapproved'] ) && ! empty( $_GET['moderation-hash'] ) ) { 445 // Unmoderated comments are only visible for 10 minutes via the moderation hash. 446 $expires = 10 * MINUTE_IN_SECONDS; 447 448 $headers['Expires'] = gmdate( $date_format, time() + $expires ); 449 $headers['Cache-Control'] = sprintf( 450 'max-age=%d, must-revalidate', 451 $expires 452 ); 453 } 454 if ( ! empty( $this->query_vars['error'] ) ) { 455 $status = (int) $this->query_vars['error']; 456 457 if ( 404 === $status ) { 458 if ( ! is_user_logged_in() ) { 459 $headers = array_merge( $headers, wp_get_nocache_headers() ); 460 } 461 462 $headers['Content-Type'] = get_option( 'html_type' ) . '; charset=' . get_option( 'blog_charset' ); 463 } elseif ( in_array( $status, array( 403, 500, 502, 503 ), true ) ) { 464 $exit_required = true; 465 } 466 } elseif ( empty( $this->query_vars['feed'] ) ) { 467 $headers['Content-Type'] = get_option( 'html_type' ) . '; charset=' . get_option( 'blog_charset' ); 468 } else { 469 // Set the correct content type for feeds. 470 $type = $this->query_vars['feed']; 471 if ( 'feed' === $this->query_vars['feed'] ) { 472 $type = get_default_feed(); 473 } 474 475 $headers['Content-Type'] = feed_content_type( $type ) . '; charset=' . get_option( 'blog_charset' ); 476 477 // We're showing a feed, so WP is indeed the only thing that last changed. 478 if ( ! empty( $this->query_vars['withcomments'] ) 479 || str_contains( $this->query_vars['feed'], 'comments-' ) 480 || ( empty( $this->query_vars['withoutcomments'] ) 481 && ( ! empty( $this->query_vars['p'] ) 482 || ! empty( $this->query_vars['name'] ) 483 || ! empty( $this->query_vars['page_id'] ) 484 || ! empty( $this->query_vars['pagename'] ) 485 || ! empty( $this->query_vars['attachment'] ) 486 || ! empty( $this->query_vars['attachment_id'] ) 487 ) 488 ) 489 ) { 490 $wp_last_modified_post = mysql2date( $date_format, get_lastpostmodified( 'GMT' ), false ); 491 $wp_last_modified_comment = mysql2date( $date_format, get_lastcommentmodified( 'GMT' ), false ); 492 493 if ( strtotime( $wp_last_modified_post ) > strtotime( $wp_last_modified_comment ) ) { 494 $wp_last_modified = $wp_last_modified_post; 495 } else { 496 $wp_last_modified = $wp_last_modified_comment; 497 } 498 } else { 499 $wp_last_modified = mysql2date( $date_format, get_lastpostmodified( 'GMT' ), false ); 500 } 501 502 if ( ! $wp_last_modified ) { 503 $wp_last_modified = gmdate( $date_format ); 504 } 505 506 $wp_last_modified .= ' GMT'; 507 $wp_etag = '"' . md5( $wp_last_modified ) . '"'; 508 509 $headers['Last-Modified'] = $wp_last_modified; 510 $headers['ETag'] = $wp_etag; 511 512 // Support for conditional GET. 513 if ( isset( $_SERVER['HTTP_IF_NONE_MATCH'] ) ) { 514 $client_etag = wp_unslash( $_SERVER['HTTP_IF_NONE_MATCH'] ); 515 } else { 516 $client_etag = ''; 517 } 518 519 if ( isset( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) { 520 $client_last_modified = trim( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ); 521 } else { 522 $client_last_modified = ''; 523 } 524 525 // If string is empty, return 0. If not, attempt to parse into a timestamp. 526 $client_modified_timestamp = $client_last_modified ? strtotime( $client_last_modified ) : 0; 527 528 // Make a timestamp for our most recent modification. 529 $wp_modified_timestamp = strtotime( $wp_last_modified ); 530 531 if ( ( $client_last_modified && $client_etag ) 532 ? ( ( $client_modified_timestamp >= $wp_modified_timestamp ) && ( $client_etag === $wp_etag ) ) 533 : ( ( $client_modified_timestamp >= $wp_modified_timestamp ) || ( $client_etag === $wp_etag ) ) 534 ) { 535 $status = 304; 536 $exit_required = true; 537 } 538 } 539 540 if ( is_singular() ) { 541 $post = $wp_query->post ?? null; 542 543 // Only set X-Pingback for single posts that allow pings. 544 if ( $post && pings_open( $post ) ) { 545 $headers['X-Pingback'] = get_bloginfo( 'pingback_url', 'display' ); 546 } 547 548 // Send nocache headers for password protected posts to avoid unwanted caching. 549 if ( ! empty( $post->post_password ) ) { 550 $headers = array_merge( $headers, wp_get_nocache_headers() ); 551 } 552 } 553 554 /** 555 * Filters the HTTP headers before they're sent to the browser. 556 * 557 * @since 2.8.0 558 * 559 * @param string[] $headers Associative array of headers to be sent. 560 * @param WP $wp Current WordPress environment instance. 561 */ 562 $headers = apply_filters( 'wp_headers', $headers, $this ); 563 564 if ( ! empty( $status ) ) { 565 status_header( $status ); 566 } 567 568 // If Last-Modified is set to false, it should not be sent (no-cache situation). 569 if ( isset( $headers['Last-Modified'] ) && false === $headers['Last-Modified'] ) { 570 unset( $headers['Last-Modified'] ); 571 572 if ( ! headers_sent() ) { 573 header_remove( 'Last-Modified' ); 574 } 575 } 576 577 if ( ! headers_sent() ) { 578 foreach ( (array) $headers as $name => $field_value ) { 579 header( "{$name}: {$field_value}" ); 580 } 581 } 582 583 if ( $exit_required ) { 584 exit; 585 } 586 587 /** 588 * Fires once the requested HTTP headers for caching, content type, etc. have been sent. 589 * 590 * The {@see 'wp_finalized_template_enhancement_output_buffer'} action may be used to send 591 * headers after rendering the template into an output buffer. 592 * 593 * @since 2.1.0 594 * 595 * @param WP $wp Current WordPress environment instance (passed by reference). 596 */ 597 do_action_ref_array( 'send_headers', array( &$this ) ); 598 } 599 600 /** 601 * Sets the query string property based off of the query variable property. 602 * 603 * The {@see 'query_string'} filter is deprecated, but still works. Plugins should 604 * use the {@see 'request'} filter instead. 605 * 606 * @since 2.0.0 607 */ 608 public function build_query_string() { 609 $this->query_string = ''; 610 611 foreach ( (array) array_keys( $this->query_vars ) as $wpvar ) { 612 if ( '' !== $this->query_vars[ $wpvar ] ) { 613 $this->query_string .= ( strlen( $this->query_string ) < 1 ) ? '' : '&'; 614 615 if ( ! is_scalar( $this->query_vars[ $wpvar ] ) ) { // Discard non-scalars. 616 continue; 617 } 618 619 $this->query_string .= $wpvar . '=' . rawurlencode( $this->query_vars[ $wpvar ] ); 620 } 621 } 622 623 if ( has_filter( 'query_string' ) ) { // Don't bother filtering and parsing if no plugins are hooked in. 624 /** 625 * Filters the query string before parsing. 626 * 627 * @since 1.5.0 628 * @deprecated 2.1.0 Use {@see 'query_vars'} or {@see 'request'} filters instead. 629 * 630 * @param string $query_string The query string to modify. 631 */ 632 $this->query_string = apply_filters_deprecated( 633 'query_string', 634 array( $this->query_string ), 635 '2.1.0', 636 'query_vars, request' 637 ); 638 639 parse_str( $this->query_string, $this->query_vars ); 640 } 641 } 642 643 /** 644 * Set up the WordPress Globals. 645 * 646 * The query_vars property will be extracted to the GLOBALS. So care should 647 * be taken when naming global variables that might interfere with the 648 * WordPress environment. 649 * 650 * @since 2.0.0 651 * 652 * @global WP_Query $wp_query WordPress Query object. 653 * @global string $query_string Query string for the loop. 654 * @global array $posts The found posts. 655 * @global WP_Post|null $post The current post, if available. 656 * @global string $request The SQL statement for the request. 657 * @global int $more Only set, if single page or post. 658 * @global int $single If single page or post. Only set, if single page or post. 659 * @global WP_User|false|null $authordata Only set, if author archive. 660 */ 661 public function register_globals() { 662 global $wp_query; 663 664 // Extract updated query vars back into global namespace. 665 foreach ( (array) $wp_query->query_vars as $key => $value ) { 666 $GLOBALS[ $key ] = $value; 667 } 668 669 $GLOBALS['query_string'] = $this->query_string; 670 $GLOBALS['posts'] = & $wp_query->posts; 671 $GLOBALS['post'] = $wp_query->post ?? null; 672 $GLOBALS['request'] = $wp_query->request; 673 674 if ( $wp_query->is_single() || $wp_query->is_page() ) { 675 $GLOBALS['more'] = 1; 676 $GLOBALS['single'] = 1; 677 } 678 679 if ( $wp_query->is_author() ) { 680 $GLOBALS['authordata'] = get_userdata( get_queried_object_id() ); 681 } 682 } 683 684 /** 685 * Set up the current user. 686 * 687 * @since 2.0.0 688 */ 689 public function init() { 690 wp_get_current_user(); 691 } 692 693 /** 694 * Set up the Loop based on the query variables. 695 * 696 * @since 2.0.0 697 * 698 * @global WP_Query $wp_the_query WordPress Query object. 699 */ 700 public function query_posts() { 701 global $wp_the_query; 702 $this->build_query_string(); 703 $wp_the_query->query( $this->query_vars ); 704 } 705 706 /** 707 * Redirects random content requests to a randomly selected post. 708 * 709 * For random content requests, runs the main query to select a single random post 710 * from the requested archive and redirects to it. The post is selected by looking up 711 * random post IDs, see {@see wp_random_content_posts_pre_query()}, as sorting posts 712 * randomly requires the database to read every eligible post. For example, `example.com/random/` 713 * redirects to a random post and `example.com/random/category/news/` redirects to a 714 * random post in the "news" category. 715 * 716 * The random post is selected by the main query, so {@see 'pre_get_posts'} callbacks 717 * customizing the archive apply to the selection. While the query runs, callbacks 718 * enforcing the eligible posts, order and limit are added after any other callbacks: 719 * 720 * - {@see wp_random_content_pre_get_posts()} on the {@see 'pre_get_posts'} action. 721 * - {@see wp_random_content_posts_where()} on the {@see 'posts_where'} filter. 722 * - {@see wp_random_content_posts_orderby()} on the {@see 'posts_orderby'} filter. 723 * - {@see wp_random_content_post_limits()} on the {@see 'post_limits'} filter. 724 * - {@see wp_random_content_posts_fields()} on the {@see 'posts_fields'} filter. 725 * - {@see wp_random_content_posts_pre_query()} on the {@see 'posts_pre_query'} filter. 726 * 727 * If a post is selected, the redirect is sent by {@see wp_random_content_redirect()} 728 * on the {@see 'template_redirect'} action at priority 100, so the request is set up 729 * and the {@see 'wp'} action has fired before the redirect. 730 * 731 * If no post is selected, for example on an empty archive, the request is a 404 as 732 * there is no post to redirect to. If a post is selected, the request ends with 733 * the redirect. Otherwise the request continues with the results of the main 734 * query, which is not run again. 735 * 736 * Search requests are never random content requests. A search request that includes 737 * the `random` query variable is redirected to the search results without it, see 738 * {@see WP::redirect_random_search()}. 739 * 740 * Requests that are not for posts ignore the `random` query variable, they are neither 741 * random content requests nor redirected. These are requests for robots.txt, the 742 * favicon, sitemaps, feeds and trackbacks. 743 * 744 * @since 7.2.0 745 * 746 * @see wp_is_random_content_query() 747 * @global WP_Query $wp_the_query WordPress Query object. 748 * 749 * @return bool Whether the main query was run for a random content request. 750 */ 751 public function handle_random(): bool { 752 global $wp_the_query; 753 754 if ( ! isset( $this->query_vars['random'] ) || ! wp_is_random_content_redirect_enabled() ) { 755 return false; 756 } 757 758 /* 759 * Random content can only be requested from posts. Requests for robots.txt, the 760 * favicon, sitemaps, feeds and trackbacks ignore the `random` query variable. 761 * 762 * Embeds are not included as only singular requests are embeds, which are never 763 * random content requests. 764 */ 765 foreach ( array( 'robots', 'favicon', 'sitemap', 'feed', 'tb' ) as $query_var ) { 766 if ( ! empty( $this->query_vars[ $query_var ] ) ) { 767 return false; 768 } 769 } 770 771 if ( isset( $this->query_vars['s'] ) ) { 772 $this->redirect_random_search(); 773 774 // The request was not redirected, run the search as if `random` was not requested. 775 return false; 776 } 777 778 add_action( 'pre_get_posts', 'wp_random_content_pre_get_posts', 20 ); 779 add_filter( 'posts_where', 'wp_random_content_posts_where', 20, 2 ); 780 add_filter( 'posts_orderby', 'wp_random_content_posts_orderby', 20, 2 ); 781 add_filter( 'post_limits', 'wp_random_content_post_limits', 20, 2 ); 782 add_filter( 'posts_fields', 'wp_random_content_posts_fields', 20, 2 ); 783 add_filter( 'posts_pre_query', 'wp_random_content_posts_pre_query', 20, 2 ); 784 785 $this->query_posts(); 786 787 remove_action( 'pre_get_posts', 'wp_random_content_pre_get_posts', 20 ); 788 remove_filter( 'posts_where', 'wp_random_content_posts_where', 20 ); 789 remove_filter( 'posts_orderby', 'wp_random_content_posts_orderby', 20 ); 790 remove_filter( 'post_limits', 'wp_random_content_post_limits', 20 ); 791 remove_filter( 'posts_fields', 'wp_random_content_posts_fields', 20 ); 792 remove_filter( 'posts_pre_query', 'wp_random_content_posts_pre_query', 20 ); 793 794 if ( ! wp_is_random_content_query( $wp_the_query ) ) { 795 return true; 796 } 797 798 if ( $wp_the_query->post instanceof WP_Post ) { 799 add_action( 'template_redirect', 'wp_random_content_redirect', 100 ); 800 } else { 801 $wp_the_query->set_404(); 802 status_header( 404 ); 803 nocache_headers(); 804 } 805 806 return true; 807 } 808 809 /** 810 * Redirects search requests for random content to the search results. 811 * 812 * Random content can not be requested from search results. Instead, a search 813 * request that includes the `random` query variable is redirected to 814 * the same request without it. 815 * 816 * The location depends on how random content was requested: 817 * 818 * - By the `random` query string parameter: the requested path is retained and the 819 * parameter is removed. For example, `example.com/search/foo/?random` redirects to 820 * `example.com/search/foo/` and `example.com/?s=foo&random` to `example.com/?s=foo`. 821 * - By a rewrite rule, such as those using the random base: the path is replaced by the 822 * query variables of the request, so the location never includes the random base. 823 * For example, `example.com/random/category/news/?s=foo` redirects to 824 * `example.com/?s=foo&category_name=news`. 825 * 826 * Other query string parameters, including those that are not query variables, are 827 * retained. The redirect happens before the main query is run, so no search is 828 * performed for the redirected request. 829 * 830 * As with random content requests, only front end GET and HEAD requests are redirected. 831 * The request is not redirected when the location would be the requested URL. This is 832 * the case when random content is not requested by the URL, for example by a filter, 833 * or is requested by a rewrite rule for the home page. 834 * 835 * @since 7.2.0 836 * 837 * @global WP_Rewrite $wp_rewrite WordPress rewrite component. 838 */ 839 protected function redirect_random_search(): void { 840 global $wp_rewrite; 841 842 if ( is_admin() ) { 843 return; 844 } 845 846 $request_method = isset( $_SERVER['REQUEST_METHOD'] ) && is_string( $_SERVER['REQUEST_METHOD'] ) ? strtoupper( $_SERVER['REQUEST_METHOD'] ) : ''; 847 if ( 'GET' !== $request_method && 'HEAD' !== $request_method ) { 848 return; 849 } 850 851 $requested_path = ''; 852 853 if ( is_string( $this->request ) && '' !== $this->request ) { 854 /* 855 * The requested path is URL-encoded unless it is from PATH_INFO. Encode any 856 * characters that are not safe in a redirect without decoding the path, as 857 * doing so would change its meaning. For example, a plus is a space in the 858 * path of a search. 859 * 860 * The path is from $_SERVER, so is unslashed first. The slashes are not part 861 * of the request. 862 */ 863 $requested_path = (string) preg_replace_callback( 864 '|[^a-z0-9\-._~+%/]|i', 865 static fn ( array $matches ): string => rawurlencode( $matches[0] ), 866 wp_unslash( $this->request ) 867 ); 868 $requested_path = user_trailingslashit( $requested_path ); 869 870 // PATHINFO permalinks are prefixed by the index file, which PATH_INFO does not include. 871 if ( '' !== $wp_rewrite->root && ! str_starts_with( $requested_path, $wp_rewrite->root ) ) { 872 $requested_path = $wp_rewrite->root . $requested_path; 873 } 874 } 875 876 $path = $requested_path; 877 $query_args = $_GET; 878 879 wp_parse_str( $this->matched_query, $matched_query_vars ); 880 881 if ( isset( $matched_query_vars['random'] ) ) { 882 /* 883 * The path requests random content, so can not be retained. Replace it with 884 * the query variables it was rewritten to. 885 */ 886 $path = ''; 887 $query_args = array_merge( $query_args, $this->query_vars ); 888 } 889 890 unset( $query_args['random'] ); 891 892 $location = add_query_arg( $this->urlencode_query_args( $query_args ), home_url( '/' . $path ) ); 893 894 /* 895 * The redirect removes the random request from the URL. If there is nothing to 896 * remove the location is the requested URL, which would redirect repeatedly. This 897 * is the case when random content is not requested by the URL, for example by a 898 * filter, or is requested by a rewrite rule for the home page. 899 */ 900 if ( add_query_arg( $this->urlencode_query_args( $_GET ), home_url( '/' . $requested_path ) ) === $location ) { 901 return; 902 } 903 904 // Only consider redirecting permitted locations so wp_safe_redirect doesn't redirect to the fallback. 905 if ( ! wp_validate_redirect( $location, '' ) ) { 906 return; 907 } 908 909 if ( wp_safe_redirect( $location, 301 ) ) { 910 exit; 911 } 912 } 913 914 /** 915 * URL-encodes the names and values of query string parameters. 916 * 917 * Unlike urlencode_deep(), the parameter names are encoded as well as the values. A 918 * name is from the request, so may include characters that separate parameters. 919 * 920 * The values are unslashed before they are encoded. The names are not, as slashes 921 * are only added to the values of the superglobals. 922 * 923 * @since 7.2.0 924 * 925 * @param array<mixed> $query_args Query string parameters. The values are expected to 926 * be slashed, the names are not. 927 * @return array<string, mixed> URL-encoded query string parameters. Values that are 928 * neither scalar nor an array are removed. 929 */ 930 private function urlencode_query_args( array $query_args ): array { 931 $encoded = array(); 932 933 foreach ( $query_args as $name => $value ) { 934 $name = urlencode( (string) $name ); 935 936 if ( is_array( $value ) ) { 937 $encoded[ $name ] = $this->urlencode_query_args( $value ); 938 } elseif ( is_scalar( $value ) ) { 939 $encoded[ $name ] = urlencode( wp_unslash( (string) $value ) ); 940 } 941 } 942 943 return $encoded; 944 } 945 946 /** 947 * Set the Headers for 404, if nothing is found for requested URL. 948 * 949 * Issue a 404 if a request doesn't match any posts and doesn't match any object 950 * (e.g. an existing-but-empty category, tag, author) and a 404 was not already issued, 951 * and if the request was not a search or the homepage. 952 * 953 * Otherwise, issue a 200. 954 * 955 * This sets headers after posts have been queried. handle_404() really means "handle status". 956 * By inspecting the result of querying posts, seemingly successful requests can be switched to 957 * a 404 so that canonical redirection logic can kick in. 958 * 959 * @since 2.0.0 960 * 961 * @global WP_Query $wp_query WordPress Query object. 962 */ 963 public function handle_404() { 964 global $wp_query; 965 966 /** 967 * Filters whether to short-circuit default header status handling. 968 * 969 * Returning a non-false value from the filter will short-circuit the handling 970 * and return early. 971 * 972 * @since 4.5.0 973 * 974 * @param bool $preempt Whether to short-circuit default header status handling. Default false. 975 * @param WP_Query $wp_query WordPress Query object. 976 */ 977 if ( false !== apply_filters( 'pre_handle_404', false, $wp_query ) ) { 978 return; 979 } 980 981 // If we've already issued a 404, bail. 982 if ( is_404() ) { 983 return; 984 } 985 986 $set_404 = true; 987 988 // Never 404 here for the admin, robots, favicon, or sitemaps. 989 // Sitemap routes send their own status in WP_Sitemaps::render_sitemaps(). 990 if ( is_admin() || is_robots() || is_favicon() || is_sitemap() ) { 991 $set_404 = false; 992 993 // If posts were found, check for paged content. 994 } elseif ( $wp_query->posts ) { 995 $content_found = true; 996 997 if ( is_singular() ) { 998 $post = $wp_query->post ?? null; 999 $next = '<!--nextpage-->'; 1000 1001 // Check for paged content that exceeds the max number of pages. 1002 if ( $post && ! empty( $this->query_vars['page'] ) ) { 1003 // Check if content is actually intended to be paged. 1004 if ( str_contains( $post->post_content, $next ) ) { 1005 $page = trim( $this->query_vars['page'], '/' ); 1006 $content_found = (int) $page <= ( substr_count( $post->post_content, $next ) + 1 ); 1007 } else { 1008 $content_found = false; 1009 } 1010 } 1011 } 1012 1013 // The posts page does not support the <!--nextpage--> pagination. 1014 if ( $wp_query->is_posts_page && ! empty( $this->query_vars['page'] ) ) { 1015 $content_found = false; 1016 } 1017 1018 if ( $content_found ) { 1019 $set_404 = false; 1020 } 1021 1022 // We will 404 for paged queries, as no posts were found. 1023 } elseif ( ! is_paged() ) { 1024 $author = get_query_var( 'author' ); 1025 1026 // Don't 404 for authors without posts as long as they matched an author on this site. 1027 if ( is_author() && is_numeric( $author ) && $author > 0 && is_user_member_of_blog( $author ) 1028 // Don't 404 for these queries if they matched an object. 1029 || ( is_tag() || is_category() || is_tax() || is_post_type_archive() ) && get_queried_object() 1030 // Don't 404 for these queries either. 1031 || is_home() || is_search() || is_feed() 1032 ) { 1033 $set_404 = false; 1034 } 1035 } 1036 1037 if ( $set_404 ) { 1038 // Guess it's time to 404. 1039 $wp_query->set_404(); 1040 status_header( 404 ); 1041 nocache_headers(); 1042 } else { 1043 status_header( 200 ); 1044 } 1045 } 1046 1047 /** 1048 * Sets up all of the variables required by the WordPress environment. 1049 * 1050 * The action {@see 'wp'} has one parameter that references the WP object. It 1051 * allows for accessing the properties and methods to further manipulate the 1052 * object. 1053 * 1054 * @since 2.0.0 1055 * 1056 * @param string|array $query_args Passed to parse_request(). 1057 */ 1058 public function main( $query_args = '' ) { 1059 $this->init(); 1060 1061 $parsed = $this->parse_request( $query_args ); 1062 1063 if ( $parsed ) { 1064 if ( ! $this->handle_random() ) { 1065 $this->query_posts(); 1066 } 1067 $this->handle_404(); 1068 $this->register_globals(); 1069 } 1070 1071 $this->send_headers(); 1072 1073 /** 1074 * Fires once the WordPress environment has been set up. 1075 * 1076 * @since 2.1.0 1077 * 1078 * @param WP $wp Current WordPress environment instance (passed by reference). 1079 */ 1080 do_action_ref_array( 'wp', array( &$this ) ); 1081 } 1082 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
| Generated : Mon Nov 30 08:20:01 2026 | Cross-referenced by PHPXref |