wp/wp-includes/ms-functions.php
changeset 9 177826044cd9
parent 7 cf61fcea0001
child 16 a86126ab1dd4
--- a/wp/wp-includes/ms-functions.php	Mon Oct 14 18:06:33 2019 +0200
+++ b/wp/wp-includes/ms-functions.php	Mon Oct 14 18:28:13 2019 +0200
@@ -39,15 +39,16 @@
  */
 function get_active_blog_for_user( $user_id ) {
 	$blogs = get_blogs_of_user( $user_id );
-	if ( empty( $blogs ) )
+	if ( empty( $blogs ) ) {
 		return;
+	}
 
 	if ( ! is_multisite() ) {
 		return $blogs[ get_current_blog_id() ];
 	}
 
 	$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 );
@@ -67,18 +68,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 != get_current_network_id() )
+				if ( $blog->site_id != get_current_network_id() ) {
 					continue;
+				}
 				$details = get_site( $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 )
+					$ret = $details;
+					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) )
-						update_user_meta( $user_id, 'source_domain', $blog->domain );
+					}
+					if ( ! get_user_meta( $user_id, 'source_domain', true ) ) {
+						update_user_meta( $user_id, 'source_domain', $details->domain );
+					}
 					break;
 				}
 			}
@@ -97,7 +101,7 @@
  * The count is cached and updated twice daily. This is not a live count.
  *
  * @since MU (3.0.0)
- * @since 4.8.0 The $network_id parameter has been added.
+ * @since 4.8.0 The `$network_id` parameter has been added.
  *
  * @param int|null $network_id ID of the network. Default is the current network.
  * @return int Number of active users on the network.
@@ -112,8 +116,8 @@
  * The count is cached and updated twice daily. This is not a live count.
  *
  * @since MU (3.0.0)
- * @since 3.7.0 The $network_id parameter has been deprecated.
- * @since 4.8.0 The $network_id parameter is now being used.
+ * @since 3.7.0 The `$network_id` parameter has been deprecated.
+ * @since 4.8.0 The `$network_id` parameter is now being used.
  *
  * @param int|null $network_id ID of the network. Default is the current network.
  * @return int Number of active sites on the network.
@@ -152,7 +156,7 @@
  * @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 );
 
@@ -184,13 +188,13 @@
 		return new WP_Error( 'user_cannot_be_added', __( 'User cannot be added to this site.' ) );
 	}
 
-	if ( !get_user_meta($user_id, 'primary_blog', true) ) {
-		update_user_meta($user_id, 'primary_blog', $blog_id);
+	if ( ! get_user_meta( $user_id, 'primary_blog', true ) ) {
+		update_user_meta( $user_id, 'primary_blog', $blog_id );
 		$site = get_site( $blog_id );
 		update_user_meta( $user_id, 'source_domain', $site->domain );
 	}
 
-	$user->set_role($role);
+	$user->set_role( $role );
 
 	/**
 	 * Fires immediately after a user is added to a site.
@@ -226,9 +230,9 @@
  * @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.
@@ -242,36 +246,37 @@
 
 	// 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);
 	$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 != '' ) {
@@ -330,22 +335,24 @@
  */
 function get_blog_id_from_url( $domain, $path = '/' ) {
 	$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;
+	}
 
-	$args = array(
-		'domain' => $domain,
-		'path' => $path,
-		'fields' => 'ids',
-		'number' => 1,
+	$args   = array(
+		'domain'                 => $domain,
+		'path'                   => $path,
+		'fields'                 => 'ids',
+		'number'                 => 1,
+		'update_site_meta_cache' => false,
 	);
 	$result = get_sites( $args );
-	$id = array_shift( $result );
+	$id     = array_shift( $result );
 
 	if ( ! $id ) {
 		wp_cache_set( md5( $domain . $path ), -1, 'blog-id-cache' );
@@ -374,20 +381,22 @@
  */
 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 ) && false !== strpos( $user_email, '@', 1 ) ) {
-		$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;
@@ -433,13 +442,13 @@
  * @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.' ) );
@@ -448,23 +457,24 @@
 
 	$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 */
 	$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( $user_email ) ) {
@@ -473,57 +483,69 @@
 		$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.' ) );
 	}
 
 	// 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!' ) );
+	}
 
 	$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!'));
+		$limited_email_domains = array_map( 'strtolower', $limited_email_domains );
+		$emaildomain           = strtolower( substr( $user_email, 1 + strpos( $user_email, '@' ) ) );
+		if ( ! in_array( $emaildomain, $limited_email_domains, true ) ) {
+			$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           = time();
+		$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 = time() - 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,
+	);
 
 	/**
 	 * Filters the validated user registration details.
@@ -573,11 +595,11 @@
 	global $wpdb, $domain;
 
 	$current_network = get_network();
-	$base = $current_network->path;
+	$base            = $current_network->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' );
@@ -592,15 +614,17 @@
 		$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.' ) );
+	}
 
 	/**
 	 * Filters the minimum site name length required when validating a site signup.
@@ -617,12 +641,14 @@
 	}
 
 	// 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_network->site_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_network->site_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!' ) );
+	}
 
 	/**
 	 * Filters the new site name during registration.
@@ -636,39 +662,56 @@
 	 */
 	$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_network->id) )
