[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

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

   1  <?php
   2  /**
   3   * Site API: WP_Site_Query class
   4   *
   5   * @package WordPress
   6   * @subpackage Sites
   7   * @since 4.6.0
   8   */
   9  
  10  /**
  11   * Core class used for querying sites.
  12   *
  13   * @since 4.6.0
  14   *
  15   * @see WP_Site_Query::__construct() for accepted arguments.
  16   */
  17  #[AllowDynamicProperties]
  18  class WP_Site_Query {
  19  
  20      /**
  21       * SQL for database query.
  22       *
  23       * @since 4.6.0
  24       * @var string
  25       */
  26      public $request;
  27  
  28      /**
  29       * SQL query clauses.
  30       *
  31       * @since 4.6.0
  32       * @var array
  33       */
  34      protected $sql_clauses = array(
  35          'select'  => '',
  36          'from'    => '',
  37          'where'   => array(),
  38          'groupby' => '',
  39          'orderby' => '',
  40          'limits'  => '',
  41      );
  42  
  43      /**
  44       * Metadata query container.
  45       *
  46       * @since 5.1.0
  47       * @var WP_Meta_Query
  48       */
  49      public $meta_query = false;
  50  
  51      /**
  52       * Metadata query clauses.
  53       *
  54       * @since 5.1.0
  55       * @var array
  56       */
  57      protected $meta_query_clauses;
  58  
  59      /**
  60       * Date query container.
  61       *
  62       * @since 4.6.0
  63       * @var WP_Date_Query A date query instance.
  64       */
  65      public $date_query = false;
  66  
  67      /**
  68       * Query vars set by the user.
  69       *
  70       * @since 4.6.0
  71       * @var array
  72       */
  73      public $query_vars;
  74  
  75      /**
  76       * Default values for query vars.
  77       *
  78       * @since 4.6.0
  79       * @var array
  80       */
  81      public $query_var_defaults;
  82  
  83      /**
  84       * List of sites located by the query.
  85       *
  86       * @since 4.6.0
  87       * @var array
  88       */
  89      public $sites;
  90  
  91      /**
  92       * The amount of found sites for the current query.
  93       *
  94       * @since 4.6.0
  95       * @var int
  96       */
  97      public $found_sites = 0;
  98  
  99      /**
 100       * The number of pages.
 101       *
 102       * @since 4.6.0
 103       * @var int
 104       */
 105      public $max_num_pages = 0;
 106  
 107      /**
 108       * Sets up the site query, based on the query vars passed.
 109       *
 110       * @since 4.6.0
 111       * @since 4.8.0 Introduced the 'lang_id', 'lang__in', and 'lang__not_in' parameters.
 112       * @since 5.1.0 Introduced the 'update_site_meta_cache', 'meta_query', 'meta_key',
 113       *              'meta_compare_key', 'meta_value', 'meta_type', and 'meta_compare' parameters.
 114       * @since 5.3.0 Introduced the 'meta_type_key' parameter.
 115       *
 116       * @param string|array $query {
 117       *     Optional. Array or query string of site query parameters. Default empty.
 118       *
 119       *     @type int[]           $site__in               Array of site IDs to include. Default empty.
 120       *     @type int[]           $site__not_in           Array of site IDs to exclude. Default empty.
 121       *     @type bool            $count                  Whether to return a site count (true) or array of site objects.
 122       *                                                   Default false.
 123       *     @type array           $date_query             Date query clauses to limit sites by. See WP_Date_Query.
 124       *                                                   Default null.
 125       *     @type string          $fields                 Site fields to return. Accepts 'ids' (returns an array of site IDs)
 126       *                                                   or empty (returns an array of complete site objects). Default empty.
 127       *     @type int             $ID                     A site ID to only return that site. Default empty.
 128       *     @type int             $number                 Maximum number of sites to retrieve. Default 100.
 129       *     @type int             $offset                 Number of sites to offset the query. Used to build LIMIT clause.
 130       *                                                   Default 0.
 131       *     @type bool            $no_found_rows          Whether to disable the `SQL_CALC_FOUND_ROWS` query. Default true.
 132       *     @type string|array    $orderby                Site status or array of statuses. Accepts:
 133       *                                                   - 'id'
 134       *                                                   - 'domain'
 135       *                                                   - 'path'
 136       *                                                   - 'network_id'
 137       *                                                   - 'last_updated'
 138       *                                                   - 'registered'
 139       *                                                   - 'domain_length'
 140       *                                                   - 'path_length'
 141       *                                                   - 'site__in'
 142       *                                                   - 'network__in'
 143       *                                                   - 'deleted'
 144       *                                                   - 'mature'
 145       *                                                   - 'spam'
 146       *                                                   - 'archived'
 147       *                                                   - 'public'
 148       *                                                   - false, an empty array, or 'none' to disable `ORDER BY` clause.
 149       *                                                   Default 'id'.
 150       *     @type string          $order                  How to order retrieved sites. Accepts 'ASC', 'DESC'. Default 'ASC'.
 151       *     @type int             $network_id             Limit results to those affiliated with a given network ID. If 0,
 152       *                                                   include all networks. Default 0.
 153       *     @type int[]           $network__in            Array of network IDs to include affiliated sites for. Default empty.
 154       *     @type int[]           $network__not_in        Array of network IDs to exclude affiliated sites for. Default empty.
 155       *     @type string          $domain                 Limit results to those affiliated with a given domain. Default empty.
 156       *     @type string[]        $domain__in             Array of domains to include affiliated sites for. Default empty.
 157       *     @type string[]        $domain__not_in         Array of domains to exclude affiliated sites for. Default empty.
 158       *     @type string          $path                   Limit results to those affiliated with a given path. Default empty.
 159       *     @type string[]        $path__in               Array of paths to include affiliated sites for. Default empty.
 160       *     @type string[]        $path__not_in           Array of paths to exclude affiliated sites for. Default empty.
 161       *     @type int             $public                 Limit results to public sites. Accepts 1 or 0. Default empty.
 162       *     @type int             $archived               Limit results to archived sites. Accepts 1 or 0. Default empty.
 163       *     @type int             $mature                 Limit results to mature sites. Accepts 1 or 0. Default empty.
 164       *     @type int             $spam                   Limit results to spam sites. Accepts 1 or 0. Default empty.
 165       *     @type int             $deleted                Limit results to deleted sites. Accepts 1 or 0. Default empty.
 166       *     @type int             $lang_id                Limit results to a language ID. Default empty.
 167       *     @type string[]        $lang__in               Array of language IDs to include affiliated sites for. Default empty.
 168       *     @type string[]        $lang__not_in           Array of language IDs to exclude affiliated sites for. Default empty.
 169       *     @type string          $search                 Search term(s) to retrieve matching sites for. Default empty.
 170       *     @type string[]        $search_columns         Array of column names to be searched. Accepts 'domain' and 'path'.
 171       *                                                   Default empty array.
 172       *     @type bool            $update_site_cache      Whether to prime the cache for found sites. Default true.
 173       *     @type bool            $update_site_meta_cache Whether to prime the metadata cache for found sites. Default true.
 174       *     @type string|string[] $meta_key               Meta key or keys to filter by.
 175       *     @type string|string[] $meta_value             Meta value or values to filter by.
 176       *     @type string          $meta_compare           MySQL operator used for comparing the meta value.
 177       *                                                   See WP_Meta_Query::__construct() for accepted values and default value.
 178       *     @type string          $meta_compare_key       MySQL operator used for comparing the meta key.
 179       *                                                   See WP_Meta_Query::__construct() for accepted values and default value.
 180       *     @type string          $meta_type              MySQL data type that the meta_value column will be CAST to for comparisons.
 181       *                                                   See WP_Meta_Query::__construct() for accepted values and default value.
 182       *     @type string          $meta_type_key          MySQL data type that the meta_key column will be CAST to for comparisons.
 183       *                                                   See WP_Meta_Query::__construct() for accepted values and default value.
 184       *     @type array           $meta_query             An associative array of WP_Meta_Query arguments.
 185       *                                                   See WP_Meta_Query::__construct() for accepted values.
 186       * }
 187       */
 188  	public function __construct( $query = '' ) {
 189          $this->query_var_defaults = array(
 190              'fields'                 => '',
 191              'ID'                     => '',
 192              'site__in'               => '',
 193              'site__not_in'           => '',
 194              'number'                 => 100,
 195              'offset'                 => '',
 196              'no_found_rows'          => true,
 197              'orderby'                => 'id',
 198              'order'                  => 'ASC',
 199              'network_id'             => 0,
 200              'network__in'            => '',
 201              'network__not_in'        => '',
 202              'domain'                 => '',
 203              'domain__in'             => '',
 204              'domain__not_in'         => '',
 205              'path'                   => '',
 206              'path__in'               => '',
 207              'path__not_in'           => '',
 208              'public'                 => null,
 209              'archived'               => null,
 210              'mature'                 => null,
 211              'spam'                   => null,
 212              'deleted'                => null,
 213              'lang_id'                => null,
 214              'lang__in'               => '',
 215              'lang__not_in'           => '',
 216              'search'                 => '',
 217              'search_columns'         => array(),
 218              'count'                  => false,
 219              'date_query'             => null, // See WP_Date_Query.
 220              'update_site_cache'      => true,
 221              'update_site_meta_cache' => true,
 222              'meta_query'             => '',
 223              'meta_key'               => '',
 224              'meta_value'             => '',
 225              'meta_type'              => '',
 226              'meta_compare'           => '',
 227          );
 228  
 229          if ( ! empty( $query ) ) {
 230              $this->query( $query );
 231          }
 232      }
 233  
 234      /**
 235       * Parses arguments passed to the site query with default query parameters.
 236       *
 237       * @since 4.6.0
 238       *
 239       * @see WP_Site_Query::__construct()
 240       *
 241       * @param string|array $query Array or string of WP_Site_Query arguments. See WP_Site_Query::__construct().
 242       */
 243  	public function parse_query( $query = '' ) {
 244          if ( empty( $query ) ) {
 245              $query = $this->query_vars;
 246          }
 247  
 248          $this->query_vars = wp_parse_args( $query, $this->query_var_defaults );
 249  
 250          /**
 251           * Fires after the site query vars have been parsed.
 252           *
 253           * @since 4.6.0
 254           *
 255           * @param WP_Site_Query $query The WP_Site_Query instance (passed by reference).
 256           */
 257          do_action_ref_array( 'parse_site_query', array( &$this ) );
 258      }
 259  
 260      /**
 261       * Sets up the WordPress query for retrieving sites.
 262       *
 263       * @since 4.6.0
 264       *
 265       * @param string|array $query Array or URL query string of parameters.
 266       * @return WP_Site[]|int[]|int List of WP_Site objects, a list of site IDs when 'fields' is set to 'ids',
 267       *                             or the number of sites when 'count' is passed as a query var.
 268       *
 269       * @phpstan-return (
 270       *     $query is array{ count: true, ... } ? int : (
 271       *         $query is array{ fields: 'ids', ... } ? int[] : array<int, WP_Site>
 272       *     )
 273       * )
 274       */
 275  	public function query( $query ) {
 276          $this->query_vars = wp_parse_args( $query );
 277  
 278          return $this->get_sites();
 279      }
 280  
 281      /**
 282       * Retrieves a list of sites matching the query vars.
 283       *
 284       * @since 4.6.0
 285       *
 286       * @global wpdb $wpdb WordPress database abstraction object.
 287       *
 288       * @return WP_Site[]|int[]|int List of WP_Site objects, a list of site IDs when 'fields' is set to 'ids',
 289       *                             or the number of sites when 'count' is passed as a query var.
 290       */
 291  	public function get_sites() {
 292          global $wpdb;
 293  
 294          $this->parse_query();
 295  
 296          // Parse meta query.
 297          $this->meta_query = new WP_Meta_Query();
 298          $this->meta_query->parse_query_vars( $this->query_vars );
 299  
 300          /**
 301           * Fires before sites are retrieved.
 302           *
 303           * @since 4.6.0
 304           *
 305           * @param WP_Site_Query $query Current instance of WP_Site_Query (passed by reference).
 306           */
 307          do_action_ref_array( 'pre_get_sites', array( &$this ) );
 308  
 309          // Reparse query vars, in case they were modified in a 'pre_get_sites' callback.
 310          $this->meta_query->parse_query_vars( $this->query_vars );
 311          if ( ! empty( $this->meta_query->queries ) ) {
 312              $this->meta_query_clauses = $this->meta_query->get_sql( 'blog', $wpdb->blogs, 'blog_id', $this );
 313          }
 314  
 315          $site_data = null;
 316  
 317          /**
 318           * Filters the site data before the get_sites query takes place.
 319           *
 320           * Return a non-null value to bypass WordPress' default site queries.
 321           *
 322           * The expected return type from this filter depends on the value passed
 323           * in the request query vars:
 324           * - When `$this->query_vars['count']` is set, the filter should return
 325           *   the site count as an integer.
 326           * - When `'ids' === $this->query_vars['fields']`, the filter should return
 327           *   an array of site IDs.
 328           * - Otherwise the filter should return an array of WP_Site objects.
 329           *
 330           * Note that if the filter returns an array of site data, it will be assigned
 331           * to the `sites` property of the current WP_Site_Query instance.
 332           *
 333           * Filtering functions that require pagination information are encouraged to set
 334           * the `found_sites` and `max_num_pages` properties of the WP_Site_Query object,
 335           * passed to the filter by reference. If WP_Site_Query does not perform a database
 336           * query, it will not have enough information to generate these values itself.
 337           *
 338           * @since 5.2.0
 339           * @since 5.6.0 The returned array of site data is assigned to the `sites` property
 340           *              of the current WP_Site_Query instance.
 341           *
 342           * @param WP_Site[]|int[]|int|null $site_data Return an array of site data to short-circuit WP's site query,
 343           *                                            the site count as an integer if `$this->query_vars['count']` is set,
 344           *                                            or null to run the normal queries.
 345           * @param WP_Site_Query            $query     The WP_Site_Query instance, passed by reference.
 346           */
 347          $site_data = apply_filters_ref_array( 'sites_pre_query', array( $site_data, &$this ) );
 348  
 349          if ( null !== $site_data ) {
 350              if ( is_array( $site_data ) && ! $this->query_vars['count'] ) {
 351                  $this->sites = $site_data;
 352              }
 353  
 354              return $site_data;
 355          }
 356  
 357          // $args can include anything. Only use the args defined in the query_var_defaults to compute the key.
 358          $_args = wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) );
 359  
 360          // Ignore the $fields, $update_site_cache, $update_site_meta_cache argument as the queried result will be the same regardless.
 361          unset( $_args['fields'], $_args['update_site_cache'], $_args['update_site_meta_cache'] );
 362  
 363          $key          = md5( serialize( $_args ) );
 364          $last_changed = wp_cache_get_last_changed( 'sites' );
 365  
 366          $cache_key   = "get_sites:$key";
 367          $cache_value = wp_cache_get_salted( $cache_key, 'site-queries', $last_changed );
 368  
 369          if ( false === $cache_value ) {
 370              $site_ids = $this->get_site_ids();
 371              if ( $site_ids ) {
 372                  $this->set_found_sites();
 373              }
 374  
 375              $cache_value = array(
 376                  'site_ids'    => $site_ids,
 377                  'found_sites' => $this->found_sites,
 378              );
 379              wp_cache_set_salted( $cache_key, $cache_value, 'site-queries', $last_changed );
 380          } else {
 381              $site_ids          = $cache_value['site_ids'];
 382              $this->found_sites = $cache_value['found_sites'];
 383          }
 384  
 385          if ( $this->found_sites && $this->query_vars['number'] ) {
 386              $this->max_num_pages = (int) ceil( $this->found_sites / $this->query_vars['number'] );
 387          }
 388  
 389          // If querying for a count only, there's nothing more to do.
 390          if ( $this->query_vars['count'] ) {
 391              // $site_ids is actually a count in this case.
 392              return (int) $site_ids;
 393          }
 394  
 395          $site_ids = array_map( 'intval', $site_ids );
 396  
 397          if ( $this->query_vars['update_site_meta_cache'] ) {
 398              wp_lazyload_site_meta( $site_ids );
 399          }
 400  
 401          if ( 'ids' === $this->query_vars['fields'] ) {
 402              $this->sites = $site_ids;
 403  
 404              return $this->sites;
 405          }
 406  
 407          // Prime site network caches.
 408          if ( $this->query_vars['update_site_cache'] ) {
 409              _prime_site_caches( $site_ids, false );
 410          }
 411  
 412          // Fetch full site objects from the primed cache.
 413          $_sites = array();
 414          foreach ( $site_ids as $site_id ) {
 415              $_site = get_site( $site_id );
 416              if ( $_site ) {
 417                  $_sites[] = $_site;
 418              }
 419          }
 420  
 421          /**
 422           * Filters the site query results.
 423           *
 424           * @since 4.6.0
 425           *
 426           * @param WP_Site[]     $_sites An array of WP_Site objects.
 427           * @param WP_Site_Query $query  Current instance of WP_Site_Query (passed by reference).
 428           */
 429          $_sites = apply_filters_ref_array( 'the_sites', array( $_sites, &$this ) );
 430  
 431          // Convert to WP_Site instances.
 432          $this->sites = array_map( 'get_site', $_sites );
 433  
 434          return $this->sites;
 435      }
 436  
 437      /**
 438       * Used internally to get a list of site IDs matching the query vars.
 439       *
 440       * @since 4.6.0
 441       *
 442       * @global wpdb $wpdb WordPress database abstraction object.
 443       *
 444       * @return int|array A single count of site IDs if a count query. An array of site IDs if a full query.
 445       */
 446  	protected function get_site_ids() {
 447          global $wpdb;
 448  
 449          $order = $this->parse_order( $this->query_vars['order'] );
 450  
 451          // Disable ORDER BY with 'none', an empty array, or boolean false.
 452          if ( in_array( $this->query_vars['orderby'], array( 'none', array(), false ), true ) ) {
 453              $orderby = '';
 454          } elseif ( ! empty( $this->query_vars['orderby'] ) ) {
 455              $ordersby = is_array( $this->query_vars['orderby'] ) ?
 456                  $this->query_vars['orderby'] :
 457                  preg_split( '/[,\s]/', $this->query_vars['orderby'] );
 458  
 459              $orderby_array = array();
 460              foreach ( $ordersby as $_key => $_value ) {
 461                  if ( ! $_value ) {
 462                      continue;
 463                  }
 464  
 465                  if ( is_int( $_key ) ) {
 466                      $_orderby = $_value;
 467                      $_order   = $order;
 468                  } else {
 469                      $_orderby = $_key;
 470                      $_order   = $_value;
 471                  }
 472  
 473                  $parsed = $this->parse_orderby( $_orderby );
 474  
 475                  if ( ! $parsed ) {
 476                      continue;
 477                  }
 478  
 479                  if ( 'site__in' === $_orderby || 'network__in' === $_orderby ) {
 480                      $orderby_array[] = $parsed;
 481                      continue;
 482                  }
 483  
 484                  $orderby_array[] = $parsed . ' ' . $this->parse_order( $_order );
 485              }
 486  
 487              $orderby = implode( ', ', $orderby_array );
 488          } else {
 489              $orderby = "{$wpdb->blogs}.blog_id $order";
 490          }
 491  
 492          $number = absint( $this->query_vars['number'] );
 493          $offset = absint( $this->query_vars['offset'] );
 494          $limits = '';
 495  
 496          if ( ! empty( $number ) ) {
 497              if ( $offset ) {
 498                  $limits = 'LIMIT ' . $offset . ',' . $number;
 499              } else {
 500                  $limits = 'LIMIT ' . $number;
 501              }
 502          }
 503  
 504          if ( $this->query_vars['count'] ) {
 505              $fields = 'COUNT(*)';
 506          } else {
 507              $fields = "{$wpdb->blogs}.blog_id";
 508          }
 509  
 510          // Parse site IDs for an IN clause.
 511          $site_id = absint( $this->query_vars['ID'] );
 512          if ( ! empty( $site_id ) ) {
 513              $this->sql_clauses['where']['ID'] = $wpdb->prepare( "{$wpdb->blogs}.blog_id = %d", $site_id );
 514          }
 515  
 516          // Parse site IDs for an IN clause.
 517          if ( ! empty( $this->query_vars['site__in'] ) ) {
 518              $this->sql_clauses['where']['site__in'] = "{$wpdb->blogs}.blog_id IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['site__in'] ) ) . ' )';
 519          }
 520  
 521          // Parse site IDs for a NOT IN clause.
 522          if ( ! empty( $this->query_vars['site__not_in'] ) ) {
 523              $this->sql_clauses['where']['site__not_in'] = "{$wpdb->blogs}.blog_id NOT IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['site__not_in'] ) ) . ' )';
 524          }
 525  
 526          $network_id = absint( $this->query_vars['network_id'] );
 527  
 528          if ( ! empty( $network_id ) ) {
 529              $this->sql_clauses['where']['network_id'] = $wpdb->prepare( 'site_id = %d', $network_id );
 530          }
 531  
 532          // Parse site network IDs for an IN clause.
 533          if ( ! empty( $this->query_vars['network__in'] ) ) {
 534              $this->sql_clauses['where']['network__in'] = 'site_id IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['network__in'] ) ) . ' )';
 535          }
 536  
 537          // Parse site network IDs for a NOT IN clause.
 538          if ( ! empty( $this->query_vars['network__not_in'] ) ) {
 539              $this->sql_clauses['where']['network__not_in'] = 'site_id NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['network__not_in'] ) ) . ' )';
 540          }
 541  
 542          if ( ! empty( $this->query_vars['domain'] ) ) {
 543              $this->sql_clauses['where']['domain'] = $wpdb->prepare( 'domain = %s', $this->query_vars['domain'] );
 544          }
 545  
 546          // Parse site domain for an IN clause.
 547          if ( is_array( $this->query_vars['domain__in'] ) ) {
 548              $this->sql_clauses['where']['domain__in'] = "domain IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['domain__in'] ) ) . "' )";
 549          }
 550  
 551          // Parse site domain for a NOT IN clause.
 552          if ( is_array( $this->query_vars['domain__not_in'] ) ) {
 553              $this->sql_clauses['where']['domain__not_in'] = "domain NOT IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['domain__not_in'] ) ) . "' )";
 554          }
 555  
 556          if ( ! empty( $this->query_vars['path'] ) ) {
 557              $this->sql_clauses['where']['path'] = $wpdb->prepare( 'path = %s', $this->query_vars['path'] );
 558          }
 559  
 560          // Parse site path for an IN clause.
 561          if ( is_array( $this->query_vars['path__in'] ) ) {
 562              $this->sql_clauses['where']['path__in'] = "path IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['path__in'] ) ) . "' )";
 563          }
 564  
 565          // Parse site path for a NOT IN clause.
 566          if ( is_array( $this->query_vars['path__not_in'] ) ) {
 567              $this->sql_clauses['where']['path__not_in'] = "path NOT IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['path__not_in'] ) ) . "' )";
 568          }
 569  
 570          if ( is_numeric( $this->query_vars['archived'] ) ) {
 571              $archived                               = absint( $this->query_vars['archived'] );
 572              $this->sql_clauses['where']['archived'] = $wpdb->prepare( 'archived = %s ', absint( $archived ) );
 573          }
 574  
 575          if ( is_numeric( $this->query_vars['mature'] ) ) {
 576              $mature                               = absint( $this->query_vars['mature'] );
 577              $this->sql_clauses['where']['mature'] = $wpdb->prepare( 'mature = %d ', $mature );
 578          }
 579  
 580          if ( is_numeric( $this->query_vars['spam'] ) ) {
 581              $spam                               = absint( $this->query_vars['spam'] );
 582              $this->sql_clauses['where']['spam'] = $wpdb->prepare( 'spam = %d ', $spam );
 583          }
 584  
 585          if ( is_numeric( $this->query_vars['deleted'] ) ) {
 586              $deleted                               = absint( $this->query_vars['deleted'] );
 587              $this->sql_clauses['where']['deleted'] = $wpdb->prepare( 'deleted = %d ', $deleted );
 588          }
 589  
 590          if ( is_numeric( $this->query_vars['public'] ) ) {
 591              $public                               = absint( $this->query_vars['public'] );
 592              $this->sql_clauses['where']['public'] = $wpdb->prepare( 'public = %d ', $public );
 593          }
 594  
 595          if ( is_numeric( $this->query_vars['lang_id'] ) ) {
 596              $lang_id                               = absint( $this->query_vars['lang_id'] );
 597              $this->sql_clauses['where']['lang_id'] = $wpdb->prepare( 'lang_id = %d ', $lang_id );
 598          }
 599  
 600          // Parse site language IDs for an IN clause.
 601          if ( ! empty( $this->query_vars['lang__in'] ) ) {
 602              $this->sql_clauses['where']['lang__in'] = 'lang_id IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['lang__in'] ) ) . ' )';
 603          }
 604  
 605          // Parse site language IDs for a NOT IN clause.
 606          if ( ! empty( $this->query_vars['lang__not_in'] ) ) {
 607              $this->sql_clauses['where']['lang__not_in'] = 'lang_id NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['lang__not_in'] ) ) . ' )';
 608          }
 609  
 610          // Falsey search strings are ignored.
 611          if ( strlen( $this->query_vars['search'] ) ) {
 612              $search_columns = array();
 613  
 614              if ( $this->query_vars['search_columns'] ) {
 615                  $search_columns = array_intersect( $this->query_vars['search_columns'], array( 'domain', 'path' ) );
 616              }
 617  
 618              if ( ! $search_columns ) {
 619                  $search_columns = array( 'domain', 'path' );
 620              }
 621  
 622              /**
 623               * Filters the columns to search in a WP_Site_Query search.
 624               *
 625               * The default columns include 'domain' and 'path.
 626               *
 627               * @since 4.6.0
 628               *
 629               * @param string[]      $search_columns Array of column names to be searched.
 630               * @param string        $search         Text being searched.
 631               * @param WP_Site_Query $query          The current WP_Site_Query instance.
 632               */
 633              $search_columns = apply_filters( 'site_search_columns', $search_columns, $this->query_vars['search'], $this );
 634  
 635              $this->sql_clauses['where']['search'] = $this->get_search_sql( $this->query_vars['search'], $search_columns );
 636          }
 637  
 638          $date_query = $this->query_vars['date_query'];
 639          if ( ! empty( $date_query ) && is_array( $date_query ) ) {
 640              $this->date_query = new WP_Date_Query( $date_query, 'registered' );
 641  
 642              // Strip leading 'AND'.
 643              $this->sql_clauses['where']['date_query'] = preg_replace( '/^\s*AND\s*/', '', $this->date_query->get_sql() );
 644          }
 645  
 646          $join    = '';
 647          $groupby = '';
 648  
 649          if ( ! empty( $this->meta_query_clauses ) ) {
 650              $join .= $this->meta_query_clauses['join'];
 651  
 652              // Strip leading 'AND'.
 653              $this->sql_clauses['where']['meta_query'] = preg_replace( '/^\s*AND\s*/', '', $this->meta_query_clauses['where'] );
 654  
 655              if ( ! $this->query_vars['count'] ) {
 656                  $groupby = "{$wpdb->blogs}.blog_id";
 657              }
 658          }
 659  
 660          $where = implode( ' AND ', $this->sql_clauses['where'] );
 661  
 662          $pieces = array( 'fields', 'join', 'where', 'orderby', 'limits', 'groupby' );
 663  
 664          /**
 665           * Filters the site query clauses.
 666           *
 667           * @since 4.6.0
 668           *
 669           * @param string[]      $clauses {
 670           *     Associative array of the clauses for the query.
 671           *
 672           *     @type string $fields   The SELECT clause of the query.
 673           *     @type string $join     The JOIN clause of the query.
 674           *     @type string $where    The WHERE clause of the query.
 675           *     @type string $orderby  The ORDER BY clause of the query.
 676           *     @type string $limits   The LIMIT clause of the query.
 677           *     @type string $groupby  The GROUP BY clause of the query.
 678           * }
 679           * @param WP_Site_Query $query   Current instance of WP_Site_Query (passed by reference).
 680           */
 681          $clauses = apply_filters_ref_array( 'sites_clauses', array( compact( $pieces ), &$this ) );
 682  
 683          $fields  = $clauses['fields'] ?? '';
 684          $join    = $clauses['join'] ?? '';
 685          $where   = $clauses['where'] ?? '';
 686          $orderby = $clauses['orderby'] ?? '';
 687          $limits  = $clauses['limits'] ?? '';
 688          $groupby = $clauses['groupby'] ?? '';
 689  
 690          if ( $where ) {
 691              $where = 'WHERE ' . $where;
 692          }
 693  
 694          if ( $groupby ) {
 695              $groupby = 'GROUP BY ' . $groupby;
 696          }
 697  
 698          if ( $orderby ) {
 699              $orderby = "ORDER BY $orderby";
 700          }
 701  
 702          $found_rows = '';
 703          if ( ! $this->query_vars['no_found_rows'] ) {
 704              $found_rows = 'SQL_CALC_FOUND_ROWS';
 705          }
 706  
 707          $this->sql_clauses['select']  = "SELECT $found_rows $fields";
 708          $this->sql_clauses['from']    = "FROM $wpdb->blogs $join";
 709          $this->sql_clauses['groupby'] = $groupby;
 710          $this->sql_clauses['orderby'] = $orderby;
 711          $this->sql_clauses['limits']  = $limits;
 712  
 713          // Beginning of the string is on a new line to prevent leading whitespace. See https://core.trac.wordpress.org/ticket/56841.
 714          $this->request =
 715              "{$this->sql_clauses['select']}
 716               {$this->sql_clauses['from']}
 717               {$where}
 718               {$this->sql_clauses['groupby']}
 719               {$this->sql_clauses['orderby']}
 720               {$this->sql_clauses['limits']}";
 721  
 722          if ( $this->query_vars['count'] ) {
 723              return (int) $wpdb->get_var( $this->request );
 724          }
 725  
 726          $site_ids = $wpdb->get_col( $this->request );
 727  
 728          return array_map( 'intval', $site_ids );
 729      }
 730  
 731      /**
 732       * Populates found_sites and max_num_pages properties for the current query
 733       * if the limit clause was used.
 734       *
 735       * @since 4.6.0
 736       *
 737       * @global wpdb $wpdb WordPress database abstraction object.
 738       */
 739  	private function set_found_sites() {
 740          global $wpdb;
 741  
 742          if ( $this->query_vars['number'] && ! $this->query_vars['no_found_rows'] ) {
 743              /**
 744               * Filters the query used to retrieve found site count.
 745               *
 746               * @since 4.6.0
 747               *
 748               * @param string        $found_sites_query SQL query. Default 'SELECT FOUND_ROWS()'.
 749               * @param WP_Site_Query $site_query        The `WP_Site_Query` instance.
 750               */
 751              $found_sites_query = apply_filters( 'found_sites_query', 'SELECT FOUND_ROWS()', $this );
 752  
 753              $this->found_sites = (int) $wpdb->get_var( $found_sites_query );
 754          }
 755      }
 756  
 757      /**
 758       * Used internally to generate an SQL string for searching across multiple columns.
 759       *
 760       * @since 4.6.0
 761       *
 762       * @global wpdb $wpdb WordPress database abstraction object.
 763       *
 764       * @param string   $search  Search string.
 765       * @param string[] $columns Array of columns to search.
 766       * @return string Search SQL.
 767       */
 768  	protected function get_search_sql( $search, $columns ) {
 769          global $wpdb;
 770  
 771          if ( str_contains( $search, '*' ) ) {
 772              $like = '%' . implode( '%', array_map( array( $wpdb, 'esc_like' ), explode( '*', $search ) ) ) . '%';
 773          } else {
 774              $like = '%' . $wpdb->esc_like( $search ) . '%';
 775          }
 776  
 777          $searches = array();
 778          foreach ( $columns as $column ) {
 779              $searches[] = $wpdb->prepare( "$column LIKE %s", $like );
 780          }
 781  
 782          return '(' . implode( ' OR ', $searches ) . ')';
 783      }
 784  
 785      /**
 786       * Parses and sanitizes 'orderby' keys passed to the site query.
 787       *
 788       * @since 4.6.0
 789       *
 790       * @global wpdb $wpdb WordPress database abstraction object.
 791       *
 792       * @param string $orderby Alias for the field to order by.
 793       * @return string|false Value to used in the ORDER clause. False otherwise.
 794       */
 795  	protected function parse_orderby( $orderby ) {
 796          global $wpdb;
 797  
 798          $parsed = false;
 799  
 800          switch ( $orderby ) {
 801              case 'site__in':
 802                  $site__in = implode( ',', array_map( 'absint', $this->query_vars['site__in'] ) );
 803                  $parsed   = "FIELD( {$wpdb->blogs}.blog_id, $site__in )";
 804                  break;
 805              case 'network__in':
 806                  $network__in = implode( ',', array_map( 'absint', $this->query_vars['network__in'] ) );
 807                  $parsed      = "FIELD( {$wpdb->blogs}.site_id, $network__in )";
 808                  break;
 809              case 'domain':
 810              case 'last_updated':
 811              case 'path':
 812              case 'registered':
 813              case 'deleted':
 814              case 'spam':
 815              case 'mature':
 816              case 'archived':
 817              case 'public':
 818                  $parsed = $orderby;
 819                  break;
 820              case 'network_id':
 821                  $parsed = 'site_id';
 822                  break;
 823              case 'domain_length':
 824                  $parsed = 'CHAR_LENGTH(domain)';
 825                  break;
 826              case 'path_length':
 827                  $parsed = 'CHAR_LENGTH(path)';
 828                  break;
 829              case 'id':
 830                  $parsed = "{$wpdb->blogs}.blog_id";
 831                  break;
 832          }
 833  
 834          if ( ! empty( $parsed ) || empty( $this->meta_query_clauses ) ) {
 835              return $parsed;
 836          }
 837  
 838          $meta_clauses = $this->meta_query->get_clauses();
 839          if ( empty( $meta_clauses ) ) {
 840              return $parsed;
 841          }
 842  
 843          $primary_meta_query = reset( $meta_clauses );
 844          if ( ! empty( $primary_meta_query['key'] ) && $primary_meta_query['key'] === $orderby ) {
 845              $orderby = 'meta_value';
 846          }
 847  
 848          switch ( $orderby ) {
 849              case 'meta_value':
 850                  if ( ! empty( $primary_meta_query['type'] ) ) {
 851                      $parsed = "CAST({$primary_meta_query['alias']}.meta_value AS {$primary_meta_query['cast']})";
 852                  } else {
 853                      $parsed = "{$primary_meta_query['alias']}.meta_value";
 854                  }
 855                  break;
 856              case 'meta_value_num':
 857                  $parsed = "{$primary_meta_query['alias']}.meta_value+0";
 858                  break;
 859              default:
 860                  if ( isset( $meta_clauses[ $orderby ] ) ) {
 861                      $meta_clause = $meta_clauses[ $orderby ];
 862                      $parsed      = "CAST({$meta_clause['alias']}.meta_value AS {$meta_clause['cast']})";
 863                  }
 864          }
 865  
 866          return $parsed;
 867      }
 868  
 869      /**
 870       * Parses an 'order' query variable and cast it to 'ASC' or 'DESC' as necessary.
 871       *
 872       * @since 4.6.0
 873       *
 874       * @param string $order The 'order' query variable.
 875       * @return string The sanitized 'order' query variable.
 876       */
 877  	protected function parse_order( $order ) {
 878          if ( ! is_string( $order ) || empty( $order ) ) {
 879              return 'ASC';
 880          }
 881  
 882          if ( 'ASC' === strtoupper( $order ) ) {
 883              return 'ASC';
 884          } else {
 885              return 'DESC';
 886          }
 887      }
 888  }


Generated : Thu Oct 15 08:20:32 2026 Cross-referenced by PHPXref