Index: wp-includes/class-wp-network.php
--- wp-includes/class-wp-network.php
+++ wp-includes/class-wp-network.php
@@ -0,0 +1,540 @@
+<?php
+
+/**
+ * Main network class
+ *
+ * This class contains the values and functional methods for interacting with
+ * a network of WordPress sites. Traditionally used for multisite, this class
+ * is used by the $current_site global to setup the current network
+ *
+ * This class is most useful in WordPress multi-network installations where the
+ * ability to interact with any network of sites is required.
+ *
+ * @since WordPress (4.3.0)
+ */
+class WP_Network {
+
+	/**
+	 * Unique numerical ID
+	 *
+	 * @since WordPress (4.3.0)
+	 *
+	 * @var int
+	 */
+	public $id = 0;
+
+	/**
+	 * Domain of this network
+	 *
+	 * @since WordPress (4.3.0)
+	 *
+	 * @var string
+	 */
+	public $domain = '';
+
+	/**
+	 * Path of this network
+	 *
+	 * @since WordPress (4.3.0)
+	 *
+	 * @var string
+	 */
+	public $path = '';
+
+	/**
+	 * The ID of the site mapped to this network
+	 *
+	 * Named "blog" vs. "site" for legacy reasons
+	 *
+	 * @since WordPress (4.3.0)
+	 *
+	 * @var int
+	 */
+	public $blog_id = '';
+
+	/**
+	 * Domain used for cookies for this network
+	 *
+	 * @since WordPress (4.3.0)
+	 *
+	 * @var int
+	 */
+	public $cookie_domain = '';
+
+	/**
+	 * Array of core options for this network
+	 *
+	 * @since WordPress (4.3.0)
+	 *
+	 * @var array
+	 */
+	public $core_options = array();
+
+	/**
+	 * Name of this network
+	 *
+	 * Named "nite" vs. "network" for legacy reasons
+	 *
+	 * @since WordPress (4.3.0)
+	 *
+	 * @var string
+	 */
+	public $site_name = '';
+
+	/**
+	 * Create a new WP_Network object
+	 *
+	 * Will populate all relevant data if a network ID or object is passed
+	 *
+	 * @since WordPress (4.3.0)
+	 *
+	 * @param mixed $network stdClass object or network ID
+	 * @return object
+	 */
+	public function __construct( $network = false ) {
+
+		// Bail if not populating from an existing network
+		if ( empty( $network ) ) {
+			return;
+		}
+
+		// Get the network ID
+		if ( is_object( $network ) && isset( $network->id ) ) {
+			$network_id = $network->id;
+		} elseif ( is_numeric( $network ) ) {
+			$network_id = (int) $network;
+		} else {
+			return;
+		}
+
+		// Populate network object and return it
+		if ( ! empty( $network_id ) ) {
+			$this->populate( $network_id );
+			return $this;
+		}
+	}
+
+	public function populate( $network_id = 0 ) {
+
+		// Query for network
+		$network = self::get_by_id( $network_id );
+
+		// Bail if no network to update
+		if ( false === $network ) {
+			return false;
+		}
+
+		// Set the main data
+		$this->set_main_data( $network );
+
+		// Set supplemental data based on the needs of multisite
+		$this->set_cookie_domain();
+		$this->set_core_options();
+		$this->set_site_name();
+	}
+
+	/**
+	 * Set the network ID, domain, and path
+	 *
+	 * @since WordPress (4.3.0)
+	 */
+	private function set_main_data( $network ) {
+		$this->id     = $network->id;
+		$this->domain = $network->domain;
+		$this->path   = $network->path;
+	}
+
+	/**
+	 * Set the cookie domain, based on the network domain
+	 *
+	 * @todo What if the domain of the network doesn't match the current site?
+	 *
+	 * @since WordPress (4.3.0)
+	 */
+	private function set_cookie_domain() {
+		$this->cookie_domain = $this->domain;
+		if ( 'www.' === substr( $this->cookie_domain, 0, 4 ) ) {
+			$this->cookie_domain = substr( $this->cookie_domain, 4 );
+		}
+	}
+
+	/**
+	 * Set the core options for this network object
+	 *
+	 * @since WordPress (4.3.0)
+	 */
+	private function set_core_options() {
+		$this->core_options = self::get_core_options( $this->id );
+	}
+
+	/**
+	 * @todo What if the domain of the network doesn't match the current site?
+	 */
+	private function set_site_name() {
+
+		// Attempt to use core option
+		if ( empty( $this->core_options['site_name'] ) ) {
+			$this->site_name = $this->core_options['site_name'];
+
+		// Fallback to domain
+		} else {
+			$this->site_name = ucfirst( $this->domain );
+		}
+	}
+
+	public static function get_by_id( $network_id = 0 ) {
+		global $wpdb;
+
+		// Check cache
+		$network = wp_cache_get( $network_id, 'networks' );
+
+		// Cache miss
+		if ( false === $network ) {
+
+			// Query for network data
+			$network = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->site} WHERE id = %d", $network_id ) );
+
+			// Bail if network cannot be found
+			if ( empty( $network ) || is_wp_error( $network ) ) {
+				$network = false;
+			}
+
+			// Add network to cache
+			wp_cache_add( $network_id, $network, 'networks' );
+		}
+
+		// Return the network
+		return $network;
+	}
+
+	/**
+	 * Retrieve a network by its domain and path.
+	 *
+	 * @since 4.3.0
+	 *
+	 * @param string   $domain   Domain to check.
+	 * @param string   $path     Path to check.
+	 * @param int|null $segments Path segments to use. Defaults to null, or the full path.
+	 *
+	 * @return object|bool Network object if successful. False when no network is found.
+	 */
+	public static function get_by_path( $domain = '', $path = '', $segments = null ) {
+		global $wpdb;
+
+		$domains = array( $domain );
+		$pieces  = explode( '.', $domain );
+
+		/*
+		 * It's possible one domain to search is 'com', but it might as well
+		 * be 'localhost' or some other locally mapped domain.
+		 */
+		while ( array_shift( $pieces ) ) {
+			if ( ! empty( $pieces ) ) {
+				$domains[] = implode( '.', $pieces );
+			}
+		}
+
+		/*
+		 * If we've gotten to this function during normal execution, there is
+		 * more than one network installed. At this point, who knows how many
+		 * we have. Attempt to optimize for the situation where networks are
+		 * only domains, thus meaning paths never need to be considered.
+		 *
+		 * This is a very basic optimization; anything further could have
+		 * drawbacks depending on the setup, so this is best done per-install.
+		 */
+		$using_paths = true;
+		if ( wp_using_ext_object_cache() ) {
+			$using_paths = wp_cache_get( 'networks_have_paths', 'site-options' );
+			if ( false === $using_paths ) {
+				$using_paths = (bool) $wpdb->get_var( "SELECT id FROM {$wpdb->site} WHERE path <> '/' LIMIT 1" );
+				wp_cache_add( 'networks_have_paths', (int) $using_paths, 'site-options'  );
+			}
+		}
+
+		$paths = array();
+		if ( true === $using_paths ) {
+			$path_segments = array_filter( explode( '/', trim( $path, '/' ) ) );
+
+			/**
+			 * Filter the number of path segments to consider when searching for a site.
+			 *
+			 * @since 3.9.0
+			 *
+			 * @param int|null $segments The number of path segments to consider. WordPress by default looks at
+			 *                           one path segment. The function default of null only makes sense when you
+			 *                           know the requested path should match a network.
+			 * @param string   $domain   The requested domain.
+			 * @param string   $path     The requested path, in full.
+			 */
+			$segments = apply_filters( 'network_by_path_segments_count', $segments, $domain, $path );
+
+			if ( ( null !== $segments ) && count( $path_segments ) > $segments ) {
+				$path_segments = array_slice( $path_segments, 0, $segments );
+			}
+
+			while ( count( $path_segments ) ) {
+				$paths[] = '/' . implode( '/', $path_segments ) . '/';
+				array_pop( $path_segments );
+			}
+
+			$paths[] = '/';
+		}
+
+		/**
+		 * Determine a network by its domain and path.
+		 *
+		 * This allows one to short-circuit the default logic, perhaps by
+		 * replacing it with a routine that is more optimal for your setup.
+		 *
+		 * Return null to avoid the short-circuit. Return false if no network
+		 * can be found at the requested domain and path. Otherwise, return
+		 * an object from wp_get_network().
+		 *
+		 * @since 3.9.0
+		 *
+		 * @param null|bool|object $network  Network value to return by path.
+		 * @param string           $domain   The requested domain.
+		 * @param string           $path     The requested path, in full.
+		 * @param int|null         $segments The suggested number of paths to consult.
+		 *                                   Default null, meaning the entire path was to be consulted.
+		 * @param array            $paths    The paths to search for, based on $path and $segments.
+		 */
+		$pre = apply_filters( 'pre_get_network_by_path', null, $domain, $path, $segments, $paths );
+		if ( null !== $pre ) {
+			return $pre;
+		}
+
+		// @todo Consider additional optimization routes, perhaps as an opt-in for plugins.
+		// We already have paths covered. What about how far domains should be drilled down (including www)?
+
+		$search_domains = "'" . implode( "', '", $wpdb->_escape( $domains ) ) . "'";
+
+		if ( false === $using_paths ) {
+			$network = $wpdb->get_row( "SELECT * FROM {$wpdb->site}
+										WHERE domain IN ({$search_domains})
+										ORDER BY CHAR_LENGTH(domain)
+										DESC LIMIT 1" );
+
+			if ( ! empty( $network ) && ! is_wp_error( $network ) ) {
+				return new WP_Network( $network->id );
+			}
+
+			return false;
+
+		} else {
+			$search_paths = "'" . implode( "', '", $wpdb->_escape( $paths ) ) . "'";
+			$networks     = $wpdb->get_results( "SELECT * FROM {$wpdb->site}
+												 WHERE domain IN ({$search_domains})
+												 AND path IN ({$search_paths})
+												 ORDER BY CHAR_LENGTH(domain) DESC, CHAR_LENGTH(path) DESC" );
+		}
+
+		/*
+		 * Domains are sorted by length of domain, then by length of path.
+		 * The domain must match for the path to be considered. Otherwise,
+		 * a network with the path of / will suffice.
+		 */
+		$found = false;
+		foreach ( $networks as $network ) {
+			if ( ( $network->domain === $domain ) || ( "www.{$network->domain}" === $domain ) ) {
+				if ( in_array( $network->path, $paths, true ) ) {
+					$found = true;
+					break;
+				}
+			}
+			if ( $network->path === '/' ) {
+				$found = true;
+				break;
+			}
+		}
+
+		if ( true === $found ) {
+			return new WP_Network( $network->id );
+		}
+
+		return false;
+	}
+	
+	public static function get_core_options( $network_id = 0 ) {
+		global $wpdb;
+
+		// Setup core options query
+		$meta_keys       = self::get_core_option_keys();
+		$core_options_in = "'" . implode( "', '", $meta_keys ) . "'";
+		$sql             = $wpdb->prepare( "SELECT meta_key, meta_value
+											FROM {$wpdb->sitemeta}
+											WHERE meta_key IN ({$core_options_in})
+											AND site_id = %d", $network_id );
+
+		// Query for core network options
+		$options = $wpdb->get_results( $sql );
+
+		// Bail if no options found
+		if ( empty( $options ) || is_wp_error( $options ) ) {
+			return array();
+		}
+
+		// Setup return value array
+		$retval = array();
+
+		// Loop through options and add them to the object cache
+		foreach ( $options as $option ) {
+
+			// Setup option values to cache
+			$key                = $option->meta_key;
+			$cache_key          = "{$network_id}:$key";
+			$option->meta_value = maybe_unserialize( $option->meta_value );
+
+			// Cache the option value
+			wp_cache_set( $cache_key, $option->meta_value, 'site-options' );
+
+			// Add option to array
+			$retval[ $option->meta_key ] = $option->meta_value;
+		}
+
+		// Return the options
+		return $options;
+	}
+
+	public static function get_core_option_keys() {
+		return array(
+			'site_name',
+			'siteurl',
+			'active_sitewide_plugins',
+			'_site_transient_timeout_theme_roots',
+			'_site_transient_theme_roots',
+			'site_admins',
+			'can_compress_scripts',
+			'global_terms_enabled',
+			'ms_files_rewriting'
+		);
+	}
+
+	/**
+	 * Get all active network-wide plugins for this network
+	 *
+	 * @since WordPress (4.3.0)
+	 *
+	 * @param int $network_id
+	 * @return array
+	 */
+	public static function get_active_network_plugins( $network_id = 0 ) {
+		$network_options = self::get_core_options( $network_id );
+		$active_plugins  = $network_options['active_sitewide_plugins'];
+		if ( empty( $active_plugins ) ) {
+			return array();
+		}
+
+		// Setup the plugins array
+		$plugins        = array();
+		$active_plugins = array_keys( $active_plugins );
+
+		// Sort plugins array
+		sort( $active_plugins );
+
+		foreach ( $active_plugins as $plugin ) {
+			if ( self::validate_network_plugin( $plugin ) ) {
+				$plugins[] = WP_PLUGIN_DIR . '/' . $plugin;
+			}
+		}
+
+		return $plugins;
+	}
+
+	/**
+	 * Ensure a single network-wide plugin is valid
+	 *
+	 * @since WordPress (4.3.0)
+	 *
+	 * @param type $plugin
+	 *
+	 * @return boolean
+	 */
+	private static function validate_network_plugin( $plugin = '' ) {
+
+		// $plugin must validate as file
+		if ( ! validate_file( $plugin ) ) {
+			return false;
+		}
+
+		// $plugin must end with '.php'
+		if ( '.php' !== substr( $plugin, -4 ) ) {
+			return false;
+		}
+
+		// $plugin must exist
+		if ( ! file_exists( WP_PLUGIN_DIR . '/' . $plugin ) ) {
+			return false;
+		}
+
+		return true;
+	}
+
+	public static function add( $domain = '', $path = '' ) {
+		
+	}
+
+	/**
+	 * Update a networks domain & path based on its ID
+	 * 
+	 * @since WordPress (4.3.0)
+	 *
+	 * @global type $wpdb
+	 *
+	 * @param int    $network_id Existing network ID
+	 * @param string $domain     New network domain
+	 * @param string $path       New network path
+	 *
+	 * @return mixed False if network not found. Results of query if updated.
+	 */
+	public static function update( $network_id = 0, $domain = '', $path = '' ) {
+		global $wpdb;
+
+		// Does network exist
+		$network = self::get_by_id( $network_id );
+
+		// Bail if no network to update
+		if ( false === $network ) {
+			return false;
+		}
+
+		// Set the domain
+		if ( ! empty( $domain ) ) {
+			$network->domain = $domain;
+		}
+
+		// Set the path
+		if ( ! empty( $path ) ) {
+			$network->path = $path;
+		}
+
+		// Query for network data
+		$sql     = $wpdb->prepare( "UPDATE {$wpdb->site} SET domain = %s, path = %s WHERE id = %d", $network->domain, $network->path, $network->id );
+		$network = $wpdb->query( $sql );
+
+		// Bail if network cannot be found
+		if ( empty( $network ) || is_wp_error( $network ) ) {
+			return false;
+		}
+
+		// Return results of WPDB::query()
+		return $network;
+	}
+
+	public static function delete( $network_id = 0 ) {
+		global $wpdb;
+
+		// Does network exist
+		$network = self::get_by_id( $network_id );
+
+		// Bail if no network to delete
+		if ( false === $network ) {
+			return false;
+		}
+
+		// Query for network data
+		$sql     = $wpdb->prepare( "DELETE FROM {$wpdb->site} WHERE id = %d", $network->id );
+		$network = $wpdb->query( $sql );
+	}
+}
Index: wp-includes/ms-load.php
--- wp-includes/ms-load.php
+++ wp-includes/ms-load.php
@@ -16,11 +16,14 @@
  * @return bool True if subdomain configuration is enabled, false otherwise.
  */
 function is_subdomain_install() {
-	if ( defined('SUBDOMAIN_INSTALL') )
+
+	if ( defined( 'SUBDOMAIN_INSTALL' ) ) {
 		return SUBDOMAIN_INSTALL;
+	}
 
-	if ( defined('VHOST') && VHOST == 'yes' )
+	if ( defined( 'VHOST' ) && ( VHOST === 'yes' ) ) {
 		return true;
+	}
 
 	return false;
 }
@@ -37,22 +40,7 @@
  * @return array Files to include.
  */
 function wp_get_active_network_plugins() {
-	$active_plugins = (array) get_site_option( 'active_sitewide_plugins', array() );
-	if ( empty( $active_plugins ) )
-		return array();
-
-	$plugins = array();
-	$active_plugins = array_keys( $active_plugins );
-	sort( $active_plugins );
-
-	foreach ( $active_plugins as $plugin ) {
-		if ( ! validate_file( $plugin ) // $plugin must validate as file
-			&& '.php' == substr( $plugin, -4 ) // $plugin must end with '.php'
-			&& file_exists( WP_PLUGIN_DIR . '/' . $plugin ) // $plugin must exist
-			)
-		$plugins[] = WP_PLUGIN_DIR . '/' . $plugin;
-	}
-	return $plugins;
+	return WP_Network::get_active_network_plugins();
 }
 
 /**
@@ -113,149 +101,248 @@
 }
 
 /**
- * Retrieve a network object by its domain and path.
+ * Set relevant multisite globals
  *
- * @since 3.9.0
+ * @since WordPress (4.3.0)
  *
- * @param string   $domain   Domain to check.
- * @param string   $path     Path to check.
- * @param int|null $segments Path segments to use. Defaults to null, or the full path.
- * @return object|bool Network object if successful. False when no network is found.
+ * @global object $current_site
+ * @global object $current_blog
+ * @global object $wpdb
+ *
+ * @return if already set by sunrise.php
  */
-function get_network_by_path( $domain, $path, $segments = null ) {
-	global $wpdb;
+function ms_set_current_globals() {
+	global $current_site, $current_blog, $wpdb;
 
-	$domains = array( $domain );
-	$pieces = explode( '.', $domain );
+	// Bail if network and site are already set
+	if ( isset( $current_site ) && isset( $current_blog ) ) {
+		return;
+	}
 
-	/*
-	 * It's possible one domain to search is 'com', but it might as well
-	 * be 'localhost' or some other locally mapped domain.
-	 */
-	while ( array_shift( $pieces ) ) {
-		if ( $pieces ) {
-			$domains[] = implode( '.', $pieces );
-		}
+	// Given the domain and path, let's try to identify the network and site.
+	// Usually, it's easier to query the site first, which declares its network.
+	// In limited situations, though, we either can or must find the network first.
+
+	$domain = strtolower( stripslashes( $_SERVER['HTTP_HOST'] ) );
+	if ( substr( $domain, -3 ) == ':80' ) {
+		$domain               = substr( $domain, 0, -3 );
+		$_SERVER['HTTP_HOST'] = substr( $_SERVER['HTTP_HOST'], 0, -3 );
+	} elseif ( substr( $domain, -4 ) == ':443' ) {
+		$domain               = substr( $domain, 0, -4 );
+		$_SERVER['HTTP_HOST'] = substr( $_SERVER['HTTP_HOST'], 0, -4 );
 	}
 
+	$path = stripslashes( $_SERVER['REQUEST_URI'] );
+	if ( is_admin() ) {
+		$path = preg_replace( '#(.*)/wp-admin/.*#', '$1/', $path );
+	}
+	list( $path ) = explode( '?', $path );
+
+	// If the network is defined in wp-config.php, we can simply use that.
+	if ( defined( 'DOMAIN_CURRENT_SITE' ) && defined( 'PATH_CURRENT_SITE' ) ) {
+		$current_site         = new WP_Network();
+		$current_site->id     = defined( 'SITE_ID_CURRENT_SITE' ) ? SITE_ID_CURRENT_SITE : 1;
+		$current_site->domain = DOMAIN_CURRENT_SITE;
+		$current_site->path   = PATH_CURRENT_SITE;
+
+		if ( defined( 'BLOG_ID_CURRENT_SITE' ) ) {
+			$current_site->blog_id = BLOG_ID_CURRENT_SITE;
+		} elseif ( defined( 'BLOGID_CURRENT_SITE' ) ) { // deprecated.
+			$current_site->blog_id = BLOGID_CURRENT_SITE;
+		}
+
+		if ( 0 === strcasecmp( $current_site->domain, $domain ) && 0 === strcasecmp( $current_site->path, $path ) ) {
+			$current_blog = get_site_by_path( $domain, $path );
+
+		// If the current network has a path and also matches the domain and
+		// path of the request, we need to look for a site using the first path
+		// segment following the network's path.
+		} elseif ( '/' !== $current_site->path && 0 === strcasecmp( $current_site->domain, $domain ) && 0 === stripos( $path, $current_site->path ) ) {
+			$current_blog = get_site_by_path( $domain, $path, 1 + count( explode( '/', trim( $current_site->path, '/' ) ) ) );
+
+		// Otherwise, use the first path segment (as usual).
+		} else {
+			$current_blog = get_site_by_path( $domain, $path, 1 );
+		}
+
 	/*
-	 * If we've gotten to this function during normal execution, there is
-	 * more than one network installed. At this point, who knows how many
-	 * we have. Attempt to optimize for the situation where networks are
-	 * only domains, thus meaning paths never need to be considered.
-	 *
-	 * This is a very basic optimization; anything further could have drawbacks
-	 * depending on the setup, so this is best done per-install.
+	 * A "subdomain" install can be re-interpreted to mean "can support anydomain".
+	 * If we're not dealing with one of these installs, then the important part
+	 * is determining the network first, because we need the network's path to
+	 * identify any sites.
 	 */
-	$using_paths = true;
-	if ( wp_using_ext_object_cache() ) {
-		$using_paths = wp_cache_get( 'networks_have_paths', 'site-options' );
-		if ( false === $using_paths ) {
-			$using_paths = (bool) $wpdb->get_var( "SELECT id FROM $wpdb->site WHERE path <> '/' LIMIT 1" );
-			wp_cache_add( 'networks_have_paths', (int) $using_paths, 'site-options'  );
+	} elseif ( ! is_subdomain_install() ) {
+
+		// Attempt to get the current network from cache
+		$current_site = wp_cache_get( 'current_network', 'site-options' );
+		if ( false === $current_site ) {
+
+			// Are there even two networks installed?
+			$one_network = $wpdb->get_row( "SELECT * FROM {$wpdb->site} LIMIT 2" );
+			if ( 1 === $wpdb->num_rows ) {
+				$current_site = new WP_Network( $one_network );
+				wp_cache_add( 'current_network', $current_site, 'site-options' );
+			} elseif ( 0 === $wpdb->num_rows ) {
+				ms_not_installed();
+			}
 		}
-	}
 
-	$paths = array();
-	if ( $using_paths ) {
-		$path_segments = array_filter( explode( '/', trim( $path, "/" ) ) );
+		// No network found, so attempt to query it by path
+		if ( empty( $current_site ) ) {
+			$current_site = get_network_by_path( $domain, $path, 1 );
+		}
 
-		/**
-		 * Filter the number of path segments to consider when searching for a site.
-		 *
-		 * @since 3.9.0
-		 *
-		 * @param int|null $segments The number of path segments to consider. WordPress by default looks at
-		 *                           one path segment. The function default of null only makes sense when you
-		 *                           know the requested path should match a network.
-		 * @param string   $domain   The requested domain.
-		 * @param string   $path     The requested path, in full.
-		 */
-		$segments = apply_filters( 'network_by_path_segments_count', $segments, $domain, $path );
+		// Bail if no network found
+		if ( empty( $current_site ) ) {
+			ms_not_installed();
+	
+		// Set current site if path matches
+		} elseif ( $path === $current_site->path ) {
+			$current_blog = get_site_by_path( $domain, $path );
 
-		if ( null !== $segments && count($path_segments ) > $segments ) {
-			$path_segments = array_slice( $path_segments, 0, $segments );
+		// Search the network path + one more path segment (on top of the network path).
+		} else {
+			$current_blog = get_site_by_path( $domain, $path, substr_count( $current_site->path, '/' ) );
 		}
+	} else {
 
-		while ( count( $path_segments ) ) {
-			$paths[] = '/' . implode( '/', $path_segments ) . '/';
-			array_pop( $path_segments );
+		// Find the site by the domain and at most the first path segment.
+		$current_blog = get_site_by_path( $domain, $path, 1 );
+		if ( ! empty( $current_blog ) ) {
+			$network_id   = $current_blog->site_id ? $current_blog->site_id : 1;
+			$current_site = new WP_Network( $network_id );
+
+		// If you don't have a site with the same domain/path as a network,
+		// you're pretty screwed, but...
+		} else {
+			$current_site = get_network_by_path( $domain, $path, 1 );
 		}
+	}
 
-		$paths[] = '/';
+	// The network declared by the site trumps any constants.
+	if ( ! empty( $current_blog ) && ( $current_blog->site_id !== $current_site->id ) ) {
+		$current_site = new WP_Network( $current_blog->site_id );
 	}
 
-	/**
-	 * Determine a network by its domain and path.
-	 *
-	 * This allows one to short-circuit the default logic, perhaps by
-	 * replacing it with a routine that is more optimal for your setup.
-	 *
-	 * Return null to avoid the short-circuit. Return false if no network
-	 * can be found at the requested domain and path. Otherwise, return
-	 * an object from wp_get_network().
-	 *
-	 * @since 3.9.0
-	 *
-	 * @param null|bool|object $network  Network value to return by path.
-	 * @param string           $domain   The requested domain.
-	 * @param string           $path     The requested path, in full.
-	 * @param int|null         $segments The suggested number of paths to consult.
-	 *                                   Default null, meaning the entire path was to be consulted.
-	 * @param array            $paths    The paths to search for, based on $path and $segments.
-	 */
-	$pre = apply_filters( 'pre_get_network_by_path', null, $domain, $path, $segments, $paths );
-	if ( null !== $pre ) {
-		return $pre;
+	// Bail if no network has been found by now
+	if ( empty( $current_site ) ) {
+		ms_not_installed();
 	}
 
-	// @todo Consider additional optimization routes, perhaps as an opt-in for plugins.
-	// We already have paths covered. What about how far domains should be drilled down (including www)?
+	// @todo Investigate when exactly this can occur.
+	if ( empty( $current_blog ) && defined( 'WP_INSTALLING' ) ) {
+		$current_blog = new stdClass;
+		$current_blog->blog_id = $blog_id = 1;
+	}
 
-	$search_domains = "'" . implode( "', '", $wpdb->_escape( $domains ) ) . "'";
+	// No site has been found, bail.
+	if ( empty( $current_blog ) ) {
 
-	if ( ! $using_paths ) {
-		$network = $wpdb->get_row( "SELECT id, domain, path FROM $wpdb->site
-			WHERE domain IN ($search_domains) ORDER BY CHAR_LENGTH(domain) DESC LIMIT 1" );
-		if ( $network ) {
-			return wp_get_network( $network );
-		}
-		return false;
+		// We're going to redirect to the network URL, with some possible modifications.
+		$scheme      = is_ssl() ? 'https' : 'http';
+		$destination = "$scheme://{$current_site->domain}{$current_site->path}";
 
-	} else {
-		$search_paths = "'" . implode( "', '", $wpdb->_escape( $paths ) ) . "'";
-		$networks = $wpdb->get_results( "SELECT id, domain, path FROM $wpdb->site
-			WHERE domain IN ($search_domains) AND path IN ($search_paths)
-			ORDER BY CHAR_LENGTH(domain) DESC, CHAR_LENGTH(path) DESC" );
-	}
+		/**
+		 * Fires when a network can be determined but a site cannot.
+		 *
+		 * At the time of this action, the only recourse is to redirect somewhere
+		 * and exit. If you want to declare a particular site, do so earlier.
+		 *
+		 * @since 3.9.0
+		 *
+		 * @param object $current_site The network that had been determined.
+		 * @param string $domain       The domain used to search for a site.
+		 * @param string $path         The path used to search for a site.
+		 */
+		do_action( 'ms_site_not_found', $current_site, $domain, $path );
 
-	/*
-	 * Domains are sorted by length of domain, then by length of path.
-	 * The domain must match for the path to be considered. Otherwise,
-	 * a network with the path of / will suffice.
-	 */
-	$found = false;
-	foreach ( $networks as $network ) {
-		if ( $network->domain === $domain || "www.$network->domain" === $domain ) {
-			if ( in_array( $network->path, $paths, true ) ) {
-				$found = true;
-				break;
+		// For a "subdomain" install, redirect to the signup form specifically.
+		if ( is_subdomain_install() && ! defined( 'NOBLOGREDIRECT' ) ) {
+			$destination .= 'wp-signup.php?new=' . str_replace( '.' . $current_site->domain, '', $domain );
+
+		// For a "subdomain" install, the NOBLOGREDIRECT constant
+		// can be used to avoid a redirect to the signup form.
+		// Using the ms_site_not_found action is preferred to the constant.
+		} elseif ( is_subdomain_install() ) {
+			if ( '%siteurl%' !== NOBLOGREDIRECT ) {
+				$destination = NOBLOGREDIRECT;
 			}
+
+		// If the domain we were searching for matches the network's domain,
+		// it's no use redirecting back to ourselves -- it'll cause a loop.
+		// As we couldn't find a site, we're simply not installed.
+		} elseif ( 0 === strcasecmp( $current_site->domain, $domain ) ) {
+			ms_not_installed();
 		}
-		if ( $network->path === '/' ) {
-			$found = true;
-			break;
-		}
+
+		header( 'Location: ' . $destination );
+		exit;
 	}
 
-	if ( $found ) {
-		return wp_get_network( $network );
+	// Figure out the current network's main site.
+	if ( ! isset( $current_site->blog_id ) ) {
+		if ( ( $current_blog->domain === $current_site->domain ) && ( $current_blog->path === $current_site->path ) ) {
+			$current_site->blog_id = $current_blog->blog_id;
+		} elseif ( ! $current_site->blog_id = wp_cache_get( 'network:' . $current_site->id . ':main_site', 'site-options' ) ) {
+			$current_site->blog_id = $wpdb->get_var( $wpdb->prepare( "SELECT blog_id FROM $wpdb->blogs WHERE domain = %s AND path = %s", $current_site->domain, $current_site->path ) );
+			wp_cache_add( 'network:' . $current_site->id . ':main_site', $current_site->blog_id, 'site-options' );
+		}
 	}
 
-	return false;
+	// Set some legacy globals
+	$GLOBALS['blog_id'] = $current_blog->blog_id;
+	$GLOBALS['public']  = $current_blog->public;
+	$GLOBALS['site_id'] = $current_blog->site_id;
+
+	// Load the site options
+	wp_load_core_site_options( $current_site->id );	
 }
 
 /**
+ * Set the table prefix according to current site
+ *
+ * @since WordPress (4.3.0)
+ *
+ * @global object $wpdb
+ * @global string $table_prefix
+ * @global object $current_blog
+ */
+function ms_set_table_prefix() {
+	global $wpdb, $table_prefix, $current_blog;
+
+	$wpdb->set_prefix( $table_prefix, false );
+	$wpdb->set_blog_id( $current_blog->blog_id, $current_blog->site_id );
+	$table_prefix = $wpdb->get_blog_prefix();
+}
+
+/**
+ * Set globals used when switching between sites
+ *
+ * @since WordPress (4.3.0)
+ *
+ * @see switch_to_blog()
+ * @see restore_current_blog()
+ */
+function ms_set_switched_stacks() {
+	$GLOBALS['_wp_switched_stack'] = array();
+	$GLOBALS['switched']           = false;	
+}
+
+/**
+ * Retrieve a network object by its domain and path.
+ *
+ * @since 3.9.0
+ *
+ * @param string   $domain   Domain to check.
+ * @param string   $path     Path to check.
+ * @param int|null $segments Path segments to use. Defaults to null, or the full path.
+ * @return object|bool Network object if successful. False when no network is found.
+ */
+function get_network_by_path( $domain, $path, $segments = null ) {
+	return WP_Network::get_by_path( $domain, $path, $segments );
+}
+
+/**
  * Retrieve an object containing information about the requested network.
  *
  * @since 3.9.0
@@ -264,16 +351,7 @@
  * @return object|bool Object containing network information if found, false if not.
  */
 function wp_get_network( $network ) {
-	global $wpdb;
-
-	if ( ! is_object( $network ) ) {
-		$network = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->site WHERE id = %d", $network ) );
-		if ( ! $network ) {
-			return false;
-		}
-	}
-
-	return $network;
+	return new WP_Network( $network );
 }
 
 /**
Index: wp-includes/ms-settings.php
--- wp-includes/ms-settings.php
+++ wp-includes/ms-settings.php
@@ -10,204 +10,29 @@
  * @since 3.0.0
  */
 
-/** Include Multisite initialization functions */
+// Require multisite initialization functions
 require_once( ABSPATH . WPINC . '/ms-load.php' );
 require_once( ABSPATH . WPINC . '/ms-default-constants.php' );
 
+// Allow custom multisite/network detection & configuration
 if ( defined( 'SUNRISE' ) ) {
 	include_once( WP_CONTENT_DIR . '/sunrise.php' );
 }
 
-/** Check for and define SUBDOMAIN_INSTALL and the deprecated VHOST constant. */
+// Check for and define SUBDOMAIN_INSTALL (and the deprecated VHOST constant)
 ms_subdomain_constants();
 
-if ( !isset( $current_site ) || !isset( $current_blog ) ) {
+// Attempt to set the relevant globals
+ms_set_current_globals();
 
-	// Given the domain and path, let's try to identify the network and site.
-	// Usually, it's easier to query the site first, which declares its network.
-	// In limited situations, though, we either can or must find the network first.
+// $table_prefix can be set in sunrise.php
+ms_set_table_prefix();
 
-	$domain = strtolower( stripslashes( $_SERVER['HTTP_HOST'] ) );
-	if ( substr( $domain, -3 ) == ':80' ) {
-		$domain = substr( $domain, 0, -3 );
-		$_SERVER['HTTP_HOST'] = substr( $_SERVER['HTTP_HOST'], 0, -3 );
-	} elseif ( substr( $domain, -4 ) == ':443' ) {
-		$domain = substr( $domain, 0, -4 );
-		$_SERVER['HTTP_HOST'] = substr( $_SERVER['HTTP_HOST'], 0, -4 );
-	}
+// Setup site-switching globals
+ms_set_switched_stacks();
 
-	$path = stripslashes( $_SERVER['REQUEST_URI'] );
-	if ( is_admin() ) {
-		$path = preg_replace( '#(.*)/wp-admin/.*#', '$1/', $path );
-	}
-	list( $path ) = explode( '?', $path );
-
-	// If the network is defined in wp-config.php, we can simply use that.
-	if ( defined( 'DOMAIN_CURRENT_SITE' ) && defined( 'PATH_CURRENT_SITE' ) ) {
-		$current_site = new stdClass;
-		$current_site->id = defined( 'SITE_ID_CURRENT_SITE' ) ? SITE_ID_CURRENT_SITE : 1;
-		$current_site->domain = DOMAIN_CURRENT_SITE;
-		$current_site->path = PATH_CURRENT_SITE;
-		if ( defined( 'BLOG_ID_CURRENT_SITE' ) ) {
-			$current_site->blog_id = BLOG_ID_CURRENT_SITE;
-		} elseif ( defined( 'BLOGID_CURRENT_SITE' ) ) { // deprecated.
-			$current_site->blog_id = BLOGID_CURRENT_SITE;
-		}
-
-		if ( 0 === strcasecmp( $current_site->domain, $domain ) && 0 === strcasecmp( $current_site->path, $path ) ) {
-			$current_blog = get_site_by_path( $domain, $path );
-		} elseif ( '/' !== $current_site->path && 0 === strcasecmp( $current_site->domain, $domain ) && 0 === stripos( $path, $current_site->path ) ) {
-			// If the current network has a path and also matches the domain and path of the request,
-			// we need to look for a site using the first path segment following the network's path.
-			$current_blog = get_site_by_path( $domain, $path, 1 + count( explode( '/', trim( $current_site->path, '/' ) ) ) );
-		} else {
-			// Otherwise, use the first path segment (as usual).
-			$current_blog = get_site_by_path( $domain, $path, 1 );
-		}
-
-	} elseif ( ! is_subdomain_install() ) {
-		/*
-		 * A "subdomain" install can be re-interpreted to mean "can support any domain".
-		 * If we're not dealing with one of these installs, then the important part is determining
-		 * the network first, because we need the network's path to identify any sites.
-		 */
-		if ( ! $current_site = wp_cache_get( 'current_network', 'site-options' ) ) {
-			// Are there even two networks installed?
-			$one_network = $wpdb->get_row( "SELECT * FROM $wpdb->site LIMIT 2" ); // [sic]
-			if ( 1 === $wpdb->num_rows ) {
-				$current_site = wp_get_network( $one_network );
-				wp_cache_add( 'current_network', $current_site, 'site-options' );
-			} elseif ( 0 === $wpdb->num_rows ) {
-				ms_not_installed();
-			}
-		}
-		if ( empty( $current_site ) ) {
-			$current_site = get_network_by_path( $domain, $path, 1 );
-		}
-
-		if ( empty( $current_site ) ) {
-			ms_not_installed();
-		} elseif ( $path === $current_site->path ) {
-			$current_blog = get_site_by_path( $domain, $path );
-		} else {
-			// Search the network path + one more path segment (on top of the network path).
-			$current_blog = get_site_by_path( $domain, $path, substr_count( $current_site->path, '/' ) );
-		}
-	} else {
-		// Find the site by the domain and at most the first path segment.
-		$current_blog = get_site_by_path( $domain, $path, 1 );
-		if ( $current_blog ) {
-			$current_site = wp_get_network( $current_blog->site_id ? $current_blog->site_id : 1 );
-		} else {
-			// If you don't have a site with the same domain/path as a network, you're pretty screwed, but:
-			$current_site = get_network_by_path( $domain, $path, 1 );
-		}
-	}
-
-	// The network declared by the site trumps any constants.
-	if ( $current_blog && $current_blog->site_id != $current_site->id ) {
-		$current_site = wp_get_network( $current_blog->site_id );
-	}
-
-	// No network has been found, bail.
-	if ( empty( $current_site ) ) {
-		ms_not_installed();
-	}
-
-	// @todo Investigate when exactly this can occur.
-	if ( empty( $current_blog ) && defined( 'WP_INSTALLING' ) ) {
-		$current_blog = new stdClass;
-		$current_blog->blog_id = $blog_id = 1;
-	}
-
-	// No site has been found, bail.
-	if ( empty( $current_blog ) ) {
-		// We're going to redirect to the network URL, with some possible modifications.
-		$scheme = is_ssl() ? 'https' : 'http';
-		$destination = "$scheme://{$current_site->domain}{$current_site->path}";
-
-		/**
-		 * Fires when a network can be determined but a site cannot.
-		 *
-		 * At the time of this action, the only recourse is to redirect somewhere
-		 * and exit. If you want to declare a particular site, do so earlier.
-		 *
-		 * @since 3.9.0
-		 *
-		 * @param object $current_site The network that had been determined.
-		 * @param string $domain       The domain used to search for a site.
-		 * @param string $path         The path used to search for a site.
-		 */
-		do_action( 'ms_site_not_found', $current_site, $domain, $path );
-
-		if ( is_subdomain_install() && ! defined( 'NOBLOGREDIRECT' ) ) {
-			// For a "subdomain" install, redirect to the signup form specifically.
-			$destination .= 'wp-signup.php?new=' . str_replace( '.' . $current_site->domain, '', $domain );
-		} elseif ( is_subdomain_install() ) {
-			// For a "subdomain" install, the NOBLOGREDIRECT constant
-			// can be used to avoid a redirect to the signup form.
-			// Using the ms_site_not_found action is preferred to the constant.
-			if ( '%siteurl%' !== NOBLOGREDIRECT ) {
-				$destination = NOBLOGREDIRECT;
-			}
-		} elseif ( 0 === strcasecmp( $current_site->domain, $domain ) ) {
-			/*
-			 * If the domain we were searching for matches the network's domain,
-			 * it's no use redirecting back to ourselves -- it'll cause a loop.
-			 * As we couldn't find a site, we're simply not installed.
-			 */
-			ms_not_installed();
-		}
-
-		header( 'Location: ' . $destination );
-		exit;
-	}
-
-	// @todo What if the domain of the network doesn't match the current site?
-	$current_site->cookie_domain = $current_site->domain;
-	if ( 'www.' === substr( $current_site->cookie_domain, 0, 4 ) ) {
-		$current_site->cookie_domain = substr( $current_site->cookie_domain, 4 );
-	}
-
-	// Figure out the current network's main site.
-	if ( ! isset( $current_site->blog_id ) ) {
-		if ( $current_blog->domain === $current_site->domain && $current_blog->path === $current_site->path ) {
-			$current_site->blog_id = $current_blog->blog_id;
-		} elseif ( ! $current_site->blog_id = wp_cache_get( 'network:' . $current_site->id . ':main_site', 'site-options' ) ) {
-			$current_site->blog_id = $wpdb->get_var( $wpdb->prepare( "SELECT blog_id FROM $wpdb->blogs WHERE domain = %s AND path = %s",
-				$current_site->domain, $current_site->path ) );
-			wp_cache_add( 'network:' . $current_site->id . ':main_site', $current_site->blog_id, 'site-options' );
-		}
-	}
-
-	$blog_id = $current_blog->blog_id;
-	$public  = $current_blog->public;
-
-	if ( empty( $current_blog->site_id ) ) {
-		// This dates to [MU134] and shouldn't be relevant anymore,
-		// but it could be possible for arguments passed to insert_blog() etc.
-		$current_blog->site_id = 1;
-	}
-
-	$site_id = $current_blog->site_id;
-	wp_load_core_site_options( $site_id );
-}
-
-$wpdb->set_prefix( $table_prefix, false ); // $table_prefix can be set in sunrise.php
-$wpdb->set_blog_id( $current_blog->blog_id, $current_blog->site_id );
-$table_prefix = $wpdb->get_blog_prefix();
-$_wp_switched_stack = array();
-$switched = false;
-
 // need to init cache again after blog_id is set
 wp_start_object_cache();
 
-if ( ! isset( $current_site->site_name ) ) {
-	$current_site->site_name = get_site_option( 'site_name' );
-	if ( ! $current_site->site_name ) {
-		$current_site->site_name = ucfirst( $current_site->domain );
-	}
-}
-
 // Define upload directory constants
 ms_upload_constants();
Index: wp-includes/option.php
--- wp-includes/option.php
+++ wp-includes/option.php
@@ -180,33 +180,29 @@
 }
 
 /**
- * Loads and caches certain often requested site options if is_multisite() and a persistent cache is not being used.
+ * Loads and caches certain often requested site options if is_multisite() and
+ * a persistent cache is not being used.
  *
  * @since 3.0.0
  *
- * @param int $site_id Optional site ID for which to query the options. Defaults to the current site.
+ * @param int $network_id Optional site ID for which to query the options.
+ *                        Defaults to the current site.
  */
-function wp_load_core_site_options( $site_id = null ) {
+function wp_load_core_site_options( $network_id = null ) {
 	global $wpdb;
 
-	if ( !is_multisite() || wp_using_ext_object_cache() || defined( 'WP_INSTALLING' ) )
+	// Bail if not multisite
+	if ( ! is_multisite() || wp_using_ext_object_cache() || defined( 'WP_INSTALLING' ) ) {
 		return;
+	}
 
-	if ( empty($site_id) )
-		$site_id = $wpdb->siteid;
-
-	$core_options = array('site_name', 'siteurl', 'active_sitewide_plugins', '_site_transient_timeout_theme_roots', '_site_transient_theme_roots', 'site_admins', 'can_compress_scripts', 'global_terms_enabled', 'ms_files_rewriting' );
-
-	$core_options_in = "'" . implode("', '", $core_options) . "'";
-	$options = $wpdb->get_results( $wpdb->prepare("SELECT meta_key, meta_value FROM $wpdb->sitemeta WHERE meta_key IN ($core_options_in) AND site_id = %d", $site_id) );
-
-	foreach ( $options as $option ) {
-		$key = $option->meta_key;
-		$cache_key = "{$site_id}:$key";
-		$option->meta_value = maybe_unserialize( $option->meta_value );
-
-		wp_cache_set( $cache_key, $option->meta_value, 'site-options' );
+	// Use the current 
+	if ( empty( $network_id ) ) {
+		$network_id = $wpdb->siteid;
 	}
+
+	// Load core options for this network
+	WP_Network::get_core_options( $network_id );
 }
 
 /**
