Make WordPress Core

Ticket #35791: 35791.3.patch

File 35791.3.patch, 35.1 KB (added by flixos90, 9 years ago)

minor adjustments

  • src/wp-includes/class-wp-site-query.php

     
     1<?php
     2
     3/**
     4 * Site API: WP_Site_Query class
     5 *
     6 * @package WordPress
     7 * @subpackage Sites
     8 * @since 4.6.0
     9 */
     10
     11/**
     12 * Core class used for querying sites.
     13 *
     14 * @since 4.6.0
     15 *
     16 * @see WP_Site_Query::__construct() for accepted arguments.
     17 */
     18class WP_Site_Query {
     19
     20        /**
     21         * SQL for database query.
     22         *
     23         * @since 4.6.0
     24         * @access public
     25         * @var string
     26         */
     27        public $request;
     28
     29        /**
     30         * SQL query clauses.
     31         *
     32         * @since 4.6.0
     33         * @access protected
     34         * @var array
     35         */
     36        protected $sql_clauses = array(
     37                'select'  => '',
     38                'from'    => '',
     39                'where'   => array(),
     40                'groupby' => '',
     41                'orderby' => '',
     42                'limits'  => '',
     43        );
     44
     45        /**
     46         * SQL WHERE clause.
     47         *
     48         * Stored after the 'sites_clauses' filter is run on the compiled WHERE sub-clauses.
     49         *
     50         * @since 4.6.0
     51         * @access protected
     52         * @var string
     53         */
     54        protected $filtered_where_clause;
     55
     56        /**
     57         * Date query container
     58         *
     59         * @since 4.6.0
     60         * @access public
     61         * @var object WP_Date_Query
     62         */
     63        public $date_query = false;
     64
     65        /**
     66         * Query vars set by the user.
     67         *
     68         * @since 4.6.0
     69         * @access public
     70         * @var array
     71         */
     72        public $query_vars;
     73
     74        /**
     75         * Default values for query vars.
     76         *
     77         * @since 4.6.0
     78         * @access public
     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         * @access public
     88         * @var array
     89         */
     90        public $sites;
     91
     92        /**
     93         * The amount of found sites for the current query.
     94         *
     95         * @since 4.6.0
     96         * @access public
     97         * @var int
     98         */
     99        public $found_sites = 0;
     100
     101        /**
     102         * The number of pages.
     103         *
     104         * @since 4.6.0
     105         * @access public
     106         * @var int
     107         */
     108        public $max_num_pages = 0;
     109
     110        /**
     111         * Make private/protected methods readable for backwards compatibility.
     112         *
     113         * @since 4.6.0
     114         * @access public
     115         *
     116         * @param callable $name Method to call.
     117         * @param array $arguments Arguments to pass when calling.
     118         *
     119         * @return mixed|false Return value of the callback, false otherwise.
     120         */
     121        public function __call( $name, $arguments ) {
     122                if ( 'get_search_sql' === $name ) {
     123                        return call_user_func_array( array( $this, $name ), $arguments );
     124                }
     125
     126                return false;
     127        }
     128
     129        /**
     130         * Constructor.
     131         *
     132         * Sets up the site query, based on the query vars passed.
     133         *
     134         * @since 4.6.0
     135         * @access public
     136         *
     137         * @param string|array $query {
     138         *     Optional. Array or query string of site query parameters. Default empty.
     139         *
     140         * @type array $site__in Array of site IDs to include. Default empty.
     141         * @type array $site__not_in Array of site IDs to exclude. Default empty.
     142         * @type array $date_query Date query clauses to limit sites by. See WP_Date_Query.
     143         *                                                   Default null.
     144         * @type string $fields Site fields to return. Accepts 'ids' for site IDs
     145         *                                                   only, 'count' for a site count or empty for all fields. Default empty.
     146         * @type int $ID Currently unused.
     147         * @type int $number Maximum number of sites to retrieve.
     148         *                                                   Default null (no limit).
     149         * @type int $offset Number of sites to offset the query. Used to build
     150         *                                                   LIMIT clause. Default 0.
     151         * @type bool $no_found_rows Whether to disable the `SQL_CALC_FOUND_ROWS` query.
     152         *                                                   Default: true.
     153         * @type string|array $orderby Site status or array of statuses. To use 'meta_value'
     154         *                                                   or 'meta_value_num', `$meta_key` must also be defined.
     155         *                                                   To sort by a specific `$meta_query` clause, use that
     156         *                                                   clause's array key. Accepts 'site_agent',
     157         *                                                   'site_approved', 'site_author',
     158         *                                                   'site_author_email', 'site_author_IP',
     159         *                                                   'site_author_url', 'site_content', 'site_date',
     160         *                                                   'site_date_gmt', 'blog_id', 'site_karma',
     161         *                                                   'site_parent', 'site_id', 'site_type',
     162         *                                                   'user_id', 'site__in', 'meta_value', 'meta_value_num',
     163         *                                                   the value of $meta_key, and the array keys of
     164         *                                                   `$meta_query`. Also accepts false, an empty array, or
     165         *                                                   'none' to disable `ORDER BY` clause.
     166         *                                                   Default: 'site_date_gmt'.
     167         * @type string $order How to order retrieved sites. Accepts 'ASC', 'DESC'.
     168         *                                                   Default: 'DESC'.
     169         * @type string $domain Limit results to those affiliated with a given network ID.
     170         *                                                   Default current network id.
     171         * @type array $domain__in Array of domains to include affiliated sites for.
     172         *                                                   Default empty.
     173         * @type array $domain__not_in Array of domains to exclude affiliated sites for.
     174         *                                                   Default empty.
     175         * @type string $path Limit results to those affiliated with a given network ID.
     176         *                                                   Default current network id.
     177         * @type array $path__in Array of paths to include affiliated sites for.
     178         *                                                   Default empty.
     179         * @type array $path__not_in Array of paths to exclude affiliated sites for.
     180         *                                                   Default empty.
     181         * @type int $network_id Limit results to those affiliated with a given network ID.
     182         *                                                   Default current network id.
     183         * @type array $network__in Array of network IDs to include affiliated sites for.
     184         *                                                   Default empty.
     185         * @type array $network__not_in Array of network IDs to exclude affiliated sites for.
     186         *                                                   Default empty.
     187         * @type string $search Search term(s) to retrieve matching sites for.
     188         *                                                   Default empty.
     189         * @type bool $update_site_cache Whether to prime the cache for site networks.
     190         *                                                   Default false.
     191         * }
     192         */
     193        public function __construct( $query = '' ) {
     194                $this->query_var_defaults = array(
     195                        'fields'            => '',
     196                        'ID'                => '',
     197                        'site__in'          => '',
     198                        'site__not_in'      => '',
     199                        'number'            => '',
     200                        'offset'            => '',
     201                        'no_found_rows'     => true,
     202                        'orderby'           => '',
     203                        'order'             => 'DESC',
     204                        'network_id'        => 0,
     205                        'network__in'       => '',
     206                        'network__not_in'   => '',
     207                        'domain'            => '',
     208                        'domain__in'        => '',
     209                        'domain__not_in'    => '',
     210                        'path'              => '',
     211                        'path__in'          => '',
     212                        'path__not_in'      => '',
     213                        'public'            => 'all',
     214                        'archived'          => 'all',
     215                        'mature'            => 'all',
     216                        'spam'              => 'all',
     217                        'deleted'           => 'all',
     218                        'search'            => '',
     219                        'date_query'        => null, // See WP_Date_Query
     220                        'update_site_cache' => true,
     221                );
     222
     223                if ( ! empty( $query ) ) {
     224                        $this->query( $query );
     225                }
     226        }
     227
     228        /**
     229         * Parse arguments passed to the site query with default query parameters.
     230         *
     231         * @since  4.6.0 Extracted from WP_Site_Query::query().
     232         *
     233         * @access public
     234         *
     235         * @param string|array $query WP_Site_Query arguments. See WP_Site_Query::__construct()
     236         */
     237        public function parse_query( $query = '' ) {
     238                if ( empty( $query ) ) {
     239                        $query = $this->query_vars;
     240                }
     241
     242                $this->query_vars = wp_parse_args( $query, $this->query_var_defaults );
     243                do_action_ref_array( 'parse_site_query', array( &$this ) );
     244        }
     245
     246        /**
     247         * Sets up the WordPress query for retrieving sites.
     248         *
     249         * @since 4.6.0
     250         * @access public
     251         *
     252         * @param string|array $query Array or URL query string of parameters.
     253         *
     254         * @return array|int List of sites, or number of sites when the 'fields' query var is set to 'count'.
     255         */
     256        public function query( $query ) {
     257                $this->query_vars = wp_parse_args( $query );
     258
     259                return $this->get_sites();
     260        }
     261
     262        /**
     263         * Get a list of sites matching the query vars.
     264         *
     265         * @since 4.6.0
     266         * @access public
     267         *
     268         * @global wpdb $wpdb WordPress database abstraction object.
     269         *
     270         * @return int|array The list of sites.
     271         */
     272        public function get_sites() {
     273                global $wpdb;
     274
     275                $this->parse_query();
     276
     277
     278                /**
     279                 * Fires before sites are retrieved.
     280                 *
     281                 * @since 4.6.0
     282                 *
     283                 * @param WP_Site_Query &$this Current instance of WP_Site_Query, passed by reference.
     284                 */
     285                do_action_ref_array( 'pre_get_sites', array( &$this ) );
     286
     287                // $args can include anything. Only use the args defined in the query_var_defaults to compute the key.
     288                $key          = md5( serialize( wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) ) ) );
     289                $last_changed = wp_cache_get( 'last_changed', 'site' );
     290                if ( ! $last_changed ) {
     291                        $last_changed = microtime();
     292                        wp_cache_set( 'last_changed', $last_changed, 'site' );
     293                }
     294                $cache_key = "get_site_ids:$key:$last_changed";
     295
     296                $site_ids = wp_cache_get( $cache_key, 'site' );
     297                if ( false === $site_ids ) {
     298                        $site_ids = $this->get_site_ids();
     299                        wp_cache_add( $cache_key, $site_ids, 'site' );
     300                }
     301
     302                // If querying for a count only, there's nothing more to do.
     303                if ( 'count' === $this->query_vars['fields'] ) {
     304                        // $site_ids is actually a count in this case.
     305                        return intval( $site_ids );
     306                }
     307
     308                $site_ids = array_map( 'intval', $site_ids );
     309
     310                $this->site_count = count( $this->sites );
     311
     312                if ( $site_ids && $this->query_vars['number'] && ! $this->query_vars['no_found_rows'] ) {
     313                        /**
     314                         * Filter the query used to retrieve found site count.
     315                         *
     316                         * @since 4.6.0
     317                         *
     318                         * @param string $found_sites_query SQL query. Default 'SELECT FOUND_ROWS()'.
     319                         * @param WP_Site_Query $site_query The `WP_Site_Query` instance.
     320                         */
     321                        $found_sites_query = apply_filters( 'found_sites_query', 'SELECT FOUND_ROWS()', $this );
     322                        $this->found_sites = (int) $wpdb->get_var( $found_sites_query );
     323
     324                        $this->max_num_pages = ceil( $this->found_sites / $this->query_vars['number'] );
     325                }
     326
     327                if ( 'ids' === $this->query_vars['fields'] ) {
     328                        $this->sites = $site_ids;
     329
     330                        return $this->sites;
     331                }
     332
     333                // Fetch full site objects from the primed cache.
     334                $_sites = array();
     335                foreach ( $site_ids as $site_id ) {
     336                        if ( $_site = get_site( $site_id ) ) {
     337                                $_sites[] = $_site;
     338                        }
     339                }
     340
     341                // Prime site network caches.
     342                if ( $this->query_vars['update_site_cache'] ) {
     343                        $site_ids = array();
     344                        foreach ( $_sites as $_site ) {
     345                                $site_ids[] = $_site->site_id;
     346                        }
     347                        _prime_site_caches( $site_ids );
     348                }
     349
     350                /**
     351                 * Filter the site query results.
     352                 *
     353                 * @since 4.6.0
     354                 *
     355                 * @param array $results An array of sites.
     356                 * @param WP_Site_Query &$this Current instance of WP_Site_Query, passed by reference.
     357                 */
     358                $_sites = apply_filters_ref_array( 'the_sites', array( $_sites, &$this ) );
     359
     360                // Convert to WP_Site instances
     361                $sites = array_map( 'get_site', $_sites );
     362
     363                $this->sites = $sites;
     364
     365                return $this->sites;
     366        }
     367
     368        /**
     369         * Used internally to get a list of site IDs matching the query vars.
     370         *
     371         * @since 4.6.0
     372         * @access protected
     373         *
     374         * @global wpdb $wpdb WordPress database abstraction object.
     375         */
     376        protected function get_site_ids() {
     377                global $wpdb;
     378
     379                $order = ( 'ASC' == strtoupper( $this->query_vars['order'] ) ) ? 'ASC' : 'DESC';
     380
     381                // Disable ORDER BY with 'none', an empty array, or boolean false.
     382                if ( in_array( $this->query_vars['orderby'], array( 'none', array(), false ), true ) ) {
     383                        $orderby = '';
     384                } elseif ( ! empty( $this->query_vars['orderby'] ) ) {
     385                        $ordersby = is_array( $this->query_vars['orderby'] ) ?
     386                                $this->query_vars['orderby'] :
     387                                preg_split( '/[,\s]/', $this->query_vars['orderby'] );
     388
     389                        $orderby_array         = array();
     390                        $found_orderby_blog_id = false;
     391                        foreach ( $ordersby as $_key => $_value ) {
     392                                if ( ! $_value ) {
     393                                        continue;
     394                                }
     395
     396                                if ( is_int( $_key ) ) {
     397                                        $_orderby = $_value;
     398                                        $_order   = $order;
     399                                } else {
     400                                        $_orderby = $_key;
     401                                        $_order   = $_value;
     402                                }
     403
     404                                if ( ! $found_orderby_blog_id && in_array( $_orderby, array( 'blog_id', 'site__in' ) ) ) {
     405                                        $found_orderby_blog_id = true;
     406                                }
     407
     408                                $parsed = $this->parse_orderby( $_orderby );
     409
     410                                if ( ! $parsed ) {
     411                                        continue;
     412                                }
     413
     414                                if ( 'site__in' === $_orderby ) {
     415                                        $orderby_array[] = $parsed;
     416                                        continue;
     417                                }
     418
     419                                $orderby_array[] = $parsed . ' ' . $this->parse_order( $_order );
     420                        }
     421
     422                        $orderby = implode( ', ', $orderby_array );
     423                } else {
     424                        $orderby = "blog_id $order";
     425                }
     426
     427                $number = absint( $this->query_vars['number'] );
     428                $offset = absint( $this->query_vars['offset'] );
     429
     430                if ( ! empty( $number ) ) {
     431                        if ( $offset ) {
     432                                $limits = 'LIMIT ' . $offset . ',' . $number;
     433                        } else {
     434                                $limits = 'LIMIT ' . $number;
     435                        }
     436                }
     437
     438                if ( 'count' === $this->query_vars['fields'] ) {
     439                        $fields = 'COUNT(*)';
     440                } else {
     441                        $fields = "blog_id";
     442                }
     443
     444                // Parse site IDs for an IN clause.
     445                $site_id = absint( $this->query_vars['ID'] );
     446                if ( ! empty( $site_id ) ) {
     447                        $this->sql_clauses['where']['ID'] = $wpdb->prepare( 'blog_id = %d', $site_id );
     448                }
     449
     450                // Parse site IDs for an IN clause.
     451                if ( ! empty( $this->query_vars['site__in'] ) ) {
     452                        $this->sql_clauses['where']['site__in'] = "blog_id IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['site__in'] ) ) . ' )';
     453                }
     454
     455                // Parse site IDs for a NOT IN clause.
     456                if ( ! empty( $this->query_vars['site__not_in'] ) ) {
     457                        $this->sql_clauses['where']['site__not_in'] = "blog_id NOT IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['site__not_in'] ) ) . ' )';
     458                }
     459
     460                $network_id = absint( $this->query_vars['network_id'] );
     461                if ( ! empty( $network_id ) ) {
     462                        $this->sql_clauses['where']['network_id'] = $wpdb->prepare( 'site_id = %d', $network_id );
     463                }
     464
     465                // Parse site network IDs for an IN clause.
     466                if ( ! empty( $this->query_vars['network__in'] ) ) {
     467                        $this->sql_clauses['where']['network__in'] = 'site_id IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['network__in'] ) ) . ' )';
     468                }
     469
     470                // Parse site network IDs for a NOT IN clause.
     471                if ( ! empty( $this->query_vars['network__not_in'] ) ) {
     472                        $this->sql_clauses['where']['network__not_in'] = 'site_id NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['network__not_in'] ) ) . ' )';
     473                }
     474
     475
     476                if ( ! empty( $this->query_vars['domain'] ) ) {
     477                        $this->sql_clauses['where']['domain'] = $wpdb->prepare( 'domain = %s', $this->query_vars['domain'] );
     478                }
     479
     480                // Parse site domain for an IN clause.
     481                if ( is_array( $this->query_vars['domain__in'] ) ) {
     482                        $this->sql_clauses['where']['domain__in'] = "domain IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['domain__in'] ) ) . "' )";
     483                }
     484
     485                // Parse site domain for a NOT IN clause.
     486                if ( is_array( $this->query_vars['domain__not_in'] ) ) {
     487                        $this->sql_clauses['where']['domain__not_in'] = "domain NOT IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['domain__not_in'] ) ) . "' )";
     488                }
     489
     490
     491                if ( ! empty( $this->query_vars['path'] ) ) {
     492                        $this->sql_clauses['where']['path'] = $wpdb->prepare( 'path = %s', $this->query_vars['path'] );
     493                }
     494
     495                // Parse site path for an IN clause.
     496                if ( is_array( $this->query_vars['path__in'] ) ) {
     497                        $this->sql_clauses['where']['path__in'] = "path IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['path__in'] ) ) . "' )";
     498                }
     499
     500                // Parse site path for a NOT IN clause.
     501                if ( is_array( $this->query_vars['path__not_in'] ) ) {
     502                        $this->sql_clauses['where']['path__not_in'] = "path NOT IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['path__not_in'] ) ) . "' )";
     503                }
     504
     505
     506                if ( is_numeric( $this->query_vars['archived'] ) ) {
     507                        $archived                               = absint( $this->query_vars['archived'] );
     508                        $this->sql_clauses['where']['archived'] = $wpdb->prepare( "archived = %d ", $archived );
     509                }
     510
     511                if ( is_numeric( $this->query_vars['mature'] ) ) {
     512                        $mature                               = absint( $this->query_vars['mature'] );
     513                        $this->sql_clauses['where']['mature'] = $wpdb->prepare( "mature = %d ", $mature );
     514                }
     515
     516                if ( is_numeric( $this->query_vars['spam'] ) ) {
     517                        $spam                               = absint( $this->query_vars['spam'] );
     518                        $this->sql_clauses['where']['spam'] = $wpdb->prepare( "spam = %d ", $spam );
     519                }
     520
     521                if ( is_numeric( $this->query_vars['deleted'] ) ) {
     522                        $deleted                               = absint( $this->query_vars['deleted'] );
     523                        $this->sql_clauses['where']['deleted'] = $wpdb->prepare( "deleted = %d ", $deleted );
     524                }
     525
     526                // Falsy search strings are ignored.
     527                if ( strlen( $this->query_vars['search'] ) ) {
     528                        $search_sql = $this->get_search_sql(
     529                                $this->query_vars['search'],
     530                                array( 'domain', 'path' )
     531                        );
     532
     533                        // Strip leading 'AND'.
     534                        $this->sql_clauses['where']['search'] = preg_replace( '/^\s*AND\s*/', '', $search_sql );
     535                }
     536
     537                $date_query = $this->query_vars['date_query'];
     538                if ( ! empty( $date_query ) && is_array( $date_query ) ) {
     539                        $date_query_object                        = new WP_Date_Query( $date_query, 'registered' );
     540                        $this->sql_clauses['where']['date_query'] = preg_replace( '/^\s*AND\s*/', '', $date_query_object->get_sql() );
     541                }
     542
     543                $where = implode( ' AND ', $this->sql_clauses['where'] );
     544
     545                $pieces = array( 'fields', 'join', 'where', 'orderby', 'limits', 'groupby' );
     546                /**
     547                 * Filter the site query clauses.
     548                 *
     549                 * @since 4.6.0
     550                 *
     551                 * @param array $pieces A compacted array of site query clauses.
     552                 * @param WP_Site_Query &$this Current instance of WP_Site_Query, passed by reference.
     553                 */
     554                $clauses = apply_filters_ref_array( 'sites_clauses', array( compact( $pieces ), &$this ) );
     555                $fields  = isset( $clauses['fields'] ) ? $clauses['fields'] : '';
     556                $join    = isset( $clauses['join'] ) ? $clauses['join'] : '';
     557                $where   = isset( $clauses['where'] ) ? $clauses['where'] : '';
     558                $orderby = isset( $clauses['orderby'] ) ? $clauses['orderby'] : '';
     559                $limits  = isset( $clauses['limits'] ) ? $clauses['limits'] : '';
     560                $groupby = isset( $clauses['groupby'] ) ? $clauses['groupby'] : '';
     561
     562                $this->filtered_where_clause = $where;
     563
     564                if ( $where ) {
     565                        $where = 'WHERE ' . $where;
     566                }
     567
     568                if ( $groupby ) {
     569                        $groupby = 'GROUP BY ' . $groupby;
     570                }
     571
     572                if ( $orderby ) {
     573                        $orderby = "ORDER BY $orderby";
     574                }
     575
     576                $found_rows = '';
     577                if ( ! $this->query_vars['no_found_rows'] ) {
     578                        $found_rows = 'SQL_CALC_FOUND_ROWS';
     579                }
     580
     581                $this->sql_clauses['select']  = "SELECT $found_rows $fields";
     582                $this->sql_clauses['from']    = "FROM $wpdb->blogs $join";
     583                $this->sql_clauses['groupby'] = $groupby;
     584                $this->sql_clauses['orderby'] = $orderby;
     585                $this->sql_clauses['limits']  = $limits;
     586
     587                $this->request = "{$this->sql_clauses['select']} {$this->sql_clauses['from']} {$where} {$this->sql_clauses['groupby']} {$this->sql_clauses['orderby']} {$this->sql_clauses['limits']}";
     588
     589                if ( 'count' === $this->query_vars['fields'] ) {
     590                        return intval( $wpdb->get_var( $this->request ) );
     591                } else {
     592                        $site_ids = $wpdb->get_col( $this->request );
     593
     594                        return array_map( 'intval', $site_ids );
     595                }
     596        }
     597
     598        /**
     599         * Used internally to generate an SQL string for searching across multiple columns
     600         *
     601         * @since 4.6.0
     602         * @access protected
     603         *
     604         * @global wpdb $wpdb WordPress database abstraction object.
     605         *
     606         * @param string $string
     607         * @param array $cols
     608         *
     609         * @return string
     610         */
     611        protected function get_search_sql( $string, $cols ) {
     612                global $wpdb;
     613
     614                $like = '%' . $wpdb->esc_like( $string ) . '%';
     615
     616                $searches = array();
     617                foreach ( $cols as $col ) {
     618                        $searches[] = $wpdb->prepare( "$col LIKE %s", $like );
     619                }
     620
     621                return ' AND (' . implode( ' OR ', $searches ) . ')';
     622        }
     623
     624        /**
     625         * Parse and sanitize 'orderby' keys passed to the site query.
     626         *
     627         * @since 4.6.0
     628         * @access protected
     629         *
     630         * @global wpdb $wpdb WordPress database abstraction object.
     631         *
     632         * @param string $orderby Alias for the field to order by.
     633         *
     634         * @return string|false Value to used in the ORDER clause. False otherwise.
     635         */
     636        protected function parse_orderby( $orderby ) {
     637                global $wpdb;
     638
     639                switch ( $orderby ) {
     640                        case 'domain':
     641                        case 'last_updated':
     642                        case 'path':
     643                        case 'registered':
     644                                $_orderby = $orderby;
     645                                break;
     646                        case 'network_id':
     647                                $_orderby = "site_id";
     648                                break;
     649                        case 'ids':
     650                        default:
     651                                $_orderby = "blog_id";
     652                                break;
     653                }
     654
     655                $parsed = "$_orderby";
     656
     657
     658                return $parsed;
     659        }
     660
     661        /**
     662         * Parse an 'order' query variable and cast it to ASC or DESC as necessary.
     663         *
     664         * @since 4.6.0
     665         * @access protected
     666         *
     667         * @param string $order The 'order' query variable.
     668         *
     669         * @return string The sanitized 'order' query variable.
     670         */
     671        protected function parse_order( $order ) {
     672                if ( ! is_string( $order ) || empty( $order ) ) {
     673                        return 'DESC';
     674                }
     675
     676                if ( 'ASC' === strtoupper( $order ) ) {
     677                        return 'ASC';
     678                } else {
     679                        return 'DESC';
     680                }
     681        }
     682}
  • src/wp-includes/date.php

     
    489489                global $wpdb;
    490490
    491491                $valid_columns = array(
    492                         'post_date', 'post_date_gmt', 'post_modified',
    493                         'post_modified_gmt', 'comment_date', 'comment_date_gmt',
     492                        'post_date',
     493                        'post_date_gmt',
     494                        'post_modified',
     495                        'post_modified_gmt',
     496                        'comment_date',
     497                        'comment_date_gmt',
    494498                        'user_registered',
     499                        'registered',
     500                        'last_updated',
    495501                );
    496502
    497503                // Attempt to detect a table prefix.
     
    525531                                $wpdb->users => array(
    526532                                        'user_registered',
    527533                                ),
     534                                $wpdb->blogs => array(
     535                                        'registered',
     536                                        'last_updated',
     537                                ),
    528538                        );
    529539
    530540                        // If it's a known column name, add the appropriate table prefix.
  • src/wp-includes/http.php

     
    607607 * @return bool
    608608 */
    609609function ms_allowed_http_request_hosts( $is_external, $host ) {
    610         global $wpdb;
    611610        static $queried = array();
    612         if ( $is_external )
     611        if ( $is_external ) {
    613612                return $is_external;
    614         if ( $host === get_current_site()->domain )
     613        }
     614        if ( $host === get_current_site()->domain ) {
    615615                return true;
    616         if ( isset( $queried[ $host ] ) )
     616        }
     617        if ( isset( $queried[ $host ] ) ) {
    617618                return $queried[ $host ];
    618         $queried[ $host ] = (bool) $wpdb->get_var( $wpdb->prepare( "SELECT domain FROM $wpdb->blogs WHERE domain = %s LIMIT 1", $host ) );
     619        }
     620        $query            = new WP_Site_Query();
     621        $result           = $query->query( array( 'domain' => $host, 'count' => true ) );
     622        $queried[ $host ] = (bool) $result;
     623
    619624        return $queried[ $host ];
    620625}
    621626
  • src/wp-includes/ms-blogs.php

     
    9999                $path = $current_site->path . $slug . '/';
    100100        }
    101101
    102         $blog_id = $wpdb->get_var( $wpdb->prepare("SELECT blog_id FROM {$wpdb->blogs} WHERE domain = %s AND path = %s", $domain, $path) );
     102        $query   = new WP_Site_Query();
     103        $result  = $query->query( array( 'domain' => $domain, 'path' => $path, 'fields' => 'ids' ) );
     104        $blog_id = array_shift( $result );
     105
    103106        wp_cache_set( 'get_id_from_blogname_' . $slug, $blog_id, 'blog-details' );
     107
    104108        return $blog_id;
    105109}
    106110
     
    126130                } elseif ( isset($fields['domain']) && isset($fields['path']) ) {
    127131                        $key = md5( $fields['domain'] . $fields['path'] );
    128132                        $blog = wp_cache_get($key, 'blog-lookup');
    129                         if ( false !== $blog )
     133                        if ( false !== $blog ) {
    130134                                return $blog;
     135                        }
     136
     137                        $domains = array( $fields['domain'] );
    131138                        if ( substr( $fields['domain'], 0, 4 ) == 'www.' ) {
    132                                 $nowww = substr( $fields['domain'], 4 );
    133                                 $blog = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->blogs WHERE domain IN (%s,%s) AND path = %s ORDER BY CHAR_LENGTH(domain) DESC", $nowww, $fields['domain'], $fields['path'] ) );
    134                         } else {
    135                                 $blog = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->blogs WHERE domain = %s AND path = %s", $fields['domain'], $fields['path'] ) );
     139                                $domains[] = substr( $fields['domain'], 4 );
    136140                        }
     141
     142                        $query  = new WP_Site_Query();
     143                        $args = array( 'domain__in' => $domains, 'path' => $fields['path'], 'number' => 1 );
     144                        $result = $query->query( $args );
     145                        $blog   = array_shift( $result );
     146
    137147                        if ( $blog ) {
    138148                                wp_cache_set($blog->blog_id . 'short', $blog, 'blog-details');
    139149                                $blog_id = $blog->blog_id;
     
    143153                } elseif ( isset($fields['domain']) && is_subdomain_install() ) {
    144154                        $key = md5( $fields['domain'] );
    145155                        $blog = wp_cache_get($key, 'blog-lookup');
    146                         if ( false !== $blog )
     156                        if ( false !== $blog ) {
    147157                                return $blog;
     158                        }
     159                        $domains = array($fields['domain']);
    148160                        if ( substr( $fields['domain'], 0, 4 ) == 'www.' ) {
    149                                 $nowww = substr( $fields['domain'], 4 );
    150                                 $blog = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->blogs WHERE domain IN (%s,%s) ORDER BY CHAR_LENGTH(domain) DESC", $nowww, $fields['domain'] ) );
    151                         } else {
    152                                 $blog = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->blogs WHERE domain = %s", $fields['domain'] ) );
     161                                $domains[] = substr( $fields['domain'], 4 );
    153162                        }
     163
     164                        $query = new WP_Site_Query();
     165                        $args = array( 'domain__in' => $domains, 'number' => 1 );
     166                        $result = $query->query( $args );
     167                        $blog   = array_shift( $result );
     168
    154169                        if ( $blog ) {
    155170                                wp_cache_set($blog->blog_id . 'short', $blog, 'blog-details');
    156171                                $blog_id = $blog->blog_id;
     
    457472}
    458473
    459474/**
     475 * Retrieves site data given a site ID or site object.
     476 *
     477 * If an object is passed then the site data will be cached and then returned
     478 * after being passed through a filter. If the site is empty, then the global
     479 * site variable will be used, if it is set.
     480 *
     481 * @since 4.6.0
     482 *
     483 * @global WP_Site $site
     484 *
     485 * @param WP_Site|string|int $site Site to retrieve.
     486 * @param string $output Optional. OBJECT or ARRAY_A or ARRAY_N constants.
     487 *
     488 * @return WP_Site|array|null Depends on $output value.
     489 */
     490function get_site( &$site = null, $output = OBJECT ) {
     491        global $current_blog;
     492        if ( empty( $site ) && isset( $current_blog ) ) {
     493                $site = $current_blog;
     494        }
     495
     496        if ( $site instanceof WP_Site ) {
     497                $_site = $site;
     498        } elseif ( is_object( $site ) ) {
     499                $_site = new WP_Site( $site );
     500        } else {
     501                $_site = WP_Site::get_instance( $site );
     502        }
     503
     504        if ( ! $_site ) {
     505                return null;
     506        }
     507
     508        /**
     509         * Fires after a site is retrieved.
     510         *
     511         * @since 4.6.0
     512         *
     513         * @param mixed $_site Site data.
     514         */
     515        $_site = apply_filters( 'get_site', $_site );
     516
     517        if ( $output == OBJECT ) {
     518                return $_site;
     519        } elseif ( $output == ARRAY_A ) {
     520                return $_site->to_array();
     521        } elseif ( $output == ARRAY_N ) {
     522                return array_values( $_site->to_array() );
     523        }
     524
     525        return $_site;
     526}
     527
     528/**
     529 * Adds any sites from the given ids to the cache that do not already exist in cache
     530 *
     531 * @since 4.6.0
     532 * @access private
     533 *
     534 * @see update_site_cache()
     535 *
     536 * @global wpdb $wpdb WordPress database abstraction object.
     537 *
     538 * @param array $ids ID list.
     539 */
     540function _prime_site_caches( $ids ) {
     541        global $wpdb;
     542
     543        $non_cached_ids = _get_non_cached_ids( $ids, 'sites' );
     544        if ( ! empty( $non_cached_ids ) ) {
     545                $fresh_sites = $wpdb->get_results( sprintf( "SELECT * FROM $wpdb->blogs WHERE blog_id IN (%s)", join( ",", $non_cached_ids ) ) );
     546
     547                update_site_cache( $fresh_sites );
     548        }
     549}
     550
     551/**
     552 * Updates sites in cache.
     553 *
     554 * @since 4.6.0
     555 *
     556 * @param array $sites Array of site objects, passed by reference.
     557 */
     558function update_site_cache( &$sites ) {
     559        if ( ! $sites ) {
     560                return;
     561        }
     562
     563        foreach ( $sites as $site ) {
     564                wp_cache_add( $site->blog_id, $site, 'sites' );
     565        }
     566}
     567
     568/**
    460569 * Retrieve option value for a given blog id based on name of option.
    461570 *
    462571 * If the option does not exist or does not have a value, then the return value
  • src/wp-includes/ms-functions.php

     
    308308        global $wpdb;
    309309
    310310        $domain = strtolower( $domain );
    311         $path = strtolower( $path );
    312         $id = wp_cache_get( md5( $domain . $path ), 'blog-id-cache' );
     311        $path   = strtolower( $path );
     312        $id     = wp_cache_get( md5( $domain . $path ), 'blog-id-cache' );
    313313
    314         if ( $id == -1 ) // blog does not exist
     314        if ( $id == - 1 ) // blog does not exist
     315        {
    315316                return 0;
    316         elseif ( $id )
     317        } elseif ( $id ) {
    317318                return (int) $id;
     319        }
    318320
    319         $id = $wpdb->get_var( $wpdb->prepare( "SELECT blog_id FROM $wpdb->blogs WHERE domain = %s and path = %s /* get_blog_id_from_url */", $domain, $path ) );
     321        $query  = new WP_Site_Query();
     322        $result = $query->query( array( 'domain' => $domain, 'path' => $path, 'fields' => 'ids' ) );
     323        $id     = array_shift( $result );
     324        if ( ! $id ) {
     325                wp_cache_set( md5( $domain . $path ), - 1, 'blog-id-cache' );
    320326
    321         if ( ! $id ) {
    322                 wp_cache_set( md5( $domain . $path ), -1, 'blog-id-cache' );
    323327                return 0;
    324328        }
    325329
     
    12551259 * @return int
    12561260 */
    12571261function domain_exists($domain, $path, $site_id = 1) {
    1258         global $wpdb;
    12591262        $path = trailingslashit( $path );
    1260         $result = $wpdb->get_var( $wpdb->prepare("SELECT blog_id FROM $wpdb->blogs WHERE domain = %s AND path = %s AND site_id = %d", $domain, $path, $site_id) );
    12611263
     1264        $query = new WP_Site_Query();
     1265        $args = array( 'path' => $path, 'domain' => $domain, 'network' => $site_id, 'number' => 1, 'fields' => 'ids' );
     1266        $result = $query->query( $args );
     1267        $site   = array_shift( $result );
     1268
    12621269        /**
    12631270         * Filter whether a blogname is taken.
    12641271         *
    12651272         * @since 3.5.0
    12661273         *
    1267          * @param int|null $result  The blog_id if the blogname exists, null otherwise.
     1274         * @param int|null $site  The blog_id if the blogname exists, null otherwise.
    12681275         * @param string   $domain  Domain to be checked.
    12691276         * @param string   $path    Path to be checked.
    12701277         * @param int      $site_id Site ID. Relevant only on multi-network installs.
    12711278         */
    1272         return apply_filters( 'domain_exists', $result, $domain, $path, $site_id );
     1279        return apply_filters( 'domain_exists', $site, $domain, $path, $site_id );
    12731280}
    12741281
    12751282/**
     
    22522259function wp_update_network_site_counts() {
    22532260        global $wpdb;
    22542261
    2255         $count = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(blog_id) as c FROM $wpdb->blogs WHERE site_id = %d AND spam = '0' AND deleted = '0' and archived = '0'", $wpdb->siteid) );
     2262
     2263        $query = new WP_Site_Query();
     2264        $args = array( 'network_id' => $wpdb->siteid, 'spam' => 0, 'deleted' => 0, 'archived' => 0, 'count' => true );
     2265        $count = $query->query( $args );
     2266
    22562267        update_site_option( 'blog_count', $count );
    22572268}
    22582269
     
    24322443function wp_get_sites( $args = array() ) {
    24332444        global $wpdb;
    24342445
    2435         if ( wp_is_large_network() )
    2436                 return array();
    2437 
    24382446        $defaults = array(
    24392447                'network_id' => $wpdb->siteid,
    2440                 'public'     => null,
    2441                 'archived'   => null,
    2442                 'mature'     => null,
    2443                 'spam'       => null,
    2444                 'deleted'    => null,
     2448                'fields'     => '',
    24452449                'limit'      => 100,
    24462450                'offset'     => 0,
    24472451        );
    24482452
    24492453        $args = wp_parse_args( $args, $defaults );
    24502454
    2451         $query = "SELECT * FROM $wpdb->blogs WHERE 1=1 ";
     2455        $query = new WP_Site_Query();
    24522456
    2453         if ( isset( $args['network_id'] ) && ( is_array( $args['network_id'] ) || is_numeric( $args['network_id'] ) ) ) {
    2454                 $network_ids = implode( ',', wp_parse_id_list( $args['network_id'] ) );
    2455                 $query .= "AND site_id IN ($network_ids) ";
     2457        $sites = $query->query( $args );
     2458        if ( empty( $args['fields'] ) ) {
     2459                $sites = array_map( 'get_site', $sites, array_fill( 0, count( $sites ), ARRAY_A ) );
    24562460        }
    2457 
    2458         if ( isset( $args['public'] ) )
    2459                 $query .= $wpdb->prepare( "AND public = %d ", $args['public'] );
    2460 
    2461         if ( isset( $args['archived'] ) )
    2462                 $query .= $wpdb->prepare( "AND archived = %d ", $args['archived'] );
    2463 
    2464         if ( isset( $args['mature'] ) )
    2465                 $query .= $wpdb->prepare( "AND mature = %d ", $args['mature'] );
    2466 
    2467         if ( isset( $args['spam'] ) )
    2468                 $query .= $wpdb->prepare( "AND spam = %d ", $args['spam'] );
    2469 
    2470         if ( isset( $args['deleted'] ) )
    2471                 $query .= $wpdb->prepare( "AND deleted = %d ", $args['deleted'] );
    2472 
    2473         if ( isset( $args['limit'] ) && $args['limit'] ) {
    2474                 if ( isset( $args['offset'] ) && $args['offset'] )
    2475                         $query .= $wpdb->prepare( "LIMIT %d , %d ", $args['offset'], $args['limit'] );
    2476                 else
    2477                         $query .= $wpdb->prepare( "LIMIT %d ", $args['limit'] );
    2478         }
    2479 
    2480         $site_results = $wpdb->get_results( $query, ARRAY_A );
    2481 
    2482         return $site_results;
     2461        return $sites;
    24832462}
    24842463
    24852464/**
  • src/wp-includes/ms-load.php

     
    231231        $domains = array( $domain );
    232232        if ( 'www.' === substr( $domain, 0, 4 ) ) {
    233233                $domains[] = substr( $domain, 4 );
    234                 $search_domains = "'" . implode( "', '", $wpdb->_escape( $domains ) ) . "'";
    235234        }
    236235
    237         if ( count( $paths ) > 1 ) {
    238                 $search_paths = "'" . implode( "', '", $wpdb->_escape( $paths ) ) . "'";
    239         }
    240 
    241         if ( count( $domains ) > 1 && count( $paths ) > 1 ) {
    242                 $site = $wpdb->get_row( "SELECT * FROM $wpdb->blogs WHERE domain IN ($search_domains) AND path IN ($search_paths) ORDER BY CHAR_LENGTH(domain) DESC, CHAR_LENGTH(path) DESC LIMIT 1" );
    243         } elseif ( count( $domains ) > 1 ) {
    244                 $sql = $wpdb->prepare( "SELECT * FROM $wpdb->blogs WHERE path = %s", $paths[0] );
    245                 $sql .= " AND domain IN ($search_domains) ORDER BY CHAR_LENGTH(domain) DESC LIMIT 1";
    246                 $site = $wpdb->get_row( $sql );
    247         } elseif ( count( $paths ) > 1 ) {
    248                 $sql = $wpdb->prepare( "SELECT * FROM $wpdb->blogs WHERE domain = %s", $domains[0] );
    249                 $sql .= " AND path IN ($search_paths) ORDER BY CHAR_LENGTH(path) DESC LIMIT 1";
    250                 $site = $wpdb->get_row( $sql );
    251         } else {
    252                 $site = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->blogs WHERE domain = %s AND path = %s", $domains[0], $paths[0] ) );
    253         }
    254 
     236        $query = new WP_Site_Query();
     237        $args = array( 'path__in' => $path, 'domain__in' => $domains, 'number' => 1 );
     238        $result = $query->query( $args );
     239        $site   = array_shift( $result );
    255240        if ( $site ) {
    256241                // @todo get_blog_details()
    257242                return $site;
  • src/wp-settings.php

     
    9999
    100100// Initialize multisite if enabled.
    101101if ( is_multisite() ) {
     102        require( ABSPATH . WPINC . '/class-wp-site-query.php' );
    102103        require( ABSPATH . WPINC . '/ms-blogs.php' );
    103104        require( ABSPATH . WPINC . '/ms-settings.php' );
    104105} elseif ( ! defined( 'MULTISITE' ) ) {