+	if ( domain_exists( $mydomain, $path, $current_network->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 = time() - 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,
+	);
 
 	/**
 	 * Filters site details and error messages following registration.
@@ -703,7 +746,7 @@
  * @param string $user_email The user's email address.
  * @param array  $meta       Optional. Signup meta data. 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() . wp_rand() . $domain ), 0, 16 );
@@ -725,16 +768,19 @@
 	 */
 	$meta = apply_filters( 'signup_site_meta', $meta, $domain, $path, $title, $user, $user_email, $key );
 
-	$wpdb->insert( $wpdb->signups, array(
-		'domain' => $domain,
-		'path' => $path,
-		'title' => $title,
-		'user_login' => $user,
-		'user_email' => $user_email,
-		'registered' => current_time('mysql', true),
-		'activation_key' => $key,
-		'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 ),
+			'activation_key' => $key,
+			'meta'           => serialize( $meta ),
+		)
+	);
 
 	/**
 	 * Fires after site signup information has been written to the database.
@@ -770,9 +816,9 @@
 	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() . wp_rand() . $user_email ), 0, 16 );
+	$key        = substr( md5( time() . wp_rand() . $user_email ), 0, 16 );
 
 	/**
 	 * Filters the metadata for a user signup.
@@ -788,16 +834,19 @@
 	 */
 	$meta = apply_filters( 'signup_user_meta', $meta, $user, $user_email, $key );
 
-	$wpdb->insert( $wpdb->signups, array(
-		'domain' => '',
-		'path' => '',
-		'title' => '',
-		'user_login' => $user,
-		'user_email' => $user_email,
-		'registered' => current_time('mysql', true),
-		'activation_key' => $key,
-		'meta' => serialize( $meta )
-	) );
+	$wpdb->insert(
+		$wpdb->signups,
+		array(
+			'domain'         => '',
+			'path'           => '',
+			'title'          => '',
+			'user_login'     => $user,
+			'user_email'     => $user_email,
+			'registered'     => current_time( 'mysql', true ),
+			'activation_key' => $key,
+			'meta'           => serialize( $meta ),
+		)
+	);
 
 	/**
 	 * Fires after a user's signup information has been written to the database.
@@ -856,19 +905,21 @@
 	}
 
 	// Send email with activation link.
-	if ( !is_subdomain_install() || get_current_network_id() != 1 )
-		$activate_url = network_site_url("wp-activate.php?key=$key");
-	else
+	if ( ! is_subdomain_install() || get_current_network_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";
+	}
+	$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";
 
-	$user = get_user_by( 'login', $user_login );
+	$user            = get_user_by( 'login', $user_login );
 	$switched_locale = switch_to_locale( get_user_locale( $user ) );
 
 	$message = sprintf(
@@ -888,9 +939,16 @@
 		 * @param string $key        Activation key created in wpmu_signup_blog().
 		 * @param array  $meta       Signup meta data. 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_login, $user_email, $key, $meta
+		apply_filters(
+			'wpmu_signup_blog_notification_email',
+			__( "To activate your blog, please click the following link:\n\n%1\$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%2\$s" ),
+			$domain,
+			$path,
+			$title,
+			$user_login,
+			$user_email,
+			$key,
+			$meta
 		),
 		$activate_url,
 		esc_url( "http://{$domain}{$path}" ),
@@ -912,10 +970,17 @@
 		 * @param string $key        Activation key created in wpmu_signup_blog().
 		 * @param array  $meta       Signup meta data. By default, contains the requested privacy setting and lang_id.
 		 */
-		apply_filters( 'wpmu_signup_blog_notification_subject',
+		apply_filters(
+			'wpmu_signup_blog_notification_subject',
 			/* translators: New site notification email subject. 1: Network name, 2: New site URL */
 			_x( '[%1$s] Activate %2$s', 'New site notification email subject' ),
-			$domain, $path, $title, $user_login, $user_email, $key, $meta
+			$domain,
+			$path,
+			$title,
+			$user_login,
+			$user_email,
+			$key,
+			$meta
 		),
 		$from_name,
 		esc_url( 'http://' . $domain . $path )
@@ -962,19 +1027,21 @@
 	 * @param string $key        Activation key created in wpmu_signup_user().
 	 * @param array  $meta       Signup meta data. Default empty array.
 	 */
-	if ( ! apply_filters( 'wpmu_signup_user_notification', $user_login, $user_email, $key, $meta ) )
+	if ( ! apply_filters( 'wpmu_signup_user_notification', $user_login, $user_email, $key, $meta ) ) {
 		return false;
+	}
 
-	$user = get_user_by( 'login', $user_login );
+	$user            = get_user_by( 'login', $user_login );
 	$switched_locale = switch_to_locale( get_user_locale( $user ) );
 
 	// 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(
+	}
+	$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(
 		/**
 		 * Filters the content of the notification email for new user sign-up.
 		 *
@@ -988,9 +1055,13 @@
 		 * @param string $key        Activation key created in wpmu_signup_user().
 		 * @param array  $meta       Signup meta data. Default empty array.
 		 */
-		apply_filters( 'wpmu_signup_user_notification_email',
+		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_login, $user_email, $key, $meta
+			$user_login,
+			$user_email,
+			$key,
+			$meta
 		),
 		site_url( "wp-activate.php?key=$key" )
 	);
@@ -1007,10 +1078,14 @@
 		 * @param string $key        Activation key created in wpmu_signup_user().
 		 * @param array  $meta       Signup meta data. Default empty array.
 		 */
-		apply_filters( 'wpmu_signup_user_notification_subject',
+		apply_filters(
+			'wpmu_signup_user_notification_subject',
 			/* translators: New user notification email subject. 1: Network name, 2: New user login */
 			_x( '[%1$s] Activate %2$s', 'New user notification email subject' ),
-			$user_login, $user_email, $key, $meta
+			$user_login,
+			$user_email,
+			$key,
+			$meta
 		),
 		$from_name,
 		$user_login
@@ -1039,41 +1114,53 @@
  * @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 );
+	}
+
+	$now = current_time( 'mysql', true );
 
