[ Index ]

PHP Cross Reference of WordPress

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


Generated: Mon Nov 18 01:00:04 2019 Cross-referenced by PHPXref 0.7.1