Make WordPress Core

Ticket #35791: 35791-class.4.patch

File 35791-class.4.patch, 33.4 KB (added by flixos90, 9 years ago)

added unit tests + docs fixes

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

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

    Property changes on: src/wp-includes/class-wp-site-query.php
    ___________________________________________________________________
    Added: svn:executable
    ## -0,0 +1 ##
    +*
    \ No newline at end of property
     
    198198                        $this->$key = $value;
    199199                }
    200200        }
     201
     202        /**
     203     * Converts an object to array.
     204         *
     205         * @since 4.6.0
     206         * @access public
     207         *
     208         * @return array Object as array.
     209         */
     210        public function to_array() {
     211                return get_object_vars( $this );
     212        }
    201213}
  • src/wp-includes/date.php

     
    491491                $valid_columns = array(
    492492                        'post_date', 'post_date_gmt', 'post_modified',
    493493                        'post_modified_gmt', 'comment_date', 'comment_date_gmt',
    494                         'user_registered',
     494                        'user_registered', 'registered', 'last_updated',
    495495                );
    496496
    497497                // Attempt to detect a table prefix.
     
    525525                                $wpdb->users => array(
    526526                                        'user_registered',
    527527                                ),
     528                                $wpdb->blogs => array(
     529                                        'registered',
     530                                        'last_updated',
     531                                ),
    528532                        );
    529533
    530534                        // If it's a known column name, add the appropriate table prefix.
  • src/wp-includes/ms-blogs.php

     
    455455        wp_cache_delete( 'get_id_from_blogname_' . trim( $blog->path, '/' ), 'blog-details' );
    456456        wp_cache_delete( $domain_path_key, 'blog-id-cache' );
    457457
     458        $last_changed = microtime();
     459        wp_cache_set( 'last_changed', $last_changed, 'sites' );
     460
    458461        /**
    459462         * Fires immediately after a site has been removed from the object cache.
    460463         *
     
    468471}
    469472
    470473/**
     474 * Retrieves site data given a site ID or site object.
     475 *
     476 * If an object is passed then the site data will be cached and then returned
     477 * after being passed through a filter. If the site is empty, then the global
     478 * site variable will be used, if it is set.
     479 *
     480 * @since 4.6.0
     481 *
     482 * @global WP_Site $site
     483 *
     484 * @param WP_Site|string|int $site Site to retrieve.
     485 * @param string $output Optional. OBJECT or ARRAY_A or ARRAY_N constants.
     486 * @return WP_Site|array|null Depends on $output value.
     487 */
     488function get_site( &$site = null, $output = OBJECT ) {
     489        global $current_blog;
     490        if ( empty( $site ) && isset( $current_blog ) ) {
     491                $site = $current_blog;
     492        }
     493
     494        if ( $site instanceof WP_Site ) {
     495                $_site = $site;
     496        } elseif ( is_object( $site ) ) {
     497                $_site = new WP_Site( $site );
     498        } else {
     499                $_site = WP_Site::get_instance( $site );
     500        }
     501
     502        if ( ! $_site ) {
     503                return null;
     504        }
     505
     506        /**
     507         * Fires after a site is retrieved.
     508         *
     509         * @since 4.6.0
     510         *
     511         * @param mixed $_site Site data.
     512         */
     513        $_site = apply_filters( 'get_site', $_site );
     514
     515        if ( $output == OBJECT ) {
     516                return $_site;
     517        } elseif ( $output == ARRAY_A ) {
     518                return $_site->to_array();
     519        } elseif ( $output == ARRAY_N ) {
     520                return array_values( $_site->to_array() );
     521        }
     522
     523        return $_site;
     524}
     525
     526/**
     527 * Adds any sites from the given ids to the cache that do not already exist in cache
     528 *
     529 * @since 4.6.0
     530 * @access private
     531 *
     532 * @see update_site_cache()
     533 *
     534 * @global wpdb $wpdb WordPress database abstraction object.
     535 *
     536 * @param array $ids ID list.
     537 */
     538function _prime_site_caches( $ids ) {
     539        global $wpdb;
     540
     541        $non_cached_ids = _get_non_cached_ids( $ids, 'sites' );
     542        if ( ! empty( $non_cached_ids ) ) {
     543                $fresh_sites = $wpdb->get_results( sprintf( "SELECT * FROM $wpdb->blogs WHERE blog_id IN (%s)", join( ",", $non_cached_ids ) ) );
     544
     545                update_site_cache( $fresh_sites );
     546        }
     547}
     548
     549/**
     550 * Updates sites in cache.
     551 *
     552 * @since 4.6.0
     553 *
     554 * @param array $sites Array of site objects, passed by reference.
     555 */
     556function update_site_cache( &$sites ) {
     557        if ( ! $sites ) {
     558                return;
     559        }
     560
     561        foreach ( $sites as $site ) {
     562                wp_cache_add( $site->blog_id, $site, 'sites' );
     563                wp_cache_add( $site->blog_id . 'short', $site, 'blog-details' );
     564        }
     565}
     566
     567/**
    471568 * Retrieve option value for a given blog id based on name of option.
    472569 *
    473570 * If the option does not exist or does not have a value, then the return value
  • 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' ) ) {
  • tests/phpunit/tests/multisite/siteQuery.php

     
     1<?php
     2
     3if ( is_multisite() ) :
     4
     5/**
     6 * Test site query functionality in multisite.
     7 *
     8 * @group ms-site
     9 * @group multisite
     10 */
     11class Tests_Multisite_Site_Query extends WP_UnitTestCase {
     12        protected static $network_ids;
     13        protected static $site_ids;
     14
     15        protected $suppress = false;
     16
     17        function setUp() {
     18                global $wpdb;
     19                parent::setUp();
     20                $this->suppress = $wpdb->suppress_errors();
     21        }
     22
     23        function tearDown() {
     24                global $wpdb;
     25                $wpdb->suppress_errors( $this->suppress );
     26                parent::tearDown();
     27        }
     28
     29        public static function wpSetUpBeforeClass( $factory ) {
     30                self::$network_ids = array(
     31                        'wordpress.org/'         => array( 'domain' => 'wordpress.org', 'path' => '/' ),
     32                        'make.wordpress.org/'    => array( 'domain' => 'make.wordpress.org', 'path' => '/' ),
     33                        'www.wordpress.net/'     => array( 'domain' => 'www.wordpress.net', 'path' => '/' ),
     34                );
     35
     36                foreach ( self::$network_ids as &$id ) {
     37                        $id = $factory->network->create( $id );
     38                }
     39                unset( $id );
     40
     41                self::$site_ids = array(
     42                        'wordpress.org/'              => array( 'domain' => 'wordpress.org',      'path' => '/',         'site_id' => self::$network_ids['wordpress.org/'] ),
     43                        'wordpress.org/foo/'          => array( 'domain' => 'wordpress.org',      'path' => '/foo/',     'site_id' => self::$network_ids['wordpress.org/'] ),
     44                        'wordpress.org/foo/bar/'      => array( 'domain' => 'wordpress.org',      'path' => '/foo/bar/', 'site_id' => self::$network_ids['wordpress.org/'] ),
     45                        'make.wordpress.org/'         => array( 'domain' => 'make.wordpress.org', 'path' => '/',         'site_id' => self::$network_ids['make.wordpress.org/'] ),
     46                        'make.wordpress.org/foo/'     => array( 'domain' => 'make.wordpress.org', 'path' => '/foo/',     'site_id' => self::$network_ids['make.wordpress.org/'] ),
     47                        'www.w.org/'                  => array( 'domain' => 'www.w.org',          'path' => '/' ),
     48                        'www.w.org/foo/'              => array( 'domain' => 'www.w.org',          'path' => '/foo/' ),
     49                        'www.w.org/foo/bar/'          => array( 'domain' => 'www.w.org',          'path' => '/foo/bar/' ),
     50                );
     51
     52                foreach ( self::$site_ids as &$id ) {
     53                        $id = $factory->blog->create( $id );
     54                }
     55                unset( $id );
     56        }
     57
     58        public static function wpTearDownAfterClass() {
     59                global $wpdb;
     60
     61                foreach( self::$site_ids as $id ) {
     62                        wpmu_delete_blog( $id, true );
     63                }
     64
     65                foreach( self::$network_ids as $id ) {
     66                        $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->sitemeta} WHERE site_id = %d", $id ) );
     67                        $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->site} WHERE id= %d", $id ) );
     68                }
     69
     70                wp_update_network_site_counts();
     71        }
     72
     73        public function test_query() {
     74                $q = new WP_Site_Query();
     75                $found = $q->query( array(
     76                        'fields'       => 'ids',
     77                        // Exclude main site since we don't have control over it here.
     78                        'site__not_in' => array( 1 ),
     79                ) );
     80
     81                $this->assertEqualSets( array_values( self::$site_ids ), $found );
     82        }
     83
     84        public function test_query_by_id() {
     85                $q = new WP_Site_Query();
     86                $found = $q->query( array(
     87                        'fields' => 'ids',
     88                        'ID'     => self::$site_ids['www.w.org/'],
     89                ) );
     90
     91                $this->assertEqualSets( array( self::$site_ids['www.w.org/'] ), $found );
     92        }
     93
     94        public function test_query_by_ids() {
     95                $expected = array( self::$site_ids['wordpress.org/'], self::$site_ids['wordpress.org/foo/'] );
     96
     97                $q = new WP_Site_Query();
     98                $found = $q->query( array(
     99                        'fields'   => 'ids',
     100                        'site__in' => $expected,
     101                ) );
     102
     103                $this->assertEqualSets( $expected, $found );
     104        }
     105
     106        public function test_query_by_excluded_ids() {
     107                $excluded = array( self::$site_ids['wordpress.org/'], self::$site_ids['wordpress.org/foo/'] );
     108                $expected = array_diff( self::$site_ids, $excluded );
     109
     110                // Exclude main site since we don't have control over it here.
     111                $excluded[] = 1;
     112
     113                $q = new WP_Site_Query();
     114                $found = $q->query( array(
     115                        'fields'       => 'ids',
     116                        'site__not_in' => $excluded,
     117                ) );
     118
     119                $this->assertEqualSets( $expected, $found );
     120        }
     121
     122        public function test_query_by_network() {
     123                $q = new WP_Site_Query();
     124                $found = $q->query( array(
     125                        'fields'       => 'ids',
     126                        // Exclude main site since we don't have control over it here.
     127                        'site__not_in' => array( 1 ),
     128                        'network_id'   => self::$network_ids['make.wordpress.org/'],
     129                ) );
     130
     131                $this->assertEqualSets( array( self::$site_ids['make.wordpress.org/'], self::$site_ids['make.wordpress.org/foo/'] ), $found );
     132
     133                $q = new WP_Site_Query();
     134                $found = $q->query( array(
     135                        'fields'       => 'ids',
     136                        // Exclude main site since we don't have control over it here.
     137                        'site__not_in' => array( 1 ),
     138                        'network_id'   => self::$network_ids['www.wordpress.net/'],
     139                ) );
     140
     141                $this->assertEmpty( $found );
     142        }
     143
     144        public function test_query_by_domain() {
     145                $q = new WP_Site_Query();
     146                $found = $q->query( array(
     147                        'fields'       => 'ids',
     148                        // Exclude main site since we don't have control over it here.
     149                        'site__not_in' => array( 1 ),
     150                        'domain'       => 'www.w.org',
     151                ) );
     152
     153                $this->assertEqualSets( array( self::$site_ids['www.w.org/'], self::$site_ids['www.w.org/foo/'], self::$site_ids['www.w.org/foo/bar/'] ), $found );
     154        }
     155
     156        public function test_query_by_path() {
     157                $q = new WP_Site_Query();
     158                $found = $q->query( array(
     159                        'fields'       => 'ids',
     160                        // Exclude main site since we don't have control over it here.
     161                        'site__not_in' => array( 1 ),
     162                        'path'         => '/foo/bar/',
     163                ) );
     164
     165                $this->assertEqualSets( array( self::$site_ids['wordpress.org/foo/bar/'], self::$site_ids['www.w.org/foo/bar/'] ), $found );
     166
     167                $q = new WP_Site_Query();
     168                $found = $q->query( array(
     169                        'fields'       => 'ids',
     170                        // Exclude main site since we don't have control over it here.
     171                        'site__not_in' => array( 1 ),
     172                        'path'         => '/foo/bar/foo/',
     173                ) );
     174
     175                $this->assertEmpty( $found );
     176        }
     177
     178        public function test_query_archived_sites() {
     179                $q = new WP_Site_Query();
     180                $found = $q->query( array(
     181                        'fields'       => 'ids',
     182                        // Exclude main site since we don't have control over it here.
     183                        'site__not_in' => array( 1 ),
     184                        'archived'     => '0',
     185                ) );
     186
     187                $this->assertEqualSets( array_values( self::$site_ids ), $found );
     188        }
     189
     190        public function test_query_deleted_sites() {
     191                $q = new WP_Site_Query();
     192                $found = $q->query( array(
     193                        'fields'       => 'ids',
     194                        // Exclude main site since we don't have control over it here.
     195                        'site__not_in' => array( 1 ),
     196                        'deleted'      => '1',
     197                ) );
     198
     199                $this->assertEmpty( $found );
     200        }
     201
     202        public function test_query_by_search() {
     203                $q = new WP_Site_Query();
     204                $found = $q->query( array(
     205                        'fields'       => 'ids',
     206                        // Exclude main site since we don't have control over it here.
     207                        'site__not_in' => array( 1 ),
     208                        'search'       => 'ke.wordp',
     209                ) );
     210
     211                $this->assertEqualSets( array( self::$site_ids['make.wordpress.org/'], self::$site_ids['make.wordpress.org/foo/'] ), $found );
     212        }
     213}
     214
     215endif;