Index: wp-content/themes/twentyfifteen/header.php
===================================================================
--- wp-content/themes/twentyfifteen/header.php	(revision 37134)
+++ wp-content/themes/twentyfifteen/header.php	(working copy)
@@ -50,3 +50,4 @@
 	</div><!-- .sidebar -->
 
 	<div id="content" class="site-content">
+<?php wp_update_network_site_counts();
\ No newline at end of file
Index: wp-includes/class-wp-site-query.php
===================================================================
--- wp-includes/class-wp-site-query.php	(revision 0)
+++ wp-includes/class-wp-site-query.php	(working copy)
@@ -0,0 +1,685 @@
+<?php
+
+/**
+ * Site API: WP_Site_Query class
+ *
+ * @package WordPress
+ * @subpackage Sites
+ * @since 4.6.0
+ */
+
+/**
+ * Core class used for querying sites.
+ *
+ * @since 4.6.0
+ *
+ * @see WP_Site_Query::__construct() for accepted arguments.
+ */
+class WP_Site_Query {
+
+	/**
+	 * SQL for database query.
+	 *
+	 * @since 4.6.0
+	 * @access public
+	 * @var string
+	 */
+	public $request;
+
+	/**
+	 * SQL query clauses.
+	 *
+	 * @since 4.6.0
+	 * @access protected
+	 * @var array
+	 */
+	protected $sql_clauses = array(
+		'select'  => '',
+		'from'    => '',
+		'where'   => array(),
+		'groupby' => '',
+		'orderby' => '',
+		'limits'  => '',
+	);
+
+	/**
+	 * SQL WHERE clause.
+	 *
+	 * Stored after the 'sites_clauses' filter is run on the compiled WHERE sub-clauses.
+	 *
+	 * @since 4.6.0
+	 * @access protected
+	 * @var string
+	 */
+	protected $filtered_where_clause;
+
+	/**
+	 * Date query container
+	 *
+	 * @since 4.6.0
+	 * @access public
+	 * @var object WP_Date_Query
+	 */
+	public $date_query = false;
+
+	/**
+	 * Query vars set by the user.
+	 *
+	 * @since 4.6.0
+	 * @access public
+	 * @var array
+	 */
+	public $query_vars;
+
+	/**
+	 * Default values for query vars.
+	 *
+	 * @since 4.6.0
+	 * @access public
+	 * @var array
+	 */
+	public $query_var_defaults;
+
+	/**
+	 * List of sites located by the query.
+	 *
+	 * @since 4.6.0
+	 * @access public
+	 * @var array
+	 */
+	public $sites;
+
+	/**
+	 * The amount of found sites for the current query.
+	 *
+	 * @since 4.6.0
+	 * @access public
+	 * @var int
+	 */
+	public $found_sites = 0;
+
+	/**
+	 * The number of pages.
+	 *
+	 * @since 4.6.0
+	 * @access public
+	 * @var int
+	 */
+	public $max_num_pages = 0;
+
+	/**
+	 * Make private/protected methods readable for backwards compatibility.
+	 *
+	 * @since 4.6.0
+	 * @access public
+	 *
+	 * @param callable $name Method to call.
+	 * @param array $arguments Arguments to pass when calling.
+	 *
+	 * @return mixed|false Return value of the callback, false otherwise.
+	 */
+	public function __call( $name, $arguments ) {
+		if ( 'get_search_sql' === $name ) {
+			return call_user_func_array( array( $this, $name ), $arguments );
+		}
+
+		return false;
+	}
+
+	/**
+	 * Constructor.
+	 *
+	 * Sets up the site query, based on the query vars passed.
+	 *
+	 * @since 4.6.0
+	 * @access public
+	 *
+	 * @param string|array $query {
+	 *     Optional. Array or query string of site query parameters. Default empty.
+	 *
+	 * @type array $site__in Array of site IDs to include. Default empty.
+	 * @type array $site__not_in Array of site IDs to exclude. Default empty.
+	 * @type bool $count Whether to return a site count (true) or array of
+	 *                                                   site objects (false). Default false.
+	 * @type array $date_query Date query clauses to limit sites by. See WP_Date_Query.
+	 *                                                   Default null.
+	 * @type string $fields Site fields to return. Accepts 'ids' for site IDs
+	 *                                                   only or empty for all fields. Default empty.
+	 * @type int $ID Currently unused.
+	 * @type int $number Maximum number of sites to retrieve.
+	 *                                                   Default null (no limit).
+	 * @type int $offset Number of sites to offset the query. Used to build
+	 *                                                   LIMIT clause. Default 0.
+	 * @type bool $no_found_rows Whether to disable the `SQL_CALC_FOUND_ROWS` query.
+	 *                                                   Default: true.
+	 * @type string|array $orderby Site status or array of statuses. To use 'meta_value'
+	 *                                                   or 'meta_value_num', `$meta_key` must also be defined.
+	 *                                                   To sort by a specific `$meta_query` clause, use that
+	 *                                                   clause's array key. Accepts 'site_agent',
+	 *                                                   'site_approved', 'site_author',
+	 *                                                   'site_author_email', 'site_author_IP',
+	 *                                                   'site_author_url', 'site_content', 'site_date',
+	 *                                                   'site_date_gmt', 'blog_id', 'site_karma',
+	 *                                                   'site_parent', 'site_id', 'site_type',
+	 *                                                   'user_id', 'site__in', 'meta_value', 'meta_value_num',
+	 *                                                   the value of $meta_key, and the array keys of
+	 *                                                   `$meta_query`. Also accepts false, an empty array, or
+	 *                                                   'none' to disable `ORDER BY` clause.
+	 *                                                   Default: 'site_date_gmt'.
+	 * @type string $order How to order retrieved sites. Accepts 'ASC', 'DESC'.
+	 *                                                   Default: 'DESC'.
+	 * @type string $domain Limit results to those affiliated with a given network ID.
+	 *                                                   Default current network id.
+	 * @type array $domain__in Array of domains to include affiliated sites for.
+	 *                                                   Default empty.
+	 * @type array $domain__not_in Array of domains to exclude affiliated sites for.
+	 *                                                   Default empty.
+	 * @type string $path Limit results to those affiliated with a given network ID.
+	 *                                                   Default current network id.
+	 * @type array $path__in Array of paths to include affiliated sites for.
+	 *                                                   Default empty.
+	 * @type array $path__not_in Array of paths to exclude affiliated sites for.
+	 *                                                   Default empty.
+	 * @type int $network_id Limit results to those affiliated with a given network ID.
+	 *                                                   Default current network id.
+	 * @type array $network__in Array of network IDs to include affiliated sites for.
+	 *                                                   Default empty.
+	 * @type array $network__not_in Array of network IDs to exclude affiliated sites for.
+	 *                                                   Default empty.
+	 * @type string $search Search term(s) to retrieve matching sites for.
+	 *                                                   Default empty.
+	 * @type bool $update_site_cache Whether to prime the cache for site networks.
+	 *                                                   Default false.
+	 * }
+	 */
+	public function __construct( $query = '' ) {
+		$this->query_var_defaults = array(
+			'fields'            => '',
+			'ID'                => '',
+			'site__in'          => '',
+			'site__not_in'      => '',
+			'number'            => '',
+			'offset'            => '',
+			'no_found_rows'     => true,
+			'orderby'           => '',
+			'order'             => 'DESC',
+			'network_id'        => 0,
+			'network__in'       => '',
+			'network__not_in'   => '',
+			'domain'            => '',
+			'domain__in'        => '',
+			'domain__not_in'    => '',
+			'path'              => '',
+			'path__in'          => '',
+			'path__not_in'      => '',
+			'public'            => 'all',
+			'archived'          => 'all',
+			'mature'            => 'all',
+			'spam'              => 'all',
+			'deleted'           => 'all',
+			'search'            => '',
+			'count'             => false,
+			'date_query'        => null, // See WP_Date_Query
+			'update_site_cache' => true,
+		);
+
+		if ( ! empty( $query ) ) {
+			$this->query( $query );
+		}
+	}
+
+	/**
+	 * Parse arguments passed to the site query with default query parameters.
+	 *
+	 * @since  4.6.0 Extracted from WP_Site_Query::query().
+	 *
+	 * @access public
+	 *
+	 * @param string|array $query WP_Site_Query arguments. See WP_Site_Query::__construct()
+	 */
+	public function parse_query( $query = '' ) {
+		if ( empty( $query ) ) {
+			$query = $this->query_vars;
+		}
+
+		$this->query_vars = wp_parse_args( $query, $this->query_var_defaults );
+		do_action_ref_array( 'parse_site_query', array( &$this ) );
+	}
+
+	/**
+	 * Sets up the WordPress query for retrieving sites.
+	 *
+	 * @since 4.6.0
+	 * @access public
+	 *
+	 * @param string|array $query Array or URL query string of parameters.
+	 *
+	 * @return array|int List of sites, or number of sites when 'count' is passed as a query var.
+	 */
+	public function query( $query ) {
+		$this->query_vars = wp_parse_args( $query );
+
+		return $this->get_sites();
+	}
+
+	/**
+	 * Get a list of sites matching the query vars.
+	 *
+	 * @since 4.6.0
+	 * @access public
+	 *
+	 * @global wpdb $wpdb WordPress database abstraction object.
+	 *
+	 * @return int|array The list of sites.
+	 */
+	public function get_sites() {
+		global $wpdb;
+
+		$this->parse_query();
+
+
+		/**
+		 * Fires before sites are retrieved.
+		 *
+		 * @since 4.6.0
+		 *
+		 * @param WP_Site_Query &$this Current instance of WP_Site_Query, passed by reference.
+		 */
+		do_action_ref_array( 'pre_get_sites', array( &$this ) );
+
+		// $args can include anything. Only use the args defined in the query_var_defaults to compute the key.
+		$key          = md5( serialize( wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) ) ) );
+		$last_changed = wp_cache_get( 'last_changed', 'site' );
+		if ( ! $last_changed ) {
+			$last_changed = microtime();
+			wp_cache_set( 'last_changed', $last_changed, 'site' );
+		}
+		$cache_key = "get_site_ids:$key:$last_changed";
+
+		$site_ids = wp_cache_get( $cache_key, 'site' );
+		if ( false === $site_ids ) {
+			$site_ids = $this->get_site_ids();
+			wp_cache_add( $cache_key, $site_ids, 'site' );
+		}
+
+		// If querying for a count only, there's nothing more to do.
+		if ( $this->query_vars['count'] ) {
+			// $site_ids is actually a count in this case.
+			return intval( $site_ids );
+		}
+
+		$site_ids = array_map( 'intval', $site_ids );
+
+		$this->site_count = count( $this->sites );
+
+		if ( $site_ids && $this->query_vars['number'] && ! $this->query_vars['no_found_rows'] ) {
+			/**
+			 * Filter the query used to retrieve found site count.
+			 *
+			 * @since 4.6.0
+			 *
+			 * @param string $found_sites_query SQL query. Default 'SELECT FOUND_ROWS()'.
+			 * @param WP_Site_Query $site_query The `WP_Site_Query` instance.
+			 */
+			$found_sites_query = apply_filters( 'found_sites_query', 'SELECT FOUND_ROWS()', $this );
+			$this->found_sites = (int) $wpdb->get_var( $found_sites_query );
+
+			$this->max_num_pages = ceil( $this->found_sites / $this->query_vars['number'] );
+		}
+
+		if ( 'ids' == $this->query_vars['fields'] ) {
+			$this->sites = $site_ids;
+
+			return $this->sites;
+		}
+
+		// Fetch full site objects from the primed cache.
+		$_sites = array();
+		foreach ( $site_ids as $site_id ) {
+			if ( $_site = get_site( $site_id ) ) {
+				$_sites[] = $_site;
+			}
+		}
+
+		// Prime site network caches.
+		if ( $this->query_vars['update_site_cache'] ) {
+			$site_ids = array();
+			foreach ( $_sites as $_site ) {
+				$site_ids[] = $_site->site_id;
+			}
+			_prime_site_caches( $site_ids );
+		}
+
+		/**
+		 * Filter the site query results.
+		 *
+		 * @since 4.6.0
+		 *
+		 * @param array $results An array of sites.
+		 * @param WP_Site_Query &$this Current instance of WP_Site_Query, passed by reference.
+		 */
+		$_sites = apply_filters_ref_array( 'the_sites', array( $_sites, &$this ) );
+
+		// Convert to WP_Site instances
+		$sites = array_map( 'get_site', $_sites );
+
+		$this->sites = $sites;
+
+		return $this->sites;
+	}
+
+	/**
+	 * Used internally to get a list of site IDs matching the query vars.
+	 *
+	 * @since 4.6.0
+	 * @access protected
+	 *
+	 * @global wpdb $wpdb WordPress database abstraction object.
+	 */
+	protected function get_site_ids() {
+		global $wpdb;
+
+		$order = ( 'ASC' == strtoupper( $this->query_vars['order'] ) ) ? 'ASC' : 'DESC';
+
+		// Disable ORDER BY with 'none', an empty array, or boolean false.
+		if ( in_array( $this->query_vars['orderby'], array( 'none', array(), false ), true ) ) {
+			$orderby = '';
+		} elseif ( ! empty( $this->query_vars['orderby'] ) ) {
+			$ordersby = is_array( $this->query_vars['orderby'] ) ?
+				$this->query_vars['orderby'] :
+				preg_split( '/[,\s]/', $this->query_vars['orderby'] );
+
+			$orderby_array         = array();
+			$found_orderby_blog_id = false;
+			foreach ( $ordersby as $_key => $_value ) {
+				if ( ! $_value ) {
+					continue;
+				}
+
+				if ( is_int( $_key ) ) {
+					$_orderby = $_value;
+					$_order   = $order;
+				} else {
+					$_orderby = $_key;
+					$_order   = $_value;
+				}
+
+				if ( ! $found_orderby_blog_id && in_array( $_orderby, array( 'blog_id', 'site__in' ) ) ) {
+					$found_orderby_blog_id = true;
+				}
+
+				$parsed = $this->parse_orderby( $_orderby );
+
+				if ( ! $parsed ) {
+					continue;
+				}
+
+				if ( 'site__in' === $_orderby ) {
+					$orderby_array[] = $parsed;
+					continue;
+				}
+
+				$orderby_array[] = $parsed . ' ' . $this->parse_order( $_order );
+			}
+
+			$orderby = implode( ', ', $orderby_array );
+		} else {
+			$orderby = "blog_id $order";
+		}
+
+		$number = absint( $this->query_vars['number'] );
+		$offset = absint( $this->query_vars['offset'] );
+
+		if ( ! empty( $number ) ) {
+			if ( $offset ) {
+				$limits = 'LIMIT ' . $offset . ',' . $number;
+			} else {
+				$limits = 'LIMIT ' . $number;
+			}
+		}
+
+		if ( $this->query_vars['count'] ) {
+			$fields = 'COUNT(*)';
+		} else {
+			$fields = "blog_id";
+		}
+
+		// Parse site IDs for an IN clause.
+		$site_id = absint( $this->query_vars['ID'] );
+		if ( ! empty( $site_id ) ) {
+			$this->sql_clauses['where']['ID'] = $wpdb->prepare( 'blog_id = %d', $site_id );
+		}
+
+		// Parse site IDs for an IN clause.
+		if ( ! empty( $this->query_vars['site__in'] ) ) {
+			$this->sql_clauses['where']['site__in'] = "blog_id IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['site__in'] ) ) . ' )';
+		}
+
+		// Parse site IDs for a NOT IN clause.
+		if ( ! empty( $this->query_vars['site__not_in'] ) ) {
+			$this->sql_clauses['where']['site__not_in'] = "blog_id NOT IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['site__not_in'] ) ) . ' )';
+		}
+
+		$network_id = absint( $this->query_vars['network_id'] );
+		if ( ! empty( $network_id ) ) {
+			$this->sql_clauses['where']['network_id'] = $wpdb->prepare( 'site_id = %d', $network_id );
+		}
+
+		// Parse site network IDs for an IN clause.
+		if ( ! empty( $this->query_vars['network__in'] ) ) {
+			$this->sql_clauses['where']['network__in'] = 'site_id IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['network__in'] ) ) . ' )';
+		}
+
+		// Parse site network IDs for a NOT IN clause.
+		if ( ! empty( $this->query_vars['network__not_in'] ) ) {
+			$this->sql_clauses['where']['network__not_in'] = 'site_id NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['network__not_in'] ) ) . ' )';
+		}
+
+
+		if ( ! empty( $this->query_vars['domain'] ) ) {
+			$this->sql_clauses['where']['domain'] = $wpdb->prepare( 'domain = %s', $this->query_vars['domain'] );
+		}
+
+		// Parse site domain for an IN clause.
+		if ( is_array( $this->query_vars['domain__in'] ) ) {
+			$this->sql_clauses['where']['domain__in'] = "domain IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['domain__in'] ) ) . "' )";
+		}
+
+		// Parse site domain for a NOT IN clause.
+		if ( is_array( $this->query_vars['domain__not_in'] ) ) {
+			$this->sql_clauses['where']['domain__not_in'] = "domain NOT IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['domain__not_in'] ) ) . "' )";
+		}
+
+
+		if ( ! empty( $this->query_vars['path'] ) ) {
+			$this->sql_clauses['where']['path'] = $wpdb->prepare( 'path = %s', $this->query_vars['path'] );
+		}
+
+		// Parse site path for an IN clause.
+		if ( is_array( $this->query_vars['path__in'] ) ) {
+			$this->sql_clauses['where']['path__in'] = "path IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['path__in'] ) ) . "' )";
+		}
+
+		// Parse site path for a NOT IN clause.
+		if ( is_array( $this->query_vars['path__not_in'] ) ) {
+			$this->sql_clauses['where']['path__not_in'] = "path NOT IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['path__not_in'] ) ) . "' )";
+		}
+
+
+		if ( is_numeric( $this->query_vars['archived'] ) ) {
+			$archived                               = absint( $this->query_vars['archived'] );
+			$this->sql_clauses['where']['archived'] = $wpdb->prepare( "archived = %d ", $archived );
+		}
+
+		if ( is_numeric( $this->query_vars['mature'] ) ) {
+			$mature                               = absint( $this->query_vars['mature'] );
+			$this->sql_clauses['where']['mature'] = $wpdb->prepare( "mature = %d ", $mature );
+		}
+
+		if ( is_numeric( $this->query_vars['spam'] ) ) {
+			$spam                               = absint( $this->query_vars['spam'] );
+			$this->sql_clauses['where']['spam'] = $wpdb->prepare( "spam = %d ", $spam );
+		}
+
+		if ( is_numeric( $this->query_vars['deleted'] ) ) {
+			$deleted                               = absint( $this->query_vars['deleted'] );
+			$this->sql_clauses['where']['deleted'] = $wpdb->prepare( "deleted = %d ", $deleted );
+		}
+
+		// Falsy search strings are ignored.
+		if ( strlen( $this->query_vars['search'] ) ) {
+			$search_sql = $this->get_search_sql(
+				$this->query_vars['search'],
+				array( 'domain', 'path' )
+			);
+
+			// Strip leading 'AND'.
+			$this->sql_clauses['where']['search'] = preg_replace( '/^\s*AND\s*/', '', $search_sql );
+		}
+
+		$date_query = $this->query_vars['date_query'];
+		if ( ! empty( $date_query ) && is_array( $date_query ) ) {
+			$date_query_object                        = new WP_Date_Query( $date_query, 'registered' );
+			$this->sql_clauses['where']['date_query'] = preg_replace( '/^\s*AND\s*/', '', $date_query_object->get_sql() );
+		}
+
+		$where = implode( ' AND ', $this->sql_clauses['where'] );
+
+		$pieces = array( 'fields', 'join', 'where', 'orderby', 'limits', 'groupby' );
+		/**
+		 * Filter the site query clauses.
+		 *
+		 * @since 4.6.0
+		 *
+		 * @param array $pieces A compacted array of site query clauses.
+		 * @param WP_Site_Query &$this Current instance of WP_Site_Query, passed by reference.
+		 */
+		$clauses = apply_filters_ref_array( 'sites_clauses', array( compact( $pieces ), &$this ) );
+		$fields  = isset( $clauses['fields'] ) ? $clauses['fields'] : '';
+		$join    = isset( $clauses['join'] ) ? $clauses['join'] : '';
+		$where   = isset( $clauses['where'] ) ? $clauses['where'] : '';
+		$orderby = isset( $clauses['orderby'] ) ? $clauses['orderby'] : '';
+		$limits  = isset( $clauses['limits'] ) ? $clauses['limits'] : '';
+		$groupby = isset( $clauses['groupby'] ) ? $clauses['groupby'] : '';
+
+		$this->filtered_where_clause = $where;
+
+		if ( $where ) {
+			$where = 'WHERE ' . $where;
+		}
+
+		if ( $groupby ) {
+			$groupby = 'GROUP BY ' . $groupby;
+		}
+
+		if ( $orderby ) {
+			$orderby = "ORDER BY $orderby";
+		}
+
+		$found_rows = '';
+		if ( ! $this->query_vars['no_found_rows'] ) {
+			$found_rows = 'SQL_CALC_FOUND_ROWS';
+		}
+
+		$this->sql_clauses['select']  = "SELECT $found_rows $fields";
+		$this->sql_clauses['from']    = "FROM $wpdb->blogs $join";
+		$this->sql_clauses['groupby'] = $groupby;
+		$this->sql_clauses['orderby'] = $orderby;
+		$this->sql_clauses['limits']  = $limits;
+
+		$this->request = "{$this->sql_clauses['select']} {$this->sql_clauses['from']} {$where} {$this->sql_clauses['groupby']} {$this->sql_clauses['orderby']} {$this->sql_clauses['limits']}";
+
+		if ( $this->query_vars['count'] ) {
+			return intval( $wpdb->get_var( $this->request ) );
+		} else {
+			$site_ids = $wpdb->get_col( $this->request );
+
+			return array_map( 'intval', $site_ids );
+		}
+	}
+
+	/**
+	 * Used internally to generate an SQL string for searching across multiple columns
+	 *
+	 * @since 4.6.0
+	 * @access protected
+	 *
+	 * @global wpdb $wpdb WordPress database abstraction object.
+	 *
+	 * @param string $string
+	 * @param array $cols
+	 *
+	 * @return string
+	 */
+	protected function get_search_sql( $string, $cols ) {
+		global $wpdb;
+
+		$like = '%' . $wpdb->esc_like( $string ) . '%';
+
+		$searches = array();
+		foreach ( $cols as $col ) {
+			$searches[] = $wpdb->prepare( "$col LIKE %s", $like );
+		}
+
+		return ' AND (' . implode( ' OR ', $searches ) . ')';
+	}
+
+	/**
+	 * Parse and sanitize 'orderby' keys passed to the site query.
+	 *
+	 * @since 4.6.0
+	 * @access protected
+	 *
+	 * @global wpdb $wpdb WordPress database abstraction object.
+	 *
+	 * @param string $orderby Alias for the field to order by.
+	 *
+	 * @return string|false Value to used in the ORDER clause. False otherwise.
+	 */
+	protected function parse_orderby( $orderby ) {
+		global $wpdb;
+
+		switch ( $orderby ) {
+			case 'domain':
+			case 'last_updated':
+			case 'path':
+			case 'registered':
+				$_orderby = $orderby;
+				break;
+			case 'network_id':
+				$_orderby = "site_id";
+				break;
+			case 'ids':
+			default:
+				$_orderby = "blog_id";
+				break;
+		}
+
+		$parsed = "$_orderby";
+
+
+		return $parsed;
+	}
+
+	/**
+	 * Parse an 'order' query variable and cast it to ASC or DESC as necessary.
+	 *
+	 * @since 4.6.0
+	 * @access protected
+	 *
+	 * @param string $order The 'order' query variable.
+	 *
+	 * @return string The sanitized 'order' query variable.
+	 */
+	protected function parse_order( $order ) {
+		if ( ! is_string( $order ) || empty( $order ) ) {
+			return 'DESC';
+		}
+
+		if ( 'ASC' === strtoupper( $order ) ) {
+			return 'ASC';
+		} else {
+			return 'DESC';
+		}
+	}
+}