-	if ( ! $user_id )
-		return new WP_Error('create_user', __('Could not create user'), $signup);
-
-	$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.
@@ -1085,23 +1172,41 @@
 		 * @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 );
+		return array(
+			'user_id'  => $user_id,
+			'password' => $password,
+			'meta'     => $meta,
+		);
 	}
 
 	$blog_id = wpmu_create_blog( $signup->domain, $signup->path, $signup->title, $user_id, $meta, get_current_network_id() );
 
 	// 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.
 	 *
@@ -1115,7 +1220,13 @@
 	 */
 	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,
+	);
 }
 
 /**
@@ -1137,8 +1248,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' );
@@ -1174,7 +1286,7 @@
  * @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. Array of key=>value pairs used to set initial site options.
+ * @param array  $options    Optional. Array of key=>value pairs used to set initial site options.
  *                           If valid status keys are included ('public', 'archived', 'mature',
  *                           'spam', 'deleted', or 'lang_id') the given site status(es) will be
  *                           updated. Otherwise, keys and values will be used to set options for
@@ -1182,67 +1294,47 @@
  * @param int    $network_id Optional. Network ID. Only relevant on multi-network installations.
  * @return int|WP_Error Returns WP_Error object on failure, the new site ID on success.
  */
-function wpmu_create_blog( $domain, $path, $title, $user_id, $meta = array(), $network_id = 1 ) {
+function wpmu_create_blog( $domain, $path, $title, $user_id, $options = array(), $network_id = 1 ) {
 	$defaults = array(
 		'public' => 0,
-		'WPLANG' => get_network_option( $network_id, 'WPLANG' ),
 	);
-	$meta = wp_parse_args( $meta, $defaults );
+	$options  = wp_parse_args( $options, $defaults );
 
-	$domain = preg_replace( '/\s+/', '', sanitize_user( $domain, true ) );
-
-	if ( is_subdomain_install() )
-		$domain = str_replace( '@', '', $domain );
-
-	$title = strip_tags( $title );
+	$title   = strip_tags( $title );
 	$user_id = (int) $user_id;
 
-	if ( empty($path) )
-		$path = '/';
-
 	// Check if the domain has been used already. We should return an error message.
-	if ( domain_exists($domain, $path, $network_id) )
+	if ( domain_exists( $domain, $path, $network_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, $network_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);
-
-	add_user_to_blog($blog_id, $user_id, 'administrator');
+	$site_data_whitelist = array( 'public', 'archived', 'mature', 'spam', 'deleted', 'lang_id' );
 
-	foreach ( $meta as $key => $value ) {
-		if ( in_array( $key, array( 'public', 'archived', 'mature', 'spam', 'deleted', 'lang_id' ) ) )
-			update_blog_status( $blog_id, $key, $value );
-		else
-			update_option( $key, $value );
-	}
-
-	update_option( 'blog_public', (int) $meta['public'] );
+	$site_data = array_merge(
+		array(
+			'domain'     => $domain,
+			'path'       => $path,
+			'network_id' => $network_id,
+		),
+		array_intersect_key( $options, array_flip( $site_data_whitelist ) )
+	);
 
-	if ( ! is_super_admin( $user_id ) && ! get_user_meta( $user_id, 'primary_blog', true ) )
-		update_user_meta( $user_id, 'primary_blog', $blog_id );
+	// Data to pass to wp_initialize_site().
+	$site_initialization_data = array(
+		'title'   => $title,
+		'user_id' => $user_id,
+		'options' => array_diff_key( $options, array_flip( $site_data_whitelist ) ),
+	);
 
-	restore_current_blog();
-	/**
-	 * Fires immediately after a new site is created.
-	 *
-	 * @since MU (3.0.0)
-	 *
-	 * @param int    $blog_id    Site ID.
-	 * @param int    $user_id    User ID.
-	 * @param string $domain     Site domain.
-	 * @param string $path       Site path.
-	 * @param int    $network_id Network ID. Only relevant on multi-network installations.
-	 * @param array  $meta       Meta data. Used to set initial site options.
-	 */
-	do_action( 'wpmu_new_blog', $blog_id, $user_id, $domain, $path, $network_id, $meta );
+	$blog_id = wp_insert_site( array_merge( $site_data, $site_initialization_data ) );
+
+	if ( is_wp_error( $blog_id ) ) {
+		return $blog_id;
+	}
 
 	wp_cache_set( 'last_changed', microtime(), 'sites' );
 
@@ -1256,32 +1348,47 @@
  * the notification email.
  *
  * @since MU (3.0.0)
+ * @since 5.1.0 $blog_id now supports input from the {@see 'wp_initialize_site'} action.
  *
- * @param int    $blog_id    The new site's ID.
- * @param string $deprecated Not used.
+ * @param WP_Site|int $blog_id    The new site's object or ID.
+ * @param string      $deprecated Not used.
  * @return bool
  */
 function newblog_notify_siteadmin( $blog_id, $deprecated = '' ) {
-	if ( get_site_option( 'registrationnotification' ) != 'yes' )
+	if ( is_object( $blog_id ) ) {
+		$blog_id = $blog_id->blog_id;
+	}
+
+	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();
 
 	/* translators: New site notification email. 1: Site URL, 2: User IP address, 3: Settings screen URL */
-	$msg = sprintf( __( 'New Site: %1$s
+	$msg = sprintf(
+		__(
+			'New Site: %1$s
 URL: %2$s
 Remote IP address: %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
+	);
 	/**
 	 * Filters the message body of the new site activation email sent
 	 * to the network administrator.
@@ -1308,22 +1415,31 @@
  * @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'));
+	$options_site_url = esc_url( network_admin_url( 'settings.php' ) );
 	/* translators: New user notification email. 1: User login, 2: User IP address, 3: Settings screen URL */
-	$msg = sprintf(__('New User: %1$s
+	$msg = sprintf(
+		__(
+			'New User: %1$s
 Remote IP address: %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
+	);
 
 	/**
 	 * Filters the message body of the new user activation email sent
@@ -1335,7 +1451,7 @@
 	 * @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;
 }
 
@@ -1356,13 +1472,14 @@
  * @return int|null The site ID if the site name exists, null otherwise.
  */
 function domain_exists( $domain, $path, $network_id = 1 ) {
-	$path = trailingslashit( $path );
-	$args = array(
-		'network_id' => $network_id,
-		'domain'     => $domain,
-		'path'       => $path,
-		'fields'     => 'ids',
-		'number'     => 1,
+	$path   = trailingslashit( $path );
+	$args   = array(
+		'network_id'             => $network_id,
+		'domain'                 => $domain,
+		'path'                   => $path,
+		'fields'                 => 'ids',
+		'number'                 => 1,
+		'update_site_meta_cache' => false,
 	);
 	$result = get_sites( $args );
 	$result = array_shift( $result );
@@ -1384,133 +1501,6 @@
 }
 
 /**
- * Store basic site info in the blogs table.
- *
- * This function creates a row in the wp_blogs table and returns
- * the new blog's ID. It is the first step in creating a new blog.
- *
- * @since MU (3.0.0)
- *
- * @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    $network_id Unless you're running a multi-network installation, be sure to set this value to 1.
- * @return int|false The ID of the new row
- */
-function insert_blog($domain, $path, $network_id) {
-	global $wpdb;
-
-	$path = trailingslashit($path);
-	$network_id = (int) $network_id;
-
-	$result = $wpdb->insert( $wpdb->blogs, array('site_id' => $network_id, 'domain' => $domain, 'path' => $path, 'registered' => current_time('mysql')) );
-	if ( ! $result )
-		return false;
-
-	$blog_id = $wpdb->insert_id;
-	clean_blog_cache( $blog_id );
-
-	wp_maybe_update_network_site_counts( $network_id );
-
-	return $blog_id;
-}
-
-/**
- * Install an empty blog.
- *
- * Creates the new blog tables and options. If calling this function
- * directly, be sure to use switch_to_blog() first, so that $wpdb
- * points to the new blog.
- *
- * @since MU (3.0.0)
- *
- * @global wpdb     $wpdb
- * @global WP_Roles $wp_roles
- *
- * @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 = '' ) {
-	global $wpdb, $wp_roles;
-
-	// Cast for security
-	$blog_id = (int) $blog_id;
-
-	require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
-
-	$suppress = $wpdb->suppress_errors();
-	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 );
-
-	// Set everything up
-	make_db_current_silent( 'blog' );
-	populate_options();
-	populate_roles();
-
-	// populate_roles() clears previous role definitions so we start over.
-	$wp_roles = new WP_Roles();
-
-	$siteurl = $home = untrailingslashit( $url );
-
-	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( get_network()->site_id ), PHP_URL_SCHEME ) ) {
- 			$home = set_url_scheme( $home, 'https' );
- 		}
-
-	}
-
-	update_option( 'siteurl', $siteurl );
-	update_option( 'home', $home );
-
-	if ( get_site_option( 'ms_files_rewriting' ) )
-		update_option( 'upload_path', UPLOADBLOGSDIR . "/$blog_id/files" );
-	else
-		update_option( 'upload_path', get_blog_option( get_network()->site_id, 'upload_path' ) );
-
-	update_option( 'blogname', wp_unslash( $blog_title ) );
-	update_option( 'admin_email', '' );
-
-	// 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 . 'capabilities', null, true ); // delete all
-}
-
-/**
- * Set blog defaults.
- *
- * This function creates a row in the wp_blogs table.
- *
- * @since MU (3.0.0)
- * @deprecated MU
- * @deprecated Use wp_install_defaults()
- *
- * @global wpdb $wpdb WordPress database abstraction object.
- *
- * @param int $blog_id Ignored in this function.
- * @param int $user_id
- */
-function install_blog_defaults($blog_id, $user_id) {
-	global $wpdb;
-
-	require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
-
-	$suppress = $wpdb->suppress_errors();
-
-	wp_install_defaults($user_id);
-
-	$wpdb->suppress_errors( $suppress );
-}
-
-/**
  * Notify a user that their blog activation has been successful.
  *
  * Filter {@see 'wpmu_welcome_notification'} to disable or bypass.
@@ -1543,8 +1533,9 @@
 	 * @param string   $title    Site title.
 	 * @param array    $meta     Signup meta data. By default, contains the requested privacy setting and lang_id.
 	 */
-	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;
+	}
 
 	$user = get_userdata( $user_id );
 
@@ -1553,7 +1544,8 @@
 	$welcome_email = get_site_option( 'welcome_email' );
 	if ( $welcome_email == false ) {
 		/* translators: Do not translate USERNAME, SITE_NAME, BLOG_URL, PASSWORD: those are placeholders. */
-		$welcome_email = __( 'Howdy USERNAME,
+		$welcome_email = __(
+			'Howdy USERNAME,
 
 Your new SITE_NAME site has been successfully set up at:
 BLOG_URL
@@ -1566,10 +1558,11 @@
 
 We hope you enjoy your new site. Thanks!
 
---The Team @ SITE_NAME' );
+--The Team @ SITE_NAME'
+		);
 	}
 
-	$url = get_blogaddress_by_id($blog_id);
+	$url = get_blogaddress_by_id( $blog_id );
 
 	$welcome_email = str_replace( 'SITE_NAME', $current_network->site_name, $welcome_email );
 	$welcome_email = str_replace( 'BLOG_TITLE', $title, $welcome_email );
@@ -1592,17 +1585,19 @@
 	 * @param array  $meta          Signup meta data. By default, contains the requested privacy setting and lang_id.
 	 */
 	$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_network->site_name ) )
+	if ( empty( $current_network->site_name ) ) {
 		$current_network->site_name = 'WordPress';
+	}
 
 	/* translators: New site notification email subject. 1: Network name, 2: New site name */
 	$subject = __( 'New %1$s Site: %2$s' );
@@ -1643,7 +1638,7 @@
 	$current_network = get_network();
 
 	/**
- 	 * Filters whether to bypass the welcome email after user activation.
+	 * Filters whether to bypass the welcome email after user activation.
 	 *
 	 * Returning false disables the welcome email.
 	 *
@@ -1653,8 +1648,9 @@
 	 * @param string $password User password.
 	 * @param array  $meta     Signup meta data. Default empty array.
 	 */
-	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' );
 
@@ -1682,15 +1678,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_network->site_name ) )
+	if ( empty( $current_network->site_name ) ) {
 		$current_network->site_name = 'WordPress';
+	}
 
 	/* translators: New user notification email subject. 1: Network name, 2: New user login */
 	$subject = __( 'New %1$s User: %2$s' );
@@ -1702,7 +1700,7 @@
 	 *
 	 * @param string $subject Subject of the email.
 	 */
-	$subject = apply_filters( 'update_welcome_user_subject', sprintf( $subject, $current_network->site_name, $user->user_login) );
+	$subject = apply_filters( 'update_welcome_user_subject', sprintf( $subject, $current_network->site_name, $user->user_login ) );
 	wp_mail( $user->user_email, wp_specialchars_decode( $subject ), $message, $message_headers );
 
 	if ( $switched_locale ) {
@@ -1747,28 +1745,28 @@
 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,
 				);
 			}
 		}
@@ -1780,77 +1778,6 @@
 // Misc functions
 
 /**
- * Get the size of a directory.
- *
- * A helper function that is used primarily to check whether
- * a blog has exceeded its allowed upload space.
- *
- * @since MU (3.0.0)
- *
- * @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 ) )
-		$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' );
-	} else {
-		$dirsize[ $directory ][ 'size' ] = recurse_dirsize( $directory );
-	}
-
-	set_transient( 'dirsize_cache', $dirsize, HOUR_IN_SECONDS );
-	return $dirsize[ $directory ][ 'size' ];
-}
-
-/**
- * Get the size of a directory recursively.
- *
- * Used by get_dirsize() to get a directory's size when it contains
- * other directories.
- *
- * @since MU (3.0.0)
- * @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.
- * @return int|false Size in MB if a valid directory. False if not.
- */
-function recurse_dirsize( $directory, $exclude = null ) {
-	$size = 0;
-
-	$directory = untrailingslashit( $directory );
-
-	if ( ! file_exists( $directory ) || ! is_dir( $directory ) || ! is_readable( $directory ) || $directory === $exclude ) {
-		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)) {
-					$handlesize = recurse_dirsize( $path, $exclude );
-					if ($handlesize > 0)
-						$size += $handlesize;
-				}
-			}
-		}
-		closedir($handle);
-	}
-	return $size;
-}
-
-/**
  * Check an array of MIME types against a whitelist.
  *
  * WordPress ships with a set of allowed upload filetypes,
@@ -1865,12 +1792,13 @@
  * @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;
@@ -1899,17 +1827,36 @@
  * Logs the user email, IP, and registration date of a new site.
  *
  * @since MU (3.0.0)
+ * @since 5.1.0 Parameters now support input from the {@see 'wp_initialize_site'} action.
  *
  * @global wpdb $wpdb WordPress database abstraction object.
  *
- * @param int $blog_id
- * @param int $user_id
+ * @param WP_Site|int $blog_id The new site's object or ID.
+ * @param int|array   $user_id User ID, or array of arguments including 'user_id'.
  */
 function wpmu_log_new_registrations( $blog_id, $user_id ) {
 	global $wpdb;
+
+	if ( is_object( $blog_id ) ) {
+		$blog_id = $blog_id->blog_id;
+	}
+
+	if ( is_array( $user_id ) ) {
+		$user_id = ! empty( $user_id['user_id'] ) ? $user_id['user_id'] : 0;
+	}
+
 	$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' ),
+			)
+		);
+	}
 }
 
 /**
@@ -1930,34 +1877,50 @@
 	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++ ) {
 		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 ) {
@@ -1971,17 +1934,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;
 }
@@ -2010,11 +1975,13 @@
  * @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 ) ) ) {
-		return sprintf( __( 'This file is too big. Files must be less than %d KB in size.' ) . '<br />', get_site_option( 'fileupload_maxk', 1500 ) );
+	if ( strlen( $upload['bits'] ) > ( KB_IN_BYTES * get_site_option( 'fileupload_maxk', 1500 ) ) ) {
+		/* translators: %s: maximum allowed file size in kilobytes */
+		return sprintf( __( 'This file is too big. Files must be less than %s KB in size.' ) . '<br />', get_site_option( 'fileupload_maxk', 1500 ) );
 	}
 
 	return $upload;
