[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> class-wp.php (source)

   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       * @var string[]
  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', 'pagename', 'page_id', 'error', 'attachment', 'attachment_id', 'subpost', 'subpost_id', 'preview', 'robots', 'favicon', '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       * @var string[]
  27       */
  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', 'title', 'fields' );
  29  
  30      /**
  31       * Extra query variables set by the user.
  32       *
  33       * @since 2.1.0
  34       * @var array
  35       */
  36      public $extra_query_vars = array();
  37  
  38      /**
  39       * Query variables for setting up the WordPress Query Loop.
  40       *
  41       * @since 2.0.0
  42       * @var array
  43       */
  44      public $query_vars = array();
  45  
  46      /**
  47       * String parsed to set the query variables.
  48       *
  49       * @since 2.0.0
  50       * @var string
  51       */
  52      public $query_string = '';
  53  
  54      /**
  55       * The request path, e.g. 2015/05/06.
  56       *
  57       * @since 2.0.0
  58       * @var string
  59       */
  60      public $request = '';
  61  
  62      /**
  63       * Rewrite rule the request matched.
  64       *
  65       * @since 2.0.0
  66       * @var string
  67       */
  68      public $matched_rule = '';
  69  
  70      /**
  71       * Rewrite query the request matched.
  72       *
  73       * @since 2.0.0
  74       * @var string
  75       */
  76      public $matched_query = '';
  77  
  78      /**
  79       * Whether already did the permalink.
  80       *
  81       * @since 2.0.0
  82       * @var bool
  83       */
  84      public $did_permalink = false;
  85  
  86      /**
  87       * Adds a query variable to the list of public query variables.
  88       *
  89       * @since 2.1.0
  90       *
  91       * @param string $qv Query variable name.
  92       */
  93  	public function add_query_var( $qv ) {
  94          if ( ! in_array( $qv, $this->public_query_vars, true ) ) {
  95              $this->public_query_vars[] = $qv;
  96          }
  97      }
  98  
  99      /**
 100       * Removes a query variable from a list of public query variables.
 101       *
 102       * @since 4.5.0
 103       *
 104       * @param string $name Query variable name.
 105       */
 106  	public function remove_query_var( $name ) {
 107          $this->public_query_vars = array_diff( $this->public_query_vars, array( $name ) );
 108      }
 109  
 110      /**
 111       * Sets the value of a query variable.
 112       *
 113       * @since 2.3.0
 114       *
 115       * @param string $key   Query variable name.
 116       * @param mixed  $value Query variable value.
 117       */
 118  	public function set_query_var( $key, $value ) {
 119          $this->query_vars[ $key ] = $value;
 120      }
 121  
 122      /**
 123       * Parses the request to find the correct WordPress query.
 124       *
 125       * Sets up the query variables based on the request. There are also many
 126       * filters and actions that can be used to further manipulate the result.
 127       *
 128       * @since 2.0.0
 129       * @since 6.0.0 A return value was added.
 130       *
 131       * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
 132       *
 133       * @param array|string $extra_query_vars Set the extra query variables.
 134       * @return bool Whether the request was parsed.
 135       */
 136  	public function parse_request( $extra_query_vars = '' ) {
 137          global $wp_rewrite;
 138  
 139          /**
 140           * Filters whether to parse the request.
 141           *
 142           * @since 3.5.0
 143           *
 144           * @param bool         $bool             Whether or not to parse the request. Default true.
 145           * @param WP           $wp               Current WordPress environment instance.
 146           * @param array|string $extra_query_vars Extra passed query variables.
 147           */
 148          if ( ! apply_filters( 'do_parse_request', true, $this, $extra_query_vars ) ) {
 149              return false;
 150          }
 151  
 152          $this->query_vars     = array();
 153          $post_type_query_vars = array();
 154  
 155          if ( is_array( $extra_query_vars ) ) {
 156              $this->extra_query_vars = & $extra_query_vars;
 157          } elseif ( ! empty( $extra_query_vars ) ) {
 158              parse_str( $extra_query_vars, $this->extra_query_vars );
 159          }
 160          // Process PATH_INFO, REQUEST_URI, and 404 for permalinks.
 161  
 162          // Fetch the rewrite rules.
 163          $rewrite = $wp_rewrite->wp_rewrite_rules();
 164  
 165          if ( ! empty( $rewrite ) ) {
 166              // If we match a rewrite rule, this will be cleared.
 167              $error               = '404';
 168              $this->did_permalink = true;
 169  
 170              $pathinfo         = $_SERVER['PATH_INFO'] ?? '';
 171              list( $pathinfo ) = explode( '?', $pathinfo );
 172              $pathinfo         = str_replace( '%', '%25', $pathinfo );
 173  
 174              list( $req_uri ) = explode( '?', $_SERVER['REQUEST_URI'] );
 175              $self            = $_SERVER['PHP_SELF'];
 176  
 177              $home_path       = parse_url( home_url(), PHP_URL_PATH );
 178              $home_path_regex = '';
 179              if ( is_string( $home_path ) && '' !== $home_path ) {
 180                  $home_path       = trim( $home_path, '/' );
 181                  $home_path_regex = sprintf( '|^%s|i', preg_quote( $home_path, '|' ) );
 182              }
 183  
 184              /*
 185               * Trim path info from the end and the leading home path from the front.
 186               * For path info requests, this leaves us with the requesting filename, if any.
 187               * For 404 requests, this leaves us with the requested permalink.
 188               */
 189              $req_uri  = str_replace( $pathinfo, '', $req_uri );
 190              $req_uri  = trim( $req_uri, '/' );
 191              $pathinfo = trim( $pathinfo, '/' );
 192              $self     = trim( $self, '/' );
 193  
 194              if ( ! empty( $home_path_regex ) ) {
 195                  $req_uri  = preg_replace( $home_path_regex, '', $req_uri );
 196                  $req_uri  = trim( $req_uri, '/' );
 197                  $pathinfo = preg_replace( $home_path_regex, '', $pathinfo );
 198                  $pathinfo = trim( $pathinfo, '/' );
 199                  $self     = preg_replace( $home_path_regex, '', $self );
 200                  $self     = trim( $self, '/' );
 201              }
 202  
 203              // The requested permalink is in $pathinfo for path info requests and $req_uri for other requests.
 204              if ( ! empty( $pathinfo ) && ! preg_match( '|^.*' . $wp_rewrite->index . '$|', $pathinfo ) ) {
 205                  $requested_path = $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                  }
 211  
 212                  $requested_path = $req_uri;
 213              }
 214  
 215              $requested_file = $req_uri;
 216  
 217              $this->request = $requested_path;
 218  
 219              // Look for matches.
 220              $request_match = $requested_path;
 221              if ( empty( $request_match ) ) {
 222                  // An empty request could only match against ^$ regex.
 223                  if ( isset( $rewrite['$'] ) ) {
 224                      $this->matched_rule = '$';
 225                      $query              = $rewrite['$'];
 226                      $matches            = array( '' );
 227                  }
 228              } else {
 229                  foreach ( (array) $rewrite as $match => $query ) {
 230                      // If the requested file is the anchor of the match, prepend it to the path info.
 231                      if ( ! empty( $requested_file )
 232                          && str_starts_with( $match, $requested_file )
 233                          && $requested_file !== $requested_path
 234                      ) {
 235                          $request_match = $requested_file . '/' . $requested_path;
 236                      }
 237  
 238                      if ( preg_match( "#^$match#", $request_match, $matches )
 239                          || preg_match( "#^$match#", urldecode( $request_match ), $matches )
 240                      ) {
 241  
 242                          if ( $wp_rewrite->use_verbose_page_rules
 243                              && preg_match( '/pagename=\$matches\[([0-9]+)\]/', $query, $varmatch )
 244                          ) {
 245                              // This is a verbose page match, let's check to be sure about it.
 246                              $page = get_page_by_path( $matches[ $varmatch[1] ] );
 247  
 248                              if ( ! $page ) {
 249                                  continue;
 250                              }
 251  
 252                              $post_status_obj = get_post_status_object( $page->post_status );
 253  
 254                              if ( ! $post_status_obj->public && ! $post_status_obj->protected
 255                                  && ! $post_status_obj->private && $post_status_obj->exclude_from_search
 256                              ) {
 257                                  continue;
 258                              }
 259                          }
 260  
 261                          // Got a match.
 262                          $this->matched_rule = $match;
 263                          break;
 264                      }
 265                  }
 266              }
 267  
 268              if ( ! empty( $this->matched_rule ) ) {
 269                  // Trim the query of everything up to the '?'.
 270                  $query = preg_replace( '!^.+\?!', '', $query );
 271  
 272                  // Substitute the substring matches into the query.
 273                  $query = addslashes( WP_MatchesMapRegex::apply( $query, $matches ) );
 274  
 275                  $this->matched_query = $query;
 276  
 277                  // Parse the query.
 278                  parse_str( $query, $perma_query_vars );
 279  
 280                  // Clear the 404 error var since we found something.
 281                  unset( $error, $_GET['error'] );
 282              }
 283  
 284              // If req_uri is empty or if it is a request for ourself, unset error.
 285              if ( empty( $requested_path ) || $requested_file === $self
 286                  || str_contains( $_SERVER['PHP_SELF'], 'wp-admin/' )
 287              ) {
 288                  unset( $error, $_GET['error'] );
 289  
 290                  if ( isset( $perma_query_vars ) && str_contains( $_SERVER['PHP_SELF'], 'wp-admin/' ) ) {
 291                      unset( $perma_query_vars );
 292                  }
 293  
 294                  $this->did_permalink = false;
 295              }
 296          }
 297  
 298          /**
 299           * Filters the query variables allowed before processing.
 300           *
 301           * Allows (publicly allowed) query vars to be added, removed, or changed prior
 302           * to executing the query. Needed to allow custom rewrite rules using your own arguments
 303           * to work, or any other custom query variables you want to be publicly available.
 304           *
 305           * @since 1.5.0
 306           *
 307           * @param string[] $public_query_vars The array of allowed query variable names.
 308           */
 309          $this->public_query_vars = apply_filters( 'query_vars', $this->public_query_vars );
 310  
 311          foreach ( get_post_types( array(), 'objects' ) as $post_type => $t ) {
 312              if ( is_post_type_viewable( $t ) && $t->query_var ) {
 313                  $post_type_query_vars[ $t->query_var ] = $post_type;
 314              }
 315          }
 316  
 317          foreach ( $this->public_query_vars as $wpvar ) {
 318              if ( isset( $this->extra_query_vars[ $wpvar ] ) ) {
 319                  $this->query_vars[ $wpvar ] = $this->extra_query_vars[ $wpvar ];
 320              } elseif ( isset( $_GET[ $wpvar ] ) && isset( $_POST[ $wpvar ] )
 321                  && $_GET[ $wpvar ] !== $_POST[ $wpvar ]
 322              ) {
 323                  wp_die(
 324                      __( 'A variable mismatch has been detected.' ),
 325                      __( 'Sorry, you are not allowed to view this item.' ),
 326                      400
 327                  );
 328              } elseif ( isset( $_POST[ $wpvar ] ) ) {
 329                  $this->query_vars[ $wpvar ] = $_POST[ $wpvar ];
 330              } elseif ( isset( $_GET[ $wpvar ] ) ) {
 331                  $this->query_vars[ $wpvar ] = $_GET[ $wpvar ];
 332              } elseif ( isset( $perma_query_vars[ $wpvar ] ) ) {
 333                  $this->query_vars[ $wpvar ] = $perma_query_vars[ $wpvar ];
 334              }
 335  
 336              if ( ! empty( $this->query_vars[ $wpvar ] ) ) {
 337                  if ( ! is_array( $this->query_vars[ $wpvar ] ) ) {
 338                      $this->query_vars[ $wpvar ] = (string) $this->query_vars[ $wpvar ];
 339                  } else {
 340                      foreach ( $this->query_vars[ $wpvar ] as $vkey => $v ) {
 341                          if ( is_scalar( $v ) ) {
 342                              $this->query_vars[ $wpvar ][ $vkey ] = (string) $v;
 343                          }
 344                      }
 345                  }
 346  
 347                  if ( isset( $post_type_query_vars[ $wpvar ] ) ) {
 348                      $this->query_vars['post_type'] = $post_type_query_vars[ $wpvar ];
 349                      $this->query_vars['name']      = $this->query_vars[ $wpvar ];
 350                  }
 351              }
 352          }
 353  
 354          // Convert urldecoded spaces back into '+'.
 355          foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy => $t ) {
 356              if ( $t->query_var && isset( $this->query_vars[ $t->query_var ] ) ) {
 357                  $this->query_vars[ $t->query_var ] = str_replace( ' ', '+', $this->query_vars[ $t->query_var ] );
 358              }
 359          }
 360  
 361          // Don't allow non-publicly queryable taxonomies to be queried from the front end.
 362          if ( ! is_admin() ) {
 363              foreach ( get_taxonomies( array( 'publicly_queryable' => false ), 'objects' ) as $taxonomy => $t ) {
 364                  /*
 365                   * Disallow when set to the 'taxonomy' query var.
 366                   * Non-publicly queryable taxonomies cannot register custom query vars. See register_taxonomy().
 367                   */
 368                  if ( isset( $this->query_vars['taxonomy'] ) && $taxonomy === $this->query_vars['taxonomy'] ) {
 369                      unset( $this->query_vars['taxonomy'], $this->query_vars['term'] );
 370                  }
 371              }
 372          }
 373  
 374          // Limit publicly queried post_types to those that are 'publicly_queryable'.
 375          if ( isset( $this->query_vars['post_type'] ) ) {
 376              $queryable_post_types = get_post_types( array( 'publicly_queryable' => true ) );
 377  
 378              if ( ! is_array( $this->query_vars['post_type'] ) ) {
 379                  if ( ! in_array( $this->query_vars['post_type'], $queryable_post_types, true ) ) {
 380                      unset( $this->query_vars['post_type'] );
 381                  }
 382              } else {
 383                  $this->query_vars['post_type'] = array_intersect( $this->query_vars['post_type'], $queryable_post_types );
 384              }
 385          }
 386  
 387          // Resolve conflicts between posts with numeric slugs and date archive queries.
 388          $this->query_vars = wp_resolve_numeric_slug_conflicts( $this->query_vars );
 389  
 390          foreach ( (array) $this->private_query_vars as $var ) {
 391              if ( isset( $this->extra_query_vars[ $var ] ) ) {
 392                  $this->query_vars[ $var ] = $this->extra_query_vars[ $var ];
 393              }
 394          }
 395  
 396          if ( isset( $error ) ) {
 397              $this->query_vars['error'] = $error;
 398          }
 399  
 400          /**
 401           * Filters the array of parsed query variables.
 402           *
 403           * @since 2.1.0
 404           *
 405           * @param array $query_vars The array of requested query variables.
 406           */
 407          $this->query_vars = apply_filters( 'request', $this->query_vars );
 408  
 409          /**
 410           * Fires once all query variables for the current request have been parsed.
 411           *
 412           * @since 2.1.0
 413           *
 414           * @param WP $wp Current WordPress environment instance (passed by reference).
 415           */
 416          do_action_ref_array( 'parse_request', array( &$this ) );
 417  
 418          return true;
 419      }
 420  
 421      /**
 422       * Sends additional HTTP headers for caching, content type, etc.
 423       *
 424       * Sets the Content-Type header. Sets the 'error' status (if passed) and optionally exits.
 425       * If showing a feed, it will also send Last-Modified, ETag, and 304 status if needed.
 426       *
 427       * @since 2.0.0
 428       * @since 4.4.0 `X-Pingback` header is added conditionally for single posts that allow pings.
 429       * @since 6.1.0 Runs after posts have been queried.
 430       *
 431       * @global WP_Query $wp_query WordPress Query object.
 432       */
 433  	public function send_headers() {
 434          global $wp_query;
 435  
 436          $headers       = array();
 437          $status        = null;
 438          $exit_required = false;
 439          $date_format   = 'D, d M Y H:i:s';
 440  
 441          if ( is_user_logged_in() ) {
 442              $headers = array_merge( $headers, wp_get_nocache_headers() );
 443          } elseif ( ! empty( $_GET['unapproved'] ) && ! empty( $_GET['moderation-hash'] ) ) {
 444              // Unmoderated comments are only visible for 10 minutes via the moderation hash.
 445              $expires = 10 * MINUTE_IN_SECONDS;
 446  
 447              $headers['Expires']       = gmdate( $date_format, time() + $expires );
 448              $headers['Cache-Control'] = sprintf(
 449                  'max-age=%d, must-revalidate',
 450                  $expires
 451              );
 452          }
 453          if ( ! empty( $this->query_vars['error'] ) ) {
 454              $status = (int) $this->query_vars['error'];
 455  
 456              if ( 404 === $status ) {
 457                  if ( ! is_user_logged_in() ) {
 458                      $headers = array_merge( $headers, wp_get_nocache_headers() );
 459                  }
 460  
 461                  $headers['Content-Type'] = get_option( 'html_type' ) . '; charset=' . get_option( 'blog_charset' );
 462              } elseif ( in_array( $status, array( 403, 500, 502, 503 ), true ) ) {
 463                  $exit_required = true;
 464              }
 465          } elseif ( empty( $this->query_vars['feed'] ) ) {
 466              $headers['Content-Type'] = get_option( 'html_type' ) . '; charset=' . get_option( 'blog_charset' );
 467          } else {
 468              // Set the correct content type for feeds.
 469              $type = $this->query_vars['feed'];
 470              if ( 'feed' === $this->query_vars['feed'] ) {
 471                  $type = get_default_feed();
 472              }
 473  
 474              $headers['Content-Type'] = feed_content_type( $type ) . '; charset=' . get_option( 'blog_charset' );
 475  
 476              // We're showing a feed, so WP is indeed the only thing that last changed.
 477              if ( ! empty( $this->query_vars['withcomments'] )
 478                  || str_contains( $this->query_vars['feed'], 'comments-' )
 479                  || ( empty( $this->query_vars['withoutcomments'] )
 480                      && ( ! empty( $this->query_vars['p'] )
 481                          || ! empty( $this->query_vars['name'] )
 482                          || ! empty( $this->query_vars['page_id'] )
 483                          || ! empty( $this->query_vars['pagename'] )
 484                          || ! empty( $this->query_vars['attachment'] )
 485                          || ! empty( $this->query_vars['attachment_id'] )
 486                      )
 487                  )
 488              ) {
 489                  $wp_last_modified_post    = mysql2date( $date_format, get_lastpostmodified( 'GMT' ), false );
 490                  $wp_last_modified_comment = mysql2date( $date_format, get_lastcommentmodified( 'GMT' ), false );
 491  
 492                  if ( strtotime( $wp_last_modified_post ) > strtotime( $wp_last_modified_comment ) ) {
 493                      $wp_last_modified = $wp_last_modified_post;
 494                  } else {
 495                      $wp_last_modified = $wp_last_modified_comment;
 496                  }
 497              } else {
 498                  $wp_last_modified = mysql2date( $date_format, get_lastpostmodified( 'GMT' ), false );
 499              }
 500  
 501              if ( ! $wp_last_modified ) {
 502                  $wp_last_modified = gmdate( $date_format );
 503              }
 504  
 505              $wp_last_modified .= ' GMT';
 506              $wp_etag           = '"' . md5( $wp_last_modified ) . '"';
 507  
 508              $headers['Last-Modified'] = $wp_last_modified;
 509              $headers['ETag']          = $wp_etag;
 510  
 511              // Support for conditional GET.
 512              if ( isset( $_SERVER['HTTP_IF_NONE_MATCH'] ) ) {
 513                  $client_etag = wp_unslash( $_SERVER['HTTP_IF_NONE_MATCH'] );
 514              } else {
 515                  $client_etag = '';
 516              }
 517  
 518              if ( isset( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
 519                  $client_last_modified = trim( $_SERVER['HTTP_IF_MODIFIED_SINCE'] );
 520              } else {
 521                  $client_last_modified = '';
 522              }
 523  
 524              // If string is empty, return 0. If not, attempt to parse into a timestamp.
 525              $client_modified_timestamp = $client_last_modified ? strtotime( $client_last_modified ) : 0;
 526  
 527              // Make a timestamp for our most recent modification.
 528              $wp_modified_timestamp = strtotime( $wp_last_modified );
 529  
 530              if ( ( $client_last_modified && $client_etag )
 531                  ? ( ( $client_modified_timestamp >= $wp_modified_timestamp ) && ( $client_etag === $wp_etag ) )
 532                  : ( ( $client_modified_timestamp >= $wp_modified_timestamp ) || ( $client_etag === $wp_etag ) )
 533              ) {
 534                  $status        = 304;
 535                  $exit_required = true;
 536              }
 537          }
 538  
 539          if ( is_singular() ) {
 540              $post = $wp_query->post ?? null;
 541  
 542              // Only set X-Pingback for single posts that allow pings.
 543              if ( $post && pings_open( $post ) ) {
 544                  $headers['X-Pingback'] = get_bloginfo( 'pingback_url', 'display' );
 545              }
 546  
 547              // Send nocache headers for password protected posts to avoid unwanted caching.
 548              if ( ! empty( $post->post_password ) ) {
 549                  $headers = array_merge( $headers, wp_get_nocache_headers() );
 550              }
 551          }
 552  
 553          /**
 554           * Filters the HTTP headers before they're sent to the browser.
 555           *
 556           * @since 2.8.0
 557           *
 558           * @param string[] $headers Associative array of headers to be sent.
 559           * @param WP       $wp      Current WordPress environment instance.
 560           */
 561          $headers = apply_filters( 'wp_headers', $headers, $this );
 562  
 563          if ( ! empty( $status ) ) {
 564              status_header( $status );
 565          }
 566  
 567          // If Last-Modified is set to false, it should not be sent (no-cache situation).
 568          if ( isset( $headers['Last-Modified'] ) && false === $headers['Last-Modified'] ) {
 569              unset( $headers['Last-Modified'] );
 570  
 571              if ( ! headers_sent() ) {
 572                  header_remove( 'Last-Modified' );
 573              }
 574          }
 575  
 576          if ( ! headers_sent() ) {
 577              foreach ( (array) $headers as $name => $field_value ) {
 578                  header( "{$name}: {$field_value}" );
 579              }
 580          }
 581  
 582          if ( $exit_required ) {
 583              exit;
 584          }
 585  
 586          /**
 587           * Fires once the requested HTTP headers for caching, content type, etc. have been sent.
 588           *
 589           * The {@see 'wp_finalized_template_enhancement_output_buffer'} action may be used to send
 590           * headers after rendering the template into an output buffer.
 591           *
 592           * @since 2.1.0
 593           *
 594           * @param WP $wp Current WordPress environment instance (passed by reference).
 595           */
 596          do_action_ref_array( 'send_headers', array( &$this ) );
 597      }
 598  
 599      /**
 600       * Sets the query string property based off of the query variable property.
 601       *
 602       * The {@see 'query_string'} filter is deprecated, but still works. Plugins should
 603       * use the {@see 'request'} filter instead.
 604       *
 605       * @since 2.0.0
 606       */
 607  	public function build_query_string() {
 608          $this->query_string = '';
 609  
 610          foreach ( (array) array_keys( $this->query_vars ) as $wpvar ) {
 611              if ( '' !== $this->query_vars[ $wpvar ] ) {
 612                  $this->query_string .= ( strlen( $this->query_string ) < 1 ) ? '' : '&';
 613  
 614                  if ( ! is_scalar( $this->query_vars[ $wpvar ] ) ) { // Discard non-scalars.
 615                      continue;
 616                  }
 617  
 618                  $this->query_string .= $wpvar . '=' . rawurlencode( $this->query_vars[ $wpvar ] );
 619              }
 620          }
 621  
 622          if ( has_filter( 'query_string' ) ) {  // Don't bother filtering and parsing if no plugins are hooked in.
 623              /**
 624               * Filters the query string before parsing.
 625               *
 626               * @since 1.5.0
 627               * @deprecated 2.1.0 Use {@see 'query_vars'} or {@see 'request'} filters instead.
 628               *
 629               * @param string $query_string The query string to modify.
 630               */
 631              $this->query_string = apply_filters_deprecated(
 632                  'query_string',
 633                  array( $this->query_string ),
 634                  '2.1.0',
 635                  'query_vars, request'
 636              );
 637  
 638              parse_str( $this->query_string, $this->query_vars );
 639          }
 640      }
 641  
 642      /**
 643       * Set up the WordPress Globals.
 644       *
 645       * The query_vars property will be extracted to the GLOBALS. So care should
 646       * be taken when naming global variables that might interfere with the
 647       * WordPress environment.
 648       *
 649       * @since 2.0.0
 650       *
 651       * @global WP_Query           $wp_query     WordPress Query object.
 652       * @global string             $query_string Query string for the loop.
 653       * @global array              $posts        The found posts.
 654       * @global WP_Post|null       $post         The current post, if available.
 655       * @global string             $request      The SQL statement for the request.
 656       * @global int                $more         Only set, if single page or post.
 657       * @global int                $single       If single page or post. Only set, if single page or post.
 658       * @global WP_User|false|null $authordata   Only set, if author archive.
 659       */
 660  	public function register_globals() {
 661          global $wp_query;
 662  
 663          // Extract updated query vars back into global namespace.
 664          foreach ( (array) $wp_query->query_vars as $key => $value ) {
 665              $GLOBALS[ $key ] = $value;
 666          }
 667  
 668          $GLOBALS['query_string'] = $this->query_string;
 669          $GLOBALS['posts']        = & $wp_query->posts;
 670          $GLOBALS['post']         = $wp_query->post ?? null;
 671          $GLOBALS['request']      = $wp_query->request;
 672  
 673          if ( $wp_query->is_single() || $wp_query->is_page() ) {
 674              $GLOBALS['more']   = 1;
 675              $GLOBALS['single'] = 1;
 676          }
 677  
 678          if ( $wp_query->is_author() ) {
 679              $GLOBALS['authordata'] = get_userdata( get_queried_object_id() );
 680          }
 681      }
 682  
 683      /**
 684       * Set up the current user.
 685       *
 686       * @since 2.0.0
 687       */
 688  	public function init() {
 689          wp_get_current_user();
 690      }
 691  
 692      /**
 693       * Set up the Loop based on the query variables.
 694       *
 695       * @since 2.0.0
 696       *
 697       * @global WP_Query $wp_the_query WordPress Query object.
 698       */
 699  	public function query_posts() {
 700          global $wp_the_query;
 701          $this->build_query_string();
 702          $wp_the_query->query( $this->query_vars );
 703      }
 704  
 705      /**
 706       * Set the Headers for 404, if nothing is found for requested URL.
 707       *
 708       * Issue a 404 if a request doesn't match any posts and doesn't match any object
 709       * (e.g. an existing-but-empty category, tag, author) and a 404 was not already issued,
 710       * and if the request was not a search or the homepage.
 711       *
 712       * Otherwise, issue a 200.
 713       *
 714       * This sets headers after posts have been queried. handle_404() really means "handle status".
 715       * By inspecting the result of querying posts, seemingly successful requests can be switched to
 716       * a 404 so that canonical redirection logic can kick in.
 717       *
 718       * @since 2.0.0
 719       *
 720       * @global WP_Query $wp_query WordPress Query object.
 721       */
 722  	public function handle_404() {
 723          global $wp_query;
 724  
 725          /**
 726           * Filters whether to short-circuit default header status handling.
 727           *
 728           * Returning a non-false value from the filter will short-circuit the handling
 729           * and return early.
 730           *
 731           * @since 4.5.0
 732           *
 733           * @param bool     $preempt  Whether to short-circuit default header status handling. Default false.
 734           * @param WP_Query $wp_query WordPress Query object.
 735           */
 736          if ( false !== apply_filters( 'pre_handle_404', false, $wp_query ) ) {
 737              return;
 738          }
 739  
 740          // If we've already issued a 404, bail.
 741          if ( is_404() ) {
 742              return;
 743          }
 744  
 745          $set_404 = true;
 746  
 747          // Never 404 here for the admin, robots, favicon, or sitemaps.
 748          // Sitemap routes send their own status in WP_Sitemaps::render_sitemaps().
 749          if ( is_admin() || is_robots() || is_favicon() || is_sitemap() ) {
 750              $set_404 = false;
 751  
 752              // If posts were found, check for paged content.
 753          } elseif ( $wp_query->posts ) {
 754              $content_found = true;
 755  
 756              if ( is_singular() ) {
 757                  $post = $wp_query->post ?? null;
 758                  $next = '<!--nextpage-->';
 759  
 760                  // Check for paged content that exceeds the max number of pages.
 761                  if ( $post && ! empty( $this->query_vars['page'] ) ) {
 762                      // Check if content is actually intended to be paged.
 763                      if ( str_contains( $post->post_content, $next ) ) {
 764                          $page          = trim( $this->query_vars['page'], '/' );
 765                          $content_found = (int) $page <= ( substr_count( $post->post_content, $next ) + 1 );
 766                      } else {
 767                          $content_found = false;
 768                      }
 769                  }
 770              }
 771  
 772              // The posts page does not support the <!--nextpage--> pagination.
 773              if ( $wp_query->is_posts_page && ! empty( $this->query_vars['page'] ) ) {
 774                  $content_found = false;
 775              }
 776  
 777              if ( $content_found ) {
 778                  $set_404 = false;
 779              }
 780  
 781              // We will 404 for paged queries, as no posts were found.
 782          } elseif ( ! is_paged() ) {
 783              $author = get_query_var( 'author' );
 784  
 785              // Don't 404 for authors without posts as long as they matched an author on this site.
 786              if ( is_author() && is_numeric( $author ) && $author > 0 && is_user_member_of_blog( $author )
 787                  // Don't 404 for these queries if they matched an object.
 788                  || ( is_tag() || is_category() || is_tax() || is_post_type_archive() ) && get_queried_object()
 789                  // Don't 404 for these queries either.
 790                  || is_home() || is_search() || is_feed()
 791              ) {
 792                  $set_404 = false;
 793              }
 794          }
 795  
 796          if ( $set_404 ) {
 797              // Guess it's time to 404.
 798              $wp_query->set_404();
 799              status_header( 404 );
 800              nocache_headers();
 801          } else {
 802              status_header( 200 );
 803          }
 804      }
 805  
 806      /**
 807       * Sets up all of the variables required by the WordPress environment.
 808       *
 809       * The action {@see 'wp'} has one parameter that references the WP object. It
 810       * allows for accessing the properties and methods to further manipulate the
 811       * object.
 812       *
 813       * @since 2.0.0
 814       *
 815       * @param string|array $query_args Passed to parse_request().
 816       */
 817  	public function main( $query_args = '' ) {
 818          $this->init();
 819  
 820          $parsed = $this->parse_request( $query_args );
 821  
 822          if ( $parsed ) {
 823              $this->query_posts();
 824              $this->handle_404();
 825              $this->register_globals();
 826          }
 827  
 828          $this->send_headers();
 829  
 830          /**
 831           * Fires once the WordPress environment has been set up.
 832           *
 833           * @since 2.1.0
 834           *
 835           * @param WP $wp Current WordPress environment instance (passed by reference).
 836           */
 837          do_action_ref_array( 'wp', array( &$this ) );
 838      }
 839  }


Generated : Fri Oct 9 08:20:33 2026 Cross-referenced by PHPXref