Property changes on: wp-includes/class-wp-site-query.php
___________________________________________________________________
Added: svn:executable
## -0,0 +1 ##
+*
\ No newline at end of property
Index: wp-includes/date.php
===================================================================
--- wp-includes/date.php	(revision 37134)
+++ wp-includes/date.php	(working copy)
@@ -489,9 +489,15 @@
 		global $wpdb;
 
 		$valid_columns = array(
-			'post_date', 'post_date_gmt', 'post_modified',
-			'post_modified_gmt', 'comment_date', 'comment_date_gmt',
+			'post_date',
+			'post_date_gmt',
+			'post_modified',
+			'post_modified_gmt',
+			'comment_date',
+			'comment_date_gmt',
 			'user_registered',
+			'registered',
+			'last_updated',
 		);
 
 		// Attempt to detect a table prefix.
@@ -525,6 +531,10 @@
 				$wpdb->users => array(
 					'user_registered',
 				),
+				$wpdb->blogs => array(
+					'registered',
+					'last_updated',
+				),
 			);
 
 			// If it's a known column name, add the appropriate table prefix.
Index: wp-includes/http.php
===================================================================
--- wp-includes/http.php	(revision 37134)
+++ wp-includes/http.php	(working copy)
@@ -607,15 +607,20 @@
  * @return bool
  */
 function ms_allowed_http_request_hosts( $is_external, $host ) {
-	global $wpdb;
 	static $queried = array();
-	if ( $is_external )
+	if ( $is_external ) {
 		return $is_external;
-	if ( $host === get_current_site()->domain )
+	}
+	if ( $host === get_current_site()->domain ) {
 		return true;
-	if ( isset( $queried[ $host ] ) )
+	}
+	if ( isset( $queried[ $host ] ) ) {
 		return $queried[ $host ];
-	$queried[ $host ] = (bool) $wpdb->get_var( $wpdb->prepare( "SELECT domain FROM $wpdb->blogs WHERE domain = %s LIMIT 1", $host ) );
+	}
+	$query            = new WP_Site_Query();
+	$result           = $query->query( array( 'domain' => $host, 'count' => true ) );
+	$queried[ $host ] = (bool) $result;
+
 	return $queried[ $host ];
 }
 
Index: wp-includes/ms-blogs.php
===================================================================
--- wp-includes/ms-blogs.php	(revision 37134)
+++ wp-includes/ms-blogs.php	(working copy)
@@ -99,8 +99,12 @@
 		$path = $current_site->path . $slug . '/';
 	}
 
-	$blog_id = $wpdb->get_var( $wpdb->prepare("SELECT blog_id FROM {$wpdb->blogs} WHERE domain = %s AND path = %s", $domain, $path) );
+	$query   = new WP_Site_Query();
+	$result  = $query->query( array( 'domain' => $domain, 'path' => $path, 'fields' => 'ids' ) );
+	$blog_id = array_shift( $result );
+
 	wp_cache_set( 'get_id_from_blogname_' . $slug, $blog_id, 'blog-details' );
+
 	return $blog_id;
 }
 