@@ -2028,7 +1995,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 );
 }
 
 /**
@@ -2040,11 +2007,13 @@
  * @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'] )
-		wp_die( __( 'Please try again.' ) );
+	if ( ! wp_verify_nonce( $_POST['_signup_form'], 'signup_form_' . $_POST['signup_form_id'] ) ) {
+		$result['errors']->add( 'invalid_nonce', __( 'Unable to submit this form, please try again.' ) );
+	}
 
 	return $result;
 }
@@ -2065,8 +2034,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();
 	}
@@ -2082,23 +2052,27 @@
  * @since MU (3.0.0)
  */
 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 ) );
+	wp_die( sprintf( __( 'You have been added to this site. Please visit the <a href="%1$s">homepage</a> or <a href="%2$s">log in</a> using your username and password.' ), home_url(), admin_url() ), __( 'WordPress &rsaquo; Success' ), array( 'response' => 200 ) );
 }
 
 /**
@@ -2112,7 +2086,7 @@
 function add_existing_user_to_blog( $details = false ) {
 	if ( is_array( $details ) ) {
 		$blog_id = get_current_blog_id();
-		$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.
@@ -2143,9 +2117,9 @@
  * @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' ];
+	if ( ! empty( $meta['add_to_blog'] ) ) {
+		$blog_id = $meta['add_to_blog'];
+		$role    = $meta['new_role'];
 		remove_user_from_blog( $user_id, get_network()->site_id ); // remove user from main blog.
 
 		$result = add_user_to_blog( $blog_id, $user_id, $role );
@@ -2173,11 +2147,11 @@
  * @since MU (3.0.0)
  *
  * @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 {
@@ -2210,7 +2184,7 @@
  * @return bool
  */
 function users_can_register_signup_filter() {
-	$registration = get_site_option('registration');
+	$registration = get_site_option( 'registration' );
 	return ( $registration == 'all' || $registration == 'user' );
 }
 
@@ -2223,11 +2197,12 @@
  * @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. */
-		$text = __( 'Howdy USERNAME,
+		$text = __(
+			'Howdy USERNAME,
 
 Your new account is set up.
 
@@ -2238,7 +2213,8 @@
 
 Thanks!
 
---The Team @ SITE_NAME' );
+--The Team @ SITE_NAME'
+		);
 		update_site_option( 'welcome_user_email', $text );
 	}
 	return $text;
@@ -2258,7 +2234,7 @@
 	static $forced_content = false;
 
 	if ( '' != $force ) {
-		$old_forced = $forced_content;
+		$old_forced     = $forced_content;
 		$forced_content = $force;
 		return $old_forced;
 	}
@@ -2277,11 +2253,13 @@
  * @return string URL with https as the scheme
  */
 function filter_SSL( $url ) {
-	if ( ! is_string( $url ) )
+	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;
 }
@@ -2292,18 +2270,20 @@
  * @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 4.8.0 The $network_id parameter has been added.
+ * @since 4.8.0 The `$network_id` parameter has been added.
  *
  * @param int|null $network_id ID of the network. Default is the current network.
  */
@@ -2319,7 +2299,7 @@
  * on a network when a site is created or its status is updated.
  *
  * @since 3.7.0
- * @since 4.8.0 The $network_id parameter has been added.
+ * @since 4.8.0 The `$network_id` parameter has been added.
  *
  * @param int|null $network_id ID of the network. Default is the current network.
  */