@@ -126,14 +130,20 @@
 		} elseif ( isset($fields['domain']) && isset($fields['path']) ) {
 			$key = md5( $fields['domain'] . $fields['path'] );
 			$blog = wp_cache_get($key, 'blog-lookup');
-			if ( false !== $blog )
+			if ( false !== $blog ) {
 				return $blog;
+			}
+
+			$domains = array( $fields['domain'] );
 			if ( substr( $fields['domain'], 0, 4 ) == 'www.' ) {
-				$nowww = substr( $fields['domain'], 4 );
-				$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'] ) );
-			} else {
-				$blog = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->blogs WHERE domain = %s AND path = %s", $fields['domain'], $fields['path'] ) );
+				$domains[] = substr( $fields['domain'], 4 );
 			}
+
+			$query  = new WP_Site_Query();
+			$args = array( 'domain__in' => $domains, 'path' => $fields['path'], 'number' => 1 );
+			$result = $query->query( $args );
+			$blog   = array_shift( $result );
+
 			if ( $blog ) {
 				wp_cache_set($blog->blog_id . 'short', $blog, 'blog-details');
 				$blog_id = $blog->blog_id;
@@ -143,14 +153,19 @@
 		} elseif ( isset($fields['domain']) && is_subdomain_install() ) {
 			$key = md5( $fields['domain'] );
 			$blog = wp_cache_get($key, 'blog-lookup');
-			if ( false !== $blog )
+			if ( false !== $blog ) {
 				return $blog;
+			}
+			$domains = array($fields['domain']);
 			if ( substr( $fields['domain'], 0, 4 ) == 'www.' ) {
-				$nowww = substr( $fields['domain'], 4 );
-				$blog = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->blogs WHERE domain IN (%s,%s) ORDER BY CHAR_LENGTH(domain) DESC", $nowww, $fields['domain'] ) );
-			} else {
-				$blog = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->blogs WHERE domain = %s", $fields['domain'] ) );
+				$domains[] = substr( $fields['domain'], 4 );
 			}
+
+			$query = new WP_Site_Query();
+			$args = array( 'domain__in' => $domains, 'number' => 1 );
+			$result = $query->query( $args );
+			$blog   = array_shift( $result );
+
 			if ( $blog ) {
 				wp_cache_set($blog->blog_id . 'short', $blog, 'blog-details');
 				$blog_id = $blog->blog_id;
@@ -457,6 +472,100 @@
 }
 
 /**
+ * Retrieves site data given a site ID or site object.
+ *
+ * If an object is passed then the site data will be cached and then returned
+ * after being passed through a filter. If the site is empty, then the global
+ * site variable will be used, if it is set.
+ *
+ * @since 4.6.0
+ *
+ * @global WP_Site $site
+ *
+ * @param WP_Site|string|int $site Site to retrieve.
+ * @param string $output Optional. OBJECT or ARRAY_A or ARRAY_N constants.
+ *
+ * @return WP_Site|array|null Depends on $output value.
+ */
+function get_site( &$site = null, $output = OBJECT ) {
+	global $current_blog;
+	if ( empty( $site ) && isset( $current_blog ) ) {
+		$site = $current_blog;
+	}
+
+	if ( $site instanceof WP_Site ) {
+		$_site = $site;
+	} elseif ( is_object( $site ) ) {
+		$_site = new WP_Site( $site );
+	} else {
+		$_site = WP_Site::get_instance( $site );
+	}
+
+	if ( ! $_site ) {
+		return null;
+	}
+
+	/**
+	 * Fires after a site is retrieved.
+	 *
+	 * @since 4.6.0
+	 *
+	 * @param mixed $_site Site data.
+	 */
+	$_site = apply_filters( 'get_site', $_site );
+
+	if ( $output == OBJECT ) {
+		return $_site;
+	} elseif ( $output == ARRAY_A ) {
+		return $_site->to_array();
+	} elseif ( $output == ARRAY_N ) {
+		return array_values( $_site->to_array() );
+	}
+
+	return $_site;
+}
+
+/**
+ * Adds any sites from the given ids to the cache that do not already exist in cache
+ *
+ * @since 4.6.0
+ * @access private
+ *
+ * @see update_site_cache()
+ *
+ * @global wpdb $wpdb WordPress database abstraction object.
+ *
+ * @param array $ids ID list.
+ */
+function _prime_site_caches( $ids ) {
+	global $wpdb;
+
+	$non_cached_ids = _get_non_cached_ids( $ids, 'sites' );
+	if ( ! empty( $non_cached_ids ) ) {
+		$fresh_sites = $wpdb->get_results( sprintf( "SELECT * FROM $wpdb->blogs WHERE blog_id IN (%s)", join( ",", $non_cached_ids ) ) );
+
+		update_site_cache( $fresh_sites );
+	}
+}
+
+/**
+ * Updates sites in cache.
+ *
+ * @since 4.6.0
+ *
+ * @param array $sites Array of site objects, passed by reference.
+ */
+function update_site_cache( &$sites ) {
+	if ( ! $sites ) {
+		return;
+	}
+
+	foreach ( $sites as $site ) {
+		wp_cache_add( $site->blog_id, $site, 'sites' );
+	}
+}
+
+/**
  * Retrieve option value for a given blog id based on name of option.
  *
  * If the option does not exist or does not have a value, then the return value
Index: wp-includes/ms-functions.php
===================================================================
--- wp-includes/ms-functions.php	(revision 37134)
+++ wp-includes/ms-functions.php	(working copy)
@@ -37,19 +37,22 @@
  * @global wpdb $wpdb WordPress database abstraction object.
  *
  * @param int $user_id The unique ID of the user
+ *
  * @return WP_Site|void The blog object
  */
 function get_active_blog_for_user( $user_id ) {
 	global $wpdb;
 	$blogs = get_blogs_of_user( $user_id );
-	if ( empty( $blogs ) )
+	if ( empty( $blogs ) ) {
 		return;
+	}
 
-	if ( !is_multisite() )
-		return $blogs[$wpdb->blogid];
+	if ( ! is_multisite() ) {
+		return $blogs[ $wpdb->blogid ];
+	}
 
 	$primary_blog = get_user_meta( $user_id, 'primary_blog', true );
-	$first_blog = current($blogs);
+	$first_blog   = current( $blogs );
 	if ( false !== $primary_blog ) {
 		if ( ! isset( $blogs[ $primary_blog ] ) ) {
 			update_user_meta( $user_id, 'primary_blog', $first_blog->userblog_id );
@@ -66,18 +69,21 @@
 
 	if ( ( ! is_object( $primary ) ) || ( $primary->archived == 1 || $primary->spam == 1 || $primary->deleted == 1 ) ) {
 		$blogs = get_blogs_of_user( $user_id, true ); // if a user's primary blog is shut down, check their other blogs.
-		$ret = false;
+		$ret   = false;
 		if ( is_array( $blogs ) && count( $blogs ) > 0 ) {
 			foreach ( (array) $blogs as $blog_id => $blog ) {
-				if ( $blog->site_id != $wpdb->siteid )
+				if ( $blog->site_id != $wpdb->siteid ) {
 					continue;
+				}
 				$details = get_blog_details( $blog_id );
 				if ( is_object( $details ) && $details->archived == 0 && $details->spam == 0 && $details->deleted == 0 ) {
 					$ret = $blog;
-					if ( get_user_meta( $user_id , 'primary_blog', true ) != $blog_id )
+					if ( get_user_meta( $user_id, 'primary_blog', true ) != $blog_id ) {
 						update_user_meta( $user_id, 'primary_blog', $blog_id );
-					if ( !get_user_meta($user_id , 'source_domain', true) )
+					}
+					if ( ! get_user_meta( $user_id, 'source_domain', true ) ) {
 						update_user_meta( $user_id, 'source_domain', $blog->domain );
+					}
 					break;
 				}
 			}
@@ -84,6 +90,7 @@
 		} else {
 			return;
 		}
+
 		return $ret;
 	} else {
 		return $primary;
@@ -111,11 +118,13 @@
  * @since MU 1.0
  *
  * @param int $network_id Deprecated, not supported.
+ *
  * @return int
  */
 function get_blog_count( $network_id = 0 ) {
-	if ( func_num_args() )
+	if ( func_num_args() ) {
 		_deprecated_argument( __FUNCTION__, '3.1' );
+	}
 
 	return get_site_option( 'blog_count' );
 }
@@ -127,6 +136,7 @@
  *
  * @param int $blog_id ID of the blog.
  * @param int $post_id ID of the post you're looking for.
+ *
  * @return WP_Post|null WP_Post on success or null on failure
  */
 function get_blog_post( $blog_id, $post_id ) {
@@ -145,28 +155,30 @@
  *
  * @since MU 1.0
  *
- * @param int    $blog_id ID of the blog you're adding the user to.
- * @param int    $user_id ID of the user you're adding.
- * @param string $role    The role you want the user to have
+ * @param int $blog_id ID of the blog you're adding the user to.
+ * @param int $user_id ID of the user you're adding.
+ * @param string $role The role you want the user to have
+ *
  * @return true|WP_Error
  */
 function add_user_to_blog( $blog_id, $user_id, $role ) {
-	switch_to_blog($blog_id);
+	switch_to_blog( $blog_id );
 
 	$user = get_userdata( $user_id );
 
 	if ( ! $user ) {
 		restore_current_blog();
+
 		return new WP_Error( 'user_does_not_exist', __( 'The requested user does not exist.' ) );
 	}
 
-	if ( !get_user_meta($user_id, 'primary_blog', true) ) {
-		update_user_meta($user_id, 'primary_blog', $blog_id);
-		$details = get_blog_details($blog_id);
-		update_user_meta($user_id, 'source_domain', $details->domain);
+	if ( ! get_user_meta( $user_id, 'primary_blog', true ) ) {
+		update_user_meta( $user_id, 'primary_blog', $blog_id );
+		$details = get_blog_details( $blog_id );
+		update_user_meta( $user_id, 'source_domain', $details->domain );
 	}
 
-	$user->set_role($role);
+	$user->set_role( $role );
 
 	/**
 	 * Fires immediately after a user is added to a site.
@@ -173,14 +185,15 @@
 	 *
 	 * @since MU
 	 *
-	 * @param int    $user_id User ID.
-	 * @param string $role    User role.
-	 * @param int    $blog_id Blog ID.
+	 * @param int $user_id User ID.
+	 * @param string $role User role.
+	 * @param int $blog_id Blog ID.
 	 */
 	do_action( 'add_user_to_blog', $user_id, $role, $blog_id );
 	wp_cache_delete( $user_id, 'users' );
 	wp_cache_delete( $blog_id . '_user_count', 'blog-details' );
 	restore_current_blog();
+
 	return true;
 }
 
@@ -197,14 +210,15 @@
  *
  * @global wpdb $wpdb WordPress database abstraction object.
  *
- * @param int    $user_id  ID of the user you're removing.
- * @param int    $blog_id  ID of the blog you're removing the user from.
+ * @param int $user_id ID of the user you're removing.
+ * @param int $blog_id ID of the blog you're removing the user from.
  * @param string $reassign Optional. A user to whom to reassign posts.
+ *
  * @return true|WP_Error
  */
-function remove_user_from_blog($user_id, $blog_id = '', $reassign = '') {
+function remove_user_from_blog( $user_id, $blog_id = '', $reassign = '' ) {
 	global $wpdb;
-	switch_to_blog($blog_id);
+	switch_to_blog( $blog_id );
 	$user_id = (int) $user_id;
 	/**
 	 * Fires before a user is removed from a site.
@@ -218,21 +232,22 @@
 
 	// If being removed from the primary blog, set a new primary if the user is assigned
 	// to multiple blogs.
-	$primary_blog = get_user_meta($user_id, 'primary_blog', true);
+	$primary_blog = get_user_meta( $user_id, 'primary_blog', true );
 	if ( $primary_blog == $blog_id ) {
-		$new_id = '';
+		$new_id     = '';
 		$new_domain = '';
-		$blogs = get_blogs_of_user($user_id);
+		$blogs      = get_blogs_of_user( $user_id );
 		foreach ( (array) $blogs as $blog ) {
-			if ( $blog->userblog_id == $blog_id )
+			if ( $blog->userblog_id == $blog_id ) {
 				continue;
-			$new_id = $blog->userblog_id;
+			}
+			$new_id     = $blog->userblog_id;
 			$new_domain = $blog->domain;
 			break;
 		}
 
-		update_user_meta($user_id, 'primary_blog', $new_id);
-		update_user_meta($user_id, 'source_domain', $new_domain);
+		update_user_meta( $user_id, 'primary_blog', $new_id );
+		update_user_meta( $user_id, 'source_domain', $new_domain );
 	}
 
 	// wp_revoke_user($user_id);
@@ -239,15 +254,16 @@
 	$user = get_userdata( $user_id );
 	if ( ! $user ) {
 		restore_current_blog();
-		return new WP_Error('user_does_not_exist', __('That user does not exist.'));
+
+		return new WP_Error( 'user_does_not_exist', __( 'That user does not exist.' ) );
 	}
 
 	$user->remove_all_caps();
 
-	$blogs = get_blogs_of_user($user_id);
-	if ( count($blogs) == 0 ) {
-		update_user_meta($user_id, 'primary_blog', '');
-		update_user_meta($user_id, 'source_domain', '');
+	$blogs = get_blogs_of_user( $user_id );
+	if ( count( $blogs ) == 0 ) {
+		update_user_meta( $user_id, 'primary_blog', '' );
+		update_user_meta( $user_id, 'source_domain', '' );
 	}
 
 	if ( $reassign != '' ) {
@@ -278,6 +294,7 @@
  *
  * @param int $blog_id ID of the source blog.
  * @param int $post_id ID of the desired post.
+ *
  * @return string The post's permalink
  */
 function get_blog_permalink( $blog_id, $post_id ) {
@@ -301,7 +318,8 @@
  * @global wpdb $wpdb WordPress database abstraction object.
  *
  * @param string $domain
- * @param string $path   Optional. Not required for subdomain installations.
+ * @param string $path Optional. Not required for subdomain installations.
+ *
  * @return int 0 if no blog found, otherwise the ID of the matching blog
  */
 function get_blog_id_from_url( $domain, $path = '/' ) {
@@ -308,18 +326,22 @@
 	global $wpdb;
 
 	$domain = strtolower( $domain );
-	$path = strtolower( $path );
-	$id = wp_cache_get( md5( $domain . $path ), 'blog-id-cache' );
+	$path   = strtolower( $path );
+	$id     = wp_cache_get( md5( $domain . $path ), 'blog-id-cache' );
 
-	if ( $id == -1 ) // blog does not exist
+	if ( $id == - 1 ) // blog does not exist
+	{
 		return 0;
-	elseif ( $id )
+	} elseif ( $id ) {
 		return (int) $id;
+	}
 
-	$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 ) );
+	$query  = new WP_Site_Query();
+	$result = $query->query( array( 'domain' => $domain, 'path' => $path, 'fields' => 'ids' ) );
+	$id     = array_shift( $result );
+	if ( ! $id ) {
+		wp_cache_set( md5( $domain . $path ), - 1, 'blog-id-cache' );
 
-	if ( ! $id ) {
-		wp_cache_set( md5( $domain . $path ), -1, 'blog-id-cache' );
 		return 0;
 	}
 
@@ -341,24 +363,27 @@
  * @since MU
  *
  * @param string $user_email The email provided by the user at registration.
+ *
  * @return bool Returns true when the email address is banned.
  */
 function is_email_address_unsafe( $user_email ) {
 	$banned_names = get_site_option( 'banned_email_domains' );
-	if ( $banned_names && ! is_array( $banned_names ) )
+	if ( $banned_names && ! is_array( $banned_names ) ) {
 		$banned_names = explode( "\n", $banned_names );
+	}
 
 	$is_email_address_unsafe = false;
 
 	if ( $banned_names && is_array( $banned_names ) ) {
-		$banned_names = array_map( 'strtolower', $banned_names );
+		$banned_names     = array_map( 'strtolower', $banned_names );
 		$normalized_email = strtolower( $user_email );
 
 		list( $email_local_part, $email_domain ) = explode( '@', $normalized_email );
 
 		foreach ( $banned_names as $banned_domain ) {
-			if ( ! $banned_domain )
+			if ( ! $banned_domain ) {
 				continue;
+			}
 
 			if ( $email_domain == $banned_domain ) {
 				$is_email_address_unsafe = true;
@@ -366,7 +391,7 @@
 			}
 
 			$dotted_domain = ".$banned_domain";
-			if ( $dotted_domain === substr( $normalized_email, -strlen( $dotted_domain ) ) ) {
+			if ( $dotted_domain === substr( $normalized_email, - strlen( $dotted_domain ) ) ) {
 				$is_email_address_unsafe = true;
 				break;
 			}
@@ -378,8 +403,8 @@
 	 *
 	 * @since 3.5.0
 	 *
-	 * @param bool   $is_email_address_unsafe Whether the email address is "unsafe". Default false.
-	 * @param string $user_email              User email address.
+	 * @param bool $is_email_address_unsafe Whether the email address is "unsafe". Default false.
+	 * @param string $user_email User email address.
 	 */
 	return apply_filters( 'is_email_address_unsafe', $is_email_address_unsafe, $user_email );
 }
@@ -400,17 +425,18 @@
  *
  * @global wpdb $wpdb WordPress database abstraction object.
  *
- * @param string $user_name  The login name provided by the user.
+ * @param string $user_name The login name provided by the user.
  * @param string $user_email The email provided by the user.
+ *
  * @return array Contains username, email, and error messages.
  */
-function wpmu_validate_user_signup($user_name, $user_email) {
+function wpmu_validate_user_signup( $user_name, $user_email ) {
 	global $wpdb;
 
 	$errors = new WP_Error();
 
 	$orig_username = $user_name;
-	$user_name = preg_replace( '/\s+/', '', sanitize_user( $user_name, true ) );
+	$user_name     = preg_replace( '/\s+/', '', sanitize_user( $user_name, true ) );
 
 	if ( $user_name != $orig_username || preg_match( '/[^a-z0-9]/', $user_name ) ) {
 		$errors->add( 'user_name', __( 'Usernames can only contain lowercase letters (a-z) and numbers.' ) );
@@ -419,16 +445,17 @@
 
 	$user_email = sanitize_email( $user_email );
 
-	if ( empty( $user_name ) )
-	   	$errors->add('user_name', __( 'Please enter a username.' ) );
+	if ( empty( $user_name ) ) {
+		$errors->add( 'user_name', __( 'Please enter a username.' ) );
+	}
 
 	$illegal_names = get_site_option( 'illegal_names' );
 	if ( ! is_array( $illegal_names ) ) {
-		$illegal_names = array(  'www', 'web', 'root', 'admin', 'main', 'invite', 'administrator' );
+		$illegal_names = array( 'www', 'web', 'root', 'admin', 'main', 'invite', 'administrator' );
 		add_site_option( 'illegal_names', $illegal_names );
 	}
 	if ( in_array( $user_name, $illegal_names ) ) {
-		$errors->add( 'user_name',  __( 'Sorry, that username is not allowed.' ) );
+		$errors->add( 'user_name', __( 'Sorry, that username is not allowed.' ) );
 	}
 
 	/** This filter is documented in wp-includes/user.php */
@@ -435,14 +462,16 @@
 	$illegal_logins = (array) apply_filters( 'illegal_user_logins', array() );
 
 	if ( in_array( strtolower( $user_name ), array_map( 'strtolower', $illegal_logins ) ) ) {
-		$errors->add( 'user_name',  __( 'Sorry, that username is not allowed.' ) );
+		$errors->add( 'user_name', __( 'Sorry, that username is not allowed.' ) );
 	}
 
-	if ( is_email_address_unsafe( $user_email ) )
-		$errors->add('user_email',  __('You cannot use that email address to signup. We are having problems with them blocking some of our email. Please use another email provider.'));
+	if ( is_email_address_unsafe( $user_email ) ) {
+		$errors->add( 'user_email', __( 'You cannot use that email address to signup. We are having problems with them blocking some of our email. Please use another email provider.' ) );
+	}
 
-	if ( strlen( $user_name ) < 4 )
-		$errors->add('user_name',  __( 'Username must be at least 4 characters.' ) );
+	if ( strlen( $user_name ) < 4 ) {
+		$errors->add( 'user_name', __( 'Username must be at least 4 characters.' ) );
+	}
 
 	if ( strlen( $user_name ) > 60 ) {
 		$errors->add( 'user_name', __( 'Username may not be longer than 60 characters.' ) );
@@ -449,52 +478,62 @@
 	}
 
 	// all numeric?
-	if ( preg_match( '/^[0-9]*$/', $user_name ) )
-		$errors->add('user_name', __('Sorry, usernames must have letters too!'));
+	if ( preg_match( '/^[0-9]*$/', $user_name ) ) {
+		$errors->add( 'user_name', __( 'Sorry, usernames must have letters too!' ) );
+	}
 
-	if ( !is_email( $user_email ) )
-		$errors->add('user_email', __( 'Please enter a valid email address.' ) );
+	if ( ! is_email( $user_email ) ) {
+		$errors->add( 'user_email', __( 'Please enter a valid email address.' ) );
+	}
 
 	$limited_email_domains = get_site_option( 'limited_email_domains' );
 	if ( is_array( $limited_email_domains ) && ! empty( $limited_email_domains ) ) {
 		$emaildomain = substr( $user_email, 1 + strpos( $user_email, '@' ) );
 		if ( ! in_array( $emaildomain, $limited_email_domains ) ) {
-			$errors->add('user_email', __('Sorry, that email address is not allowed!'));
+			$errors->add( 'user_email', __( 'Sorry, that email address is not allowed!' ) );
 		}
 	}
 
 	// Check if the username has been used already.
-	if ( username_exists($user_name) )
+	if ( username_exists( $user_name ) ) {
 		$errors->add( 'user_name', __( 'Sorry, that username already exists!' ) );
+	}
 
 	// Check if the email address has been used already.
-	if ( email_exists($user_email) )
+	if ( email_exists( $user_email ) ) {
 		$errors->add( 'user_email', __( 'Sorry, that email address is already used!' ) );
+	}
 
 	// Has someone already signed up for this username?
-	$signup = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->signups WHERE user_login = %s", $user_name) );
+	$signup = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->signups WHERE user_login = %s", $user_name ) );
 	if ( $signup != null ) {
-		$registered_at =  mysql2date('U', $signup->registered);
-		$now = current_time( 'timestamp', true );
-		$diff = $now - $registered_at;
+		$registered_at = mysql2date( 'U', $signup->registered );
+		$now           = current_time( 'timestamp', true );
+		$diff          = $now - $registered_at;
 		// If registered more than two days ago, cancel registration and let this signup go through.
-		if ( $diff > 2 * DAY_IN_SECONDS )
+		if ( $diff > 2 * DAY_IN_SECONDS ) {
 			$wpdb->delete( $wpdb->signups, array( 'user_login' => $user_name ) );
-		else
-			$errors->add('user_name', __('That username is currently reserved but may be available in a couple of days.'));
+		} else {
+			$errors->add( 'user_name', __( 'That username is currently reserved but may be available in a couple of days.' ) );
+		}
 	}
 
-	$signup = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->signups WHERE user_email = %s", $user_email) );
+	$signup = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->signups WHERE user_email = %s", $user_email ) );
 	if ( $signup != null ) {
-		$diff = current_time( 'timestamp', true ) - mysql2date('U', $signup->registered);
+		$diff = current_time( 'timestamp', true ) - mysql2date( 'U', $signup->registered );
 		// If registered more than two days ago, cancel registration and let this signup go through.
-		if ( $diff > 2 * DAY_IN_SECONDS )
+		if ( $diff > 2 * DAY_IN_SECONDS ) {
 			$wpdb->delete( $wpdb->signups, array( 'user_email' => $user_email ) );
-		else
-			$errors->add('user_email', __('That email address has already been used. Please check your inbox for an activation email. It will become available in a couple of days if you do nothing.'));
+		} else {
+			$errors->add( 'user_email', __( 'That email address has already been used. Please check your inbox for an activation email. It will become available in a couple of days if you do nothing.' ) );
+		}
 	}
 
-	$result = array('user_name' => $user_name, 'orig_username' => $orig_username, 'user_email' => $user_email, 'errors' => $errors);
+	$result = array( 'user_name'     => $user_name,
+	                 'orig_username' => $orig_username,
+	                 'user_email'    => $user_email,
+	                 'errors'        => $errors
+	);
 
 	/**
 	 * Filter the validated user registration details.
@@ -507,10 +546,10 @@
 	 * @param array $result {
 	 *     The array of user name, email and the error messages.
 	 *
-	 *     @type string   $user_name     Sanitized and unique username.
-	 *     @type string   $orig_username Original username.
-	 *     @type string   $user_email    User email address.
-	 *     @type WP_Error $errors        WP_Error object containing any errors found.
+	 * @type string $user_name Sanitized and unique username.
+	 * @type string $orig_username Original username.
+	 * @type string $user_email User email address.
+	 * @type WP_Error $errors WP_Error object containing any errors found.
 	 * }
 	 */
 	return apply_filters( 'wpmu_validate_user_signup', $result );
@@ -532,12 +571,13 @@
  *
  * @since MU
  *
- * @global wpdb   $wpdb
+ * @global wpdb $wpdb
  * @global string $domain
  *
- * @param string         $blogname   The blog name provided by the user. Must be unique.
- * @param string         $blog_title The blog title provided by the user.
- * @param WP_User|string $user       Optional. The user object to check against the new site name.
+ * @param string $blogname The blog name provided by the user. Must be unique.
+ * @param string $blog_title The blog title provided by the user.
+ * @param WP_User|string $user Optional. The user object to check against the new site name.
+ *
  * @return array Contains the new site data and error messages.
  */
 function wpmu_validate_blog_signup( $blogname, $blog_title, $user = '' ) {
@@ -544,11 +584,11 @@
 	global $wpdb, $domain;
 
 	$current_site = get_current_site();
-	$base = $current_site->path;
+	$base         = $current_site->path;
 
 	$blog_title = strip_tags( $blog_title );
 
-	$errors = new WP_Error();
+	$errors        = new WP_Error();
 	$illegal_names = get_site_option( 'illegal_names' );
 	if ( $illegal_names == false ) {
 		$illegal_names = array( 'www', 'web', 'root', 'admin', 'main', 'invite', 'administrator' );
@@ -563,26 +603,31 @@
 		$illegal_names = array_merge( $illegal_names, get_subdirectory_reserved_names() );
 	}
 
-	if ( empty( $blogname ) )
-		$errors->add('blogname', __( 'Please enter a site name.' ) );
+	if ( empty( $blogname ) ) {
+		$errors->add( 'blogname', __( 'Please enter a site name.' ) );
+	}
 
 	if ( preg_match( '/[^a-z0-9]+/', $blogname ) ) {
 		$errors->add( 'blogname', __( 'Site names can only contain lowercase letters (a-z) and numbers.' ) );
 	}
 
-	if ( in_array( $blogname, $illegal_names ) )
-		$errors->add('blogname',  __( 'That name is not allowed.' ) );
+	if ( in_array( $blogname, $illegal_names ) ) {
+		$errors->add( 'blogname', __( 'That name is not allowed.' ) );
+	}
 
-	if ( strlen( $blogname ) < 4 && !is_super_admin() )
-		$errors->add('blogname',  __( 'Site name must be at least 4 characters.' ) );
+	if ( strlen( $blogname ) < 4 && ! is_super_admin() ) {
+		$errors->add( 'blogname', __( 'Site name must be at least 4 characters.' ) );
+	}
 
 	// do not allow users to create a blog that conflicts with a page on the main blog.
-	if ( !is_subdomain_install() && $wpdb->get_var( $wpdb->prepare( "SELECT post_name FROM " . $wpdb->get_blog_prefix( $current_site->blog_id ) . "posts WHERE post_type = 'page' AND post_name = %s", $blogname ) ) )
+	if ( ! is_subdomain_install() && $wpdb->get_var( $wpdb->prepare( "SELECT post_name FROM " . $wpdb->get_blog_prefix( $current_site->blog_id ) . "posts WHERE post_type = 'page' AND post_name = %s", $blogname ) ) ) {
 		$errors->add( 'blogname', __( 'Sorry, you may not use that site name.' ) );
+	}
 
 	// all numeric?
-	if ( preg_match( '/^[0-9]*$/', $blogname ) )
-		$errors->add('blogname', __('Sorry, site names must have letters too!'));
+	if ( preg_match( '/^[0-9]*$/', $blogname ) ) {
+		$errors->add( 'blogname', __( 'Sorry, site names must have letters too!' ) );
+	}
 
 	/**
 	 * Filter the new site name during registration.
@@ -596,39 +641,49 @@
 	 */
 	$blogname = apply_filters( 'newblogname', $blogname );
 
-	$blog_title = wp_unslash(  $blog_title );
+	$blog_title = wp_unslash( $blog_title );
 
-	if ( empty( $blog_title ) )
-		$errors->add('blog_title', __( 'Please enter a site title.' ) );
+	if ( empty( $blog_title ) ) {
+		$errors->add( 'blog_title', __( 'Please enter a site title.' ) );
+	}
 
 	// Check if the domain/path has been used already.
 	if ( is_subdomain_install() ) {
 		$mydomain = $blogname . '.' . preg_replace( '|^www\.|', '', $domain );
-		$path = $base;
+		$path     = $base;
 	} else {
 		$mydomain = "$domain";
-		$path = $base.$blogname.'/';
+		$path     = $base . $blogname . '/';
 	}
-	if ( domain_exists($mydomain, $path, $current_site->id) )
+	if ( domain_exists( $mydomain, $path, $current_site->id ) ) {
 		$errors->add( 'blogname', __( 'Sorry, that site already exists!' ) );
+	}
 
 	if ( username_exists( $blogname ) ) {
-		if ( ! is_object( $user ) || ( is_object($user) && ( $user->user_login != $blogname ) ) )
+		if ( ! is_object( $user ) || ( is_object( $user ) && ( $user->user_login != $blogname ) ) ) {
 			$errors->add( 'blogname', __( 'Sorry, that site is reserved!' ) );
+		}
 	}
 
 	// Has someone already signed up for this domain?
-	$signup = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->signups WHERE domain = %s AND path = %s", $mydomain, $path) ); // TODO: Check email too?
-	if ( ! empty($signup) ) {
-		$diff = current_time( 'timestamp', true ) - mysql2date('U', $signup->registered);
+	$signup = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->signups WHERE domain = %s AND path = %s", $mydomain, $path ) ); // TODO: Check email too?
+	if ( ! empty( $signup ) ) {
+		$diff = current_time( 'timestamp', true ) - mysql2date( 'U', $signup->registered );
 		// If registered more than two days ago, cancel registration and let this signup go through.
-		if ( $diff > 2 * DAY_IN_SECONDS )
-			$wpdb->delete( $wpdb->signups, array( 'domain' => $mydomain , 'path' => $path ) );
-		else
-			$errors->add('blogname', __('That site is currently reserved but may be available in a couple days.'));
+		if ( $diff > 2 * DAY_IN_SECONDS ) {
+			$wpdb->delete( $wpdb->signups, array( 'domain' => $mydomain, 'path' => $path ) );
+		} else {
+			$errors->add( 'blogname', __( 'That site is currently reserved but may be available in a couple days.' ) );
+		}
 	}
 
-	$result = array('domain' => $mydomain, 'path' => $path, 'blogname' => $blogname, 'blog_title' => $blog_title, 'user' => $user, 'errors' => $errors);
+	$result = array( 'domain'     => $mydomain,
+	                 'path'       => $path,
+	                 'blogname'   => $blogname,
+	                 'blog_title' => $blog_title,
+	                 'user'       => $user,
+	                 'errors'     => $errors
+	);
 
 	/**
 	 * Filter site details and error messages following registration.
@@ -638,12 +693,12 @@
 	 * @param array $result {
 	 *     Array of domain, path, blog name, blog title, user and error messages.
 	 *
-	 *     @type string         $domain     Domain for the site.
-	 *     @type string         $path       Path for the site. Used in subdirectory installs.
-	 *     @type string         $blogname   The unique site name (slug).
-	 *     @type string         $blog_title Blog title.
-	 *     @type string|WP_User $user       By default, an empty string. A user object if provided.
-	 *     @type WP_Error       $errors     WP_Error containing any errors found.
+	 * @type string $domain Domain for the site.
+	 * @type string $path Path for the site. Used in subdirectory installs.
+	 * @type string $blogname The unique site name (slug).
+	 * @type string $blog_title Blog title.
+	 * @type string|WP_User $user By default, an empty string. A user object if provided.
+	 * @type WP_Error $errors WP_Error containing any errors found.
 	 * }
 	 */
 	return apply_filters( 'wpmu_validate_blog_signup', $result );
@@ -656,28 +711,28 @@
  *
  * @global wpdb $wpdb WordPress database abstraction object.
  *
- * @param string $domain     The requested domain.
- * @param string $path       The requested path.
- * @param string $title      The requested site title.
- * @param string $user       The user's requested login name.
+ * @param string $domain The requested domain.
+ * @param string $path The requested path.
+ * @param string $title The requested site title.
+ * @param string $user The user's requested login name.
  * @param string $user_email The user's email address.
- * @param array  $meta       By default, contains the requested privacy setting and lang_id.
+ * @param array $meta By default, contains the requested privacy setting and lang_id.
  */
-function wpmu_signup_blog( $domain, $path, $title, $user, $user_email, $meta = array() )  {
+function wpmu_signup_blog( $domain, $path, $title, $user, $user_email, $meta = array() ) {
 	global $wpdb;
 
-	$key = substr( md5( time() . rand() . $domain ), 0, 16 );
-	$meta = serialize($meta);
+	$key  = substr( md5( time() . rand() . $domain ), 0, 16 );
+	$meta = serialize( $meta );
 
 	$wpdb->insert( $wpdb->signups, array(
-		'domain' => $domain,
-		'path' => $path,
-		'title' => $title,
-		'user_login' => $user,
-		'user_email' => $user_email,
-		'registered' => current_time('mysql', true),
+		'domain'         => $domain,
+		'path'           => $path,
+		'title'          => $title,
+		'user_login'     => $user,
+		'user_email'     => $user_email,
+		'registered'     => current_time( 'mysql', true ),
 		'activation_key' => $key,
-		'meta' => $meta
+		'meta'           => $meta
 	) );
 
 	/**
@@ -685,13 +740,13 @@
 	 *
 	 * @since 4.4.0
 	 *
-	 * @param string $domain     The requested domain.
-	 * @param string $path       The requested path.
-	 * @param string $title      The requested site title.
-	 * @param string $user       The user's requested login name.
+	 * @param string $domain The requested domain.
+	 * @param string $path The requested path.
+	 * @param string $title The requested site title.
+	 * @param string $user The user's requested login name.
 	 * @param string $user_email The user's email address.
-	 * @param string $key        The user's activation key
-	 * @param array  $meta       By default, contains the requested privacy setting and lang_id.
+	 * @param string $key The user's activation key
+	 * @param array $meta By default, contains the requested privacy setting and lang_id.
 	 */
 	do_action( 'after_signup_site', $domain, $path, $title, $user, $user_email, $key, $meta );
 }
@@ -706,28 +761,28 @@
  *
  * @global wpdb $wpdb WordPress database abstraction object.
  *
- * @param string $user       The user's requested login name.
+ * @param string $user The user's requested login name.
  * @param string $user_email The user's email address.
- * @param array  $meta       By default, this is an empty array.
+ * @param array $meta By default, this is an empty array.
  */
 function wpmu_signup_user( $user, $user_email, $meta = array() ) {
 	global $wpdb;
 
 	// Format data
-	$user = preg_replace( '/\s+/', '', sanitize_user( $user, true ) );
+	$user       = preg_replace( '/\s+/', '', sanitize_user( $user, true ) );
 	$user_email = sanitize_email( $user_email );
-	$key = substr( md5( time() . rand() . $user_email ), 0, 16 );
-	$meta = serialize($meta);
+	$key        = substr( md5( time() . rand() . $user_email ), 0, 16 );
+	$meta       = serialize( $meta );
 
 	$wpdb->insert( $wpdb->signups, array(
-		'domain' => '',
-		'path' => '',
-		'title' => '',
-		'user_login' => $user,
-		'user_email' => $user_email,
-		'registered' => current_time('mysql', true),
+		'domain'         => '',
+		'path'           => '',
+		'title'          => '',
+		'user_login'     => $user,
+		'user_email'     => $user_email,
+		'registered'     => current_time( 'mysql', true ),
 		'activation_key' => $key,
-		'meta' => $meta
+		'meta'           => $meta
 	) );
 
 	/**
@@ -735,10 +790,10 @@
 	 *
 	 * @since 4.4.0
 	 *
-	 * @param string $user       The user's requested login name.
+	 * @param string $user The user's requested login name.
 	 * @param string $user_email The user's email address.
-	 * @param string $key        The user's activation key
-	 * @param array  $meta       Additional signup meta. By default, this is an empty array.
+	 * @param string $key The user's activation key
+	 * @param array $meta Additional signup meta. By default, this is an empty array.
 	 */
 	do_action( 'after_signup_user', $user, $user_email, $key, $meta );
 }
@@ -758,13 +813,14 @@
  *
  * @since MU
  *
- * @param string $domain     The new blog domain.
- * @param string $path       The new blog path.
- * @param string $title      The site title.
- * @param string $user       The user's login name.
+ * @param string $domain The new blog domain.
+ * @param string $path The new blog path.
+ * @param string $title The site title.
+ * @param string $user The user's login name.
  * @param string $user_email The user's email address.
- * @param string $key        The activation key created in wpmu_signup_blog()
- * @param array  $meta       By default, contains the requested privacy setting and lang_id.
+ * @param string $key The activation key created in wpmu_signup_blog()
+ * @param array $meta By default, contains the requested privacy setting and lang_id.
+ *
  * @return bool
  */
 function wpmu_signup_blog_notification( $domain, $path, $title, $user, $user_email, $key, $meta = array() ) {
@@ -773,13 +829,13 @@
 	 *
 	 * @since MU
 	 *
-	 * @param string|bool $domain     Site domain.
-	 * @param string      $path       Site path.
-	 * @param string      $title      Site title.
-	 * @param string      $user       User login name.
-	 * @param string      $user_email User email address.
-	 * @param string      $key        Activation key created in wpmu_signup_blog().
-	 * @param array       $meta       By default, contains the requested privacy setting and lang_id.
+	 * @param string|bool $domain Site domain.
+	 * @param string $path Site path.
+	 * @param string $title Site title.
+	 * @param string $user User login name.
+	 * @param string $user_email User email address.
+	 * @param string $key Activation key created in wpmu_signup_blog().
+	 * @param array $meta By default, contains the requested privacy setting and lang_id.
 	 */
 	if ( ! apply_filters( 'wpmu_signup_blog_notification', $domain, $path, $title, $user, $user_email, $key, $meta ) ) {
 		return false;
@@ -786,34 +842,36 @@
 	}
 
 	// Send email with activation link.
-	if ( !is_subdomain_install() || get_current_site()->id != 1 )
-		$activate_url = network_site_url("wp-activate.php?key=$key");
-	else
-		$activate_url = "http://{$domain}{$path}wp-activate.php?key=$key"; // @todo use *_url() API
+	if ( ! is_subdomain_install() || get_current_site()->id != 1 ) {
+		$activate_url = network_site_url( "wp-activate.php?key=$key" );
+	} else {
+		$activate_url = "http://{$domain}{$path}wp-activate.php?key=$key";
+	} // @todo use *_url() API
 
-	$activate_url = esc_url($activate_url);
-	$admin_email = get_site_option( 'admin_email' );
-	if ( $admin_email == '' )
+	$activate_url = esc_url( $activate_url );
+	$admin_email  = get_site_option( 'admin_email' );
+	if ( $admin_email == '' ) {
 		$admin_email = 'support@' . $_SERVER['SERVER_NAME'];
-	$from_name = get_site_option( 'site_name' ) == '' ? 'WordPress' : esc_html( get_site_option( 'site_name' ) );
-	$message_headers = "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
-	$message = sprintf(
-		/**
-		 * Filter the message content of the new blog notification email.
-		 *
-		 * Content should be formatted for transmission via wp_mail().
-		 *
-		 * @since MU
-		 *
-		 * @param string $content    Content of the notification email.
-		 * @param string $domain     Site domain.
-		 * @param string $path       Site path.
-		 * @param string $title      Site title.
-		 * @param string $user       User login name.
-		 * @param string $user_email User email address.
-		 * @param string $key        Activation key created in wpmu_signup_blog().
-		 * @param array  $meta       By default, contains the requested privacy setting and lang_id.
-		 */
+	}
+	$from_name       = get_site_option( 'site_name' ) == '' ? 'WordPress' : esc_html( get_site_option( 'site_name' ) );
+	$message_headers = "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option( 'blog_charset' ) . "\"\n";
+	$message         = sprintf(
+	/**
+	 * Filter the message content of the new blog notification email.
+	 *
+	 * Content should be formatted for transmission via wp_mail().
+	 *
+	 * @since MU
+	 *
+	 * @param string $content Content of the notification email.
+	 * @param string $domain Site domain.
+	 * @param string $path Site path.
+	 * @param string $title Site title.
+	 * @param string $user User login name.
+	 * @param string $user_email User email address.
+	 * @param string $key Activation key created in wpmu_signup_blog().
+	 * @param array $meta By default, contains the requested privacy setting and lang_id.
+	 */
 		apply_filters( 'wpmu_signup_blog_notification_email',
 			__( "To activate your blog, please click the following link:\n\n%s\n\nAfter you activate, you will receive *another email* with your login.\n\nAfter you activate, you can visit your site here:\n\n%s" ),
 			$domain, $path, $title, $user, $user_email, $key, $meta
@@ -824,20 +882,20 @@
 	);
 	// TODO: Don't hard code activation link.
 	$subject = sprintf(
-		/**
-		 * Filter the subject of the new blog notification email.
-		 *
-		 * @since MU
-		 *
-		 * @param string $subject    Subject of the notification email.
-		 * @param string $domain     Site domain.
-		 * @param string $path       Site path.
-		 * @param string $title      Site title.
-		 * @param string $user       User login name.
-		 * @param string $user_email User email address.
-		 * @param string $key        Activation key created in wpmu_signup_blog().
-		 * @param array  $meta       By default, contains the requested privacy setting and lang_id.
-		 */
+	/**
+	 * Filter the subject of the new blog notification email.
+	 *
+	 * @since MU
+	 *
+	 * @param string $subject Subject of the notification email.
+	 * @param string $domain Site domain.
+	 * @param string $path Site path.
+	 * @param string $title Site title.
+	 * @param string $user User login name.
+	 * @param string $user_email User email address.
+	 * @param string $key Activation key created in wpmu_signup_blog().
+	 * @param array $meta By default, contains the requested privacy setting and lang_id.
+	 */
 		apply_filters( 'wpmu_signup_blog_notification_subject',
 			__( '[%1$s] Activate %2$s' ),
 			$domain, $path, $title, $user, $user_email, $key, $meta
@@ -846,6 +904,7 @@
 		esc_url( 'http://' . $domain . $path )
 	);
 	wp_mail( $user_email, wp_specialchars_decode( $subject ), $message, $message_headers );
+
 	return true;
 }
 
@@ -864,10 +923,11 @@
  *
  * @since MU
  *
- * @param string $user       The user's login name.
+ * @param string $user The user's login name.
  * @param string $user_email The user's email address.
- * @param string $key        The activation key created in wpmu_signup_user()
- * @param array  $meta       By default, an empty array.
+ * @param string $key The activation key created in wpmu_signup_user()
+ * @param array $meta By default, an empty array.
+ *
  * @return bool
  */
 function wpmu_signup_user_notification( $user, $user_email, $key, $meta = array() ) {
@@ -876,34 +936,36 @@
 	 *
 	 * @since MU
 	 *
-	 * @param string $user       User login name.
+	 * @param string $user User login name.
 	 * @param string $user_email User email address.
-	 * @param string $key        Activation key created in wpmu_signup_user().
-	 * @param array  $meta       Signup meta data.
+	 * @param string $key Activation key created in wpmu_signup_user().
+	 * @param array $meta Signup meta data.
 	 */
-	if ( ! apply_filters( 'wpmu_signup_user_notification', $user, $user_email, $key, $meta ) )
+	if ( ! apply_filters( 'wpmu_signup_user_notification', $user, $user_email, $key, $meta ) ) {
 		return false;
+	}
 
 	// Send email with activation link.
 	$admin_email = get_site_option( 'admin_email' );
-	if ( $admin_email == '' )
+	if ( $admin_email == '' ) {
 		$admin_email = 'support@' . $_SERVER['SERVER_NAME'];
-	$from_name = get_site_option( 'site_name' ) == '' ? 'WordPress' : esc_html( get_site_option( 'site_name' ) );
-	$message_headers = "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
-	$message = sprintf(
-		/**
-		 * Filter the content of the notification email for new user sign-up.
-		 *
-		 * Content should be formatted for transmission via wp_mail().
-		 *
-		 * @since MU
-		 *
-		 * @param string $content    Content of the notification email.
-		 * @param string $user       User login name.
-		 * @param string $user_email User email address.
-		 * @param string $key        Activation key created in wpmu_signup_user().
-		 * @param array  $meta       Signup meta data.
-		 */
+	}
+	$from_name       = get_site_option( 'site_name' ) == '' ? 'WordPress' : esc_html( get_site_option( 'site_name' ) );
+	$message_headers = "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option( 'blog_charset' ) . "\"\n";
+	$message         = sprintf(
+	/**
+	 * Filter the content of the notification email for new user sign-up.
+	 *
+	 * Content should be formatted for transmission via wp_mail().
+	 *
+	 * @since MU
+	 *
+	 * @param string $content Content of the notification email.
+	 * @param string $user User login name.
+	 * @param string $user_email User email address.
+	 * @param string $key Activation key created in wpmu_signup_user().
+	 * @param array $meta Signup meta data.
+	 */
 		apply_filters( 'wpmu_signup_user_notification_email',
 			__( "To activate your user, please click the following link:\n\n%s\n\nAfter you activate, you will receive *another email* with your login." ),
 			$user, $user_email, $key, $meta
@@ -912,17 +974,17 @@
 	);
 	// TODO: Don't hard code activation link.
 	$subject = sprintf(
-		/**
-		 * Filter the subject of the notification email of new user signup.
-		 *
-		 * @since MU
-		 *
-		 * @param string $subject    Subject of the notification email.
-		 * @param string $user       User login name.
-		 * @param string $user_email User email address.
-		 * @param string $key        Activation key created in wpmu_signup_user().
-		 * @param array  $meta       Signup meta data.
-		 */
+	/**
+	 * Filter the subject of the notification email of new user signup.
+	 *
+	 * @since MU
+	 *
+	 * @param string $subject Subject of the notification email.
+	 * @param string $user User login name.
+	 * @param string $user_email User email address.
+	 * @param string $key Activation key created in wpmu_signup_user().
+	 * @param array $meta Signup meta data.
+	 */
 		apply_filters( 'wpmu_signup_user_notification_subject',
 			__( '[%1$s] Activate %2$s' ),
 			$user, $user_email, $key, $meta
@@ -931,6 +993,7 @@
 		$user
 	);
 	wp_mail( $user_email, wp_specialchars_decode( $subject ), $message, $message_headers );
+
 	return true;
 }
 
@@ -947,43 +1010,49 @@
  * @global wpdb $wpdb WordPress database abstraction object.
  *
  * @param string $key The activation key provided to the user.
+ *
  * @return array|WP_Error An array containing information about the activated user and/or blog
  */
-function wpmu_activate_signup($key) {
+function wpmu_activate_signup( $key ) {
 	global $wpdb;
 
-	$signup = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->signups WHERE activation_key = %s", $key) );
+	$signup = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->signups WHERE activation_key = %s", $key ) );
 
-	if ( empty( $signup ) )
+	if ( empty( $signup ) ) {
 		return new WP_Error( 'invalid_key', __( 'Invalid activation key.' ) );
+	}
 
 	if ( $signup->active ) {
-		if ( empty( $signup->domain ) )
+		if ( empty( $signup->domain ) ) {
 			return new WP_Error( 'already_active', __( 'The user is already active.' ), $signup );
-		else
+		} else {
 			return new WP_Error( 'already_active', __( 'The site is already active.' ), $signup );
+		}
 	}
 
-	$meta = maybe_unserialize($signup->meta);
+	$meta     = maybe_unserialize( $signup->meta );
 	$password = wp_generate_password( 12, false );
 
-	$user_id = username_exists($signup->user_login);
+	$user_id = username_exists( $signup->user_login );
 
-	if ( ! $user_id )
-		$user_id = wpmu_create_user($signup->user_login, $password, $signup->user_email);
-	else
+	if ( ! $user_id ) {
+		$user_id = wpmu_create_user( $signup->user_login, $password, $signup->user_email );
+	} else {
 		$user_already_exists = true;
+	}
 
-	if ( ! $user_id )
-		return new WP_Error('create_user', __('Could not create user'), $signup);
+	if ( ! $user_id ) {
+		return new WP_Error( 'create_user', __( 'Could not create user' ), $signup );
+	}
 
-	$now = current_time('mysql', true);
+	$now = current_time( 'mysql', true );
 
-	if ( empty($signup->domain) ) {
-		$wpdb->update( $wpdb->signups, array('active' => 1, 'activated' => $now), array('activation_key' => $key) );
+	if ( empty( $signup->domain ) ) {
+		$wpdb->update( $wpdb->signups, array( 'active' => 1, 'activated' => $now ), array( 'activation_key' => $key ) );
 
-		if ( isset( $user_already_exists ) )
-			return new WP_Error( 'user_already_exists', __( 'That username is already activated.' ), $signup);
+		if ( isset( $user_already_exists ) ) {
+			return new WP_Error( 'user_already_exists', __( 'That username is already activated.' ), $signup );
+		}
 
 		/**
 		 * Fires immediately after a new user is activated.
@@ -990,11 +1059,12 @@
 		 *
 		 * @since MU
 		 *
-		 * @param int   $user_id  User ID.
-		 * @param int   $password User password.
-		 * @param array $meta     Signup meta data.
+		 * @param int $user_id User ID.
+		 * @param int $password User password.
+		 * @param array $meta Signup meta data.
 		 */
 		do_action( 'wpmu_activate_user', $user_id, $password, $meta );
+
 		return array( 'user_id' => $user_id, 'password' => $password, 'meta' => $meta );
 	}
 
@@ -1001,31 +1071,39 @@
 	$blog_id = wpmu_create_blog( $signup->domain, $signup->path, $signup->title, $user_id, $meta, $wpdb->siteid );
 
 	// TODO: What to do if we create a user but cannot create a blog?
-	if ( is_wp_error($blog_id) ) {
+	if ( is_wp_error( $blog_id ) ) {
 		// If blog is taken, that means a previous attempt to activate this blog failed in between creating the blog and
 		// setting the activation flag. Let's just set the active flag and instruct the user to reset their password.
 		if ( 'blog_taken' == $blog_id->get_error_code() ) {
 			$blog_id->add_data( $signup );
-			$wpdb->update( $wpdb->signups, array( 'active' => 1, 'activated' => $now ), array( 'activation_key' => $key ) );
+			$wpdb->update( $wpdb->signups, array( 'active'    => 1,
+			                                      'activated' => $now
+			), array( 'activation_key' => $key ) );
 		}
+
 		return $blog_id;
 	}
 
-	$wpdb->update( $wpdb->signups, array('active' => 1, 'activated' => $now), array('activation_key' => $key) );
+	$wpdb->update( $wpdb->signups, array( 'active' => 1, 'activated' => $now ), array( 'activation_key' => $key ) );
 	/**
 	 * Fires immediately after a site is activated.
 	 *
 	 * @since MU
 	 *
-	 * @param int    $blog_id       Blog ID.
-	 * @param int    $user_id       User ID.
-	 * @param int    $password      User password.
-	 * @param string $signup_title  Site title.
-	 * @param array  $meta          Signup meta data.
+	 * @param int $blog_id Blog ID.
+	 * @param int $user_id User ID.
+	 * @param int $password User password.
+	 * @param string $signup_title Site title.
+	 * @param array $meta Signup meta data.
 	 */
 	do_action( 'wpmu_activate_blog', $blog_id, $user_id, $password, $signup->title, $meta );
 
-	return array('blog_id' => $blog_id, 'user_id' => $user_id, 'password' => $password, 'title' => $signup->title, 'meta' => $meta);
+	return array( 'blog_id'  => $blog_id,
+	              'user_id'  => $user_id,
+	              'password' => $password,
+	              'title'    => $signup->title,
+	              'meta'     => $meta
+	);
 }
 
 /**
@@ -1039,8 +1117,9 @@
  * @since MU
  *
  * @param string $user_name The new user's login name.
- * @param string $password  The new user's password.
- * @param string $email     The new user's email address.
+ * @param string $password The new user's password.
+ * @param string $email The new user's email address.
+ *
  * @return int|false Returns false on failure, or int $user_id on success
  */
 function wpmu_create_user( $user_name, $password, $email ) {
@@ -1047,8 +1126,9 @@
 	$user_name = preg_replace( '/\s+/', '', sanitize_user( $user_name, true ) );
 
 	$user_id = wp_create_user( $user_name, $password, $email );
-	if ( is_wp_error( $user_id ) )
+	if ( is_wp_error( $user_id ) ) {
 		return false;
+	}
 
 	// Newly created users have no roles or caps until they are added to a blog.
 	delete_user_option( $user_id, 'capabilities' );
@@ -1080,58 +1160,65 @@
  *
  * @since MU
  *
- * @param string $domain  The new site's domain.
- * @param string $path    The new site's path.
- * @param string $title   The new site's title.
- * @param int    $user_id The user ID of the new site's admin.
- * @param array  $meta    Optional. Used to set initial site options.
- * @param int    $site_id Optional. Only relevant on multi-network installs.
+ * @param string $domain The new site's domain.
+ * @param string $path The new site's path.
+ * @param string $title The new site's title.
+ * @param int $user_id The user ID of the new site's admin.
+ * @param array $meta Optional. Used to set initial site options.
+ * @param int $site_id Optional. Only relevant on multi-network installs.
+ *
  * @return int|WP_Error Returns WP_Error object on failure, int $blog_id on success
  */
 function wpmu_create_blog( $domain, $path, $title, $user_id, $meta = array(), $site_id = 1 ) {
 	$defaults = array( 'public' => 0 );
-	$meta = wp_parse_args( $meta, $defaults );
+	$meta     = wp_parse_args( $meta, $defaults );
 
 	$domain = preg_replace( '/\s+/', '', sanitize_user( $domain, true ) );
 
-	if ( is_subdomain_install() )
+	if ( is_subdomain_install() ) {
 		$domain = str_replace( '@', '', $domain );
+	}
 
-	$title = strip_tags( $title );
+	$title   = strip_tags( $title );
 	$user_id = (int) $user_id;
 
-	if ( empty($path) )
+	if ( empty( $path ) ) {
 		$path = '/';
+	}
 
 	// Check if the domain has been used already. We should return an error message.
-	if ( domain_exists($domain, $path, $site_id) )
+	if ( domain_exists( $domain, $path, $site_id ) ) {
 		return new WP_Error( 'blog_taken', __( 'Sorry, that site already exists!' ) );
+	}
 
 	if ( ! wp_installing() ) {
 		wp_installing( true );
 	}
 
-	if ( ! $blog_id = insert_blog($domain, $path, $site_id) )
-		return new WP_Error('insert_blog', __('Could not create site.'));
+	if ( ! $blog_id = insert_blog( $domain, $path, $site_id ) ) {
+		return new WP_Error( 'insert_blog', __( 'Could not create site.' ) );
+	}
 
-	switch_to_blog($blog_id);
-	install_blog($blog_id, $title);
-	wp_install_defaults($user_id);
+	switch_to_blog( $blog_id );
+	install_blog( $blog_id, $title );
+	wp_install_defaults( $user_id );
 
-	add_user_to_blog($blog_id, $user_id, 'administrator');
+	add_user_to_blog( $blog_id, $user_id, 'administrator' );
 
 	foreach ( $meta as $key => $value ) {
-		if ( in_array( $key, array( 'public', 'archived', 'mature', 'spam', 'deleted', 'lang_id' ) ) )
+		if ( in_array( $key, array( 'public', 'archived', 'mature', 'spam', 'deleted', 'lang_id' ) ) ) {
 			update_blog_status( $blog_id, $key, $value );
-		else
+		} else {
 			update_option( $key, $value );
+		}
 	}
 
 	add_option( 'WPLANG', get_site_option( 'WPLANG' ) );
 	update_option( 'blog_public', (int) $meta['public'] );
 
-	if ( ! is_super_admin( $user_id ) && ! get_user_meta( $user_id, 'primary_blog', true ) )
+	if ( ! is_super_admin( $user_id ) && ! get_user_meta( $user_id, 'primary_blog', true ) ) {
 		update_user_meta( $user_id, 'primary_blog', $blog_id );
+	}
 
 	restore_current_blog();
 	/**
@@ -1139,12 +1226,12 @@
 	 *
 	 * @since MU
 	 *
-	 * @param int    $blog_id Blog ID.
-	 * @param int    $user_id User ID.
-	 * @param string $domain  Site domain.
-	 * @param string $path    Site path.
-	 * @param int    $site_id Site ID. Only relevant on multi-network installs.
-	 * @param array  $meta    Meta data. Used to set initial site options.
+	 * @param int $blog_id Blog ID.
+	 * @param int $user_id User ID.
+	 * @param string $domain Site domain.
+	 * @param string $path Site path.
+	 * @param int $site_id Site ID. Only relevant on multi-network installs.
+	 * @param array $meta Meta data. Used to set initial site options.
 	 */
 	do_action( 'wpmu_new_blog', $blog_id, $user_id, $domain, $path, $site_id, $meta );
 
@@ -1159,23 +1246,26 @@
  *
  * @since MU
  *
- * @param int    $blog_id    The new site's ID.
+ * @param int $blog_id The new site's ID.
  * @param string $deprecated Not used.
+ *
  * @return bool
  */
 function newblog_notify_siteadmin( $blog_id, $deprecated = '' ) {
-	if ( get_site_option( 'registrationnotification' ) != 'yes' )
+	if ( get_site_option( 'registrationnotification' ) != 'yes' ) {
 		return false;
+	}
 
 	$email = get_site_option( 'admin_email' );
-	if ( is_email($email) == false )
+	if ( is_email( $email ) == false ) {
 		return false;
+	}
 
-	$options_site_url = esc_url(network_admin_url('settings.php'));
+	$options_site_url = esc_url( network_admin_url( 'settings.php' ) );
 
 	switch_to_blog( $blog_id );
 	$blogname = get_option( 'blogname' );
-	$siteurl = site_url();
+	$siteurl  = site_url();
 	restore_current_blog();
 
 	$msg = sprintf( __( 'New Site: %1$s
@@ -1182,7 +1272,7 @@
 URL: %2$s
 Remote IP: %3$s
 
-Disable these notifications: %4$s' ), $blogname, $siteurl, wp_unslash( $_SERVER['REMOTE_ADDR'] ), $options_site_url);
+Disable these notifications: %4$s' ), $blogname, $siteurl, wp_unslash( $_SERVER['REMOTE_ADDR'] ), $options_site_url );
 	/**
 	 * Filter the message body of the new site activation email sent
 	 * to the network administrator.
@@ -1194,6 +1284,7 @@
 	$msg = apply_filters( 'newblog_notify_siteadmin', $msg );
 
 	wp_mail( $email, sprintf( __( 'New Site Registration: %s' ), $siteurl ), $msg );
+
 	return true;
 }
 
@@ -1206,24 +1297,27 @@
  * @since MU
  *
  * @param int $user_id The new user's ID.
+ *
  * @return bool
  */
 function newuser_notify_siteadmin( $user_id ) {
-	if ( get_site_option( 'registrationnotification' ) != 'yes' )
+	if ( get_site_option( 'registrationnotification' ) != 'yes' ) {
 		return false;
+	}
 
 	$email = get_site_option( 'admin_email' );
 
-	if ( is_email($email) == false )
+	if ( is_email( $email ) == false ) {
 		return false;
+	}
 
 	$user = get_userdata( $user_id );
 
-	$options_site_url = esc_url(network_admin_url('settings.php'));
-	$msg = sprintf(__('New User: %1$s
+	$options_site_url = esc_url( network_admin_url( 'settings.php' ) );
+	$msg              = sprintf( __( 'New User: %1$s
 Remote IP: %2$s
 
-Disable these notifications: %3$s'), $user->user_login, wp_unslash( $_SERVER['REMOTE_ADDR'] ), $options_site_url);
+Disable these notifications: %3$s' ), $user->user_login, wp_unslash( $_SERVER['REMOTE_ADDR'] ), $options_site_url );
 
 	/**
 	 * Filter the message body of the new user activation email sent
@@ -1231,11 +1325,12 @@
 	 *
 	 * @since MU
 	 *
-	 * @param string  $msg  Email body.
+	 * @param string $msg Email body.
 	 * @param WP_User $user WP_User instance of the new user.
 	 */
 	$msg = apply_filters( 'newuser_notify_siteadmin', $msg, $user );
-	wp_mail( $email, sprintf(__('New User Registration: %s'), $user->user_login), $msg );
+	wp_mail( $email, sprintf( __( 'New User Registration: %s' ), $user->user_login ), $msg );
+
 	return true;
 }
 
@@ -1249,27 +1344,31 @@
  *
  * @global wpdb $wpdb WordPress database abstraction object.
  *
- * @param string $domain  The domain to be checked.
- * @param string $path    The path to be checked.
- * @param int    $site_id Optional. Relevant only on multi-network installs.
+ * @param string $domain The domain to be checked.
+ * @param string $path The path to be checked.
+ * @param int $site_id Optional. Relevant only on multi-network installs.
+ *
  * @return int
  */
-function domain_exists($domain, $path, $site_id = 1) {
-	global $wpdb;
+function domain_exists( $domain, $path, $site_id = 1 ) {
 	$path = trailingslashit( $path );
-	$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) );
 
+	$query  = new WP_Site_Query();
+	$args   = array( 'path' => $path, 'domain' => $domain, 'network' => $site_id, 'number' => 1, 'fields' => 'ids' );
+	$result = $query->query( $args );
+	$site   = array_shift( $result );
+
 	/**
 	 * Filter whether a blogname is taken.
 	 *
 	 * @since 3.5.0
 	 *
-	 * @param int|null $result  The blog_id if the blogname exists, null otherwise.
-	 * @param string   $domain  Domain to be checked.
-	 * @param string   $path    Path to be checked.
-	 * @param int      $site_id Site ID. Relevant only on multi-network installs.
+	 * @param int|null $site The blog_id if the blogname exists, null otherwise.
+	 * @param string $domain Domain to be checked.
+	 * @param string $path Path to be checked.
+	 * @param int $site_id Site ID. Relevant only on multi-network installs.
 	 */
-	return apply_filters( 'domain_exists', $result, $domain, $path, $site_id );
+	return apply_filters( 'domain_exists', $site, $domain, $path, $site_id );
 }
 
 /**
@@ -1282,20 +1381,26 @@
  *
  * @global wpdb $wpdb WordPress database abstraction object.
  *
- * @param string $domain  The domain of the new site.
- * @param string $path    The path of the new site.
- * @param int    $site_id Unless you're running a multi-network install, be sure to set this value to 1.
+ * @param string $domain The domain of the new site.
+ * @param string $path The path of the new site.
+ * @param int $site_id Unless you're running a multi-network install, be sure to set this value to 1.
+ *
  * @return int|false The ID of the new row
  */
-function insert_blog($domain, $path, $site_id) {
+function insert_blog( $domain, $path, $site_id ) {
 	global $wpdb;
 
-	$path = trailingslashit($path);
+	$path    = trailingslashit( $path );
 	$site_id = (int) $site_id;
 
-	$result = $wpdb->insert( $wpdb->blogs, array('site_id' => $site_id, 'domain' => $domain, 'path' => $path, 'registered' => current_time('mysql')) );
-	if ( ! $result )
+	$result = $wpdb->insert( $wpdb->blogs, array( 'site_id'    => $site_id,
+	                                              'domain'     => $domain,
+	                                              'path'       => $path,
+	                                              'registered' => current_time( 'mysql' )
+	) );
+	if ( ! $result ) {
 		return false;
+	}
 
 	$blog_id = $wpdb->insert_id;
 	refresh_blog_details( $blog_id );
@@ -1314,10 +1419,10 @@
  *
  * @since MU
  *
- * @global wpdb     $wpdb
+ * @global wpdb $wpdb
  * @global WP_Roles $wp_roles
  *
- * @param int    $blog_id    The value returned by insert_blog().
+ * @param int $blog_id The value returned by insert_blog().
  * @param string $blog_title The title of the new site.
  */
 function install_blog( $blog_id, $blog_title = '' ) {
@@ -1329,8 +1434,9 @@
 	require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
 
 	$suppress = $wpdb->suppress_errors();
-	if ( $wpdb->get_results( "DESCRIBE {$wpdb->posts}" ) )
+	if ( $wpdb->get_results( "DESCRIBE {$wpdb->posts}" ) ) {
 		die( '<h1>' . __( 'Already Installed' ) . '</h1><p>' . __( 'You appear to have already installed WordPress. To reinstall please clear your old database tables first.' ) . '</p></body></html>' );
+	}
 	$wpdb->suppress_errors( $suppress );
 
 	$url = get_blogaddress_by_id( $blog_id );
@@ -1347,12 +1453,12 @@
 
 	if ( ! is_subdomain_install() ) {
 
- 		if ( 'https' === parse_url( get_site_option( 'siteurl' ), PHP_URL_SCHEME ) ) {
- 			$siteurl = set_url_scheme( $siteurl, 'https' );
- 		}
- 		if ( 'https' === parse_url( get_home_url( $current_site->blog_id ), PHP_URL_SCHEME ) ) {
- 			$home = set_url_scheme( $home, 'https' );
- 		}
+		if ( 'https' === parse_url( get_site_option( 'siteurl' ), PHP_URL_SCHEME ) ) {
+			$siteurl = set_url_scheme( $siteurl, 'https' );
+		}
+		if ( 'https' === parse_url( get_home_url( $current_site->blog_id ), PHP_URL_SCHEME ) ) {
+			$home = set_url_scheme( $home, 'https' );
+		}
 
 	}
 
@@ -1359,10 +1465,11 @@
 	update_option( 'siteurl', $siteurl );
 	update_option( 'home', $home );
 
-	if ( get_site_option( 'ms_files_rewriting' ) )
+	if ( get_site_option( 'ms_files_rewriting' ) ) {
 		update_option( 'upload_path', UPLOADBLOGSDIR . "/$blog_id/files" );
-	else
+	} else {
 		update_option( 'upload_path', get_blog_option( get_current_site()->blog_id, 'upload_path' ) );
+	}
 
 	update_option( 'blogname', wp_unslash( $blog_title ) );
 	update_option( 'admin_email', '' );
@@ -1369,7 +1476,7 @@
 
 	// remove all perms
 	$table_prefix = $wpdb->get_blog_prefix();
-	delete_metadata( 'user', 0, $table_prefix . 'user_level',   null, true ); // delete all
+	delete_metadata( 'user', 0, $table_prefix . 'user_level', null, true ); // delete all
 	delete_metadata( 'user', 0, $table_prefix . 'capabilities', null, true ); // delete all
 }
 
@@ -1387,7 +1494,7 @@
  * @param int $blog_id Ignored in this function.
  * @param int $user_id
  */
-function install_blog_defaults($blog_id, $user_id) {
+function install_blog_defaults( $blog_id, $user_id ) {
 	global $wpdb;
 
 	require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
@@ -1394,7 +1501,7 @@
 
 	$suppress = $wpdb->suppress_errors();
 
-	wp_install_defaults($user_id);
+	wp_install_defaults( $user_id );
 
 	$wpdb->suppress_errors( $suppress );
 }
@@ -1409,11 +1516,12 @@
  *
  * @since MU
  *
- * @param int    $blog_id
- * @param int    $user_id
+ * @param int $blog_id
+ * @param int $user_id
  * @param string $password
- * @param string $title    The new blog's title
- * @param array  $meta     Optional. Not used in the default function, but is passed along to hooks for customization.
+ * @param string $title The new blog's title
+ * @param array $meta Optional. Not used in the default function, but is passed along to hooks for customization.
+ *
  * @return bool
  */
 function wpmu_welcome_notification( $blog_id, $user_id, $password, $title, $meta = array() ) {
@@ -1426,14 +1534,15 @@
 	 *
 	 * @since MU
 	 *
-	 * @param int|bool $blog_id  Blog ID.
-	 * @param int      $user_id  User ID.
-	 * @param string   $password User password.
-	 * @param string   $title    Site title.
-	 * @param array    $meta     Signup meta data.
+	 * @param int|bool $blog_id Blog ID.
+	 * @param int $user_id User ID.
+	 * @param string $password User password.
+	 * @param string $title Site title.
+	 * @param array $meta Signup meta data.
 	 */
-	if ( ! apply_filters( 'wpmu_welcome_notification', $blog_id, $user_id, $password, $title, $meta ) )
+	if ( ! apply_filters( 'wpmu_welcome_notification', $blog_id, $user_id, $password, $title, $meta ) ) {
 		return false;
+	}
 
 	$welcome_email = get_site_option( 'welcome_email' );
 	if ( $welcome_email == false ) {
@@ -1454,7 +1563,7 @@
 --The Team @ SITE_NAME' );
 	}
 
-	$url = get_blogaddress_by_id($blog_id);
+	$url  = get_blogaddress_by_id( $blog_id );
 	$user = get_userdata( $user_id );
 
 	$welcome_email = str_replace( 'SITE_NAME', $current_site->site_name, $welcome_email );
@@ -1471,24 +1580,26 @@
 	 * @since MU
 	 *
 	 * @param string $welcome_email Message body of the email.
-	 * @param int    $blog_id       Blog ID.
-	 * @param int    $user_id       User ID.
-	 * @param string $password      User password.
-	 * @param string $title         Site title.
-	 * @param array  $meta          Signup meta data.
+	 * @param int $blog_id Blog ID.
+	 * @param int $user_id User ID.
+	 * @param string $password User password.
+	 * @param string $title Site title.
+	 * @param array $meta Signup meta data.
 	 */
 	$welcome_email = apply_filters( 'update_welcome_email', $welcome_email, $blog_id, $user_id, $password, $title, $meta );
-	$admin_email = get_site_option( 'admin_email' );
+	$admin_email   = get_site_option( 'admin_email' );
 
-	if ( $admin_email == '' )
+	if ( $admin_email == '' ) {
 		$admin_email = 'support@' . $_SERVER['SERVER_NAME'];
+	}
 
-	$from_name = get_site_option( 'site_name' ) == '' ? 'WordPress' : esc_html( get_site_option( 'site_name' ) );
-	$message_headers = "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
-	$message = $welcome_email;
+	$from_name       = get_site_option( 'site_name' ) == '' ? 'WordPress' : esc_html( get_site_option( 'site_name' ) );
+	$message_headers = "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option( 'blog_charset' ) . "\"\n";
+	$message         = $welcome_email;
 
-	if ( empty( $current_site->site_name ) )
+	if ( empty( $current_site->site_name ) ) {
 		$current_site->site_name = 'WordPress';
+	}
 
 	/**
 	 * Filter the subject of the welcome email after site activation.
@@ -1499,6 +1610,7 @@
 	 */
 	$subject = apply_filters( 'update_welcome_subject', sprintf( __( 'New %1$s Site: %2$s' ), $current_site->site_name, wp_unslash( $title ) ) );
 	wp_mail( $user->user_email, wp_specialchars_decode( $subject ), $message, $message_headers );
+
 	return true;
 }
 
@@ -1512,9 +1624,10 @@
  *
  * @since MU
  *
- * @param int    $user_id
+ * @param int $user_id
  * @param string $password
- * @param array  $meta     Optional. Not used in the default function, but is passed along to hooks for customization.
+ * @param array $meta Optional. Not used in the default function, but is passed along to hooks for customization.
+ *
  * @return bool
  */
 function wpmu_welcome_user_notification( $user_id, $password, $meta = array() ) {
@@ -1521,18 +1634,19 @@
 	$current_site = get_current_site();
 
 	/**
- 	 * Filter whether to bypass the welcome email after user activation.
+	 * Filter whether to bypass the welcome email after user activation.
 	 *
 	 * Returning false disables the welcome email.
 	 *
 	 * @since MU
 	 *
-	 * @param int    $user_id  User ID.
+	 * @param int $user_id User ID.
 	 * @param string $password User password.
-	 * @param array  $meta     Signup meta data.
+	 * @param array $meta Signup meta data.
 	 */
-	if ( ! apply_filters( 'wpmu_welcome_user_notification', $user_id, $password, $meta ) )
+	if ( ! apply_filters( 'wpmu_welcome_user_notification', $user_id, $password, $meta ) ) {
 		return false;
+	}
 
 	$welcome_email = get_site_option( 'welcome_user_email' );
 
@@ -1546,9 +1660,9 @@
 	 * @since MU
 	 *
 	 * @param string $welcome_email The message body of the account activation success email.
-	 * @param int    $user_id       User ID.
-	 * @param string $password      User password.
-	 * @param array  $meta          Signup meta data.
+	 * @param int $user_id User ID.
+	 * @param string $password User password.
+	 * @param array $meta Signup meta data.
 	 */
 	$welcome_email = apply_filters( 'update_welcome_user_email', $welcome_email, $user_id, $password, $meta );
 	$welcome_email = str_replace( 'SITE_NAME', $current_site->site_name, $welcome_email );
@@ -1558,15 +1672,17 @@
 
 	$admin_email = get_site_option( 'admin_email' );
 
-	if ( $admin_email == '' )
+	if ( $admin_email == '' ) {
 		$admin_email = 'support@' . $_SERVER['SERVER_NAME'];
+	}
 
-	$from_name = get_site_option( 'site_name' ) == '' ? 'WordPress' : esc_html( get_site_option( 'site_name' ) );
-	$message_headers = "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
-	$message = $welcome_email;
+	$from_name       = get_site_option( 'site_name' ) == '' ? 'WordPress' : esc_html( get_site_option( 'site_name' ) );
+	$message_headers = "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option( 'blog_charset' ) . "\"\n";
+	$message         = $welcome_email;
 
-	if ( empty( $current_site->site_name ) )
+	if ( empty( $current_site->site_name ) ) {
 		$current_site->site_name = 'WordPress';
+	}
 
 	/**
 	 * Filter the subject of the welcome email after user activation.
@@ -1575,8 +1691,9 @@
 	 *
 	 * @param string $subject Subject of the email.
 	 */
-	$subject = apply_filters( 'update_welcome_user_subject', sprintf( __( 'New %1$s User: %2$s' ), $current_site->site_name, $user->user_login) );
+	$subject = apply_filters( 'update_welcome_user_subject', sprintf( __( 'New %1$s User: %2$s' ), $current_site->site_name, $user->user_login ) );
 	wp_mail( $user->user_email, wp_specialchars_decode( $subject ), $message, $message_headers );
+
 	return true;
 }
 
@@ -1596,6 +1713,7 @@
  */
 function get_current_site() {
 	global $current_site;
+
 	return $current_site;
 }
 
@@ -1610,33 +1728,34 @@
  * @global wpdb $wpdb WordPress database abstraction object.
  *
  * @param int $user_id
+ *
  * @return array Contains the blog_id, post_id, post_date_gmt, and post_gmt_ts
  */
 function get_most_recent_post_of_user( $user_id ) {
 	global $wpdb;
 
-	$user_blogs = get_blogs_of_user( (int) $user_id );
+	$user_blogs       = get_blogs_of_user( (int) $user_id );
 	$most_recent_post = array();
 
 	// Walk through each blog and get the most recent post
 	// published by $user_id
 	foreach ( (array) $user_blogs as $blog ) {
-		$prefix = $wpdb->get_blog_prefix( $blog->userblog_id );
-		$recent_post = $wpdb->get_row( $wpdb->prepare("SELECT ID, post_date_gmt FROM {$prefix}posts WHERE post_author = %d AND post_type = 'post' AND post_status = 'publish' ORDER BY post_date_gmt DESC LIMIT 1", $user_id ), ARRAY_A);
+		$prefix      = $wpdb->get_blog_prefix( $blog->userblog_id );
+		$recent_post = $wpdb->get_row( $wpdb->prepare( "SELECT ID, post_date_gmt FROM {$prefix}posts WHERE post_author = %d AND post_type = 'post' AND post_status = 'publish' ORDER BY post_date_gmt DESC LIMIT 1", $user_id ), ARRAY_A );
 
 		// Make sure we found a post
-		if ( isset($recent_post['ID']) ) {
-			$post_gmt_ts = strtotime($recent_post['post_date_gmt']);
+		if ( isset( $recent_post['ID'] ) ) {
+			$post_gmt_ts = strtotime( $recent_post['post_date_gmt'] );
 
 			// If this is the first post checked or if this post is
 			// newer than the current recent post, make it the new
 			// most recent post.
-			if ( !isset($most_recent_post['post_gmt_ts']) || ( $post_gmt_ts > $most_recent_post['post_gmt_ts'] ) ) {
+			if ( ! isset( $most_recent_post['post_gmt_ts'] ) || ( $post_gmt_ts > $most_recent_post['post_gmt_ts'] ) ) {
 				$most_recent_post = array(
-					'blog_id'		=> $blog->userblog_id,
-					'post_id'		=> $recent_post['ID'],
-					'post_date_gmt'	=> $recent_post['post_date_gmt'],
-					'post_gmt_ts'	=> $post_gmt_ts
+					'blog_id'       => $blog->userblog_id,
+					'post_id'       => $recent_post['ID'],
+					'post_date_gmt' => $recent_post['post_date_gmt'],
+					'post_gmt_ts'   => $post_gmt_ts
 				);
 			}
 		}
@@ -1656,26 +1775,30 @@
  * @since MU
  *
  * @param string $directory Full path of a directory.
+ *
  * @return int Size of the directory in MB.
  */
 function get_dirsize( $directory ) {
 	$dirsize = get_transient( 'dirsize_cache' );
-	if ( is_array( $dirsize ) && isset( $dirsize[ $directory ][ 'size' ] ) )
-		return $dirsize[ $directory ][ 'size' ];
+	if ( is_array( $dirsize ) && isset( $dirsize[ $directory ]['size'] ) ) {
+		return $dirsize[ $directory ]['size'];
+	}
 
-	if ( ! is_array( $dirsize ) )
+	if ( ! is_array( $dirsize ) ) {
 		$dirsize = array();
+	}
 
 	// Exclude individual site directories from the total when checking the main site,
 	// as they are subdirectories and should not be counted.
 	if ( is_main_site() ) {
-		$dirsize[ $directory ][ 'size' ] = recurse_dirsize( $directory, $directory . '/sites' );
+		$dirsize[ $directory ]['size'] = recurse_dirsize( $directory, $directory . '/sites' );
 	} else {
-		$dirsize[ $directory ][ 'size' ] = recurse_dirsize( $directory );
+		$dirsize[ $directory ]['size'] = recurse_dirsize( $directory );
 	}
 
 	set_transient( 'dirsize_cache', $dirsize, HOUR_IN_SECONDS );
-	return $dirsize[ $directory ][ 'size' ];
+
+	return $dirsize[ $directory ]['size'];
 }
 
 /**
@@ -1688,7 +1811,8 @@
  * @since 4.3.0 $exclude parameter added.
  *
  * @param string $directory Full path of a directory.
- * @param string $exclude   Optional. Full path of a subdirectory to exclude from the total.
+ * @param string $exclude Optional. Full path of a subdirectory to exclude from the total.
+ *
  * @return int|false Size in MB if a valid directory. False if not.
  */
 function recurse_dirsize( $directory, $exclude = null ) {
@@ -1700,21 +1824,23 @@
 		return false;
 	}
 
-	if ($handle = opendir($directory)) {
-		while(($file = readdir($handle)) !== false) {
-			$path = $directory.'/'.$file;
-			if ($file != '.' && $file != '..') {
-				if (is_file($path)) {
-					$size += filesize($path);
-				} elseif (is_dir($path)) {
+	if ( $handle = opendir( $directory ) ) {
+		while ( ( $file = readdir( $handle ) ) !== false ) {
+			$path = $directory . '/' . $file;
+			if ( $file != '.' && $file != '..' ) {
+				if ( is_file( $path ) ) {
+					$size += filesize( $path );
+				} elseif ( is_dir( $path ) ) {
 					$handlesize = recurse_dirsize( $path, $exclude );
-					if ($handlesize > 0)
+					if ( $handlesize > 0 ) {
 						$size += $handlesize;
+					}
 				}
 			}
 		}
-		closedir($handle);
+		closedir( $handle );
 	}
+
 	return $size;
 }
 
@@ -1730,17 +1856,20 @@
  * @since MU
  *
  * @param array $mimes
+ *
  * @return array
  */
 function check_upload_mimes( $mimes ) {
-	$site_exts = explode( ' ', get_site_option( 'upload_filetypes', 'jpg jpeg png gif' ) );
+	$site_exts  = explode( ' ', get_site_option( 'upload_filetypes', 'jpg jpeg png gif' ) );
 	$site_mimes = array();
 	foreach ( $site_exts as $ext ) {
 		foreach ( $mimes as $ext_pattern => $mime ) {
-			if ( $ext != '' && strpos( $ext_pattern, $ext ) !== false )
-				$site_mimes[$ext_pattern] = $mime;
+			if ( $ext != '' && strpos( $ext_pattern, $ext ) !== false ) {
+				$site_mimes[ $ext_pattern ] = $mime;
+			}
 		}
 	}
+
 	return $site_mimes;
 }
 
@@ -1776,8 +1905,13 @@
 function wpmu_log_new_registrations( $blog_id, $user_id ) {
 	global $wpdb;
 	$user = get_userdata( (int) $user_id );
-	if ( $user )
-		$wpdb->insert( $wpdb->registration_log, array('email' => $user->user_email, 'IP' => preg_replace( '/[^0-9., ]/', '', wp_unslash( $_SERVER['REMOTE_ADDR'] ) ), 'blog_id' => $blog_id, 'date_registered' => current_time('mysql')) );
+	if ( $user ) {
+		$wpdb->insert( $wpdb->registration_log, array( 'email'           => $user->user_email,
+		                                               'IP'              => preg_replace( '/[^0-9., ]/', '', wp_unslash( $_SERVER['REMOTE_ADDR'] ) ),
+		                                               'blog_id'         => $blog_id,
+		                                               'date_registered' => current_time( 'mysql' )
+		) );
+	}
 }
 
 /**
@@ -1790,8 +1924,9 @@
  * @global wpdb $wpdb WordPress database abstraction object.
  * @staticvar int $global_terms_recurse
  *
- * @param int    $term_id    An ID for a term on the current blog.
+ * @param int $term_id An ID for a term on the current blog.
  * @param string $deprecated Not used.
+ *
  * @return int An ID from the global terms table mapped from $term_id.
  */
 function global_terms( $term_id, $deprecated = '' ) {
@@ -1798,34 +1933,42 @@
 	global $wpdb;
 	static $global_terms_recurse = null;
 
-	if ( !global_terms_enabled() )
+	if ( ! global_terms_enabled() ) {
 		return $term_id;
+	}
 
 	// prevent a race condition
 	$recurse_start = false;
 	if ( $global_terms_recurse === null ) {
-		$recurse_start = true;
+		$recurse_start        = true;
 		$global_terms_recurse = 1;
-	} elseif ( 10 < $global_terms_recurse++ ) {
+	} elseif ( 10 < $global_terms_recurse ++ ) {
 		return $term_id;
 	}
 
 	$term_id = intval( $term_id );
-	$c = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->terms WHERE term_id = %d", $term_id ) );
+	$c       = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->terms WHERE term_id = %d", $term_id ) );
 
 	$global_id = $wpdb->get_var( $wpdb->prepare( "SELECT cat_ID FROM $wpdb->sitecategories WHERE category_nicename = %s", $c->slug ) );
 	if ( $global_id == null ) {
 		$used_global_id = $wpdb->get_var( $wpdb->prepare( "SELECT cat_ID FROM $wpdb->sitecategories WHERE cat_ID = %d", $c->term_id ) );
 		if ( null == $used_global_id ) {
-			$wpdb->insert( $wpdb->sitecategories, array( 'cat_ID' => $term_id, 'cat_name' => $c->name, 'category_nicename' => $c->slug ) );
+			$wpdb->insert( $wpdb->sitecategories, array( 'cat_ID'            => $term_id,
+			                                             'cat_name'          => $c->name,
+			                                             'category_nicename' => $c->slug
+			) );
 			$global_id = $wpdb->insert_id;
-			if ( empty( $global_id ) )
+			if ( empty( $global_id ) ) {
 				return $term_id;
+			}
 		} else {
 			$max_global_id = $wpdb->get_var( "SELECT MAX(cat_ID) FROM $wpdb->sitecategories" );
-			$max_local_id = $wpdb->get_var( "SELECT MAX(term_id) FROM $wpdb->terms" );
+			$max_local_id  = $wpdb->get_var( "SELECT MAX(term_id) FROM $wpdb->terms" );
 			$new_global_id = max( $max_global_id, $max_local_id ) + mt_rand( 100, 400 );
-			$wpdb->insert( $wpdb->sitecategories, array( 'cat_ID' => $new_global_id, 'cat_name' => $c->name, 'category_nicename' => $c->slug ) );
+			$wpdb->insert( $wpdb->sitecategories, array( 'cat_ID'            => $new_global_id,
+			                                             'cat_name'          => $c->name,
+			                                             'category_nicename' => $c->slug
+			) );
 			$global_id = $wpdb->insert_id;
 		}
 	} elseif ( $global_id != $term_id ) {
@@ -1839,17 +1982,19 @@
 	}
 
 	if ( $global_id != $term_id ) {
-		if ( get_option( 'default_category' ) == $term_id )
+		if ( get_option( 'default_category' ) == $term_id ) {
 			update_option( 'default_category', $global_id );
+		}
 
-		$wpdb->update( $wpdb->terms, array('term_id' => $global_id), array('term_id' => $term_id) );
-		$wpdb->update( $wpdb->term_taxonomy, array('term_id' => $global_id), array('term_id' => $term_id) );
-		$wpdb->update( $wpdb->term_taxonomy, array('parent' => $global_id), array('parent' => $term_id) );
+		$wpdb->update( $wpdb->terms, array( 'term_id' => $global_id ), array( 'term_id' => $term_id ) );
+		$wpdb->update( $wpdb->term_taxonomy, array( 'term_id' => $global_id ), array( 'term_id' => $term_id ) );
+		$wpdb->update( $wpdb->term_taxonomy, array( 'parent' => $global_id ), array( 'parent' => $term_id ) );
 
-		clean_term_cache($term_id);
+		clean_term_cache( $term_id );
 	}
-	if ( $recurse_start )
+	if ( $recurse_start ) {
 		$global_terms_recurse = null;
+	}
 
 	return $global_id;
 }
@@ -1861,6 +2006,7 @@
  * @since MU
  *
  * @param array|string $deprecated Not used.
+ *
  * @return array The current site's domain
  */
 function redirect_this_site( $deprecated = '' ) {
@@ -1875,13 +2021,15 @@
  * @blessed
  *
  * @param array $upload
+ *
  * @return string|array If the upload is under the size limit, $upload is returned. Otherwise returns an error message.
  */
 function upload_is_file_too_big( $upload ) {
-	if ( ! is_array( $upload ) || defined( 'WP_IMPORTING' ) || get_site_option( 'upload_space_check_disabled' ) )
+	if ( ! is_array( $upload ) || defined( 'WP_IMPORTING' ) || get_site_option( 'upload_space_check_disabled' ) ) {
 		return $upload;
+	}
 
-	if ( strlen( $upload['bits'] )  > ( KB_IN_BYTES * get_site_option( 'fileupload_maxk', 1500 ) ) ) {
+	if ( strlen( $upload['bits'] ) > ( KB_IN_BYTES * get_site_option( 'fileupload_maxk', 1500 ) ) ) {
 		return sprintf( __( 'This file is too big. Files must be less than %d KB in size.' ) . '<br />', get_site_option( 'fileupload_maxk', 1500 ) );
 	}
 
@@ -1896,7 +2044,7 @@
 function signup_nonce_fields() {
 	$id = mt_rand();
 	echo "<input type='hidden' name='signup_form_id' value='{$id}' />";
-	wp_nonce_field('signup_form_' . $id, '_signup_form', false);
+	wp_nonce_field( 'signup_form_' . $id, '_signup_form', false );
 }
 
 /**
@@ -1905,14 +2053,17 @@
  * @since MU
  *
  * @param array $result
+ *
  * @return array
  */
 function signup_nonce_check( $result ) {
-	if ( !strpos( $_SERVER[ 'PHP_SELF' ], 'wp-signup.php' ) )
+	if ( ! strpos( $_SERVER['PHP_SELF'], 'wp-signup.php' ) ) {
 		return $result;
+	}
 
-	if ( wp_create_nonce('signup_form_' . $_POST[ 'signup_form_id' ]) != $_POST['_signup_form'] )
+	if ( wp_create_nonce( 'signup_form_' . $_POST['signup_form_id'] ) != $_POST['_signup_form'] ) {
 		wp_die( __( 'Please try again.' ) );
+	}
 
 	return $result;
 }
@@ -1933,8 +2084,9 @@
 	 * @param string $no_blog_redirect The redirect URL defined in NOBLOGREDIRECT.
 	 */
 	if ( is_main_site() && is_404() && defined( 'NOBLOGREDIRECT' ) && ( $destination = apply_filters( 'blog_redirect_404', NOBLOGREDIRECT ) ) ) {
-		if ( $destination == '%siteurl%' )
+		if ( $destination == '%siteurl%' ) {
 			$destination = network_home_url();
+		}
 		wp_redirect( $destination );
 		exit();
 	}
@@ -1950,21 +2102,25 @@
  * @since MU
  */
 function maybe_add_existing_user_to_blog() {
-	if ( false === strpos( $_SERVER[ 'REQUEST_URI' ], '/newbloguser/' ) )
+	if ( false === strpos( $_SERVER['REQUEST_URI'], '/newbloguser/' ) ) {
 		return;
+	}
 
-	$parts = explode( '/', $_SERVER[ 'REQUEST_URI' ] );
-	$key = array_pop( $parts );
+	$parts = explode( '/', $_SERVER['REQUEST_URI'] );
+	$key   = array_pop( $parts );
 
-	if ( $key == '' )
+	if ( $key == '' ) {
 		$key = array_pop( $parts );
+	}
 
 	$details = get_option( 'new_user_' . $key );
-	if ( !empty( $details ) )
+	if ( ! empty( $details ) ) {
 		delete_option( 'new_user_' . $key );
+	}
 
-	if ( empty( $details ) || is_wp_error( add_existing_user_to_blog( $details ) ) )
-		wp_die( sprintf(__('An error occurred adding you to this site. Back to the <a href="%s">homepage</a>.'), home_url() ) );
+	if ( empty( $details ) || is_wp_error( add_existing_user_to_blog( $details ) ) ) {
+		wp_die( sprintf( __( 'An error occurred adding you to this site. Back to the <a href="%s">homepage</a>.' ), home_url() ) );
+	}
 
 	wp_die( sprintf( __( 'You have been added to this site. Please visit the <a href="%s">homepage</a> or <a href="%s">log in</a> using your username and password.' ), home_url(), admin_url() ), __( 'WordPress &rsaquo; Success' ), array( 'response' => 200 ) );
 }
@@ -1977,6 +2133,7 @@
  * @global int $blog_id
  *
  * @param array $details
+ *
  * @return true|WP_Error|void
  */
 function add_existing_user_to_blog( $details = false ) {
@@ -1983,16 +2140,17 @@
 	global $blog_id;
 
 	if ( is_array( $details ) ) {
-		$result = add_user_to_blog( $blog_id, $details[ 'user_id' ], $details[ 'role' ] );
+		$result = add_user_to_blog( $blog_id, $details['user_id'], $details['role'] );
 		/**
 		 * Fires immediately after an existing user is added to a site.
 		 *
 		 * @since MU
 		 *
-		 * @param int   $user_id User ID.
-		 * @param mixed $result  True on success or a WP_Error object if the user doesn't exist.
+		 * @param int $user_id User ID.
+		 * @param mixed $result True on success or a WP_Error object if the user doesn't exist.
 		 */
 		do_action( 'added_existing_user', $details['user_id'], $result );
+
 		return $result;
 	}
 }
@@ -2006,15 +2164,15 @@
  * @since MU
  * @see add_user_to_blog()
  *
- * @param int   $user_id
+ * @param int $user_id
  * @param mixed $password Ignored.
  * @param array $meta
  */
 function add_new_user_to_blog( $user_id, $password, $meta ) {
-	if ( !empty( $meta[ 'add_to_blog' ] ) ) {
-		$blog_id = $meta[ 'add_to_blog' ];
-		$role = $meta[ 'new_role' ];
-		remove_user_from_blog($user_id, get_current_site()->blog_id); // remove user from main blog.
+	if ( ! empty( $meta['add_to_blog'] ) ) {
+		$blog_id = $meta['add_to_blog'];
+		$role    = $meta['new_role'];
+		remove_user_from_blog( $user_id, get_current_site()->blog_id ); // remove user from main blog.
 		add_user_to_blog( $blog_id, $user_id, $role );
 		update_user_meta( $user_id, 'primary_blog', $blog_id );
 	}
@@ -2037,11 +2195,12 @@
  * @since MU
  *
  * @param string|WP_User $user Optional. Defaults to current user. WP_User object,
- * 	                           or user login name as a string.
+ *                               or user login name as a string.
+ *
  * @return bool
  */
 function is_user_spammy( $user = null ) {
-    if ( ! ( $user instanceof WP_User ) ) {
+	if ( ! ( $user instanceof WP_User ) ) {
 		if ( $user ) {
 			$user = get_user_by( 'login', $user );
 		} else {
@@ -2060,7 +2219,7 @@
  * @since MU
  *
  * @param int $old_value
- * @param int $value     The new public value
+ * @param int $value The new public value
  */
 function update_blog_public( $old_value, $value ) {
 	update_blog_status( get_current_blog_id(), 'public', (int) $value );
@@ -2074,8 +2233,9 @@
  * @global wpdb $wpdb WordPress database abstraction object.
  *
  * @param string $key
- * @param int    $user_id Optional. Defaults to current user.
- * @param int    $blog_id Optional. Defaults to current blog.
+ * @param int $user_id Optional. Defaults to current user.
+ * @param int $blog_id Optional. Defaults to current blog.
+ *
  * @return bool
  */
 function is_user_option_local( $key, $user_id = 0, $blog_id = 0 ) {
@@ -2098,7 +2258,8 @@
  * @return bool
  */
 function users_can_register_signup_filter() {
-	$registration = get_site_option('registration');
+	$registration = get_site_option( 'registration' );
+
 	return ( $registration == 'all' || $registration == 'user' );
 }
 
@@ -2108,10 +2269,11 @@
  * @since MU
  *
  * @param string $text
+ *
  * @return string
  */
 function welcome_user_msg_filter( $text ) {
-	if ( !$text ) {
+	if ( ! $text ) {
 		remove_filter( 'site_option_welcome_user_email', 'welcome_user_msg_filter' );
 
 		/* translators: Do not translate USERNAME, PASSWORD, LOGINLINK, SITE_NAME: those are placeholders. */
@@ -2129,6 +2291,7 @@
 --The Team @ SITE_NAME' );
 		update_site_option( 'welcome_user_email', $text );
 	}
+
 	return $text;
 }
 
@@ -2140,6 +2303,7 @@
  * @staticvar bool $forced_content
  *
  * @param bool $force
+ *
  * @return bool True if forced, false if not forced.
  */
 function force_ssl_content( $force = '' ) {
@@ -2146,8 +2310,9 @@
 	static $forced_content = false;
 
 	if ( '' != $force ) {
-		$old_forced = $forced_content;
+		$old_forced     = $forced_content;
 		$forced_content = $force;
+
 		return $old_forced;
 	}
 
@@ -2162,14 +2327,17 @@
  * @since 2.8.5
  *
  * @param string $url URL
+ *
  * @return string URL with https as the scheme
  */
 function filter_SSL( $url ) {
-	if ( ! is_string( $url ) )
-		return get_bloginfo( 'url' ); // Return home blog url with proper scheme
+	if ( ! is_string( $url ) ) {
+		return get_bloginfo( 'url' );
+	} // Return home blog url with proper scheme
 
-	if ( force_ssl_content() && is_ssl() )
+	if ( force_ssl_content() && is_ssl() ) {
 		$url = set_url_scheme( $url, 'https' );
+	}
 
 	return $url;
 }
@@ -2180,17 +2348,19 @@
  * @since 3.1.0
  */
 function wp_schedule_update_network_counts() {
-	if ( !is_main_site() )
+	if ( ! is_main_site() ) {
 		return;
+	}
 
-	if ( ! wp_next_scheduled('update_network_counts') && ! wp_installing() )
-		wp_schedule_event(time(), 'twicedaily', 'update_network_counts');
+	if ( ! wp_next_scheduled( 'update_network_counts' ) && ! wp_installing() ) {
+		wp_schedule_event( time(), 'twicedaily', 'update_network_counts' );
+	}
 }
 
 /**
  *  Update the network-wide counts for the current network.
  *
- *  @since 3.1.0
+ * @since 3.1.0
  */
 function wp_update_network_counts() {
 	wp_update_network_user_counts();
@@ -2215,11 +2385,12 @@
 	 *
 	 * @see wp_is_large_network()
 	 *
-	 * @param bool   $small_network Whether the network is considered small.
-	 * @param string $context       Context. Either 'users' or 'sites'.
+	 * @param bool $small_network Whether the network is considered small.
+	 * @param string $context Context. Either 'users' or 'sites'.
 	 */
-	if ( ! apply_filters( 'enable_live_network_counts', $is_small_network, 'sites' ) )
+	if ( ! apply_filters( 'enable_live_network_counts', $is_small_network, 'sites' ) ) {
 		return;
+	}
 
 	wp_update_network_site_counts();
 }
@@ -2236,8 +2407,9 @@
 	$is_small_network = ! wp_is_large_network( 'users' );
 
 	/** This filter is documented in wp-includes/ms-functions.php */
-	if ( ! apply_filters( 'enable_live_network_counts', $is_small_network, 'users' ) )
+	if ( ! apply_filters( 'enable_live_network_counts', $is_small_network, 'users' ) ) {
 		return;
+	}
 
 	wp_update_network_user_counts();
 }
@@ -2252,7 +2424,11 @@
 function wp_update_network_site_counts() {
 	global $wpdb;
 
-	$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) );
+
+	$query = new WP_Site_Query();
+	$args  = array( 'network_id' => $wpdb->siteid, 'spam' => 0, 'deleted' => 0, 'archived' => 0, 'count' => true );
+	$count = $query->query( $args );
+
 	update_site_option( 'blog_count', $count );
 }
 
@@ -2304,11 +2480,13 @@
 function get_space_allowed() {
 	$space_allowed = get_option( 'blog_upload_space' );
 
-	if ( ! is_numeric( $space_allowed ) )
+	if ( ! is_numeric( $space_allowed ) ) {
 		$space_allowed = get_site_option( 'blog_upload_space' );
+	}
 
-	if ( ! is_numeric( $space_allowed ) )
+	if ( ! is_numeric( $space_allowed ) ) {
 		$space_allowed = 100;
+	}
 
 	/**
 	 * Filter the upload quota for the current site.
@@ -2333,13 +2511,15 @@
 		$allowed = 0;
 	}
 	$space_allowed = $allowed * MB_IN_BYTES;
-	if ( get_site_option( 'upload_space_check_disabled' ) )
+	if ( get_site_option( 'upload_space_check_disabled' ) ) {
 		return $space_allowed;
+	}
 
 	$space_used = get_space_used() * MB_IN_BYTES;
 
-	if ( ( $space_allowed - $space_used ) <= 0 )
+	if ( ( $space_allowed - $space_used ) <= 0 ) {
 		return 0;
+	}
 
 	return $space_allowed - $space_used;
 }
@@ -2351,8 +2531,9 @@
  * @return bool True if space is available, false otherwise.
  */
 function is_upload_space_available() {
-	if ( get_site_option( 'upload_space_check_disabled' ) )
+	if ( get_site_option( 'upload_space_check_disabled' ) ) {
 		return true;
+	}
 
 	return (bool) get_upload_space_available();
 }
@@ -2363,12 +2544,14 @@
  * @since 3.0.0
  *
  * @param  int $size Upload size limit in bytes.
+ *
  * @return int       Upload size limit in bytes.
  */
 function upload_size_limit_filter( $size ) {
 	$fileupload_maxk = KB_IN_BYTES * get_site_option( 'fileupload_maxk', 1500 );
-	if ( get_site_option( 'upload_space_check_disabled' ) )
+	if ( get_site_option( 'upload_space_check_disabled' ) ) {
 		return min( $size, $fileupload_maxk );
+	}
 
 	return min( $size, $fileupload_maxk, get_upload_space_available() );
 }
@@ -2380,25 +2563,29 @@
  * Plugins can alter this criteria using the 'wp_is_large_network' filter.
  *
  * @since 3.3.0
+ *
  * @param string $using 'sites or 'users'. Default is 'sites'.
+ *
  * @return bool True if the network meets the criteria for large. False otherwise.
  */
 function wp_is_large_network( $using = 'sites' ) {
 	if ( 'users' == $using ) {
 		$count = get_user_count();
+
 		/**
 		 * Filter whether the network is considered large.
 		 *
 		 * @since 3.3.0
 		 *
-		 * @param bool   $is_large_network Whether the network has more than 10000 users or sites.
-		 * @param string $component        The component to count. Accepts 'users', or 'sites'.
-		 * @param int    $count            The count of items for the component.
+		 * @param bool $is_large_network Whether the network has more than 10000 users or sites.
+		 * @param string $component The component to count. Accepts 'users', or 'sites'.
+		 * @param int $count The count of items for the component.
 		 */
 		return apply_filters( 'wp_is_large_network', $count > 10000, 'users', $count );
 	}
 
 	$count = get_blog_count();
+
 	/** This filter is documented in wp-includes/ms-functions.php */
 	return apply_filters( 'wp_is_large_network', $count > 10000, 'sites', $count );
 }
@@ -2414,15 +2601,15 @@
  * @param array $args {
  *     Array of default arguments. Optional.
  *
- *     @type int|array $network_id A network ID or array of network IDs. Set to null to retrieve sites
+ * @type int|array $network_id A network ID or array of network IDs. Set to null to retrieve sites
  *                                 from all networks. Defaults to current network ID.
- *     @type int       $public     Retrieve public or non-public sites. Default null, for any.
- *     @type int       $archived   Retrieve archived or non-archived sites. Default null, for any.
- *     @type int       $mature     Retrieve mature or non-mature sites. Default null, for any.
- *     @type int       $spam       Retrieve spam or non-spam sites. Default null, for any.
- *     @type int       $deleted    Retrieve deleted or non-deleted sites. Default null, for any.
- *     @type int       $limit      Number of sites to limit the query to. Default 100.
- *     @type int       $offset     Exclude the first x sites. Used in combination with the $limit parameter. Default 0.
+ * @type int $public Retrieve public or non-public sites. Default null, for any.
+ * @type int $archived Retrieve archived or non-archived sites. Default null, for any.
+ * @type int $mature Retrieve mature or non-mature sites. Default null, for any.
+ * @type int $spam Retrieve spam or non-spam sites. Default null, for any.
+ * @type int $deleted Retrieve deleted or non-deleted sites. Default null, for any.
+ * @type int $limit Number of sites to limit the query to. Default 100.
+ * @type int $offset Exclude the first x sites. Used in combination with the $limit parameter. Default 0.
  * }
  * @return array An empty array if the install is considered "large" via wp_is_large_network(). Otherwise,
  *               an associative array of site data arrays, each containing the site (network) ID, blog ID,
@@ -2432,16 +2619,8 @@
 function wp_get_sites( $args = array() ) {
 	global $wpdb;
 
-	if ( wp_is_large_network() )
-		return array();
-
 	$defaults = array(
 		'network_id' => $wpdb->siteid,
-		'public'     => null,
-		'archived'   => null,
-		'mature'     => null,
-		'spam'       => null,
-		'deleted'    => null,
 		'limit'      => 100,
 		'offset'     => 0,
 	);
@@ -2448,38 +2627,9 @@
 
 	$args = wp_parse_args( $args, $defaults );
 
-	$query = "SELECT * FROM $wpdb->blogs WHERE 1=1 ";
+	$query = new WP_Site_Query();
 
-	if ( isset( $args['network_id'] ) && ( is_array( $args['network_id'] ) || is_numeric( $args['network_id'] ) ) ) {
-		$network_ids = implode( ',', wp_parse_id_list( $args['network_id'] ) );
-		$query .= "AND site_id IN ($network_ids) ";
-	}
-
-	if ( isset( $args['public'] ) )
-		$query .= $wpdb->prepare( "AND public = %d ", $args['public'] );
-
-	if ( isset( $args['archived'] ) )
-		$query .= $wpdb->prepare( "AND archived = %d ", $args['archived'] );
-
-	if ( isset( $args['mature'] ) )
-		$query .= $wpdb->prepare( "AND mature = %d ", $args['mature'] );
-
-	if ( isset( $args['spam'] ) )
-		$query .= $wpdb->prepare( "AND spam = %d ", $args['spam'] );
-
-	if ( isset( $args['deleted'] ) )
-		$query .= $wpdb->prepare( "AND deleted = %d ", $args['deleted'] );
-
-	if ( isset( $args['limit'] ) && $args['limit'] ) {
-		if ( isset( $args['offset'] ) && $args['offset'] )
-			$query .= $wpdb->prepare( "LIMIT %d , %d ", $args['offset'], $args['limit'] );
-		else
-			$query .= $wpdb->prepare( "LIMIT %d ", $args['limit'] );
-	}
-
-	$site_results = $wpdb->get_results( $query, ARRAY_A );
-
-	return $site_results;
+	return $query->query( $args );
 }
 
 /**
@@ -2491,8 +2641,16 @@
  */
 function get_subdirectory_reserved_names() {
 	$names = array(
-		'page', 'comments', 'blog', 'files', 'feed', 'wp-admin',
-		'wp-content', 'wp-includes', 'wp-json', 'embed'
+		'page',
+		'comments',
+		'blog',
+		'files',
+		'feed',
+		'wp-admin',
+		'wp-content',
+		'wp-includes',
+		'wp-json',
+		'embed'
 	);
 
 	/**
Index: wp-includes/ms-load.php
===================================================================
--- wp-includes/ms-load.php	(revision 37134)
+++ wp-includes/ms-load.php	(working copy)
@@ -231,27 +231,12 @@
 	$domains = array( $domain );
 	if ( 'www.' === substr( $domain, 0, 4 ) ) {
 		$domains[] = substr( $domain, 4 );
-		$search_domains = "'" . implode( "', '", $wpdb->_escape( $domains ) ) . "'";
 	}
 
-	if ( count( $paths ) > 1 ) {
-		$search_paths = "'" . implode( "', '", $wpdb->_escape( $paths ) ) . "'";
-	}
-
-	if ( count( $domains ) > 1 && count( $paths ) > 1 ) {
-		$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" );
-	} elseif ( count( $domains ) > 1 ) {
-		$sql = $wpdb->prepare( "SELECT * FROM $wpdb->blogs WHERE path = %s", $paths[0] );
-		$sql .= " AND domain IN ($search_domains) ORDER BY CHAR_LENGTH(domain) DESC LIMIT 1";
-		$site = $wpdb->get_row( $sql );
-	} elseif ( count( $paths ) > 1 ) {
-		$sql = $wpdb->prepare( "SELECT * FROM $wpdb->blogs WHERE domain = %s", $domains[0] );
-		$sql .= " AND path IN ($search_paths) ORDER BY CHAR_LENGTH(path) DESC LIMIT 1";
-		$site = $wpdb->get_row( $sql );
-	} else {
-		$site = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->blogs WHERE domain = %s AND path = %s", $domains[0], $paths[0] ) );
-	}
-
+	$query = new WP_Site_Query();
+	$args = array( 'path__in' => $path, 'domain__in' => $domains, 'number' => 1 );
+	$result = $query->query( $args );
+	$site   = array_shift( $result );
 	if ( $site ) {
 		// @todo get_blog_details()
 		return $site;
Index: wp-settings.php
===================================================================
--- wp-settings.php	(revision 37134)
+++ wp-settings.php	(working copy)
@@ -99,6 +99,7 @@
 
 // Initialize multisite if enabled.
 if ( is_multisite() ) {
+	require( ABSPATH . WPINC . '/class-wp-site-query.php' );
 	require( ABSPATH . WPINC . '/ms-blogs.php' );
 	require( ABSPATH . WPINC . '/ms-settings.php' );
 } elseif ( ! defined( 'MULTISITE' ) ) {