@@ -2336,8 +2316,9 @@
 	 * @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( $network_id );
 }
@@ -2349,7 +2330,7 @@
  * on a network when a user is created or its status is updated.
  *
  * @since 3.7.0
- * @since 4.8.0 The $network_id parameter has been added.
+ * @since 4.8.0 The `$network_id` parameter has been added.
  *
  * @param int|null $network_id ID of the network. Default is the current network.
  */
@@ -2357,8 +2338,9 @@
 	$is_small_network = ! wp_is_large_network( 'users', $network_id );
 
 	/** 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( $network_id );
 }
@@ -2367,7 +2349,7 @@
  * Update the network-wide site count.
  *
  * @since 3.7.0
- * @since 4.8.0 The $network_id parameter has been added.
+ * @since 4.8.0 The `$network_id` parameter has been added.
  *
  * @param int|null $network_id ID of the network. Default is the current network.
  */
@@ -2377,13 +2359,16 @@
 		$network_id = get_current_network_id();
 	}
 
-	$count = get_sites( array(
-		'network_id' => $network_id,
-		'spam'       => 0,
-		'deleted'    => 0,
-		'archived'   => 0,
-		'count'      => true,
-	) );
+	$count = get_sites(
+		array(
+			'network_id'             => $network_id,
+			'spam'                   => 0,
+			'deleted'                => 0,
+			'archived'               => 0,
+			'count'                  => true,
+			'update_site_meta_cache' => false,
+		)
+	);
 
 	update_network_option( $network_id, 'blog_count', $count );
 }
@@ -2392,7 +2377,7 @@
  * Update the network-wide user count.
  *
  * @since 3.7.0
- * @since 4.8.0 The $network_id parameter has been added.
+ * @since 4.8.0 The `$network_id` parameter has been added.
  *
  * @global wpdb $wpdb WordPress database abstraction object.
  *
@@ -2439,11 +2424,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;
+	}
 
 	/**
 	 * Filters the upload quota for the current site.
@@ -2468,13 +2455,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;
 }
@@ -2486,8 +2475,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();
 }
@@ -2502,8 +2492,9 @@
  */
 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() );
 }
@@ -2515,7 +2506,7 @@
  * Plugins can alter this criteria using the {@see 'wp_is_large_network'} filter.
  *
  * @since 3.3.0
- * @since 4.8.0 The $network_id parameter has been added.
+ * @since 4.8.0 The `$network_id` parameter has been added.
  *
  * @param string   $using      'sites or 'users'. Default is 'sites'.
  * @param int|null $network_id ID of the network. Default is the current network.
@@ -2533,7 +2524,7 @@
 		 * Filters whether the network is considered large.
 		 *
 		 * @since 3.3.0
-		 * @since 4.8.0 The $network_id parameter has been added.
+		 * @since 4.8.0 The `$network_id` parameter has been added.
 		 *
 		 * @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'.
@@ -2557,8 +2548,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',
 	);
 
 	/**
@@ -2588,7 +2587,7 @@
 		return;
 	}
 
-	$hash = md5( $value . time() . mt_rand() );
+	$hash            = md5( $value . time() . mt_rand() );
 	$new_admin_email = array(
 		'hash'     => $hash,
 		'newemail' => $value,
@@ -2598,7 +2597,8 @@
 	$switched_locale = switch_to_locale( get_user_locale() );
 
 	/* translators: Do not translate USERNAME, ADMIN_URL, EMAIL, SITENAME, SITEURL: those are placeholders. */
-	$email_text = __( 'Howdy ###USERNAME###,
+	$email_text = __(
+		'Howdy ###USERNAME###,
 
 You recently requested to have the network admin email address on
 your network changed.
@@ -2613,7 +2613,8 @@
 
 Regards,
 All at ###SITENAME###
-###SITEURL###' );
+###SITEURL###'
+	);
 
 	/**
 	 * Filters the text of the email sent when a change of network admin email address is attempted.
@@ -2638,13 +2639,14 @@
 	$content = apply_filters( 'new_network_admin_email_content', $email_text, $new_admin_email );
 
 	$current_user = wp_get_current_user();
-	$content = str_replace( '###USERNAME###', $current_user->user_login, $content );
-	$content = str_replace( '###ADMIN_URL###', esc_url( network_admin_url( 'settings.php?network_admin_hash=' . $hash ) ), $content );
-	$content = str_replace( '###EMAIL###', $value, $content );
-	$content = str_replace( '###SITENAME###', wp_specialchars_decode( get_site_option( 'site_name' ), ENT_QUOTES ), $content );
-	$content = str_replace( '###SITEURL###', network_home_url(), $content );
+	$content      = str_replace( '###USERNAME###', $current_user->user_login, $content );
+	$content      = str_replace( '###ADMIN_URL###', esc_url( network_admin_url( 'settings.php?network_admin_hash=' . $hash ) ), $content );
+	$content      = str_replace( '###EMAIL###', $value, $content );
+	$content      = str_replace( '###SITENAME###', wp_specialchars_decode( get_site_option( 'site_name' ), ENT_QUOTES ), $content );
+	$content      = str_replace( '###SITEURL###', network_home_url(), $content );
 
-	wp_mail( $value, sprintf( __( '[%s] New Network Admin Email Address' ), wp_specialchars_decode( get_site_option( 'site_name' ), ENT_QUOTES ) ), $content );
+	/* translators: Email change notification email subject. %s: Network title */
+	wp_mail( $value, sprintf( __( '[%s] Network Admin Email Change Request' ), wp_specialchars_decode( get_site_option( 'site_name' ), ENT_QUOTES ) ), $content );
 
 	if ( $switched_locale ) {
 		restore_previous_locale();
@@ -2686,7 +2688,8 @@
 	}
 
 	/* translators: Do not translate OLD_EMAIL, NEW_EMAIL, SITENAME, SITEURL: those are placeholders. */
-	$email_change_text = __( 'Hi,
+	$email_change_text = __(
+		'Hi,
 
 This notice confirms that the network admin email address was changed on ###SITENAME###.
 
@@ -2696,12 +2699,13 @@
 
 Regards,
 All at ###SITENAME###
-###SITEURL###' );
+###SITEURL###'
+	);
 
 	$email_change_email = array(
 		'to'      => $old_email,
 		/* translators: Network admin email change notification email subject. %s: Network title */
-		'subject' => __( '[%s] Notice of Network Admin Email Change' ),
+		'subject' => __( '[%s] Network Admin Email Changed' ),
 		'message' => $email_change_text,
 		'headers' => '',
 	);
@@ -2732,13 +2736,18 @@
 	 */
 	$email_change_email = apply_filters( 'network_admin_email_change_email', $email_change_email, $old_email, $new_email, $network_id );
 
-	$email_change_email['message'] = str_replace( '###OLD_EMAIL###', $old_email,    $email_change_email['message'] );
-	$email_change_email['message'] = str_replace( '###NEW_EMAIL###', $new_email,    $email_change_email['message'] );
-	$email_change_email['message'] = str_replace( '###SITENAME###',  $network_name, $email_change_email['message'] );
-	$email_change_email['message'] = str_replace( '###SITEURL###',   home_url(),    $email_change_email['message'] );
+	$email_change_email['message'] = str_replace( '###OLD_EMAIL###', $old_email, $email_change_email['message'] );
+	$email_change_email['message'] = str_replace( '###NEW_EMAIL###', $new_email, $email_change_email['message'] );
+	$email_change_email['message'] = str_replace( '###SITENAME###', $network_name, $email_change_email['message'] );
+	$email_change_email['message'] = str_replace( '###SITEURL###', home_url(), $email_change_email['message'] );
 
-	wp_mail( $email_change_email['to'], sprintf(
-		$email_change_email['subject'],
-		$network_name
-	), $email_change_email['message'], $email_change_email['headers'] );
+	wp_mail(
+		$email_change_email['to'],
+		sprintf(
+			$email_change_email['subject'],
+			$network_name
+		),
+		$email_change_email['message'],
+		$email_change_email['headers']
+	);
 }