wp/wp-admin/includes/upgrade.php
changeset 9 177826044cd9
parent 7 cf61fcea0001
child 16 a86126ab1dd4
equal deleted inserted replaced
8:c7c34916027a 9:177826044cd9
     7  * @package WordPress
     7  * @package WordPress
     8  * @subpackage Administration
     8  * @subpackage Administration
     9  */
     9  */
    10 
    10 
    11 /** Include user installation customization script. */
    11 /** Include user installation customization script. */
    12 if ( file_exists(WP_CONTENT_DIR . '/install.php') )
    12 if ( file_exists( WP_CONTENT_DIR . '/install.php' ) ) {
    13 	require (WP_CONTENT_DIR . '/install.php');
    13 	require( WP_CONTENT_DIR . '/install.php' );
       
    14 }
    14 
    15 
    15 /** WordPress Administration API */
    16 /** WordPress Administration API */
    16 require_once(ABSPATH . 'wp-admin/includes/admin.php');
    17 require_once( ABSPATH . 'wp-admin/includes/admin.php' );
    17 
    18 
    18 /** WordPress Schema API */
    19 /** WordPress Schema API */
    19 require_once(ABSPATH . 'wp-admin/includes/schema.php');
    20 require_once( ABSPATH . 'wp-admin/includes/schema.php' );
    20 
    21 
    21 if ( !function_exists('wp_install') ) :
    22 if ( ! function_exists( 'wp_install' ) ) :
    22 /**
    23 	/**
    23  * Installs the site.
    24 	 * Installs the site.
    24  *
    25 	 *
    25  * Runs the required functions to set up and populate the database,
    26 	 * Runs the required functions to set up and populate the database,
    26  * including primary admin user and initial options.
    27 	 * including primary admin user and initial options.
    27  *
    28 	 *
    28  * @since 2.1.0
    29 	 * @since 2.1.0
    29  *
    30 	 *
    30  * @param string $blog_title    Site title.
    31 	 * @param string $blog_title    Site title.
    31  * @param string $user_name     User's username.
    32 	 * @param string $user_name     User's username.
    32  * @param string $user_email    User's email.
    33 	 * @param string $user_email    User's email.
    33  * @param bool   $public        Whether site is public.
    34 	 * @param bool   $public        Whether site is public.
    34  * @param string $deprecated    Optional. Not used.
    35 	 * @param string $deprecated    Optional. Not used.
    35  * @param string $user_password Optional. User's chosen password. Default empty (random password).
    36 	 * @param string $user_password Optional. User's chosen password. Default empty (random password).
    36  * @param string $language      Optional. Language chosen. Default empty.
    37 	 * @param string $language      Optional. Language chosen. Default empty.
    37  * @return array Array keys 'url', 'user_id', 'password', and 'password_message'.
    38 	 * @return array Array keys 'url', 'user_id', 'password', and 'password_message'.
    38  */
       
    39 function wp_install( $blog_title, $user_name, $user_email, $public, $deprecated = '', $user_password = '', $language = '' ) {
       
    40 	if ( !empty( $deprecated ) )
       
    41 		_deprecated_argument( __FUNCTION__, '2.6.0' );
       
    42 
       
    43 	wp_check_mysql_version();
       
    44 	wp_cache_flush();
       
    45 	make_db_current_silent();
       
    46 	populate_options();
       
    47 	populate_roles();
       
    48 
       
    49 	update_option('blogname', $blog_title);
       
    50 	update_option('admin_email', $user_email);
       
    51 	update_option('blog_public', $public);
       
    52 
       
    53 	// Freshness of site - in the future, this could get more specific about actions taken, perhaps.
       
    54 	update_option( 'fresh_site', 1 );
       
    55 
       
    56 	if ( $language ) {
       
    57 		update_option( 'WPLANG', $language );
       
    58 	}
       
    59 
       
    60 	$guessurl = wp_guess_url();
       
    61 
       
    62 	update_option('siteurl', $guessurl);
       
    63 
       
    64 	// If not a public blog, don't ping.
       
    65 	if ( ! $public )
       
    66 		update_option('default_pingback_flag', 0);
       
    67 
       
    68 	/*
       
    69 	 * Create default user. If the user already exists, the user tables are
       
    70 	 * being shared among sites. Just set the role in that case.
       
    71 	 */
    39 	 */
    72 	$user_id = username_exists($user_name);
    40 	function wp_install( $blog_title, $user_name, $user_email, $public, $deprecated = '', $user_password = '', $language = '' ) {
    73 	$user_password = trim($user_password);
    41 		if ( ! empty( $deprecated ) ) {
    74 	$email_password = false;
    42 			_deprecated_argument( __FUNCTION__, '2.6.0' );
    75 	if ( !$user_id && empty($user_password) ) {
    43 		}
    76 		$user_password = wp_generate_password( 12, false );
    44 
    77 		$message = __('<strong><em>Note that password</em></strong> carefully! It is a <em>random</em> password that was generated just for you.');
    45 		wp_check_mysql_version();
    78 		$user_id = wp_create_user($user_name, $user_password, $user_email);
    46 		wp_cache_flush();
    79 		update_user_option($user_id, 'default_password_nag', true, true);
    47 		make_db_current_silent();
    80 		$email_password = true;
    48 		populate_options();
    81 	} elseif ( ! $user_id ) {
    49 		populate_roles();
    82 		// Password has been provided
    50 
    83 		$message = '<em>'.__('Your chosen password.').'</em>';
    51 		update_option( 'blogname', $blog_title );
    84 		$user_id = wp_create_user($user_name, $user_password, $user_email);
    52 		update_option( 'admin_email', $user_email );
    85 	} else {
    53 		update_option( 'blog_public', $public );
    86 		$message = __('User already exists. Password inherited.');
    54 
    87 	}
    55 		// Freshness of site - in the future, this could get more specific about actions taken, perhaps.
    88 
    56 		update_option( 'fresh_site', 1 );
    89 	$user = new WP_User($user_id);
    57 
    90 	$user->set_role('administrator');
    58 		if ( $language ) {
    91 
    59 			update_option( 'WPLANG', $language );
    92 	wp_install_defaults($user_id);
    60 		}
    93 
    61 
    94 	wp_install_maybe_enable_pretty_permalinks();
    62 		$guessurl = wp_guess_url();
    95 
    63 
    96 	flush_rewrite_rules();
    64 		update_option( 'siteurl', $guessurl );
    97 
    65 
    98 	wp_new_blog_notification($blog_title, $guessurl, $user_id, ($email_password ? $user_password : __('The password you chose during installation.') ) );
    66 		// If not a public site, don't ping.
    99 
    67 		if ( ! $public ) {
   100 	wp_cache_flush();
    68 			update_option( 'default_pingback_flag', 0 );
   101 
    69 		}
       
    70 
       
    71 		/*
       
    72 		 * Create default user. If the user already exists, the user tables are
       
    73 		 * being shared among sites. Just set the role in that case.
       
    74 		 */
       
    75 		$user_id        = username_exists( $user_name );
       
    76 		$user_password  = trim( $user_password );
       
    77 		$email_password = false;
       
    78 		if ( ! $user_id && empty( $user_password ) ) {
       
    79 			$user_password = wp_generate_password( 12, false );
       
    80 			$message       = __( '<strong><em>Note that password</em></strong> carefully! It is a <em>random</em> password that was generated just for you.' );
       
    81 			$user_id       = wp_create_user( $user_name, $user_password, $user_email );
       
    82 			update_user_option( $user_id, 'default_password_nag', true, true );
       
    83 			$email_password = true;
       
    84 		} elseif ( ! $user_id ) {
       
    85 			// Password has been provided
       
    86 			$message = '<em>' . __( 'Your chosen password.' ) . '</em>';
       
    87 			$user_id = wp_create_user( $user_name, $user_password, $user_email );
       
    88 		} else {
       
    89 			$message = __( 'User already exists. Password inherited.' );
       
    90 		}
       
    91 
       
    92 		$user = new WP_User( $user_id );
       
    93 		$user->set_role( 'administrator' );
       
    94 
       
    95 		wp_install_defaults( $user_id );
       
    96 
       
    97 		wp_install_maybe_enable_pretty_permalinks();
       
    98 
       
    99 		flush_rewrite_rules();
       
   100 
       
   101 		wp_new_blog_notification( $blog_title, $guessurl, $user_id, ( $email_password ? $user_password : __( 'The password you chose during installation.' ) ) );
       
   102 
       
   103 		wp_cache_flush();
       
   104 
       
   105 		/**
       
   106 		 * Fires after a site is fully installed.
       
   107 		 *
       
   108 		 * @since 3.9.0
       
   109 		 *
       
   110 		 * @param WP_User $user The site owner.
       
   111 		 */
       
   112 		do_action( 'wp_install', $user );
       
   113 
       
   114 		return array(
       
   115 			'url'              => $guessurl,
       
   116 			'user_id'          => $user_id,
       
   117 			'password'         => $user_password,
       
   118 			'password_message' => $message,
       
   119 		);
       
   120 	}
       
   121 endif;
       
   122 
       
   123 if ( ! function_exists( 'wp_install_defaults' ) ) :
   102 	/**
   124 	/**
   103 	 * Fires after a site is fully installed.
   125 	 * Creates the initial content for a newly-installed site.
   104 	 *
   126 	 *
   105 	 * @since 3.9.0
   127 	 * Adds the default "Uncategorized" category, the first post (with comment),
       
   128 	 * first page, and default widgets for default theme for the current version.
   106 	 *
   129 	 *
   107 	 * @param WP_User $user The site owner.
   130 	 * @since 2.1.0
       
   131 	 *
       
   132 	 * @global wpdb       $wpdb
       
   133 	 * @global WP_Rewrite $wp_rewrite
       
   134 	 * @global string     $table_prefix
       
   135 	 *
       
   136 	 * @param int $user_id User ID.
   108 	 */
   137 	 */
   109 	do_action( 'wp_install', $user );
   138 	function wp_install_defaults( $user_id ) {
   110 
   139 		global $wpdb, $wp_rewrite, $table_prefix;
   111 	return array('url' => $guessurl, 'user_id' => $user_id, 'password' => $user_password, 'password_message' => $message);
   140 
   112 }
   141 		// Default category
   113 endif;
   142 		$cat_name = __( 'Uncategorized' );
   114 
   143 		/* translators: Default category slug */
   115 if ( !function_exists('wp_install_defaults') ) :
   144 		$cat_slug = sanitize_title( _x( 'Uncategorized', 'Default category slug' ) );
   116 /**
   145 
   117  * Creates the initial content for a newly-installed site.
   146 		if ( global_terms_enabled() ) {
   118  *
   147 			$cat_id = $wpdb->get_var( $wpdb->prepare( "SELECT cat_ID FROM {$wpdb->sitecategories} WHERE category_nicename = %s", $cat_slug ) );
   119  * Adds the default "Uncategorized" category, the first post (with comment),
   148 			if ( $cat_id == null ) {
   120  * first page, and default widgets for default theme for the current version.
   149 				$wpdb->insert(
   121  *
   150 					$wpdb->sitecategories,
   122  * @since 2.1.0
   151 					array(
   123  *
   152 						'cat_ID'            => 0,
   124  * @global wpdb       $wpdb
   153 						'cat_name'          => $cat_name,
   125  * @global WP_Rewrite $wp_rewrite
   154 						'category_nicename' => $cat_slug,
   126  * @global string     $table_prefix
   155 						'last_updated'      => current_time( 'mysql', true ),
   127  *
   156 					)
   128  * @param int $user_id User ID.
   157 				);
   129  */
   158 				$cat_id = $wpdb->insert_id;
   130 function wp_install_defaults( $user_id ) {
   159 			}
   131 	global $wpdb, $wp_rewrite, $table_prefix;
   160 			update_option( 'default_category', $cat_id );
   132 
   161 		} else {
   133 	// Default category
   162 			$cat_id = 1;
   134 	$cat_name = __('Uncategorized');
   163 		}
   135 	/* translators: Default category slug */
   164 
   136 	$cat_slug = sanitize_title(_x('Uncategorized', 'Default category slug'));
   165 		$wpdb->insert(
   137 
   166 			$wpdb->terms,
   138 	if ( global_terms_enabled() ) {
   167 			array(
   139 		$cat_id = $wpdb->get_var( $wpdb->prepare( "SELECT cat_ID FROM {$wpdb->sitecategories} WHERE category_nicename = %s", $cat_slug ) );
   168 				'term_id'    => $cat_id,
   140 		if ( $cat_id == null ) {
   169 				'name'       => $cat_name,
   141 			$wpdb->insert( $wpdb->sitecategories, array('cat_ID' => 0, 'cat_name' => $cat_name, 'category_nicename' => $cat_slug, 'last_updated' => current_time('mysql', true)) );
   170 				'slug'       => $cat_slug,
   142 			$cat_id = $wpdb->insert_id;
   171 				'term_group' => 0,
   143 		}
   172 			)
   144 		update_option('default_category', $cat_id);
       
   145 	} else {
       
   146 		$cat_id = 1;
       
   147 	}
       
   148 
       
   149 	$wpdb->insert( $wpdb->terms, array('term_id' => $cat_id, 'name' => $cat_name, 'slug' => $cat_slug, 'term_group' => 0) );
       
   150 	$wpdb->insert( $wpdb->term_taxonomy, array('term_id' => $cat_id, 'taxonomy' => 'category', 'description' => '', 'parent' => 0, 'count' => 1));
       
   151 	$cat_tt_id = $wpdb->insert_id;
       
   152 
       
   153 	// First post
       
   154 	$now = current_time( 'mysql' );
       
   155 	$now_gmt = current_time( 'mysql', 1 );
       
   156 	$first_post_guid = get_option( 'home' ) . '/?p=1';
       
   157 
       
   158 	if ( is_multisite() ) {
       
   159 		$first_post = get_site_option( 'first_post' );
       
   160 
       
   161 		if ( ! $first_post ) {
       
   162 			/* translators: %s: site link */
       
   163 			$first_post = __( 'Welcome to %s. This is your first post. Edit or delete it, then start blogging!' );
       
   164 		}
       
   165 
       
   166 		$first_post = sprintf( $first_post,
       
   167 			sprintf( '<a href="%s">%s</a>', esc_url( network_home_url() ), get_network()->site_name )
       
   168 		);
   173 		);
   169 
       
   170 		// Back-compat for pre-4.4
       
   171 		$first_post = str_replace( 'SITE_URL', esc_url( network_home_url() ), $first_post );
       
   172 		$first_post = str_replace( 'SITE_NAME', get_network()->site_name, $first_post );
       
   173 	} else {
       
   174 		$first_post = __( 'Welcome to WordPress. This is your first post. Edit or delete it, then start writing!' );
       
   175 	}
       
   176 
       
   177 	$wpdb->insert( $wpdb->posts, array(
       
   178 		'post_author' => $user_id,
       
   179 		'post_date' => $now,
       
   180 		'post_date_gmt' => $now_gmt,
       
   181 		'post_content' => $first_post,
       
   182 		'post_excerpt' => '',
       
   183 		'post_title' => __('Hello world!'),
       
   184 		/* translators: Default post slug */
       
   185 		'post_name' => sanitize_title( _x('hello-world', 'Default post slug') ),
       
   186 		'post_modified' => $now,
       
   187 		'post_modified_gmt' => $now_gmt,
       
   188 		'guid' => $first_post_guid,
       
   189 		'comment_count' => 1,
       
   190 		'to_ping' => '',
       
   191 		'pinged' => '',
       
   192 		'post_content_filtered' => ''
       
   193 	));
       
   194 	$wpdb->insert( $wpdb->term_relationships, array('term_taxonomy_id' => $cat_tt_id, 'object_id' => 1) );
       
   195 
       
   196 	// Default comment
       
   197 	if ( is_multisite() ) {
       
   198 		$first_comment_author = get_site_option( 'first_comment_author' );
       
   199 		$first_comment_email = get_site_option( 'first_comment_email' );
       
   200 		$first_comment_url = get_site_option( 'first_comment_url', network_home_url() );
       
   201 		$first_comment = get_site_option( 'first_comment' );
       
   202 	}
       
   203 
       
   204 	$first_comment_author = ! empty( $first_comment_author ) ? $first_comment_author : __( 'A WordPress Commenter' );
       
   205 	$first_comment_email = ! empty( $first_comment_email ) ? $first_comment_email : 'wapuu@wordpress.example';
       
   206 	$first_comment_url = ! empty( $first_comment_url ) ? $first_comment_url : 'https://wordpress.org/';
       
   207 	$first_comment = ! empty( $first_comment ) ? $first_comment :  __( 'Hi, this is a comment.
       
   208 To get started with moderating, editing, and deleting comments, please visit the Comments screen in the dashboard.
       
   209 Commenter avatars come from <a href="https://gravatar.com">Gravatar</a>.' );
       
   210 	$wpdb->insert( $wpdb->comments, array(
       
   211 		'comment_post_ID' => 1,
       
   212 		'comment_author' => $first_comment_author,
       
   213 		'comment_author_email' => $first_comment_email,
       
   214 		'comment_author_url' => $first_comment_url,
       
   215 		'comment_date' => $now,
       
   216 		'comment_date_gmt' => $now_gmt,
       
   217 		'comment_content' => $first_comment
       
   218 	));
       
   219 
       
   220 	// First Page
       
   221 	if ( is_multisite() )
       
   222 		$first_page = get_site_option( 'first_page' );
       
   223 
       
   224 	$first_page = ! empty( $first_page ) ? $first_page : sprintf( __( "This is an example page. It's different from a blog post because it will stay in one place and will show up in your site navigation (in most themes). Most people start with an About page that introduces them to potential site visitors. It might say something like this:
       
   225 
       
   226 <blockquote>Hi there! I'm a bike messenger by day, aspiring actor by night, and this is my website. I live in Los Angeles, have a great dog named Jack, and I like pi&#241;a coladas. (And gettin' caught in the rain.)</blockquote>
       
   227 
       
   228 ...or something like this:
       
   229 
       
   230 <blockquote>The XYZ Doohickey Company was founded in 1971, and has been providing quality doohickeys to the public ever since. Located in Gotham City, XYZ employs over 2,000 people and does all kinds of awesome things for the Gotham community.</blockquote>
       
   231 
       
   232 As a new WordPress user, you should go to <a href=\"%s\">your dashboard</a> to delete this page and create new pages for your content. Have fun!" ), admin_url() );
       
   233 
       
   234 	$first_post_guid = get_option('home') . '/?page_id=2';
       
   235 	$wpdb->insert( $wpdb->posts, array(
       
   236 		'post_author' => $user_id,
       
   237 		'post_date' => $now,
       
   238 		'post_date_gmt' => $now_gmt,
       
   239 		'post_content' => $first_page,
       
   240 		'post_excerpt' => '',
       
   241 		'comment_status' => 'closed',
       
   242 		'post_title' => __( 'Sample Page' ),
       
   243 		/* translators: Default page slug */
       
   244 		'post_name' => __( 'sample-page' ),
       
   245 		'post_modified' => $now,
       
   246 		'post_modified_gmt' => $now_gmt,
       
   247 		'guid' => $first_post_guid,
       
   248 		'post_type' => 'page',
       
   249 		'to_ping' => '',
       
   250 		'pinged' => '',
       
   251 		'post_content_filtered' => ''
       
   252 	));
       
   253 	$wpdb->insert( $wpdb->postmeta, array( 'post_id' => 2, 'meta_key' => '_wp_page_template', 'meta_value' => 'default' ) );
       
   254 
       
   255 	// Privacy Policy page
       
   256 	if ( is_multisite() ) {
       
   257 		// Disable by default unless the suggested content is provided.
       
   258 		$privacy_policy_content = get_site_option( 'default_privacy_policy_content' );
       
   259 	} else {
       
   260 		if ( ! class_exists( 'WP_Privacy_Policy_Content' ) ) {
       
   261 			include_once( ABSPATH . 'wp-admin/includes/misc.php' );
       
   262 		}
       
   263 
       
   264 		$privacy_policy_content = WP_Privacy_Policy_Content::get_default_content();
       
   265 	}
       
   266 
       
   267 	if ( ! empty( $privacy_policy_content ) ) {
       
   268 		$privacy_policy_guid = get_option( 'home' ) . '/?page_id=3';
       
   269 
       
   270 		$wpdb->insert(
   174 		$wpdb->insert(
   271 			$wpdb->posts, array(
   175 			$wpdb->term_taxonomy,
       
   176 			array(
       
   177 				'term_id'     => $cat_id,
       
   178 				'taxonomy'    => 'category',
       
   179 				'description' => '',
       
   180 				'parent'      => 0,
       
   181 				'count'       => 1,
       
   182 			)
       
   183 		);
       
   184 		$cat_tt_id = $wpdb->insert_id;
       
   185 
       
   186 		// First post
       
   187 		$now             = current_time( 'mysql' );
       
   188 		$now_gmt         = current_time( 'mysql', 1 );
       
   189 		$first_post_guid = get_option( 'home' ) . '/?p=1';
       
   190 
       
   191 		if ( is_multisite() ) {
       
   192 			$first_post = get_site_option( 'first_post' );
       
   193 
       
   194 			if ( ! $first_post ) {
       
   195 				$first_post = "<!-- wp:paragraph -->\n<p>" .
       
   196 				/* translators: first post content, %s: site link */
       
   197 				__( 'Welcome to %s. This is your first post. Edit or delete it, then start writing!' ) .
       
   198 				"</p>\n<!-- /wp:paragraph -->";
       
   199 			}
       
   200 
       
   201 			$first_post = sprintf(
       
   202 				$first_post,
       
   203 				sprintf( '<a href="%s">%s</a>', esc_url( network_home_url() ), get_network()->site_name )
       
   204 			);
       
   205 
       
   206 			// Back-compat for pre-4.4
       
   207 			$first_post = str_replace( 'SITE_URL', esc_url( network_home_url() ), $first_post );
       
   208 			$first_post = str_replace( 'SITE_NAME', get_network()->site_name, $first_post );
       
   209 		} else {
       
   210 			$first_post = "<!-- wp:paragraph -->\n<p>" .
       
   211 			/* translators: first post content, %s: site link */
       
   212 			__( 'Welcome to WordPress. This is your first post. Edit or delete it, then start writing!' ) .
       
   213 			"</p>\n<!-- /wp:paragraph -->";
       
   214 		}
       
   215 
       
   216 		$wpdb->insert(
       
   217 			$wpdb->posts,
       
   218 			array(
   272 				'post_author'           => $user_id,
   219 				'post_author'           => $user_id,
   273 				'post_date'             => $now,
   220 				'post_date'             => $now,
   274 				'post_date_gmt'         => $now_gmt,
   221 				'post_date_gmt'         => $now_gmt,
   275 				'post_content'          => $privacy_policy_content,
   222 				'post_content'          => $first_post,
   276 				'post_excerpt'          => '',
   223 				'post_excerpt'          => '',
   277 				'comment_status'        => 'closed',
   224 				'post_title'            => __( 'Hello world!' ),
   278 				'post_title'            => __( 'Privacy Policy' ),
   225 				/* translators: Default post slug */
   279 				/* translators: Privacy Policy page slug */
   226 				'post_name'             => sanitize_title( _x( 'hello-world', 'Default post slug' ) ),
   280 				'post_name'             => __( 'privacy-policy' ),
       
   281 				'post_modified'         => $now,
   227 				'post_modified'         => $now,
   282 				'post_modified_gmt'     => $now_gmt,
   228 				'post_modified_gmt'     => $now_gmt,
   283 				'guid'                  => $privacy_policy_guid,
   229 				'guid'                  => $first_post_guid,
   284 				'post_type'             => 'page',
   230 				'comment_count'         => 1,
   285 				'post_status'           => 'draft',
       
   286 				'to_ping'               => '',
   231 				'to_ping'               => '',
   287 				'pinged'                => '',
   232 				'pinged'                => '',
   288 				'post_content_filtered' => '',
   233 				'post_content_filtered' => '',
   289 			)
   234 			)
   290 		);
   235 		);
   291 		$wpdb->insert(
   236 		$wpdb->insert(
   292 			$wpdb->postmeta, array(
   237 			$wpdb->term_relationships,
   293 				'post_id'    => 3,
   238 			array(
       
   239 				'term_taxonomy_id' => $cat_tt_id,
       
   240 				'object_id'        => 1,
       
   241 			)
       
   242 		);
       
   243 
       
   244 		// Default comment
       
   245 		if ( is_multisite() ) {
       
   246 			$first_comment_author = get_site_option( 'first_comment_author' );
       
   247 			$first_comment_email  = get_site_option( 'first_comment_email' );
       
   248 			$first_comment_url    = get_site_option( 'first_comment_url', network_home_url() );
       
   249 			$first_comment        = get_site_option( 'first_comment' );
       
   250 		}
       
   251 
       
   252 		$first_comment_author = ! empty( $first_comment_author ) ? $first_comment_author : __( 'A WordPress Commenter' );
       
   253 		$first_comment_email  = ! empty( $first_comment_email ) ? $first_comment_email : 'wapuu@wordpress.example';
       
   254 		$first_comment_url    = ! empty( $first_comment_url ) ? $first_comment_url : 'https://wordpress.org/';
       
   255 		$first_comment        = ! empty( $first_comment ) ? $first_comment : __(
       
   256 			'Hi, this is a comment.
       
   257 To get started with moderating, editing, and deleting comments, please visit the Comments screen in the dashboard.
       
   258 Commenter avatars come from <a href="https://gravatar.com">Gravatar</a>.'
       
   259 		);
       
   260 		$wpdb->insert(
       
   261 			$wpdb->comments,
       
   262 			array(
       
   263 				'comment_post_ID'      => 1,
       
   264 				'comment_author'       => $first_comment_author,
       
   265 				'comment_author_email' => $first_comment_email,
       
   266 				'comment_author_url'   => $first_comment_url,
       
   267 				'comment_date'         => $now,
       
   268 				'comment_date_gmt'     => $now_gmt,
       
   269 				'comment_content'      => $first_comment,
       
   270 			)
       
   271 		);
       
   272 
       
   273 		// First Page
       
   274 		if ( is_multisite() ) {
       
   275 			$first_page = get_site_option( 'first_page' );
       
   276 		}
       
   277 
       
   278 		if ( empty( $first_page ) ) {
       
   279 			$first_page = "<!-- wp:paragraph -->\n<p>";
       
   280 			/* translators: first page content */
       
   281 			$first_page .= __( "This is an example page. It's different from a blog post because it will stay in one place and will show up in your site navigation (in most themes). Most people start with an About page that introduces them to potential site visitors. It might say something like this:" );
       
   282 			$first_page .= "</p>\n<!-- /wp:paragraph -->\n\n";
       
   283 
       
   284 			$first_page .= "<!-- wp:quote -->\n<blockquote class=\"wp-block-quote\"><p>";
       
   285 			/* translators: first page content */
       
   286 			$first_page .= __( "Hi there! I'm a bike messenger by day, aspiring actor by night, and this is my website. I live in Los Angeles, have a great dog named Jack, and I like pi&#241;a coladas. (And gettin' caught in the rain.)" );
       
   287 			$first_page .= "</p></blockquote>\n<!-- /wp:quote -->\n\n";
       
   288 
       
   289 			$first_page .= "<!-- wp:paragraph -->\n<p>";
       
   290 			/* translators: first page content */
       
   291 			$first_page .= __( '...or something like this:' );
       
   292 			$first_page .= "</p>\n<!-- /wp:paragraph -->\n\n";
       
   293 
       
   294 			$first_page .= "<!-- wp:quote -->\n<blockquote class=\"wp-block-quote\"><p>";
       
   295 			/* translators: first page content */
       
   296 			$first_page .= __( 'The XYZ Doohickey Company was founded in 1971, and has been providing quality doohickeys to the public ever since. Located in Gotham City, XYZ employs over 2,000 people and does all kinds of awesome things for the Gotham community.' );
       
   297 			$first_page .= "</p></blockquote>\n<!-- /wp:quote -->\n\n";
       
   298 
       
   299 			$first_page .= "<!-- wp:paragraph -->\n<p>";
       
   300 			$first_page .= sprintf(
       
   301 				/* translators: first page content, %s: site admin URL */
       
   302 				__( 'As a new WordPress user, you should go to <a href="%s">your dashboard</a> to delete this page and create new pages for your content. Have fun!' ),
       
   303 				admin_url()
       
   304 			);
       
   305 			$first_page .= "</p>\n<!-- /wp:paragraph -->";
       
   306 		}
       
   307 
       
   308 		$first_post_guid = get_option( 'home' ) . '/?page_id=2';
       
   309 		$wpdb->insert(
       
   310 			$wpdb->posts,
       
   311 			array(
       
   312 				'post_author'           => $user_id,
       
   313 				'post_date'             => $now,
       
   314 				'post_date_gmt'         => $now_gmt,
       
   315 				'post_content'          => $first_page,
       
   316 				'post_excerpt'          => '',
       
   317 				'comment_status'        => 'closed',
       
   318 				'post_title'            => __( 'Sample Page' ),
       
   319 				/* translators: Default page slug */
       
   320 				'post_name'             => __( 'sample-page' ),
       
   321 				'post_modified'         => $now,
       
   322 				'post_modified_gmt'     => $now_gmt,
       
   323 				'guid'                  => $first_post_guid,
       
   324 				'post_type'             => 'page',
       
   325 				'to_ping'               => '',
       
   326 				'pinged'                => '',
       
   327 				'post_content_filtered' => '',
       
   328 			)
       
   329 		);
       
   330 		$wpdb->insert(
       
   331 			$wpdb->postmeta,
       
   332 			array(
       
   333 				'post_id'    => 2,
   294 				'meta_key'   => '_wp_page_template',
   334 				'meta_key'   => '_wp_page_template',
   295 				'meta_value' => 'default',
   335 				'meta_value' => 'default',
   296 			)
   336 			)
   297 		);
   337 		);
   298 		update_option( 'wp_page_for_privacy_policy', 3 );
   338 
   299 	}
   339 		// Privacy Policy page
   300 
   340 		if ( is_multisite() ) {
   301 	// Set up default widgets for default theme.
   341 			// Disable by default unless the suggested content is provided.
   302 	update_option( 'widget_search', array ( 2 => array ( 'title' => '' ), '_multiwidget' => 1 ) );
   342 			$privacy_policy_content = get_site_option( 'default_privacy_policy_content' );
   303 	update_option( 'widget_recent-posts', array ( 2 => array ( 'title' => '', 'number' => 5 ), '_multiwidget' => 1 ) );
   343 		} else {
   304 	update_option( 'widget_recent-comments', array ( 2 => array ( 'title' => '', 'number' => 5 ), '_multiwidget' => 1 ) );
   344 			if ( ! class_exists( 'WP_Privacy_Policy_Content' ) ) {
   305 	update_option( 'widget_archives', array ( 2 => array ( 'title' => '', 'count' => 0, 'dropdown' => 0 ), '_multiwidget' => 1 ) );
   345 				include_once( ABSPATH . 'wp-admin/includes/misc.php' );
   306 	update_option( 'widget_categories', array ( 2 => array ( 'title' => '', 'count' => 0, 'hierarchical' => 0, 'dropdown' => 0 ), '_multiwidget' => 1 ) );
   346 			}
   307 	update_option( 'widget_meta', array ( 2 => array ( 'title' => '' ), '_multiwidget' => 1 ) );
   347 
   308 	update_option( 'sidebars_widgets', array( 'wp_inactive_widgets' => array(), 'sidebar-1' => array( 0 => 'search-2', 1 => 'recent-posts-2', 2 => 'recent-comments-2', 3 => 'archives-2', 4 => 'categories-2', 5 => 'meta-2' ), 'sidebar-2' => array(), 'sidebar-3' => array(), 'array_version' => 3 ) );
   348 			$privacy_policy_content = WP_Privacy_Policy_Content::get_default_content();
   309 	if ( ! is_multisite() )
   349 		}
   310 		update_user_meta( $user_id, 'show_welcome_panel', 1 );
   350 
   311 	elseif ( ! is_super_admin( $user_id ) && ! metadata_exists( 'user', $user_id, 'show_welcome_panel' ) )
   351 		if ( ! empty( $privacy_policy_content ) ) {
   312 		update_user_meta( $user_id, 'show_welcome_panel', 2 );
   352 			$privacy_policy_guid = get_option( 'home' ) . '/?page_id=3';
   313 
   353 
   314 	if ( is_multisite() ) {
   354 			$wpdb->insert(
   315 		// Flush rules to pick up the new page.
   355 				$wpdb->posts,
   316 		$wp_rewrite->init();
   356 				array(
   317 		$wp_rewrite->flush_rules();
   357 					'post_author'           => $user_id,
   318 
   358 					'post_date'             => $now,
   319 		$user = new WP_User($user_id);
   359 					'post_date_gmt'         => $now_gmt,
   320 		$wpdb->update( $wpdb->options, array('option_value' => $user->user_email), array('option_name' => 'admin_email') );
   360 					'post_content'          => $privacy_policy_content,
   321 
   361 					'post_excerpt'          => '',
   322 		// Remove all perms except for the login user.
   362 					'comment_status'        => 'closed',
   323 		$wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id != %d AND meta_key = %s", $user_id, $table_prefix.'user_level') );
   363 					'post_title'            => __( 'Privacy Policy' ),
   324 		$wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id != %d AND meta_key = %s", $user_id, $table_prefix.'capabilities') );
   364 					/* translators: Privacy Policy page slug */
   325 
   365 					'post_name'             => __( 'privacy-policy' ),
   326 		// Delete any caps that snuck into the previously active blog. (Hardcoded to blog 1 for now.) TODO: Get previous_blog_id.
   366 					'post_modified'         => $now,
   327 		if ( !is_super_admin( $user_id ) && $user_id != 1 )
   367 					'post_modified_gmt'     => $now_gmt,
   328 			$wpdb->delete( $wpdb->usermeta, array( 'user_id' => $user_id , 'meta_key' => $wpdb->base_prefix.'1_capabilities' ) );
   368 					'guid'                  => $privacy_policy_guid,
   329 	}
   369 					'post_type'             => 'page',
   330 }
   370 					'post_status'           => 'draft',
       
   371 					'to_ping'               => '',
       
   372 					'pinged'                => '',
       
   373 					'post_content_filtered' => '',
       
   374 				)
       
   375 			);
       
   376 			$wpdb->insert(
       
   377 				$wpdb->postmeta,
       
   378 				array(
       
   379 					'post_id'    => 3,
       
   380 					'meta_key'   => '_wp_page_template',
       
   381 					'meta_value' => 'default',
       
   382 				)
       
   383 			);
       
   384 			update_option( 'wp_page_for_privacy_policy', 3 );
       
   385 		}
       
   386 
       
   387 		// Set up default widgets for default theme.
       
   388 		update_option(
       
   389 			'widget_search',
       
   390 			array(
       
   391 				2              => array( 'title' => '' ),
       
   392 				'_multiwidget' => 1,
       
   393 			)
       
   394 		);
       
   395 		update_option(
       
   396 			'widget_recent-posts',
       
   397 			array(
       
   398 				2              => array(
       
   399 					'title'  => '',
       
   400 					'number' => 5,
       
   401 				),
       
   402 				'_multiwidget' => 1,
       
   403 			)
       
   404 		);
       
   405 		update_option(
       
   406 			'widget_recent-comments',
       
   407 			array(
       
   408 				2              => array(
       
   409 					'title'  => '',
       
   410 					'number' => 5,
       
   411 				),
       
   412 				'_multiwidget' => 1,
       
   413 			)
       
   414 		);
       
   415 		update_option(
       
   416 			'widget_archives',
       
   417 			array(
       
   418 				2              => array(
       
   419 					'title'    => '',
       
   420 					'count'    => 0,
       
   421 					'dropdown' => 0,
       
   422 				),
       
   423 				'_multiwidget' => 1,
       
   424 			)
       
   425 		);
       
   426 		update_option(
       
   427 			'widget_categories',
       
   428 			array(
       
   429 				2              => array(
       
   430 					'title'        => '',
       
   431 					'count'        => 0,
       
   432 					'hierarchical' => 0,
       
   433 					'dropdown'     => 0,
       
   434 				),
       
   435 				'_multiwidget' => 1,
       
   436 			)
       
   437 		);
       
   438 		update_option(
       
   439 			'widget_meta',
       
   440 			array(
       
   441 				2              => array( 'title' => '' ),
       
   442 				'_multiwidget' => 1,
       
   443 			)
       
   444 		);
       
   445 		update_option(
       
   446 			'sidebars_widgets',
       
   447 			array(
       
   448 				'wp_inactive_widgets' => array(),
       
   449 				'sidebar-1'           => array(
       
   450 					0 => 'search-2',
       
   451 					1 => 'recent-posts-2',
       
   452 					2 => 'recent-comments-2',
       
   453 					3 => 'archives-2',
       
   454 					4 => 'categories-2',
       
   455 					5 => 'meta-2',
       
   456 				),
       
   457 				'array_version'       => 3,
       
   458 			)
       
   459 		);
       
   460 		if ( ! is_multisite() ) {
       
   461 			update_user_meta( $user_id, 'show_welcome_panel', 1 );
       
   462 		} elseif ( ! is_super_admin( $user_id ) && ! metadata_exists( 'user', $user_id, 'show_welcome_panel' ) ) {
       
   463 			update_user_meta( $user_id, 'show_welcome_panel', 2 );
       
   464 		}
       
   465 
       
   466 		if ( is_multisite() ) {
       
   467 			// Flush rules to pick up the new page.
       
   468 			$wp_rewrite->init();
       
   469 			$wp_rewrite->flush_rules();
       
   470 
       
   471 			$user = new WP_User( $user_id );
       
   472 			$wpdb->update( $wpdb->options, array( 'option_value' => $user->user_email ), array( 'option_name' => 'admin_email' ) );
       
   473 
       
   474 			// Remove all perms except for the login user.
       
   475 			$wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->usermeta WHERE user_id != %d AND meta_key = %s", $user_id, $table_prefix . 'user_level' ) );
       
   476 			$wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->usermeta WHERE user_id != %d AND meta_key = %s", $user_id, $table_prefix . 'capabilities' ) );
       
   477 
       
   478 			// Delete any caps that snuck into the previously active blog. (Hardcoded to blog 1 for now.) TODO: Get previous_blog_id.
       
   479 			if ( ! is_super_admin( $user_id ) && $user_id != 1 ) {
       
   480 				$wpdb->delete(
       
   481 					$wpdb->usermeta,
       
   482 					array(
       
   483 						'user_id'  => $user_id,
       
   484 						'meta_key' => $wpdb->base_prefix . '1_capabilities',
       
   485 					)
       
   486 				);
       
   487 			}
       
   488 		}
       
   489 	}
   331 endif;
   490 endif;
   332 
   491 
   333 /**
   492 /**
   334  * Maybe enable pretty permalinks on installation.
   493  * Maybe enable pretty permalinks on installation.
   335  *
   494  *
   357 	 * The second is PATHINFO-based permalinks for web server configurations
   516 	 * The second is PATHINFO-based permalinks for web server configurations
   358 	 * without a true rewrite module enabled.
   517 	 * without a true rewrite module enabled.
   359 	 */
   518 	 */
   360 	$permalink_structures = array(
   519 	$permalink_structures = array(
   361 		'/%year%/%monthnum%/%day%/%postname%/',
   520 		'/%year%/%monthnum%/%day%/%postname%/',
   362 		'/index.php/%year%/%monthnum%/%day%/%postname%/'
   521 		'/index.php/%year%/%monthnum%/%day%/%postname%/',
   363 	);
   522 	);
   364 
   523 
   365 	foreach ( (array) $permalink_structures as $permalink_structure ) {
   524 	foreach ( (array) $permalink_structures as $permalink_structure ) {
   366 		$wp_rewrite->set_permalink_structure( $permalink_structure );
   525 		$wp_rewrite->set_permalink_structure( $permalink_structure );
   367 
   526 
   368 		/*
   527 		/*
   369 	 	 * Flush rules with the hard option to force refresh of the web-server's
   528 		  * Flush rules with the hard option to force refresh of the web-server's
   370 	 	 * rewrite config file (e.g. .htaccess or web.config).
   529 		  * rewrite config file (e.g. .htaccess or web.config).
   371 	 	 */
   530 		  */
   372 		$wp_rewrite->flush_rules( true );
   531 		$wp_rewrite->flush_rules( true );
   373 
   532 
   374 		$test_url = '';
   533 		$test_url = '';
   375 
   534 
   376 		// Test against a real WordPress Post
   535 		// Test against a real WordPress Post
   378 		if ( $first_post ) {
   537 		if ( $first_post ) {
   379 			$test_url = get_permalink( $first_post->ID );
   538 			$test_url = get_permalink( $first_post->ID );
   380 		}
   539 		}
   381 
   540 
   382 		/*
   541 		/*
   383 	 	 * Send a request to the site, and check whether
   542 		  * Send a request to the site, and check whether
   384 	 	 * the 'x-pingback' header is returned as expected.
   543 		  * the 'x-pingback' header is returned as expected.
   385 	 	 *
   544 		  *
   386 	 	 * Uses wp_remote_get() instead of wp_remote_head() because web servers
   545 		  * Uses wp_remote_get() instead of wp_remote_head() because web servers
   387 	 	 * can block head requests.
   546 		  * can block head requests.
   388 	 	 */
   547 		  */
   389 		$response          = wp_remote_get( $test_url, array( 'timeout' => 5 ) );
   548 		$response          = wp_remote_get( $test_url, array( 'timeout' => 5 ) );
   390 		$x_pingback_header = wp_remote_retrieve_header( $response, 'x-pingback' );
   549 		$x_pingback_header = wp_remote_retrieve_header( $response, 'x-pingback' );
   391 		$pretty_permalinks = $x_pingback_header && $x_pingback_header === get_bloginfo( 'pingback_url' );
   550 		$pretty_permalinks = $x_pingback_header && $x_pingback_header === get_bloginfo( 'pingback_url' );
   392 
   551 
   393 		if ( $pretty_permalinks ) {
   552 		if ( $pretty_permalinks ) {
   403 	$wp_rewrite->flush_rules( true );
   562 	$wp_rewrite->flush_rules( true );
   404 
   563 
   405 	return false;
   564 	return false;
   406 }
   565 }
   407 
   566 
   408 if ( !function_exists('wp_new_blog_notification') ) :
   567 if ( ! function_exists( 'wp_new_blog_notification' ) ) :
   409 /**
   568 	/**
   410  * Notifies the site admin that the setup is complete.
   569 	 * Notifies the site admin that the setup is complete.
   411  *
   570 	 *
   412  * Sends an email with wp_mail to the new administrator that the site setup is complete,
   571 	 * Sends an email with wp_mail to the new administrator that the site setup is complete,
   413  * and provides them with a record of their login credentials.
   572 	 * and provides them with a record of their login credentials.
   414  *
   573 	 *
   415  * @since 2.1.0
   574 	 * @since 2.1.0
   416  *
   575 	 *
   417  * @param string $blog_title Site title.
   576 	 * @param string $blog_title Site title.
   418  * @param string $blog_url   Site url.
   577 	 * @param string $blog_url   Site url.
   419  * @param int    $user_id    User ID.
   578 	 * @param int    $user_id    User ID.
   420  * @param string $password   User's Password.
   579 	 * @param string $password   User's Password.
   421  */
   580 	 */
   422 function wp_new_blog_notification($blog_title, $blog_url, $user_id, $password) {
   581 	function wp_new_blog_notification( $blog_title, $blog_url, $user_id, $password ) {
   423 	$user = new WP_User( $user_id );
   582 		$user      = new WP_User( $user_id );
   424 	$email = $user->user_email;
   583 		$email     = $user->user_email;
   425 	$name = $user->user_login;
   584 		$name      = $user->user_login;
   426 	$login_url = wp_login_url();
   585 		$login_url = wp_login_url();
   427 	/* translators: New site notification email. 1: New site URL, 2: User login, 3: User password or password reset link, 4: Login URL */
   586 		/* translators: New site notification email. 1: New site URL, 2: User login, 3: User password or password reset link, 4: Login URL */
   428 	$message = sprintf( __( "Your new WordPress site has been successfully set up at:
   587 		$message = sprintf(
   429 
   588 			__(
   430 %1\$s
   589 				'Your new WordPress site has been successfully set up at:
       
   590 
       
   591 %1$s
   431 
   592 
   432 You can log in to the administrator account with the following information:
   593 You can log in to the administrator account with the following information:
   433 
   594 
   434 Username: %2\$s
   595 Username: %2$s
   435 Password: %3\$s
   596 Password: %3$s
   436 Log in here: %4\$s
   597 Log in here: %4$s
   437 
   598 
   438 We hope you enjoy your new site. Thanks!
   599 We hope you enjoy your new site. Thanks!
   439 
   600 
   440 --The WordPress Team
   601 --The WordPress Team
   441 https://wordpress.org/
   602 https://wordpress.org/
   442 "), $blog_url, $name, $password, $login_url );
   603 '
   443 
   604 			),
   444 	@wp_mail($email, __('New WordPress Site'), $message);
   605 			$blog_url,
   445 }
   606 			$name,
       
   607 			$password,
       
   608 			$login_url
       
   609 		);
       
   610 
       
   611 		@wp_mail( $email, __( 'New WordPress Site' ), $message );
       
   612 	}
   446 endif;
   613 endif;
   447 
   614 
   448 if ( !function_exists('wp_upgrade') ) :
   615 if ( ! function_exists( 'wp_upgrade' ) ) :
   449 /**
       
   450  * Runs WordPress Upgrade functions.
       
   451  *
       
   452  * Upgrades the database if needed during a site update.
       
   453  *
       
   454  * @since 2.1.0
       
   455  *
       
   456  * @global int  $wp_current_db_version
       
   457  * @global int  $wp_db_version
       
   458  * @global wpdb $wpdb WordPress database abstraction object.
       
   459  */
       
   460 function wp_upgrade() {
       
   461 	global $wp_current_db_version, $wp_db_version, $wpdb;
       
   462 
       
   463 	$wp_current_db_version = __get_option('db_version');
       
   464 
       
   465 	// We are up-to-date. Nothing to do.
       
   466 	if ( $wp_db_version == $wp_current_db_version )
       
   467 		return;
       
   468 
       
   469 	if ( ! is_blog_installed() )
       
   470 		return;
       
   471 
       
   472 	wp_check_mysql_version();
       
   473 	wp_cache_flush();
       
   474 	pre_schema_upgrade();
       
   475 	make_db_current_silent();
       
   476 	upgrade_all();
       
   477 	if ( is_multisite() && is_main_site() )
       
   478 		upgrade_network();
       
   479 	wp_cache_flush();
       
   480 
       
   481 	if ( is_multisite() ) {
       
   482 		$site_id = get_current_blog_id();
       
   483 
       
   484 		if ( $wpdb->get_row( $wpdb->prepare( "SELECT blog_id FROM {$wpdb->blog_versions} WHERE blog_id = %d", $site_id ) ) ) {
       
   485 			$wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->blog_versions} SET db_version = %d WHERE blog_id = %d", $wp_db_version, $site_id ) );
       
   486 		} else {
       
   487 			$wpdb->query( $wpdb->prepare( "INSERT INTO {$wpdb->blog_versions} ( `blog_id` , `db_version` , `last_updated` ) VALUES ( %d, %d, NOW() );", $site_id, $wp_db_version ) );
       
   488 		}
       
   489 	}
       
   490 
       
   491 	/**
   616 	/**
   492 	 * Fires after a site is fully upgraded.
   617 	 * Runs WordPress Upgrade functions.
   493 	 *
   618 	 *
   494 	 * @since 3.9.0
   619 	 * Upgrades the database if needed during a site update.
   495 	 *
   620 	 *
   496 	 * @param int $wp_db_version         The new $wp_db_version.
   621 	 * @since 2.1.0
   497 	 * @param int $wp_current_db_version The old (current) $wp_db_version.
   622 	 *
       
   623 	 * @global int  $wp_current_db_version
       
   624 	 * @global int  $wp_db_version
       
   625 	 * @global wpdb $wpdb WordPress database abstraction object.
   498 	 */
   626 	 */
   499 	do_action( 'wp_upgrade', $wp_db_version, $wp_current_db_version );
   627 	function wp_upgrade() {
   500 }
   628 		global $wp_current_db_version, $wp_db_version, $wpdb;
       
   629 
       
   630 		$wp_current_db_version = __get_option( 'db_version' );
       
   631 
       
   632 		// We are up-to-date. Nothing to do.
       
   633 		if ( $wp_db_version == $wp_current_db_version ) {
       
   634 			return;
       
   635 		}
       
   636 
       
   637 		if ( ! is_blog_installed() ) {
       
   638 			return;
       
   639 		}
       
   640 
       
   641 		wp_check_mysql_version();
       
   642 		wp_cache_flush();
       
   643 		pre_schema_upgrade();
       
   644 		make_db_current_silent();
       
   645 		upgrade_all();
       
   646 		if ( is_multisite() && is_main_site() ) {
       
   647 			upgrade_network();
       
   648 		}
       
   649 		wp_cache_flush();
       
   650 
       
   651 		if ( is_multisite() ) {
       
   652 			$site_id = get_current_blog_id();
       
   653 
       
   654 			if ( $wpdb->get_row( $wpdb->prepare( "SELECT blog_id FROM {$wpdb->blog_versions} WHERE blog_id = %d", $site_id ) ) ) {
       
   655 				$wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->blog_versions} SET db_version = %d WHERE blog_id = %d", $wp_db_version, $site_id ) );
       
   656 			} else {
       
   657 				$wpdb->query( $wpdb->prepare( "INSERT INTO {$wpdb->blog_versions} ( `blog_id` , `db_version` , `last_updated` ) VALUES ( %d, %d, NOW() );", $site_id, $wp_db_version ) );
       
   658 			}
       
   659 		}
       
   660 
       
   661 		/**
       
   662 		 * Fires after a site is fully upgraded.
       
   663 		 *
       
   664 		 * @since 3.9.0
       
   665 		 *
       
   666 		 * @param int $wp_db_version         The new $wp_db_version.
       
   667 		 * @param int $wp_current_db_version The old (current) $wp_db_version.
       
   668 		 */
       
   669 		do_action( 'wp_upgrade', $wp_db_version, $wp_current_db_version );
       
   670 	}
   501 endif;
   671 endif;
   502 
   672 
   503 /**
   673 /**
   504  * Functions to be called in installation and upgrade scripts.
   674  * Functions to be called in installation and upgrade scripts.
   505  *
   675  *
   512  * @global int $wp_current_db_version
   682  * @global int $wp_current_db_version
   513  * @global int $wp_db_version
   683  * @global int $wp_db_version
   514  */
   684  */
   515 function upgrade_all() {
   685 function upgrade_all() {
   516 	global $wp_current_db_version, $wp_db_version;
   686 	global $wp_current_db_version, $wp_db_version;
   517 	$wp_current_db_version = __get_option('db_version');
   687 	$wp_current_db_version = __get_option( 'db_version' );
   518 
   688 
   519 	// We are up-to-date. Nothing to do.
   689 	// We are up-to-date. Nothing to do.
   520 	if ( $wp_db_version == $wp_current_db_version )
   690 	if ( $wp_db_version == $wp_current_db_version ) {
   521 		return;
   691 		return;
       
   692 	}
   522 
   693 
   523 	// If the version is not set in the DB, try to guess the version.
   694 	// If the version is not set in the DB, try to guess the version.
   524 	if ( empty($wp_current_db_version) ) {
   695 	if ( empty( $wp_current_db_version ) ) {
   525 		$wp_current_db_version = 0;
   696 		$wp_current_db_version = 0;
   526 
   697 
   527 		// If the template option exists, we have 1.5.
   698 		// If the template option exists, we have 1.5.
   528 		$template = __get_option('template');
   699 		$template = __get_option( 'template' );
   529 		if ( !empty($template) )
   700 		if ( ! empty( $template ) ) {
   530 			$wp_current_db_version = 2541;
   701 			$wp_current_db_version = 2541;
   531 	}
   702 		}
   532 
   703 	}
   533 	if ( $wp_current_db_version < 6039 )
   704 
       
   705 	if ( $wp_current_db_version < 6039 ) {
   534 		upgrade_230_options_table();
   706 		upgrade_230_options_table();
       
   707 	}
   535 
   708 
   536 	populate_options();
   709 	populate_options();
   537 
   710 
   538 	if ( $wp_current_db_version < 2541 ) {
   711 	if ( $wp_current_db_version < 2541 ) {
   539 		upgrade_100();
   712 		upgrade_100();
   540 		upgrade_101();
   713 		upgrade_101();
   541 		upgrade_110();
   714 		upgrade_110();
   542 		upgrade_130();
   715 		upgrade_130();
   543 	}
   716 	}
   544 
   717 
   545 	if ( $wp_current_db_version < 3308 )
   718 	if ( $wp_current_db_version < 3308 ) {
   546 		upgrade_160();
   719 		upgrade_160();
   547 
   720 	}
   548 	if ( $wp_current_db_version < 4772 )
   721 
       
   722 	if ( $wp_current_db_version < 4772 ) {
   549 		upgrade_210();
   723 		upgrade_210();
   550 
   724 	}
   551 	if ( $wp_current_db_version < 4351 )
   725 
       
   726 	if ( $wp_current_db_version < 4351 ) {
   552 		upgrade_old_slugs();
   727 		upgrade_old_slugs();
   553 
   728 	}
   554 	if ( $wp_current_db_version < 5539 )
   729 
       
   730 	if ( $wp_current_db_version < 5539 ) {
   555 		upgrade_230();
   731 		upgrade_230();
   556 
   732 	}
   557 	if ( $wp_current_db_version < 6124 )
   733 
       
   734 	if ( $wp_current_db_version < 6124 ) {
   558 		upgrade_230_old_tables();
   735 		upgrade_230_old_tables();
   559 
   736 	}
   560 	if ( $wp_current_db_version < 7499 )
   737 
       
   738 	if ( $wp_current_db_version < 7499 ) {
   561 		upgrade_250();
   739 		upgrade_250();
   562 
   740 	}
   563 	if ( $wp_current_db_version < 7935 )
   741 
       
   742 	if ( $wp_current_db_version < 7935 ) {
   564 		upgrade_252();
   743 		upgrade_252();
   565 
   744 	}
   566 	if ( $wp_current_db_version < 8201 )
   745 
       
   746 	if ( $wp_current_db_version < 8201 ) {
   567 		upgrade_260();
   747 		upgrade_260();
   568 
   748 	}
   569 	if ( $wp_current_db_version < 8989 )
   749 
       
   750 	if ( $wp_current_db_version < 8989 ) {
   570 		upgrade_270();
   751 		upgrade_270();
   571 
   752 	}
   572 	if ( $wp_current_db_version < 10360 )
   753 
       
   754 	if ( $wp_current_db_version < 10360 ) {
   573 		upgrade_280();
   755 		upgrade_280();
   574 
   756 	}
   575 	if ( $wp_current_db_version < 11958 )
   757 
       
   758 	if ( $wp_current_db_version < 11958 ) {
   576 		upgrade_290();
   759 		upgrade_290();
   577 
   760 	}
   578 	if ( $wp_current_db_version < 15260 )
   761 
       
   762 	if ( $wp_current_db_version < 15260 ) {
   579 		upgrade_300();
   763 		upgrade_300();
   580 
   764 	}
   581 	if ( $wp_current_db_version < 19389 )
   765 
       
   766 	if ( $wp_current_db_version < 19389 ) {
   582 		upgrade_330();
   767 		upgrade_330();
   583 
   768 	}
   584 	if ( $wp_current_db_version < 20080 )
   769 
       
   770 	if ( $wp_current_db_version < 20080 ) {
   585 		upgrade_340();
   771 		upgrade_340();
   586 
   772 	}
   587 	if ( $wp_current_db_version < 22422 )
   773 
       
   774 	if ( $wp_current_db_version < 22422 ) {
   588 		upgrade_350();
   775 		upgrade_350();
   589 
   776 	}
   590 	if ( $wp_current_db_version < 25824 )
   777 
       
   778 	if ( $wp_current_db_version < 25824 ) {
   591 		upgrade_370();
   779 		upgrade_370();
   592 
   780 	}
   593 	if ( $wp_current_db_version < 26148 )
   781 
       
   782 	if ( $wp_current_db_version < 26148 ) {
   594 		upgrade_372();
   783 		upgrade_372();
   595 
   784 	}
   596 	if ( $wp_current_db_version < 26691 )
   785 
       
   786 	if ( $wp_current_db_version < 26691 ) {
   597 		upgrade_380();
   787 		upgrade_380();
   598 
   788 	}
   599 	if ( $wp_current_db_version < 29630 )
   789 
       
   790 	if ( $wp_current_db_version < 29630 ) {
   600 		upgrade_400();
   791 		upgrade_400();
   601 
   792 	}
   602 	if ( $wp_current_db_version < 33055 )
   793 
       
   794 	if ( $wp_current_db_version < 33055 ) {
   603 		upgrade_430();
   795 		upgrade_430();
   604 
   796 	}
   605 	if ( $wp_current_db_version < 33056 )
   797 
       
   798 	if ( $wp_current_db_version < 33056 ) {
   606 		upgrade_431();
   799 		upgrade_431();
   607 
   800 	}
   608 	if ( $wp_current_db_version < 35700 )
   801 
       
   802 	if ( $wp_current_db_version < 35700 ) {
   609 		upgrade_440();
   803 		upgrade_440();
   610 
   804 	}
   611 	if ( $wp_current_db_version < 36686 )
   805 
       
   806 	if ( $wp_current_db_version < 36686 ) {
   612 		upgrade_450();
   807 		upgrade_450();
   613 
   808 	}
   614 	if ( $wp_current_db_version < 37965 )
   809 
       
   810 	if ( $wp_current_db_version < 37965 ) {
   615 		upgrade_460();
   811 		upgrade_460();
       
   812 	}
       
   813 
       
   814 	if ( $wp_current_db_version < 44719 ) {
       
   815 		upgrade_510();
       
   816 	}
   616 
   817 
   617 	maybe_disable_link_manager();
   818 	maybe_disable_link_manager();
   618 
   819 
   619 	maybe_disable_automattic_widgets();
   820 	maybe_disable_automattic_widgets();
   620 
   821 
   632  */
   833  */
   633 function upgrade_100() {
   834 function upgrade_100() {
   634 	global $wpdb;
   835 	global $wpdb;
   635 
   836 
   636 	// Get the title and ID of every post, post_name to check if it already has a value
   837 	// Get the title and ID of every post, post_name to check if it already has a value
   637 	$posts = $wpdb->get_results("SELECT ID, post_title, post_name FROM $wpdb->posts WHERE post_name = ''");
   838 	$posts = $wpdb->get_results( "SELECT ID, post_title, post_name FROM $wpdb->posts WHERE post_name = ''" );
   638 	if ($posts) {
   839 	if ( $posts ) {
   639 		foreach ($posts as $post) {
   840 		foreach ( $posts as $post ) {
   640 			if ('' == $post->post_name) {
   841 			if ( '' == $post->post_name ) {
   641 				$newtitle = sanitize_title($post->post_title);
   842 				$newtitle = sanitize_title( $post->post_title );
   642 				$wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_name = %s WHERE ID = %d", $newtitle, $post->ID) );
   843 				$wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET post_name = %s WHERE ID = %d", $newtitle, $post->ID ) );
   643 			}
   844 			}
   644 		}
   845 		}
   645 	}
   846 	}
   646 
   847 
   647 	$categories = $wpdb->get_results("SELECT cat_ID, cat_name, category_nicename FROM $wpdb->categories");
   848 	$categories = $wpdb->get_results( "SELECT cat_ID, cat_name, category_nicename FROM $wpdb->categories" );
   648 	foreach ($categories as $category) {
   849 	foreach ( $categories as $category ) {
   649 		if ('' == $category->category_nicename) {
   850 		if ( '' == $category->category_nicename ) {
   650 			$newtitle = sanitize_title($category->cat_name);
   851 			$newtitle = sanitize_title( $category->cat_name );
   651 			$wpdb->update( $wpdb->categories, array('category_nicename' => $newtitle), array('cat_ID' => $category->cat_ID) );
   852 			$wpdb->update( $wpdb->categories, array( 'category_nicename' => $newtitle ), array( 'cat_ID' => $category->cat_ID ) );
   652 		}
   853 		}
   653 	}
   854 	}
   654 
   855 
   655 	$sql = "UPDATE $wpdb->options
   856 	$sql = "UPDATE $wpdb->options
   656 		SET option_value = REPLACE(option_value, 'wp-links/links-images/', 'wp-images/links/')
   857 		SET option_value = REPLACE(option_value, 'wp-links/links-images/', 'wp-images/links/')
   657 		WHERE option_name LIKE %s
   858 		WHERE option_name LIKE %s
   658 		AND option_value LIKE %s";
   859 		AND option_value LIKE %s";
   659 	$wpdb->query( $wpdb->prepare( $sql, $wpdb->esc_like( 'links_rating_image' ) . '%', $wpdb->esc_like( 'wp-links/links-images/' ) . '%' ) );
   860 	$wpdb->query( $wpdb->prepare( $sql, $wpdb->esc_like( 'links_rating_image' ) . '%', $wpdb->esc_like( 'wp-links/links-images/' ) . '%' ) );
   660 
   861 
   661 	$done_ids = $wpdb->get_results("SELECT DISTINCT post_id FROM $wpdb->post2cat");
   862 	$done_ids = $wpdb->get_results( "SELECT DISTINCT post_id FROM $wpdb->post2cat" );
   662 	if ($done_ids) :
   863 	if ( $done_ids ) :
   663 		$done_posts = array();
   864 		$done_posts = array();
   664 		foreach ($done_ids as $done_id) :
   865 		foreach ( $done_ids as $done_id ) :
   665 			$done_posts[] = $done_id->post_id;
   866 			$done_posts[] = $done_id->post_id;
   666 		endforeach;
   867 		endforeach;
   667 		$catwhere = ' AND ID NOT IN (' . implode(',', $done_posts) . ')';
   868 		$catwhere = ' AND ID NOT IN (' . implode( ',', $done_posts ) . ')';
   668 	else:
   869 	else :
   669 		$catwhere = '';
   870 		$catwhere = '';
   670 	endif;
   871 	endif;
   671 
   872 
   672 	$allposts = $wpdb->get_results("SELECT ID, post_category FROM $wpdb->posts WHERE post_category != '0' $catwhere");
   873 	$allposts = $wpdb->get_results( "SELECT ID, post_category FROM $wpdb->posts WHERE post_category != '0' $catwhere" );
   673 	if ($allposts) :
   874 	if ( $allposts ) :
   674 		foreach ($allposts as $post) {
   875 		foreach ( $allposts as $post ) {
   675 			// Check to see if it's already been imported
   876 			// Check to see if it's already been imported
   676 			$cat = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->post2cat WHERE post_id = %d AND category_id = %d", $post->ID, $post->post_category) );
   877 			$cat = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->post2cat WHERE post_id = %d AND category_id = %d", $post->ID, $post->post_category ) );
   677 			if (!$cat && 0 != $post->post_category) { // If there's no result
   878 			if ( ! $cat && 0 != $post->post_category ) { // If there's no result
   678 				$wpdb->insert( $wpdb->post2cat, array('post_id' => $post->ID, 'category_id' => $post->post_category) );
   879 				$wpdb->insert(
       
   880 					$wpdb->post2cat,
       
   881 					array(
       
   882 						'post_id'     => $post->ID,
       
   883 						'category_id' => $post->post_category,
       
   884 					)
       
   885 				);
   679 			}
   886 			}
   680 		}
   887 		}
   681 	endif;
   888 	endif;
   682 }
   889 }
   683 
   890 
   691  */
   898  */
   692 function upgrade_101() {
   899 function upgrade_101() {
   693 	global $wpdb;
   900 	global $wpdb;
   694 
   901 
   695 	// Clean up indices, add a few
   902 	// Clean up indices, add a few
   696 	add_clean_index($wpdb->posts, 'post_name');
   903 	add_clean_index( $wpdb->posts, 'post_name' );
   697 	add_clean_index($wpdb->posts, 'post_status');
   904 	add_clean_index( $wpdb->posts, 'post_status' );
   698 	add_clean_index($wpdb->categories, 'category_nicename');
   905 	add_clean_index( $wpdb->categories, 'category_nicename' );
   699 	add_clean_index($wpdb->comments, 'comment_approved');
   906 	add_clean_index( $wpdb->comments, 'comment_approved' );
   700 	add_clean_index($wpdb->comments, 'comment_post_ID');
   907 	add_clean_index( $wpdb->comments, 'comment_post_ID' );
   701 	add_clean_index($wpdb->links , 'link_category');
   908 	add_clean_index( $wpdb->links, 'link_category' );
   702 	add_clean_index($wpdb->links , 'link_visible');
   909 	add_clean_index( $wpdb->links, 'link_visible' );
   703 }
   910 }
   704 
   911 
   705 /**
   912 /**
   706  * Execute changes made in WordPress 1.2.
   913  * Execute changes made in WordPress 1.2.
   707  *
   914  *
   712  */
   919  */
   713 function upgrade_110() {
   920 function upgrade_110() {
   714 	global $wpdb;
   921 	global $wpdb;
   715 
   922 
   716 	// Set user_nicename.
   923 	// Set user_nicename.
   717 	$users = $wpdb->get_results("SELECT ID, user_nickname, user_nicename FROM $wpdb->users");
   924 	$users = $wpdb->get_results( "SELECT ID, user_nickname, user_nicename FROM $wpdb->users" );
   718 	foreach ($users as $user) {
   925 	foreach ( $users as $user ) {
   719 		if ('' == $user->user_nicename) {
   926 		if ( '' == $user->user_nicename ) {
   720 			$newname = sanitize_title($user->user_nickname);
   927 			$newname = sanitize_title( $user->user_nickname );
   721 			$wpdb->update( $wpdb->users, array('user_nicename' => $newname), array('ID' => $user->ID) );
   928 			$wpdb->update( $wpdb->users, array( 'user_nicename' => $newname ), array( 'ID' => $user->ID ) );
   722 		}
   929 		}
   723 	}
   930 	}
   724 
   931 
   725 	$users = $wpdb->get_results("SELECT ID, user_pass from $wpdb->users");
   932 	$users = $wpdb->get_results( "SELECT ID, user_pass from $wpdb->users" );
   726 	foreach ($users as $row) {
   933 	foreach ( $users as $row ) {
   727 		if (!preg_match('/^[A-Fa-f0-9]{32}$/', $row->user_pass)) {
   934 		if ( ! preg_match( '/^[A-Fa-f0-9]{32}$/', $row->user_pass ) ) {
   728 			$wpdb->update( $wpdb->users, array('user_pass' => md5($row->user_pass)), array('ID' => $row->ID) );
   935 			$wpdb->update( $wpdb->users, array( 'user_pass' => md5( $row->user_pass ) ), array( 'ID' => $row->ID ) );
   729 		}
   936 		}
   730 	}
   937 	}
   731 
   938 
   732 	// Get the GMT offset, we'll use that later on
   939 	// Get the GMT offset, we'll use that later on
   733 	$all_options = get_alloptions_110();
   940 	$all_options = get_alloptions_110();
   734 
   941 
   735 	$time_difference = $all_options->time_difference;
   942 	$time_difference = $all_options->time_difference;
   736 
   943 
   737 		$server_time = time()+date('Z');
   944 		$server_time = time() + date( 'Z' );
   738 	$weblogger_time = $server_time + $time_difference * HOUR_IN_SECONDS;
   945 	$weblogger_time  = $server_time + $time_difference * HOUR_IN_SECONDS;
   739 	$gmt_time = time();
   946 	$gmt_time        = time();
   740 
   947 
   741 	$diff_gmt_server = ($gmt_time - $server_time) / HOUR_IN_SECONDS;
   948 	$diff_gmt_server       = ( $gmt_time - $server_time ) / HOUR_IN_SECONDS;
   742 	$diff_weblogger_server = ($weblogger_time - $server_time) / HOUR_IN_SECONDS;
   949 	$diff_weblogger_server = ( $weblogger_time - $server_time ) / HOUR_IN_SECONDS;
   743 	$diff_gmt_weblogger = $diff_gmt_server - $diff_weblogger_server;
   950 	$diff_gmt_weblogger    = $diff_gmt_server - $diff_weblogger_server;
   744 	$gmt_offset = -$diff_gmt_weblogger;
   951 	$gmt_offset            = -$diff_gmt_weblogger;
   745 
   952 
   746 	// Add a gmt_offset option, with value $gmt_offset
   953 	// Add a gmt_offset option, with value $gmt_offset
   747 	add_option('gmt_offset', $gmt_offset);
   954 	add_option( 'gmt_offset', $gmt_offset );
   748 
   955 
   749 	// Check if we already set the GMT fields (if we did, then
   956 	// Check if we already set the GMT fields (if we did, then
   750 	// MAX(post_date_gmt) can't be '0000-00-00 00:00:00'
   957 	// MAX(post_date_gmt) can't be '0000-00-00 00:00:00'
   751 	// <michel_v> I just slapped myself silly for not thinking about it earlier
   958 	// <michel_v> I just slapped myself silly for not thinking about it earlier
   752 	$got_gmt_fields = ! ($wpdb->get_var("SELECT MAX(post_date_gmt) FROM $wpdb->posts") == '0000-00-00 00:00:00');
   959 	$got_gmt_fields = ! ( $wpdb->get_var( "SELECT MAX(post_date_gmt) FROM $wpdb->posts" ) == '0000-00-00 00:00:00' );
   753 
   960 
   754 	if (!$got_gmt_fields) {
   961 	if ( ! $got_gmt_fields ) {
   755 
   962 
   756 		// Add or subtract time to all dates, to get GMT dates
   963 		// Add or subtract time to all dates, to get GMT dates
   757 		$add_hours = intval($diff_gmt_weblogger);
   964 		$add_hours   = intval( $diff_gmt_weblogger );
   758 		$add_minutes = intval(60 * ($diff_gmt_weblogger - $add_hours));
   965 		$add_minutes = intval( 60 * ( $diff_gmt_weblogger - $add_hours ) );
   759 		$wpdb->query("UPDATE $wpdb->posts SET post_date_gmt = DATE_ADD(post_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
   966 		$wpdb->query( "UPDATE $wpdb->posts SET post_date_gmt = DATE_ADD(post_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)" );
   760 		$wpdb->query("UPDATE $wpdb->posts SET post_modified = post_date");
   967 		$wpdb->query( "UPDATE $wpdb->posts SET post_modified = post_date" );
   761 		$wpdb->query("UPDATE $wpdb->posts SET post_modified_gmt = DATE_ADD(post_modified, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE) WHERE post_modified != '0000-00-00 00:00:00'");
   968 		$wpdb->query( "UPDATE $wpdb->posts SET post_modified_gmt = DATE_ADD(post_modified, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE) WHERE post_modified != '0000-00-00 00:00:00'" );
   762 		$wpdb->query("UPDATE $wpdb->comments SET comment_date_gmt = DATE_ADD(comment_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
   969 		$wpdb->query( "UPDATE $wpdb->comments SET comment_date_gmt = DATE_ADD(comment_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)" );
   763 		$wpdb->query("UPDATE $wpdb->users SET user_registered = DATE_ADD(user_registered, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
   970 		$wpdb->query( "UPDATE $wpdb->users SET user_registered = DATE_ADD(user_registered, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)" );
   764 	}
   971 	}
   765 
   972 
   766 }
   973 }
   767 
   974 
   768 /**
   975 /**
   775  */
   982  */
   776 function upgrade_130() {
   983 function upgrade_130() {
   777 	global $wpdb;
   984 	global $wpdb;
   778 
   985 
   779 	// Remove extraneous backslashes.
   986 	// Remove extraneous backslashes.
   780 	$posts = $wpdb->get_results("SELECT ID, post_title, post_content, post_excerpt, guid, post_date, post_name, post_status, post_author FROM $wpdb->posts");
   987 	$posts = $wpdb->get_results( "SELECT ID, post_title, post_content, post_excerpt, guid, post_date, post_name, post_status, post_author FROM $wpdb->posts" );
   781 	if ($posts) {
   988 	if ( $posts ) {
   782 		foreach ($posts as $post) {
   989 		foreach ( $posts as $post ) {
   783 			$post_content = addslashes(deslash($post->post_content));
   990 			$post_content = addslashes( deslash( $post->post_content ) );
   784 			$post_title = addslashes(deslash($post->post_title));
   991 			$post_title   = addslashes( deslash( $post->post_title ) );
   785 			$post_excerpt = addslashes(deslash($post->post_excerpt));
   992 			$post_excerpt = addslashes( deslash( $post->post_excerpt ) );
   786 			if ( empty($post->guid) )
   993 			if ( empty( $post->guid ) ) {
   787 				$guid = get_permalink($post->ID);
   994 				$guid = get_permalink( $post->ID );
   788 			else
   995 			} else {
   789 				$guid = $post->guid;
   996 				$guid = $post->guid;
   790 
   997 			}
   791 			$wpdb->update( $wpdb->posts, compact('post_title', 'post_content', 'post_excerpt', 'guid'), array('ID' => $post->ID) );
   998 
       
   999 			$wpdb->update( $wpdb->posts, compact( 'post_title', 'post_content', 'post_excerpt', 'guid' ), array( 'ID' => $post->ID ) );
   792 
  1000 
   793 		}
  1001 		}
   794 	}
  1002 	}
   795 
  1003 
   796 	// Remove extraneous backslashes.
  1004 	// Remove extraneous backslashes.
   797 	$comments = $wpdb->get_results("SELECT comment_ID, comment_author, comment_content FROM $wpdb->comments");
  1005 	$comments = $wpdb->get_results( "SELECT comment_ID, comment_author, comment_content FROM $wpdb->comments" );
   798 	if ($comments) {
  1006 	if ( $comments ) {
   799 		foreach ($comments as $comment) {
  1007 		foreach ( $comments as $comment ) {
   800 			$comment_content = deslash($comment->comment_content);
  1008 			$comment_content = deslash( $comment->comment_content );
   801 			$comment_author = deslash($comment->comment_author);
  1009 			$comment_author  = deslash( $comment->comment_author );
   802 
  1010 
   803 			$wpdb->update($wpdb->comments, compact('comment_content', 'comment_author'), array('comment_ID' => $comment->comment_ID) );
  1011 			$wpdb->update( $wpdb->comments, compact( 'comment_content', 'comment_author' ), array( 'comment_ID' => $comment->comment_ID ) );
   804 		}
  1012 		}
   805 	}
  1013 	}
   806 
  1014 
   807 	// Remove extraneous backslashes.
  1015 	// Remove extraneous backslashes.
   808 	$links = $wpdb->get_results("SELECT link_id, link_name, link_description FROM $wpdb->links");
  1016 	$links = $wpdb->get_results( "SELECT link_id, link_name, link_description FROM $wpdb->links" );
   809 	if ($links) {
  1017 	if ( $links ) {
   810 		foreach ($links as $link) {
  1018 		foreach ( $links as $link ) {
   811 			$link_name = deslash($link->link_name);
  1019 			$link_name        = deslash( $link->link_name );
   812 			$link_description = deslash($link->link_description);
  1020 			$link_description = deslash( $link->link_description );
   813 
  1021 
   814 			$wpdb->update( $wpdb->links, compact('link_name', 'link_description'), array('link_id' => $link->link_id) );
  1022 			$wpdb->update( $wpdb->links, compact( 'link_name', 'link_description' ), array( 'link_id' => $link->link_id ) );
   815 		}
  1023 		}
   816 	}
  1024 	}
   817 
  1025 
   818 	$active_plugins = __get_option('active_plugins');
  1026 	$active_plugins = __get_option( 'active_plugins' );
   819 
  1027 
   820 	/*
  1028 	/*
   821 	 * If plugins are not stored in an array, they're stored in the old
  1029 	 * If plugins are not stored in an array, they're stored in the old
   822 	 * newline separated format. Convert to new format.
  1030 	 * newline separated format. Convert to new format.
   823 	 */
  1031 	 */
   824 	if ( !is_array( $active_plugins ) ) {
  1032 	if ( ! is_array( $active_plugins ) ) {
   825 		$active_plugins = explode("\n", trim($active_plugins));
  1033 		$active_plugins = explode( "\n", trim( $active_plugins ) );
   826 		update_option('active_plugins', $active_plugins);
  1034 		update_option( 'active_plugins', $active_plugins );
   827 	}
  1035 	}
   828 
  1036 
   829 	// Obsolete tables
  1037 	// Obsolete tables
   830 	$wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optionvalues');
  1038 	$wpdb->query( 'DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optionvalues' );
   831 	$wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiontypes');
  1039 	$wpdb->query( 'DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiontypes' );
   832 	$wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiongroups');
  1040 	$wpdb->query( 'DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiongroups' );
   833 	$wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiongroup_options');
  1041 	$wpdb->query( 'DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiongroup_options' );
   834 
  1042 
   835 	// Update comments table to use comment_type
  1043 	// Update comments table to use comment_type
   836 	$wpdb->query("UPDATE $wpdb->comments SET comment_type='trackback', comment_content = REPLACE(comment_content, '<trackback />', '') WHERE comment_content LIKE '<trackback />%'");
  1044 	$wpdb->query( "UPDATE $wpdb->comments SET comment_type='trackback', comment_content = REPLACE(comment_content, '<trackback />', '') WHERE comment_content LIKE '<trackback />%'" );
   837 	$wpdb->query("UPDATE $wpdb->comments SET comment_type='pingback', comment_content = REPLACE(comment_content, '<pingback />', '') WHERE comment_content LIKE '<pingback />%'");
  1045 	$wpdb->query( "UPDATE $wpdb->comments SET comment_type='pingback', comment_content = REPLACE(comment_content, '<pingback />', '') WHERE comment_content LIKE '<pingback />%'" );
   838 
  1046 
   839 	// Some versions have multiple duplicate option_name rows with the same values
  1047 	// Some versions have multiple duplicate option_name rows with the same values
   840 	$options = $wpdb->get_results("SELECT option_name, COUNT(option_name) AS dupes FROM `$wpdb->options` GROUP BY option_name");
  1048 	$options = $wpdb->get_results( "SELECT option_name, COUNT(option_name) AS dupes FROM `$wpdb->options` GROUP BY option_name" );
   841 	foreach ( $options as $option ) {
  1049 	foreach ( $options as $option ) {
   842 		if ( 1 != $option->dupes ) { // Could this be done in the query?
  1050 		if ( 1 != $option->dupes ) { // Could this be done in the query?
   843 			$limit = $option->dupes - 1;
  1051 			$limit    = $option->dupes - 1;
   844 			$dupe_ids = $wpdb->get_col( $wpdb->prepare("SELECT option_id FROM $wpdb->options WHERE option_name = %s LIMIT %d", $option->option_name, $limit) );
  1052 			$dupe_ids = $wpdb->get_col( $wpdb->prepare( "SELECT option_id FROM $wpdb->options WHERE option_name = %s LIMIT %d", $option->option_name, $limit ) );
   845 			if ( $dupe_ids ) {
  1053 			if ( $dupe_ids ) {
   846 				$dupe_ids = join($dupe_ids, ',');
  1054 				$dupe_ids = join( $dupe_ids, ',' );
   847 				$wpdb->query("DELETE FROM $wpdb->options WHERE option_id IN ($dupe_ids)");
  1055 				$wpdb->query( "DELETE FROM $wpdb->options WHERE option_id IN ($dupe_ids)" );
   848 			}
  1056 			}
   849 		}
  1057 		}
   850 	}
  1058 	}
   851 
  1059 
   852 	make_site_theme();
  1060 	make_site_theme();
   864 function upgrade_160() {
  1072 function upgrade_160() {
   865 	global $wpdb, $wp_current_db_version;
  1073 	global $wpdb, $wp_current_db_version;
   866 
  1074 
   867 	populate_roles_160();
  1075 	populate_roles_160();
   868 
  1076 
   869 	$users = $wpdb->get_results("SELECT * FROM $wpdb->users");
  1077 	$users = $wpdb->get_results( "SELECT * FROM $wpdb->users" );
   870 	foreach ( $users as $user ) :
  1078 	foreach ( $users as $user ) :
   871 		if ( !empty( $user->user_firstname ) )
  1079 		if ( ! empty( $user->user_firstname ) ) {
   872 			update_user_meta( $user->ID, 'first_name', wp_slash($user->user_firstname) );
  1080 			update_user_meta( $user->ID, 'first_name', wp_slash( $user->user_firstname ) );
   873 		if ( !empty( $user->user_lastname ) )
  1081 		}
   874 			update_user_meta( $user->ID, 'last_name', wp_slash($user->user_lastname) );
  1082 		if ( ! empty( $user->user_lastname ) ) {
   875 		if ( !empty( $user->user_nickname ) )
  1083 			update_user_meta( $user->ID, 'last_name', wp_slash( $user->user_lastname ) );
   876 			update_user_meta( $user->ID, 'nickname', wp_slash($user->user_nickname) );
  1084 		}
   877 		if ( !empty( $user->user_level ) )
  1085 		if ( ! empty( $user->user_nickname ) ) {
       
  1086 			update_user_meta( $user->ID, 'nickname', wp_slash( $user->user_nickname ) );
       
  1087 		}
       
  1088 		if ( ! empty( $user->user_level ) ) {
   878 			update_user_meta( $user->ID, $wpdb->prefix . 'user_level', $user->user_level );
  1089 			update_user_meta( $user->ID, $wpdb->prefix . 'user_level', $user->user_level );
   879 		if ( !empty( $user->user_icq ) )
  1090 		}
   880 			update_user_meta( $user->ID, 'icq', wp_slash($user->user_icq) );
  1091 		if ( ! empty( $user->user_icq ) ) {
   881 		if ( !empty( $user->user_aim ) )
  1092 			update_user_meta( $user->ID, 'icq', wp_slash( $user->user_icq ) );
   882 			update_user_meta( $user->ID, 'aim', wp_slash($user->user_aim) );
  1093 		}
   883 		if ( !empty( $user->user_msn ) )
  1094 		if ( ! empty( $user->user_aim ) ) {
   884 			update_user_meta( $user->ID, 'msn', wp_slash($user->user_msn) );
  1095 			update_user_meta( $user->ID, 'aim', wp_slash( $user->user_aim ) );
   885 		if ( !empty( $user->user_yim ) )
  1096 		}
   886 			update_user_meta( $user->ID, 'yim', wp_slash($user->user_icq) );
  1097 		if ( ! empty( $user->user_msn ) ) {
   887 		if ( !empty( $user->user_description ) )
  1098 			update_user_meta( $user->ID, 'msn', wp_slash( $user->user_msn ) );
   888 			update_user_meta( $user->ID, 'description', wp_slash($user->user_description) );
  1099 		}
   889 
  1100 		if ( ! empty( $user->user_yim ) ) {
   890 		if ( isset( $user->user_idmode ) ):
  1101 			update_user_meta( $user->ID, 'yim', wp_slash( $user->user_icq ) );
       
  1102 		}
       
  1103 		if ( ! empty( $user->user_description ) ) {
       
  1104 			update_user_meta( $user->ID, 'description', wp_slash( $user->user_description ) );
       
  1105 		}
       
  1106 
       
  1107 		if ( isset( $user->user_idmode ) ) :
   891 			$idmode = $user->user_idmode;
  1108 			$idmode = $user->user_idmode;
   892 			if ($idmode == 'nickname') $id = $user->user_nickname;
  1109 			if ( $idmode == 'nickname' ) {
   893 			if ($idmode == 'login') $id = $user->user_login;
  1110 				$id = $user->user_nickname;
   894 			if ($idmode == 'firstname') $id = $user->user_firstname;
  1111 			}
   895 			if ($idmode == 'lastname') $id = $user->user_lastname;
  1112 			if ( $idmode == 'login' ) {
   896 			if ($idmode == 'namefl') $id = $user->user_firstname.' '.$user->user_lastname;
  1113 				$id = $user->user_login;
   897 			if ($idmode == 'namelf') $id = $user->user_lastname.' '.$user->user_firstname;
  1114 			}
   898 			if (!$idmode) $id = $user->user_nickname;
  1115 			if ( $idmode == 'firstname' ) {
   899 			$wpdb->update( $wpdb->users, array('display_name' => $id), array('ID' => $user->ID) );
  1116 				$id = $user->user_firstname;
       
  1117 			}
       
  1118 			if ( $idmode == 'lastname' ) {
       
  1119 				$id = $user->user_lastname;
       
  1120 			}
       
  1121 			if ( $idmode == 'namefl' ) {
       
  1122 				$id = $user->user_firstname . ' ' . $user->user_lastname;
       
  1123 			}
       
  1124 			if ( $idmode == 'namelf' ) {
       
  1125 				$id = $user->user_lastname . ' ' . $user->user_firstname;
       
  1126 			}
       
  1127 			if ( ! $idmode ) {
       
  1128 				$id = $user->user_nickname;
       
  1129 			}
       
  1130 			$wpdb->update( $wpdb->users, array( 'display_name' => $id ), array( 'ID' => $user->ID ) );
   900 		endif;
  1131 		endif;
   901 
  1132 
   902 		// FIXME: RESET_CAPS is temporary code to reset roles and caps if flag is set.
  1133 		// FIXME: RESET_CAPS is temporary code to reset roles and caps if flag is set.
   903 		$caps = get_user_meta( $user->ID, $wpdb->prefix . 'capabilities');
  1134 		$caps = get_user_meta( $user->ID, $wpdb->prefix . 'capabilities' );
   904 		if ( empty($caps) || defined('RESET_CAPS') ) {
  1135 		if ( empty( $caps ) || defined( 'RESET_CAPS' ) ) {
   905 			$level = get_user_meta($user->ID, $wpdb->prefix . 'user_level', true);
  1136 			$level = get_user_meta( $user->ID, $wpdb->prefix . 'user_level', true );
   906 			$role = translate_level_to_role($level);
  1137 			$role  = translate_level_to_role( $level );
   907 			update_user_meta( $user->ID, $wpdb->prefix . 'capabilities', array($role => true) );
  1138 			update_user_meta( $user->ID, $wpdb->prefix . 'capabilities', array( $role => true ) );
   908 		}
  1139 		}
   909 
  1140 
   910 	endforeach;
  1141 	endforeach;
   911 	$old_user_fields = array( 'user_firstname', 'user_lastname', 'user_icq', 'user_aim', 'user_msn', 'user_yim', 'user_idmode', 'user_ip', 'user_domain', 'user_browser', 'user_description', 'user_nickname', 'user_level' );
  1142 	$old_user_fields = array( 'user_firstname', 'user_lastname', 'user_icq', 'user_aim', 'user_msn', 'user_yim', 'user_idmode', 'user_ip', 'user_domain', 'user_browser', 'user_description', 'user_nickname', 'user_level' );
   912 	$wpdb->hide_errors();
  1143 	$wpdb->hide_errors();
   913 	foreach ( $old_user_fields as $old )
  1144 	foreach ( $old_user_fields as $old ) {
   914 		$wpdb->query("ALTER TABLE $wpdb->users DROP $old");
  1145 		$wpdb->query( "ALTER TABLE $wpdb->users DROP $old" );
       
  1146 	}
   915 	$wpdb->show_errors();
  1147 	$wpdb->show_errors();
   916 
  1148 
   917 	// Populate comment_count field of posts table.
  1149 	// Populate comment_count field of posts table.
   918 	$comments = $wpdb->get_results( "SELECT comment_post_ID, COUNT(*) as c FROM $wpdb->comments WHERE comment_approved = '1' GROUP BY comment_post_ID" );
  1150 	$comments = $wpdb->get_results( "SELECT comment_post_ID, COUNT(*) as c FROM $wpdb->comments WHERE comment_approved = '1' GROUP BY comment_post_ID" );
   919 	if ( is_array( $comments ) )
  1151 	if ( is_array( $comments ) ) {
   920 		foreach ($comments as $comment)
  1152 		foreach ( $comments as $comment ) {
   921 			$wpdb->update( $wpdb->posts, array('comment_count' => $comment->c), array('ID' => $comment->comment_post_ID) );
  1153 			$wpdb->update( $wpdb->posts, array( 'comment_count' => $comment->c ), array( 'ID' => $comment->comment_post_ID ) );
       
  1154 		}
       
  1155 	}
   922 
  1156 
   923 	/*
  1157 	/*
   924 	 * Some alpha versions used a post status of object instead of attachment
  1158 	 * Some alpha versions used a post status of object instead of attachment
   925 	 * and put the mime type in post_type instead of post_mime_type.
  1159 	 * and put the mime type in post_type instead of post_mime_type.
   926 	 */
  1160 	 */
   927 	if ( $wp_current_db_version > 2541 && $wp_current_db_version <= 3091 ) {
  1161 	if ( $wp_current_db_version > 2541 && $wp_current_db_version <= 3091 ) {
   928 		$objects = $wpdb->get_results("SELECT ID, post_type FROM $wpdb->posts WHERE post_status = 'object'");
  1162 		$objects = $wpdb->get_results( "SELECT ID, post_type FROM $wpdb->posts WHERE post_status = 'object'" );
   929 		foreach ($objects as $object) {
  1163 		foreach ( $objects as $object ) {
   930 			$wpdb->update( $wpdb->posts, array(	'post_status' => 'attachment',
  1164 			$wpdb->update(
   931 												'post_mime_type' => $object->post_type,
  1165 				$wpdb->posts,
   932 												'post_type' => ''),
  1166 				array(
   933 										 array( 'ID' => $object->ID ) );
  1167 					'post_status'    => 'attachment',
   934 
  1168 					'post_mime_type' => $object->post_type,
   935 			$meta = get_post_meta($object->ID, 'imagedata', true);
  1169 					'post_type'      => '',
   936 			if ( ! empty($meta['file']) )
  1170 				),
       
  1171 				array( 'ID' => $object->ID )
       
  1172 			);
       
  1173 
       
  1174 			$meta = get_post_meta( $object->ID, 'imagedata', true );
       
  1175 			if ( ! empty( $meta['file'] ) ) {
   937 				update_attached_file( $object->ID, $meta['file'] );
  1176 				update_attached_file( $object->ID, $meta['file'] );
       
  1177 			}
   938 		}
  1178 		}
   939 	}
  1179 	}
   940 }
  1180 }
   941 
  1181 
   942 /**
  1182 /**
   951 function upgrade_210() {
  1191 function upgrade_210() {
   952 	global $wpdb, $wp_current_db_version;
  1192 	global $wpdb, $wp_current_db_version;
   953 
  1193 
   954 	if ( $wp_current_db_version < 3506 ) {
  1194 	if ( $wp_current_db_version < 3506 ) {
   955 		// Update status and type.
  1195 		// Update status and type.
   956 		$posts = $wpdb->get_results("SELECT ID, post_status FROM $wpdb->posts");
  1196 		$posts = $wpdb->get_results( "SELECT ID, post_status FROM $wpdb->posts" );
   957 
  1197 
   958 		if ( ! empty($posts) ) foreach ($posts as $post) {
  1198 		if ( ! empty( $posts ) ) {
   959 			$status = $post->post_status;
  1199 			foreach ( $posts as $post ) {
   960 			$type = 'post';
  1200 				$status = $post->post_status;
   961 
  1201 				$type   = 'post';
   962 			if ( 'static' == $status ) {
  1202 
   963 				$status = 'publish';
  1203 				if ( 'static' == $status ) {
   964 				$type = 'page';
  1204 					$status = 'publish';
   965 			} elseif ( 'attachment' == $status ) {
  1205 					$type   = 'page';
   966 				$status = 'inherit';
  1206 				} elseif ( 'attachment' == $status ) {
   967 				$type = 'attachment';
  1207 					$status = 'inherit';
   968 			}
  1208 					$type   = 'attachment';
   969 
  1209 				}
   970 			$wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_status = %s, post_type = %s WHERE ID = %d", $status, $type, $post->ID) );
  1210 
       
  1211 				$wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET post_status = %s, post_type = %s WHERE ID = %d", $status, $type, $post->ID ) );
       
  1212 			}
   971 		}
  1213 		}
   972 	}
  1214 	}
   973 
  1215 
   974 	if ( $wp_current_db_version < 3845 ) {
  1216 	if ( $wp_current_db_version < 3845 ) {
   975 		populate_roles_210();
  1217 		populate_roles_210();
   976 	}
  1218 	}
   977 
  1219 
   978 	if ( $wp_current_db_version < 3531 ) {
  1220 	if ( $wp_current_db_version < 3531 ) {
   979 		// Give future posts a post_status of future.
  1221 		// Give future posts a post_status of future.
   980 		$now = gmdate('Y-m-d H:i:59');
  1222 		$now = gmdate( 'Y-m-d H:i:59' );
   981 		$wpdb->query ("UPDATE $wpdb->posts SET post_status = 'future' WHERE post_status = 'publish' AND post_date_gmt > '$now'");
  1223 		$wpdb->query( "UPDATE $wpdb->posts SET post_status = 'future' WHERE post_status = 'publish' AND post_date_gmt > '$now'" );
   982 
  1224 
   983 		$posts = $wpdb->get_results("SELECT ID, post_date FROM $wpdb->posts WHERE post_status ='future'");
  1225 		$posts = $wpdb->get_results( "SELECT ID, post_date FROM $wpdb->posts WHERE post_status ='future'" );
   984 		if ( !empty($posts) )
  1226 		if ( ! empty( $posts ) ) {
   985 			foreach ( $posts as $post )
  1227 			foreach ( $posts as $post ) {
   986 				wp_schedule_single_event(mysql2date('U', $post->post_date, false), 'publish_future_post', array($post->ID));
  1228 				wp_schedule_single_event( mysql2date( 'U', $post->post_date, false ), 'publish_future_post', array( $post->ID ) );
       
  1229 			}
       
  1230 		}
   987 	}
  1231 	}
   988 }
  1232 }
   989 
  1233 
   990 /**
  1234 /**
   991  * Execute changes made in WordPress 2.3.
  1235  * Execute changes made in WordPress 2.3.
  1002 	if ( $wp_current_db_version < 5200 ) {
  1246 	if ( $wp_current_db_version < 5200 ) {
  1003 		populate_roles_230();
  1247 		populate_roles_230();
  1004 	}
  1248 	}
  1005 
  1249 
  1006 	// Convert categories to terms.
  1250 	// Convert categories to terms.
  1007 	$tt_ids = array();
  1251 	$tt_ids     = array();
  1008 	$have_tags = false;
  1252 	$have_tags  = false;
  1009 	$categories = $wpdb->get_results("SELECT * FROM $wpdb->categories ORDER BY cat_ID");
  1253 	$categories = $wpdb->get_results( "SELECT * FROM $wpdb->categories ORDER BY cat_ID" );
  1010 	foreach ($categories as $category) {
  1254 	foreach ( $categories as $category ) {
  1011 		$term_id = (int) $category->cat_ID;
  1255 		$term_id     = (int) $category->cat_ID;
  1012 		$name = $category->cat_name;
  1256 		$name        = $category->cat_name;
  1013 		$description = $category->category_description;
  1257 		$description = $category->category_description;
  1014 		$slug = $category->category_nicename;
  1258 		$slug        = $category->category_nicename;
  1015 		$parent = $category->category_parent;
  1259 		$parent      = $category->category_parent;
  1016 		$term_group = 0;
  1260 		$term_group  = 0;
  1017 
  1261 
  1018 		// Associate terms with the same slug in a term group and make slugs unique.
  1262 		// Associate terms with the same slug in a term group and make slugs unique.
  1019 		if ( $exists = $wpdb->get_results( $wpdb->prepare("SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $slug) ) ) {
  1263 		if ( $exists = $wpdb->get_results( $wpdb->prepare( "SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $slug ) ) ) {
  1020 			$term_group = $exists[0]->term_group;
  1264 			$term_group = $exists[0]->term_group;
  1021 			$id = $exists[0]->term_id;
  1265 			$id         = $exists[0]->term_id;
  1022 			$num = 2;
  1266 			$num        = 2;
  1023 			do {
  1267 			do {
  1024 				$alt_slug = $slug . "-$num";
  1268 				$alt_slug = $slug . "-$num";
  1025 				$num++;
  1269 				$num++;
  1026 				$slug_check = $wpdb->get_var( $wpdb->prepare("SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug) );
  1270 				$slug_check = $wpdb->get_var( $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug ) );
  1027 			} while ( $slug_check );
  1271 			} while ( $slug_check );
  1028 
  1272 
  1029 			$slug = $alt_slug;
  1273 			$slug = $alt_slug;
  1030 
  1274 
  1031 			if ( empty( $term_group ) ) {
  1275 			if ( empty( $term_group ) ) {
  1032 				$term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms GROUP BY term_group") + 1;
  1276 				$term_group = $wpdb->get_var( "SELECT MAX(term_group) FROM $wpdb->terms GROUP BY term_group" ) + 1;
  1033 				$wpdb->query( $wpdb->prepare("UPDATE $wpdb->terms SET term_group = %d WHERE term_id = %d", $term_group, $id) );
  1277 				$wpdb->query( $wpdb->prepare( "UPDATE $wpdb->terms SET term_group = %d WHERE term_id = %d", $term_group, $id ) );
  1034 			}
  1278 			}
  1035 		}
  1279 		}
  1036 
  1280 
  1037 		$wpdb->query( $wpdb->prepare("INSERT INTO $wpdb->terms (term_id, name, slug, term_group) VALUES
  1281 		$wpdb->query(
  1038 		(%d, %s, %s, %d)", $term_id, $name, $slug, $term_group) );
  1282 			$wpdb->prepare(
       
  1283 				"INSERT INTO $wpdb->terms (term_id, name, slug, term_group) VALUES
       
  1284 		(%d, %s, %s, %d)",
       
  1285 				$term_id,
       
  1286 				$name,
       
  1287 				$slug,
       
  1288 				$term_group
       
  1289 			)
       
  1290 		);
  1039 
  1291 
  1040 		$count = 0;
  1292 		$count = 0;
  1041 		if ( !empty($category->category_count) ) {
  1293 		if ( ! empty( $category->category_count ) ) {
  1042 			$count = (int) $category->category_count;
  1294 			$count    = (int) $category->category_count;
  1043 			$taxonomy = 'category';
  1295 			$taxonomy = 'category';
  1044 			$wpdb->query( $wpdb->prepare("INSERT INTO $wpdb->term_taxonomy (term_id, taxonomy, description, parent, count) VALUES ( %d, %s, %s, %d, %d)", $term_id, $taxonomy, $description, $parent, $count) );
  1296 			$wpdb->query( $wpdb->prepare( "INSERT INTO $wpdb->term_taxonomy (term_id, taxonomy, description, parent, count) VALUES ( %d, %s, %s, %d, %d)", $term_id, $taxonomy, $description, $parent, $count ) );
  1045 			$tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
  1297 			$tt_ids[ $term_id ][ $taxonomy ] = (int) $wpdb->insert_id;
  1046 		}
  1298 		}
  1047 
  1299 
  1048 		if ( !empty($category->link_count) ) {
  1300 		if ( ! empty( $category->link_count ) ) {
  1049 			$count = (int) $category->link_count;
  1301 			$count    = (int) $category->link_count;
  1050 			$taxonomy = 'link_category';
  1302 			$taxonomy = 'link_category';
  1051 			$wpdb->query( $wpdb->prepare("INSERT INTO $wpdb->term_taxonomy (term_id, taxonomy, description, parent, count) VALUES ( %d, %s, %s, %d, %d)", $term_id, $taxonomy, $description, $parent, $count) );
  1303 			$wpdb->query( $wpdb->prepare( "INSERT INTO $wpdb->term_taxonomy (term_id, taxonomy, description, parent, count) VALUES ( %d, %s, %s, %d, %d)", $term_id, $taxonomy, $description, $parent, $count ) );
  1052 			$tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
  1304 			$tt_ids[ $term_id ][ $taxonomy ] = (int) $wpdb->insert_id;
  1053 		}
  1305 		}
  1054 
  1306 
  1055 		if ( !empty($category->tag_count) ) {
  1307 		if ( ! empty( $category->tag_count ) ) {
  1056 			$have_tags = true;
  1308 			$have_tags = true;
  1057 			$count = (int) $category->tag_count;
  1309 			$count     = (int) $category->tag_count;
  1058 			$taxonomy = 'post_tag';
  1310 			$taxonomy  = 'post_tag';
  1059 			$wpdb->insert( $wpdb->term_taxonomy, compact('term_id', 'taxonomy', 'description', 'parent', 'count') );
  1311 			$wpdb->insert( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent', 'count' ) );
  1060 			$tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
  1312 			$tt_ids[ $term_id ][ $taxonomy ] = (int) $wpdb->insert_id;
  1061 		}
  1313 		}
  1062 
  1314 
  1063 		if ( empty($count) ) {
  1315 		if ( empty( $count ) ) {
  1064 			$count = 0;
  1316 			$count    = 0;
  1065 			$taxonomy = 'category';
  1317 			$taxonomy = 'category';
  1066 			$wpdb->insert( $wpdb->term_taxonomy, compact('term_id', 'taxonomy', 'description', 'parent', 'count') );
  1318 			$wpdb->insert( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent', 'count' ) );
  1067 			$tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
  1319 			$tt_ids[ $term_id ][ $taxonomy ] = (int) $wpdb->insert_id;
  1068 		}
  1320 		}
  1069 	}
  1321 	}
  1070 
  1322 
  1071 	$select = 'post_id, category_id';
  1323 	$select = 'post_id, category_id';
  1072 	if ( $have_tags )
  1324 	if ( $have_tags ) {
  1073 		$select .= ', rel_type';
  1325 		$select .= ', rel_type';
  1074 
  1326 	}
  1075 	$posts = $wpdb->get_results("SELECT $select FROM $wpdb->post2cat GROUP BY post_id, category_id");
  1327 
       
  1328 	$posts = $wpdb->get_results( "SELECT $select FROM $wpdb->post2cat GROUP BY post_id, category_id" );
  1076 	foreach ( $posts as $post ) {
  1329 	foreach ( $posts as $post ) {
  1077 		$post_id = (int) $post->post_id;
  1330 		$post_id  = (int) $post->post_id;
  1078 		$term_id = (int) $post->category_id;
  1331 		$term_id  = (int) $post->category_id;
  1079 		$taxonomy = 'category';
  1332 		$taxonomy = 'category';
  1080 		if ( !empty($post->rel_type) && 'tag' == $post->rel_type)
  1333 		if ( ! empty( $post->rel_type ) && 'tag' == $post->rel_type ) {
  1081 			$taxonomy = 'tag';
  1334 			$taxonomy = 'tag';
  1082 		$tt_id = $tt_ids[$term_id][$taxonomy];
  1335 		}
  1083 		if ( empty($tt_id) )
  1336 		$tt_id = $tt_ids[ $term_id ][ $taxonomy ];
       
  1337 		if ( empty( $tt_id ) ) {
  1084 			continue;
  1338 			continue;
  1085 
  1339 		}
  1086 		$wpdb->insert( $wpdb->term_relationships, array('object_id' => $post_id, 'term_taxonomy_id' => $tt_id) );
  1340 
       
  1341 		$wpdb->insert(
       
  1342 			$wpdb->term_relationships,
       
  1343 			array(
       
  1344 				'object_id'        => $post_id,
       
  1345 				'term_taxonomy_id' => $tt_id,
       
  1346 			)
       
  1347 		);
  1087 	}
  1348 	}
  1088 
  1349 
  1089 	// < 3570 we used linkcategories. >= 3570 we used categories and link2cat.
  1350 	// < 3570 we used linkcategories. >= 3570 we used categories and link2cat.
  1090 	if ( $wp_current_db_version < 3570 ) {
  1351 	if ( $wp_current_db_version < 3570 ) {
  1091 		/*
  1352 		/*
  1092 		 * Create link_category terms for link categories. Create a map of link
  1353 		 * Create link_category terms for link categories. Create a map of link
  1093 		 * cat IDs to link_category terms.
  1354 		 * cat IDs to link_category terms.
  1094 		 */
  1355 		 */
  1095 		$link_cat_id_map = array();
  1356 		$link_cat_id_map  = array();
  1096 		$default_link_cat = 0;
  1357 		$default_link_cat = 0;
  1097 		$tt_ids = array();
  1358 		$tt_ids           = array();
  1098 		$link_cats = $wpdb->get_results("SELECT cat_id, cat_name FROM " . $wpdb->prefix . 'linkcategories');
  1359 		$link_cats        = $wpdb->get_results( 'SELECT cat_id, cat_name FROM ' . $wpdb->prefix . 'linkcategories' );
  1099 		foreach ( $link_cats as $category) {
  1360 		foreach ( $link_cats as $category ) {
  1100 			$cat_id = (int) $category->cat_id;
  1361 			$cat_id     = (int) $category->cat_id;
  1101 			$term_id = 0;
  1362 			$term_id    = 0;
  1102 			$name = wp_slash($category->cat_name);
  1363 			$name       = wp_slash( $category->cat_name );
  1103 			$slug = sanitize_title($name);
  1364 			$slug       = sanitize_title( $name );
  1104 			$term_group = 0;
  1365 			$term_group = 0;
  1105 
  1366 
  1106 			// Associate terms with the same slug in a term group and make slugs unique.
  1367 			// Associate terms with the same slug in a term group and make slugs unique.
  1107 			if ( $exists = $wpdb->get_results( $wpdb->prepare("SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $slug) ) ) {
  1368 			if ( $exists = $wpdb->get_results( $wpdb->prepare( "SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $slug ) ) ) {
  1108 				$term_group = $exists[0]->term_group;
  1369 				$term_group = $exists[0]->term_group;
  1109 				$term_id = $exists[0]->term_id;
  1370 				$term_id    = $exists[0]->term_id;
  1110 			}
  1371 			}
  1111 
  1372 
  1112 			if ( empty($term_id) ) {
  1373 			if ( empty( $term_id ) ) {
  1113 				$wpdb->insert( $wpdb->terms, compact('name', 'slug', 'term_group') );
  1374 				$wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) );
  1114 				$term_id = (int) $wpdb->insert_id;
  1375 				$term_id = (int) $wpdb->insert_id;
  1115 			}
  1376 			}
  1116 
  1377 
  1117 			$link_cat_id_map[$cat_id] = $term_id;
  1378 			$link_cat_id_map[ $cat_id ] = $term_id;
  1118 			$default_link_cat = $term_id;
  1379 			$default_link_cat           = $term_id;
  1119 
  1380 
  1120 			$wpdb->insert( $wpdb->term_taxonomy, array('term_id' => $term_id, 'taxonomy' => 'link_category', 'description' => '', 'parent' => 0, 'count' => 0) );
  1381 			$wpdb->insert(
  1121 			$tt_ids[$term_id] = (int) $wpdb->insert_id;
  1382 				$wpdb->term_taxonomy,
       
  1383 				array(
       
  1384 					'term_id'     => $term_id,
       
  1385 					'taxonomy'    => 'link_category',
       
  1386 					'description' => '',
       
  1387 					'parent'      => 0,
       
  1388 					'count'       => 0,
       
  1389 				)
       
  1390 			);
       
  1391 			$tt_ids[ $term_id ] = (int) $wpdb->insert_id;
  1122 		}
  1392 		}
  1123 
  1393 
  1124 		// Associate links to cats.
  1394 		// Associate links to cats.
  1125 		$links = $wpdb->get_results("SELECT link_id, link_category FROM $wpdb->links");
  1395 		$links = $wpdb->get_results( "SELECT link_id, link_category FROM $wpdb->links" );
  1126 		if ( !empty($links) ) foreach ( $links as $link ) {
  1396 		if ( ! empty( $links ) ) {
  1127 			if ( 0 == $link->link_category )
  1397 			foreach ( $links as $link ) {
       
  1398 				if ( 0 == $link->link_category ) {
       
  1399 					continue;
       
  1400 				}
       
  1401 				if ( ! isset( $link_cat_id_map[ $link->link_category ] ) ) {
       
  1402 					continue;
       
  1403 				}
       
  1404 				$term_id = $link_cat_id_map[ $link->link_category ];
       
  1405 				$tt_id   = $tt_ids[ $term_id ];
       
  1406 				if ( empty( $tt_id ) ) {
       
  1407 					continue;
       
  1408 				}
       
  1409 
       
  1410 				$wpdb->insert(
       
  1411 					$wpdb->term_relationships,
       
  1412 					array(
       
  1413 						'object_id'        => $link->link_id,
       
  1414 						'term_taxonomy_id' => $tt_id,
       
  1415 					)
       
  1416 				);
       
  1417 			}
       
  1418 		}
       
  1419 
       
  1420 		// Set default to the last category we grabbed during the upgrade loop.
       
  1421 		update_option( 'default_link_category', $default_link_cat );
       
  1422 	} else {
       
  1423 		$links = $wpdb->get_results( "SELECT link_id, category_id FROM $wpdb->link2cat GROUP BY link_id, category_id" );
       
  1424 		foreach ( $links as $link ) {
       
  1425 			$link_id  = (int) $link->link_id;
       
  1426 			$term_id  = (int) $link->category_id;
       
  1427 			$taxonomy = 'link_category';
       
  1428 			$tt_id    = $tt_ids[ $term_id ][ $taxonomy ];
       
  1429 			if ( empty( $tt_id ) ) {
  1128 				continue;
  1430 				continue;
  1129 			if ( ! isset($link_cat_id_map[$link->link_category]) )
  1431 			}
  1130 				continue;
  1432 			$wpdb->insert(
  1131 			$term_id = $link_cat_id_map[$link->link_category];
  1433 				$wpdb->term_relationships,
  1132 			$tt_id = $tt_ids[$term_id];
  1434 				array(
  1133 			if ( empty($tt_id) )
  1435 					'object_id'        => $link_id,
  1134 				continue;
  1436 					'term_taxonomy_id' => $tt_id,
  1135 
  1437 				)
  1136 			$wpdb->insert( $wpdb->term_relationships, array('object_id' => $link->link_id, 'term_taxonomy_id' => $tt_id) );
  1438 			);
  1137 		}
       
  1138 
       
  1139 		// Set default to the last category we grabbed during the upgrade loop.
       
  1140 		update_option('default_link_category', $default_link_cat);
       
  1141 	} else {
       
  1142 		$links = $wpdb->get_results("SELECT link_id, category_id FROM $wpdb->link2cat GROUP BY link_id, category_id");
       
  1143 		foreach ( $links as $link ) {
       
  1144 			$link_id = (int) $link->link_id;
       
  1145 			$term_id = (int) $link->category_id;
       
  1146 			$taxonomy = 'link_category';
       
  1147 			$tt_id = $tt_ids[$term_id][$taxonomy];
       
  1148 			if ( empty($tt_id) )
       
  1149 				continue;
       
  1150 			$wpdb->insert( $wpdb->term_relationships, array('object_id' => $link_id, 'term_taxonomy_id' => $tt_id) );
       
  1151 		}
  1439 		}
  1152 	}
  1440 	}
  1153 
  1441 
  1154 	if ( $wp_current_db_version < 4772 ) {
  1442 	if ( $wp_current_db_version < 4772 ) {
  1155 		// Obsolete linkcategories table
  1443 		// Obsolete linkcategories table
  1156 		$wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'linkcategories');
  1444 		$wpdb->query( 'DROP TABLE IF EXISTS ' . $wpdb->prefix . 'linkcategories' );
  1157 	}
  1445 	}
  1158 
  1446 
  1159 	// Recalculate all counts
  1447 	// Recalculate all counts
  1160 	$terms = $wpdb->get_results("SELECT term_taxonomy_id, taxonomy FROM $wpdb->term_taxonomy");
  1448 	$terms = $wpdb->get_results( "SELECT term_taxonomy_id, taxonomy FROM $wpdb->term_taxonomy" );
  1161 	foreach ( (array) $terms as $term ) {
  1449 	foreach ( (array) $terms as $term ) {
  1162 		if ( ('post_tag' == $term->taxonomy) || ('category' == $term->taxonomy) )
  1450 		if ( ( 'post_tag' == $term->taxonomy ) || ( 'category' == $term->taxonomy ) ) {
  1163 			$count = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->term_relationships, $wpdb->posts WHERE $wpdb->posts.ID = $wpdb->term_relationships.object_id AND post_status = 'publish' AND post_type = 'post' AND term_taxonomy_id = %d", $term->term_taxonomy_id) );
  1451 			$count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships, $wpdb->posts WHERE $wpdb->posts.ID = $wpdb->term_relationships.object_id AND post_status = 'publish' AND post_type = 'post' AND term_taxonomy_id = %d", $term->term_taxonomy_id ) );
  1164 		else
  1452 		} else {
  1165 			$count = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term->term_taxonomy_id) );
  1453 			$count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term->term_taxonomy_id ) );
  1166 		$wpdb->update( $wpdb->term_taxonomy, array('count' => $count), array('term_taxonomy_id' => $term->term_taxonomy_id) );
  1454 		}
       
  1455 		$wpdb->update( $wpdb->term_taxonomy, array( 'count' => $count ), array( 'term_taxonomy_id' => $term->term_taxonomy_id ) );
  1167 	}
  1456 	}
  1168 }
  1457 }
  1169 
  1458 
  1170 /**
  1459 /**
  1171  * Remove old options from the database.
  1460  * Remove old options from the database.
  1177  */
  1466  */
  1178 function upgrade_230_options_table() {
  1467 function upgrade_230_options_table() {
  1179 	global $wpdb;
  1468 	global $wpdb;
  1180 	$old_options_fields = array( 'option_can_override', 'option_type', 'option_width', 'option_height', 'option_description', 'option_admin_level' );
  1469 	$old_options_fields = array( 'option_can_override', 'option_type', 'option_width', 'option_height', 'option_description', 'option_admin_level' );
  1181 	$wpdb->hide_errors();
  1470 	$wpdb->hide_errors();
  1182 	foreach ( $old_options_fields as $old )
  1471 	foreach ( $old_options_fields as $old ) {
  1183 		$wpdb->query("ALTER TABLE $wpdb->options DROP $old");
  1472 		$wpdb->query( "ALTER TABLE $wpdb->options DROP $old" );
       
  1473 	}
  1184 	$wpdb->show_errors();
  1474 	$wpdb->show_errors();
  1185 }
  1475 }
  1186 
  1476 
  1187 /**
  1477 /**
  1188  * Remove old categories, link2cat, and post2cat database tables.
  1478  * Remove old categories, link2cat, and post2cat database tables.
  1192  *
  1482  *
  1193  * @global wpdb $wpdb WordPress database abstraction object.
  1483  * @global wpdb $wpdb WordPress database abstraction object.
  1194  */
  1484  */
  1195 function upgrade_230_old_tables() {
  1485 function upgrade_230_old_tables() {
  1196 	global $wpdb;
  1486 	global $wpdb;
  1197 	$wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'categories');
  1487 	$wpdb->query( 'DROP TABLE IF EXISTS ' . $wpdb->prefix . 'categories' );
  1198 	$wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'link2cat');
  1488 	$wpdb->query( 'DROP TABLE IF EXISTS ' . $wpdb->prefix . 'link2cat' );
  1199 	$wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'post2cat');
  1489 	$wpdb->query( 'DROP TABLE IF EXISTS ' . $wpdb->prefix . 'post2cat' );
  1200 }
  1490 }
  1201 
  1491 
  1202 /**
  1492 /**
  1203  * Upgrade old slugs made in version 2.2.
  1493  * Upgrade old slugs made in version 2.2.
  1204  *
  1494  *
  1208  * @global wpdb $wpdb WordPress database abstraction object.
  1498  * @global wpdb $wpdb WordPress database abstraction object.
  1209  */
  1499  */
  1210 function upgrade_old_slugs() {
  1500 function upgrade_old_slugs() {
  1211 	// Upgrade people who were using the Redirect Old Slugs plugin.
  1501 	// Upgrade people who were using the Redirect Old Slugs plugin.
  1212 	global $wpdb;
  1502 	global $wpdb;
  1213 	$wpdb->query("UPDATE $wpdb->postmeta SET meta_key = '_wp_old_slug' WHERE meta_key = 'old_slug'");
  1503 	$wpdb->query( "UPDATE $wpdb->postmeta SET meta_key = '_wp_old_slug' WHERE meta_key = 'old_slug'" );
  1214 }
  1504 }
  1215 
  1505 
  1216 /**
  1506 /**
  1217  * Execute changes made in WordPress 2.5.0.
  1507  * Execute changes made in WordPress 2.5.0.
  1218  *
  1508  *
  1239  * @global wpdb $wpdb WordPress database abstraction object.
  1529  * @global wpdb $wpdb WordPress database abstraction object.
  1240  */
  1530  */
  1241 function upgrade_252() {
  1531 function upgrade_252() {
  1242 	global $wpdb;
  1532 	global $wpdb;
  1243 
  1533 
  1244 	$wpdb->query("UPDATE $wpdb->users SET user_activation_key = ''");
  1534 	$wpdb->query( "UPDATE $wpdb->users SET user_activation_key = ''" );
  1245 }
  1535 }
  1246 
  1536 
  1247 /**
  1537 /**
  1248  * Execute changes made in WordPress 2.6.
  1538  * Execute changes made in WordPress 2.6.
  1249  *
  1539  *
  1253  * @global int $wp_current_db_version
  1543  * @global int $wp_current_db_version
  1254  */
  1544  */
  1255 function upgrade_260() {
  1545 function upgrade_260() {
  1256 	global $wp_current_db_version;
  1546 	global $wp_current_db_version;
  1257 
  1547 
  1258 	if ( $wp_current_db_version < 8000 )
  1548 	if ( $wp_current_db_version < 8000 ) {
  1259 		populate_roles_260();
  1549 		populate_roles_260();
       
  1550 	}
  1260 }
  1551 }
  1261 
  1552 
  1262 /**
  1553 /**
  1263  * Execute changes made in WordPress 2.7.
  1554  * Execute changes made in WordPress 2.7.
  1264  *
  1555  *
  1269  * @global int  $wp_current_db_version
  1560  * @global int  $wp_current_db_version
  1270  */
  1561  */
  1271 function upgrade_270() {
  1562 function upgrade_270() {
  1272 	global $wpdb, $wp_current_db_version;
  1563 	global $wpdb, $wp_current_db_version;
  1273 
  1564 
  1274 	if ( $wp_current_db_version < 8980 )
  1565 	if ( $wp_current_db_version < 8980 ) {
  1275 		populate_roles_270();
  1566 		populate_roles_270();
       
  1567 	}
  1276 
  1568 
  1277 	// Update post_date for unpublished posts with empty timestamp
  1569 	// Update post_date for unpublished posts with empty timestamp
  1278 	if ( $wp_current_db_version < 8921 )
  1570 	if ( $wp_current_db_version < 8921 ) {
  1279 		$wpdb->query( "UPDATE $wpdb->posts SET post_date = post_modified WHERE post_date = '0000-00-00 00:00:00'" );
  1571 		$wpdb->query( "UPDATE $wpdb->posts SET post_date = post_modified WHERE post_date = '0000-00-00 00:00:00'" );
       
  1572 	}
  1280 }
  1573 }
  1281 
  1574 
  1282 /**
  1575 /**
  1283  * Execute changes made in WordPress 2.8.
  1576  * Execute changes made in WordPress 2.8.
  1284  *
  1577  *
  1289  * @global wpdb $wpdb WordPress database abstraction object.
  1582  * @global wpdb $wpdb WordPress database abstraction object.
  1290  */
  1583  */
  1291 function upgrade_280() {
  1584 function upgrade_280() {
  1292 	global $wp_current_db_version, $wpdb;
  1585 	global $wp_current_db_version, $wpdb;
  1293 
  1586 
  1294 	if ( $wp_current_db_version < 10360 )
  1587 	if ( $wp_current_db_version < 10360 ) {
  1295 		populate_roles_280();
  1588 		populate_roles_280();
       
  1589 	}
  1296 	if ( is_multisite() ) {
  1590 	if ( is_multisite() ) {
  1297 		$start = 0;
  1591 		$start = 0;
  1298 		while( $rows = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options ORDER BY option_id LIMIT $start, 20" ) ) {
  1592 		while ( $rows = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options ORDER BY option_id LIMIT $start, 20" ) ) {
  1299 			foreach ( $rows as $row ) {
  1593 			foreach ( $rows as $row ) {
  1300 				$value = $row->option_value;
  1594 				$value = $row->option_value;
  1301 				if ( !@unserialize( $value ) )
  1595 				if ( ! @unserialize( $value ) ) {
  1302 					$value = stripslashes( $value );
  1596 					$value = stripslashes( $value );
       
  1597 				}
  1303 				if ( $value !== $row->option_value ) {
  1598 				if ( $value !== $row->option_value ) {
  1304 					update_option( $row->option_name, $value );
  1599 					update_option( $row->option_name, $value );
  1305 				}
  1600 				}
  1306 			}
  1601 			}
  1307 			$start += 20;
  1602 			$start += 20;
  1340  * @global wpdb $wpdb WordPress database abstraction object.
  1635  * @global wpdb $wpdb WordPress database abstraction object.
  1341  */
  1636  */
  1342 function upgrade_300() {
  1637 function upgrade_300() {
  1343 	global $wp_current_db_version, $wpdb;
  1638 	global $wp_current_db_version, $wpdb;
  1344 
  1639 
  1345 	if ( $wp_current_db_version < 15093 )
  1640 	if ( $wp_current_db_version < 15093 ) {
  1346 		populate_roles_300();
  1641 		populate_roles_300();
  1347 
  1642 	}
  1348 	if ( $wp_current_db_version < 14139 && is_multisite() && is_main_site() && ! defined( 'MULTISITE' ) && get_site_option( 'siteurl' ) === false )
  1643 
       
  1644 	if ( $wp_current_db_version < 14139 && is_multisite() && is_main_site() && ! defined( 'MULTISITE' ) && get_site_option( 'siteurl' ) === false ) {
  1349 		add_site_option( 'siteurl', '' );
  1645 		add_site_option( 'siteurl', '' );
       
  1646 	}
  1350 
  1647 
  1351 	// 3.0 screen options key name changes.
  1648 	// 3.0 screen options key name changes.
  1352 	if ( wp_should_upgrade_global_tables() ) {
  1649 	if ( wp_should_upgrade_global_tables() ) {
  1353 		$sql = "DELETE FROM $wpdb->usermeta
  1650 		$sql    = "DELETE FROM $wpdb->usermeta
  1354 			WHERE meta_key LIKE %s
  1651 			WHERE meta_key LIKE %s
  1355 			OR meta_key LIKE %s
  1652 			OR meta_key LIKE %s
  1356 			OR meta_key LIKE %s
  1653 			OR meta_key LIKE %s
  1357 			OR meta_key LIKE %s
  1654 			OR meta_key LIKE %s
  1358 			OR meta_key LIKE %s
  1655 			OR meta_key LIKE %s
  1362 			OR meta_key = 'manageedit-tagscolumnshidden'
  1659 			OR meta_key = 'manageedit-tagscolumnshidden'
  1363 			OR meta_key = 'manageeditcolumnshidden'
  1660 			OR meta_key = 'manageeditcolumnshidden'
  1364 			OR meta_key = 'categories_per_page'
  1661 			OR meta_key = 'categories_per_page'
  1365 			OR meta_key = 'edit_tags_per_page'";
  1662 			OR meta_key = 'edit_tags_per_page'";
  1366 		$prefix = $wpdb->esc_like( $wpdb->base_prefix );
  1663 		$prefix = $wpdb->esc_like( $wpdb->base_prefix );
  1367 		$wpdb->query( $wpdb->prepare( $sql,
  1664 		$wpdb->query(
  1368 			$prefix . '%' . $wpdb->esc_like( 'meta-box-hidden' ) . '%',
  1665 			$wpdb->prepare(
  1369 			$prefix . '%' . $wpdb->esc_like( 'closedpostboxes' ) . '%',
  1666 				$sql,
  1370 			$prefix . '%' . $wpdb->esc_like( 'manage-'	   ) . '%' . $wpdb->esc_like( '-columns-hidden' ) . '%',
  1667 				$prefix . '%' . $wpdb->esc_like( 'meta-box-hidden' ) . '%',
  1371 			$prefix . '%' . $wpdb->esc_like( 'meta-box-order'  ) . '%',
  1668 				$prefix . '%' . $wpdb->esc_like( 'closedpostboxes' ) . '%',
  1372 			$prefix . '%' . $wpdb->esc_like( 'metaboxorder'    ) . '%',
  1669 				$prefix . '%' . $wpdb->esc_like( 'manage-' ) . '%' . $wpdb->esc_like( '-columns-hidden' ) . '%',
  1373 			$prefix . '%' . $wpdb->esc_like( 'screen_layout'   ) . '%'
  1670 				$prefix . '%' . $wpdb->esc_like( 'meta-box-order' ) . '%',
  1374 		) );
  1671 				$prefix . '%' . $wpdb->esc_like( 'metaboxorder' ) . '%',
       
  1672 				$prefix . '%' . $wpdb->esc_like( 'screen_layout' ) . '%'
       
  1673 			)
       
  1674 		);
  1375 	}
  1675 	}
  1376 
  1676 
  1377 }
  1677 }
  1378 
  1678 
  1379 /**
  1679 /**
  1392 
  1692 
  1393 	if ( $wp_current_db_version < 19061 && wp_should_upgrade_global_tables() ) {
  1693 	if ( $wp_current_db_version < 19061 && wp_should_upgrade_global_tables() ) {
  1394 		$wpdb->query( "DELETE FROM $wpdb->usermeta WHERE meta_key IN ('show_admin_bar_admin', 'plugins_last_view')" );
  1694 		$wpdb->query( "DELETE FROM $wpdb->usermeta WHERE meta_key IN ('show_admin_bar_admin', 'plugins_last_view')" );
  1395 	}
  1695 	}
  1396 
  1696 
  1397 	if ( $wp_current_db_version >= 11548 )
  1697 	if ( $wp_current_db_version >= 11548 ) {
  1398 		return;
  1698 		return;
  1399 
  1699 	}
  1400 	$sidebars_widgets = get_option( 'sidebars_widgets', array() );
  1700 
       
  1701 	$sidebars_widgets  = get_option( 'sidebars_widgets', array() );
  1401 	$_sidebars_widgets = array();
  1702 	$_sidebars_widgets = array();
  1402 
  1703 
  1403 	if ( isset($sidebars_widgets['wp_inactive_widgets']) || empty($sidebars_widgets) )
  1704 	if ( isset( $sidebars_widgets['wp_inactive_widgets'] ) || empty( $sidebars_widgets ) ) {
  1404 		$sidebars_widgets['array_version'] = 3;
  1705 		$sidebars_widgets['array_version'] = 3;
  1405 	elseif ( !isset($sidebars_widgets['array_version']) )
  1706 	} elseif ( ! isset( $sidebars_widgets['array_version'] ) ) {
  1406 		$sidebars_widgets['array_version'] = 1;
  1707 		$sidebars_widgets['array_version'] = 1;
       
  1708 	}
  1407 
  1709 
  1408 	switch ( $sidebars_widgets['array_version'] ) {
  1710 	switch ( $sidebars_widgets['array_version'] ) {
  1409 		case 1 :
  1711 		case 1:
  1410 			foreach ( (array) $sidebars_widgets as $index => $sidebar )
  1712 			foreach ( (array) $sidebars_widgets as $index => $sidebar ) {
  1411 			if ( is_array($sidebar) )
  1713 				if ( is_array( $sidebar ) ) {
  1412 			foreach ( (array) $sidebar as $i => $name ) {
  1714 					foreach ( (array) $sidebar as $i => $name ) {
  1413 				$id = strtolower($name);
  1715 						$id = strtolower( $name );
  1414 				if ( isset($wp_registered_widgets[$id]) ) {
  1716 						if ( isset( $wp_registered_widgets[ $id ] ) ) {
  1415 					$_sidebars_widgets[$index][$i] = $id;
  1717 							$_sidebars_widgets[ $index ][ $i ] = $id;
  1416 					continue;
  1718 							continue;
  1417 				}
  1719 						}
  1418 				$id = sanitize_title($name);
  1720 						$id = sanitize_title( $name );
  1419 				if ( isset($wp_registered_widgets[$id]) ) {
  1721 						if ( isset( $wp_registered_widgets[ $id ] ) ) {
  1420 					$_sidebars_widgets[$index][$i] = $id;
  1722 							$_sidebars_widgets[ $index ][ $i ] = $id;
  1421 					continue;
  1723 							continue;
  1422 				}
  1724 						}
  1423 
  1725 
  1424 				$found = false;
  1726 						$found = false;
  1425 
  1727 
  1426 				foreach ( $wp_registered_widgets as $widget_id => $widget ) {
  1728 						foreach ( $wp_registered_widgets as $widget_id => $widget ) {
  1427 					if ( strtolower($widget['name']) == strtolower($name) ) {
  1729 							if ( strtolower( $widget['name'] ) == strtolower( $name ) ) {
  1428 						$_sidebars_widgets[$index][$i] = $widget['id'];
  1730 								$_sidebars_widgets[ $index ][ $i ] = $widget['id'];
  1429 						$found = true;
  1731 								$found                             = true;
  1430 						break;
  1732 								break;
  1431 					} elseif ( sanitize_title($widget['name']) == sanitize_title($name) ) {
  1733 							} elseif ( sanitize_title( $widget['name'] ) == sanitize_title( $name ) ) {
  1432 						$_sidebars_widgets[$index][$i] = $widget['id'];
  1734 								$_sidebars_widgets[ $index ][ $i ] = $widget['id'];
  1433 						$found = true;
  1735 								$found                             = true;
  1434 						break;
  1736 								break;
       
  1737 							}
       
  1738 						}
       
  1739 
       
  1740 						if ( $found ) {
       
  1741 							continue;
       
  1742 						}
       
  1743 
       
  1744 						unset( $_sidebars_widgets[ $index ][ $i ] );
  1435 					}
  1745 					}
  1436 				}
  1746 				}
  1437 
       
  1438 				if ( $found )
       
  1439 					continue;
       
  1440 
       
  1441 				unset($_sidebars_widgets[$index][$i]);
       
  1442 			}
  1747 			}
  1443 			$_sidebars_widgets['array_version'] = 2;
  1748 			$_sidebars_widgets['array_version'] = 2;
  1444 			$sidebars_widgets = $_sidebars_widgets;
  1749 			$sidebars_widgets                   = $_sidebars_widgets;
  1445 			unset($_sidebars_widgets);
  1750 			unset( $_sidebars_widgets );
  1446 
  1751 
  1447 		case 2 :
  1752 			// intentional fall-through to upgrade to the next version.
  1448 			$sidebars_widgets = retrieve_widgets();
  1753 		case 2:
       
  1754 			$sidebars_widgets                  = retrieve_widgets();
  1449 			$sidebars_widgets['array_version'] = 3;
  1755 			$sidebars_widgets['array_version'] = 3;
  1450 			update_option( 'sidebars_widgets', $sidebars_widgets );
  1756 			update_option( 'sidebars_widgets', $sidebars_widgets );
  1451 	}
  1757 	}
  1452 }
  1758 }
  1453 
  1759 
  1469 		$wpdb->show_errors();
  1775 		$wpdb->show_errors();
  1470 	}
  1776 	}
  1471 
  1777 
  1472 	if ( $wp_current_db_version < 19799 ) {
  1778 	if ( $wp_current_db_version < 19799 ) {
  1473 		$wpdb->hide_errors();
  1779 		$wpdb->hide_errors();
  1474 		$wpdb->query("ALTER TABLE $wpdb->comments DROP INDEX comment_approved");
  1780 		$wpdb->query( "ALTER TABLE $wpdb->comments DROP INDEX comment_approved" );
  1475 		$wpdb->show_errors();
  1781 		$wpdb->show_errors();
  1476 	}
  1782 	}
  1477 
  1783 
  1478 	if ( $wp_current_db_version < 20022 && wp_should_upgrade_global_tables() ) {
  1784 	if ( $wp_current_db_version < 20022 && wp_should_upgrade_global_tables() ) {
  1479 		$wpdb->query( "DELETE FROM $wpdb->usermeta WHERE meta_key = 'themes_last_view'" );
  1785 		$wpdb->query( "DELETE FROM $wpdb->usermeta WHERE meta_key = 'themes_last_view'" );
  1498  * @global wpdb  $wpdb
  1804  * @global wpdb  $wpdb
  1499  */
  1805  */
  1500 function upgrade_350() {
  1806 function upgrade_350() {
  1501 	global $wp_current_db_version, $wpdb;
  1807 	global $wp_current_db_version, $wpdb;
  1502 
  1808 
  1503 	if ( $wp_current_db_version < 22006 && $wpdb->get_var( "SELECT link_id FROM $wpdb->links LIMIT 1" ) )
  1809 	if ( $wp_current_db_version < 22006 && $wpdb->get_var( "SELECT link_id FROM $wpdb->links LIMIT 1" ) ) {
  1504 		update_option( 'link_manager_enabled', 1 ); // Previously set to 0 by populate_options()
  1810 		update_option( 'link_manager_enabled', 1 ); // Previously set to 0 by populate_options()
       
  1811 	}
  1505 
  1812 
  1506 	if ( $wp_current_db_version < 21811 && wp_should_upgrade_global_tables() ) {
  1813 	if ( $wp_current_db_version < 21811 && wp_should_upgrade_global_tables() ) {
  1507 		$meta_keys = array();
  1814 		$meta_keys = array();
  1508 		foreach ( array_merge( get_post_types(), get_taxonomies() ) as $name ) {
  1815 		foreach ( array_merge( get_post_types(), get_taxonomies() ) as $name ) {
  1509 			if ( false !== strpos( $name, '-' ) )
  1816 			if ( false !== strpos( $name, '-' ) ) {
  1510 			$meta_keys[] = 'edit_' . str_replace( '-', '_', $name ) . '_per_page';
  1817 				$meta_keys[] = 'edit_' . str_replace( '-', '_', $name ) . '_per_page';
       
  1818 			}
  1511 		}
  1819 		}
  1512 		if ( $meta_keys ) {
  1820 		if ( $meta_keys ) {
  1513 			$meta_keys = implode( "', '", $meta_keys );
  1821 			$meta_keys = implode( "', '", $meta_keys );
  1514 			$wpdb->query( "DELETE FROM $wpdb->usermeta WHERE meta_key IN ('$meta_keys')" );
  1822 			$wpdb->query( "DELETE FROM $wpdb->usermeta WHERE meta_key IN ('$meta_keys')" );
  1515 		}
  1823 		}
  1516 	}
  1824 	}
  1517 
  1825 
  1518 	if ( $wp_current_db_version < 22422 && $term = get_term_by( 'slug', 'post-format-standard', 'post_format' ) )
  1826 	if ( $wp_current_db_version < 22422 && $term = get_term_by( 'slug', 'post-format-standard', 'post_format' ) ) {
  1519 		wp_delete_term( $term->term_id, 'post_format' );
  1827 		wp_delete_term( $term->term_id, 'post_format' );
       
  1828 	}
  1520 }
  1829 }
  1521 
  1830 
  1522 /**
  1831 /**
  1523  * Execute changes made in WordPress 3.7.
  1832  * Execute changes made in WordPress 3.7.
  1524  *
  1833  *
  1527  *
  1836  *
  1528  * @global int $wp_current_db_version
  1837  * @global int $wp_current_db_version
  1529  */
  1838  */
  1530 function upgrade_370() {
  1839 function upgrade_370() {
  1531 	global $wp_current_db_version;
  1840 	global $wp_current_db_version;
  1532 	if ( $wp_current_db_version < 25824 )
  1841 	if ( $wp_current_db_version < 25824 ) {
  1533 		wp_clear_scheduled_hook( 'wp_auto_updates_maybe_update' );
  1842 		wp_clear_scheduled_hook( 'wp_auto_updates_maybe_update' );
       
  1843 	}
  1534 }
  1844 }
  1535 
  1845 
  1536 /**
  1846 /**
  1537  * Execute changes made in WordPress 3.7.2.
  1847  * Execute changes made in WordPress 3.7.2.
  1538  *
  1848  *
  1542  *
  1852  *
  1543  * @global int $wp_current_db_version
  1853  * @global int $wp_current_db_version
  1544  */
  1854  */
  1545 function upgrade_372() {
  1855 function upgrade_372() {
  1546 	global $wp_current_db_version;
  1856 	global $wp_current_db_version;
  1547 	if ( $wp_current_db_version < 26148 )
  1857 	if ( $wp_current_db_version < 26148 ) {
  1548 		wp_clear_scheduled_hook( 'wp_maybe_auto_update' );
  1858 		wp_clear_scheduled_hook( 'wp_maybe_auto_update' );
       
  1859 	}
  1549 }
  1860 }
  1550 
  1861 
  1551 /**
  1862 /**
  1552  * Execute changes made in WordPress 3.8.0.
  1863  * Execute changes made in WordPress 3.8.0.
  1553  *
  1864  *
  1622 			$tables = $wpdb->tables( 'blog' );
  1933 			$tables = $wpdb->tables( 'blog' );
  1623 		} else {
  1934 		} else {
  1624 			$tables = $wpdb->tables( 'all' );
  1935 			$tables = $wpdb->tables( 'all' );
  1625 			if ( ! wp_should_upgrade_global_tables() ) {
  1936 			if ( ! wp_should_upgrade_global_tables() ) {
  1626 				$global_tables = $wpdb->tables( 'global' );
  1937 				$global_tables = $wpdb->tables( 'global' );
  1627 				$tables = array_diff_assoc( $tables, $global_tables );
  1938 				$tables        = array_diff_assoc( $tables, $global_tables );
  1628 			}
  1939 			}
  1629 		}
  1940 		}
  1630 
  1941 
  1631 		foreach ( $tables as $table ) {
  1942 		foreach ( $tables as $table ) {
  1632 			maybe_convert_table_to_utf8mb4( $table );
  1943 			maybe_convert_table_to_utf8mb4( $table );
  1656 		$content_length = array(
  1967 		$content_length = array(
  1657 			'type'   => 'byte',
  1968 			'type'   => 'byte',
  1658 			'length' => 65535,
  1969 			'length' => 65535,
  1659 		);
  1970 		);
  1660 	} elseif ( ! is_array( $content_length ) ) {
  1971 	} elseif ( ! is_array( $content_length ) ) {
  1661 		$length = (int) $content_length > 0 ? (int) $content_length : 65535;
  1972 		$length         = (int) $content_length > 0 ? (int) $content_length : 65535;
  1662 		$content_length = array(
  1973 		$content_length = array(
  1663 			'type'	 => 'byte',
  1974 			'type'   => 'byte',
  1664 			'length' => $length
  1975 			'length' => $length,
  1665 		);
  1976 		);
  1666 	}
  1977 	}
  1667 
  1978 
  1668 	if ( 'byte' !== $content_length['type'] || 0 === $content_length['length'] ) {
  1979 	if ( 'byte' !== $content_length['type'] || 0 === $content_length['length'] ) {
  1669 		// Sites with malformed DB schemas are on their own.
  1980 		// Sites with malformed DB schemas are on their own.
  1780 		}
  2091 		}
  1781 	}
  2092 	}
  1782 }
  2093 }
  1783 
  2094 
  1784 /**
  2095 /**
       
  2096  * Executes changes made in WordPress 5.0.0.
       
  2097  *
       
  2098  * @ignore
       
  2099  * @since 5.0.0
       
  2100  * @deprecated 5.1.0
       
  2101  */
       
  2102 function upgrade_500() {
       
  2103 }
       
  2104 
       
  2105 /**
       
  2106  * Executes changes made in WordPress 5.1.0.
       
  2107  *
       
  2108  * @ignore
       
  2109  * @since 5.1.0
       
  2110  */
       
  2111 function upgrade_510() {
       
  2112 	delete_site_option( 'upgrade_500_was_gutenberg_active' );
       
  2113 }
       
  2114 
       
  2115 /**
  1785  * Executes network-level upgrade routines.
  2116  * Executes network-level upgrade routines.
  1786  *
  2117  *
  1787  * @since 3.0.0
  2118  * @since 3.0.0
  1788  *
  2119  *
  1789  * @global int   $wp_current_db_version
  2120  * @global int   $wp_current_db_version
  1795 	// Always clear expired transients
  2126 	// Always clear expired transients
  1796 	delete_expired_transients( true );
  2127 	delete_expired_transients( true );
  1797 
  2128 
  1798 	// 2.8.
  2129 	// 2.8.
  1799 	if ( $wp_current_db_version < 11549 ) {
  2130 	if ( $wp_current_db_version < 11549 ) {
  1800 		$wpmu_sitewide_plugins = get_site_option( 'wpmu_sitewide_plugins' );
  2131 		$wpmu_sitewide_plugins   = get_site_option( 'wpmu_sitewide_plugins' );
  1801 		$active_sitewide_plugins = get_site_option( 'active_sitewide_plugins' );
  2132 		$active_sitewide_plugins = get_site_option( 'active_sitewide_plugins' );
  1802 		if ( $wpmu_sitewide_plugins ) {
  2133 		if ( $wpmu_sitewide_plugins ) {
  1803 			if ( !$active_sitewide_plugins )
  2134 			if ( ! $active_sitewide_plugins ) {
  1804 				$sitewide_plugins = (array) $wpmu_sitewide_plugins;
  2135 				$sitewide_plugins = (array) $wpmu_sitewide_plugins;
  1805 			else
  2136 			} else {
  1806 				$sitewide_plugins = array_merge( (array) $active_sitewide_plugins, (array) $wpmu_sitewide_plugins );
  2137 				$sitewide_plugins = array_merge( (array) $active_sitewide_plugins, (array) $wpmu_sitewide_plugins );
       
  2138 			}
  1807 
  2139 
  1808 			update_site_option( 'active_sitewide_plugins', $sitewide_plugins );
  2140 			update_site_option( 'active_sitewide_plugins', $sitewide_plugins );
  1809 		}
  2141 		}
  1810 		delete_site_option( 'wpmu_sitewide_plugins' );
  2142 		delete_site_option( 'wpmu_sitewide_plugins' );
  1811 		delete_site_option( 'deactivated_sitewide_plugins' );
  2143 		delete_site_option( 'deactivated_sitewide_plugins' );
  1812 
  2144 
  1813 		$start = 0;
  2145 		$start = 0;
  1814 		while( $rows = $wpdb->get_results( "SELECT meta_key, meta_value FROM {$wpdb->sitemeta} ORDER BY meta_id LIMIT $start, 20" ) ) {
  2146 		while ( $rows = $wpdb->get_results( "SELECT meta_key, meta_value FROM {$wpdb->sitemeta} ORDER BY meta_id LIMIT $start, 20" ) ) {
  1815 			foreach ( $rows as $row ) {
  2147 			foreach ( $rows as $row ) {
  1816 				$value = $row->meta_value;
  2148 				$value = $row->meta_value;
  1817 				if ( !@unserialize( $value ) )
  2149 				if ( ! @unserialize( $value ) ) {
  1818 					$value = stripslashes( $value );
  2150 					$value = stripslashes( $value );
       
  2151 				}
  1819 				if ( $value !== $row->meta_value ) {
  2152 				if ( $value !== $row->meta_value ) {
  1820 					update_site_option( $row->meta_key, $value );
  2153 					update_site_option( $row->meta_key, $value );
  1821 				}
  2154 				}
  1822 			}
  2155 			}
  1823 			$start += 20;
  2156 			$start += 20;
  1824 		}
  2157 		}
  1825 	}
  2158 	}
  1826 
  2159 
  1827 	// 3.0
  2160 	// 3.0
  1828 	if ( $wp_current_db_version < 13576 )
  2161 	if ( $wp_current_db_version < 13576 ) {
  1829 		update_site_option( 'global_terms_enabled', '1' );
  2162 		update_site_option( 'global_terms_enabled', '1' );
       
  2163 	}
  1830 
  2164 
  1831 	// 3.3
  2165 	// 3.3
  1832 	if ( $wp_current_db_version < 19390 )
  2166 	if ( $wp_current_db_version < 19390 ) {
  1833 		update_site_option( 'initial_db_version', $wp_current_db_version );
  2167 		update_site_option( 'initial_db_version', $wp_current_db_version );
       
  2168 	}
  1834 
  2169 
  1835 	if ( $wp_current_db_version < 19470 ) {
  2170 	if ( $wp_current_db_version < 19470 ) {
  1836 		if ( false === get_site_option( 'active_sitewide_plugins' ) )
  2171 		if ( false === get_site_option( 'active_sitewide_plugins' ) ) {
  1837 			update_site_option( 'active_sitewide_plugins', array() );
  2172 			update_site_option( 'active_sitewide_plugins', array() );
       
  2173 		}
  1838 	}
  2174 	}
  1839 
  2175 
  1840 	// 3.4
  2176 	// 3.4
  1841 	if ( $wp_current_db_version < 20148 ) {
  2177 	if ( $wp_current_db_version < 20148 ) {
  1842 		// 'allowedthemes' keys things by stylesheet. 'allowed_themes' keyed things by name.
  2178 		// 'allowedthemes' keys things by stylesheet. 'allowed_themes' keyed things by name.
  1843 		$allowedthemes  = get_site_option( 'allowedthemes'  );
  2179 		$allowedthemes  = get_site_option( 'allowedthemes' );
  1844 		$allowed_themes = get_site_option( 'allowed_themes' );
  2180 		$allowed_themes = get_site_option( 'allowed_themes' );
  1845 		if ( false === $allowedthemes && is_array( $allowed_themes ) && $allowed_themes ) {
  2181 		if ( false === $allowedthemes && is_array( $allowed_themes ) && $allowed_themes ) {
  1846 			$converted = array();
  2182 			$converted = array();
  1847 			$themes = wp_get_themes();
  2183 			$themes    = wp_get_themes();
  1848 			foreach ( $themes as $stylesheet => $theme_data ) {
  2184 			foreach ( $themes as $stylesheet => $theme_data ) {
  1849 				if ( isset( $allowed_themes[ $theme_data->get('Name') ] ) )
  2185 				if ( isset( $allowed_themes[ $theme_data->get( 'Name' ) ] ) ) {
  1850 					$converted[ $stylesheet ] = true;
  2186 					$converted[ $stylesheet ] = true;
       
  2187 				}
  1851 			}
  2188 			}
  1852 			update_site_option( 'allowedthemes', $converted );
  2189 			update_site_option( 'allowedthemes', $converted );
  1853 			delete_site_option( 'allowed_themes' );
  2190 			delete_site_option( 'allowed_themes' );
  1854 		}
  2191 		}
  1855 	}
  2192 	}
  1856 
  2193 
  1857 	// 3.5
  2194 	// 3.5
  1858 	if ( $wp_current_db_version < 21823 )
  2195 	if ( $wp_current_db_version < 21823 ) {
  1859 		update_site_option( 'ms_files_rewriting', '1' );
  2196 		update_site_option( 'ms_files_rewriting', '1' );
       
  2197 	}
  1860 
  2198 
  1861 	// 3.5.2
  2199 	// 3.5.2
  1862 	if ( $wp_current_db_version < 24448 ) {
  2200 	if ( $wp_current_db_version < 24448 ) {
  1863 		$illegal_names = get_site_option( 'illegal_names' );
  2201 		$illegal_names = get_site_option( 'illegal_names' );
  1864 		if ( is_array( $illegal_names ) && count( $illegal_names ) === 1 ) {
  2202 		if ( is_array( $illegal_names ) && count( $illegal_names ) === 1 ) {
  1865 			$illegal_name = reset( $illegal_names );
  2203 			$illegal_name  = reset( $illegal_names );
  1866 			$illegal_names = explode( ' ', $illegal_name );
  2204 			$illegal_names = explode( ' ', $illegal_name );
  1867 			update_site_option( 'illegal_names', $illegal_names );
  2205 			update_site_option( 'illegal_names', $illegal_names );
  1868 		}
  2206 		}
  1869 	}
  2207 	}
  1870 
  2208 
  1915 			foreach ( $tables as $table ) {
  2253 			foreach ( $tables as $table ) {
  1916 				maybe_convert_table_to_utf8mb4( $table );
  2254 				maybe_convert_table_to_utf8mb4( $table );
  1917 			}
  2255 			}
  1918 		}
  2256 		}
  1919 	}
  2257 	}
       
  2258 
       
  2259 	// 5.1
       
  2260 	if ( $wp_current_db_version < 44467 ) {
       
  2261 		$network_id = get_main_network_id();
       
  2262 		delete_network_option( $network_id, 'site_meta_supported' );
       
  2263 		is_site_meta_supported();
       
  2264 	}
  1920 }
  2265 }
  1921 
  2266 
  1922 //
  2267 //
  1923 // General functions we use to actually do stuff
  2268 // General functions we use to actually do stuff
  1924 //
  2269 //
  1936  *
  2281  *
  1937  * @param string $table_name Database table name to create.
  2282  * @param string $table_name Database table name to create.
  1938  * @param string $create_ddl SQL statement to create table.
  2283  * @param string $create_ddl SQL statement to create table.
  1939  * @return bool If table already exists or was created by function.
  2284  * @return bool If table already exists or was created by function.
  1940  */
  2285  */
  1941 function maybe_create_table($table_name, $create_ddl) {
  2286 function maybe_create_table( $table_name, $create_ddl ) {
  1942 	global $wpdb;
  2287 	global $wpdb;
  1943 
  2288 
  1944 	$query = $wpdb->prepare( "SHOW TABLES LIKE %s", $wpdb->esc_like( $table_name ) );
  2289 	$query = $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $table_name ) );
  1945 
  2290 
  1946 	if ( $wpdb->get_var( $query ) == $table_name ) {
  2291 	if ( $wpdb->get_var( $query ) == $table_name ) {
  1947 		return true;
  2292 		return true;
  1948 	}
  2293 	}
  1949 
  2294 
  1950 	// Didn't find it try to create it..
  2295 	// Didn't find it try to create it..
  1951 	$wpdb->query($create_ddl);
  2296 	$wpdb->query( $create_ddl );
  1952 
  2297 
  1953 	// We cannot directly tell that whether this succeeded!
  2298 	// We cannot directly tell that whether this succeeded!
  1954 	if ( $wpdb->get_var( $query ) == $table_name ) {
  2299 	if ( $wpdb->get_var( $query ) == $table_name ) {
  1955 		return true;
  2300 		return true;
  1956 	}
  2301 	}
  1966  *
  2311  *
  1967  * @param string $table Database table name.
  2312  * @param string $table Database table name.
  1968  * @param string $index Index name to drop.
  2313  * @param string $index Index name to drop.
  1969  * @return true True, when finished.
  2314  * @return true True, when finished.
  1970  */
  2315  */
  1971 function drop_index($table, $index) {
  2316 function drop_index( $table, $index ) {
  1972 	global $wpdb;
  2317 	global $wpdb;
  1973 	$wpdb->hide_errors();
  2318 	$wpdb->hide_errors();
  1974 	$wpdb->query("ALTER TABLE `$table` DROP INDEX `$index`");
  2319 	$wpdb->query( "ALTER TABLE `$table` DROP INDEX `$index`" );
  1975 	// Now we need to take out all the extra ones we may have created
  2320 	// Now we need to take out all the extra ones we may have created
  1976 	for ($i = 0; $i < 25; $i++) {
  2321 	for ( $i = 0; $i < 25; $i++ ) {
  1977 		$wpdb->query("ALTER TABLE `$table` DROP INDEX `{$index}_$i`");
  2322 		$wpdb->query( "ALTER TABLE `$table` DROP INDEX `{$index}_$i`" );
  1978 	}
  2323 	}
  1979 	$wpdb->show_errors();
  2324 	$wpdb->show_errors();
  1980 	return true;
  2325 	return true;
  1981 }
  2326 }
  1982 
  2327 
  1989  *
  2334  *
  1990  * @param string $table Database table name.
  2335  * @param string $table Database table name.
  1991  * @param string $index Database table index column.
  2336  * @param string $index Database table index column.
  1992  * @return true True, when done with execution.
  2337  * @return true True, when done with execution.
  1993  */
  2338  */
  1994 function add_clean_index($table, $index) {
  2339 function add_clean_index( $table, $index ) {
  1995 	global $wpdb;
  2340 	global $wpdb;
  1996 	drop_index($table, $index);
  2341 	drop_index( $table, $index );
  1997 	$wpdb->query("ALTER TABLE `$table` ADD INDEX ( `$index` )");
  2342 	$wpdb->query( "ALTER TABLE `$table` ADD INDEX ( `$index` )" );
  1998 	return true;
  2343 	return true;
  1999 }
  2344 }
  2000 
  2345 
  2001 /**
  2346 /**
  2002  * Adds column to a database table if it doesn't already exist.
  2347  * Adds column to a database table if it doesn't already exist.
  2008  * @param string $table_name  The table name to modify.
  2353  * @param string $table_name  The table name to modify.
  2009  * @param string $column_name The column name to add to the table.
  2354  * @param string $column_name The column name to add to the table.
  2010  * @param string $create_ddl  The SQL statement used to add the column.
  2355  * @param string $create_ddl  The SQL statement used to add the column.
  2011  * @return bool True if already exists or on successful completion, false on error.
  2356  * @return bool True if already exists or on successful completion, false on error.
  2012  */
  2357  */
  2013 function maybe_add_column($table_name, $column_name, $create_ddl) {
  2358 function maybe_add_column( $table_name, $column_name, $create_ddl ) {
  2014 	global $wpdb;
  2359 	global $wpdb;
  2015 	foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) {
  2360 	foreach ( $wpdb->get_col( "DESC $table_name", 0 ) as $column ) {
  2016 		if ($column == $column_name) {
  2361 		if ( $column == $column_name ) {
  2017 			return true;
  2362 			return true;
  2018 		}
  2363 		}
  2019 	}
  2364 	}
  2020 
  2365 
  2021 	// Didn't find it try to create it.
  2366 	// Didn't find it try to create it.
  2022 	$wpdb->query($create_ddl);
  2367 	$wpdb->query( $create_ddl );
  2023 
  2368 
  2024 	// We cannot directly tell that whether this succeeded!
  2369 	// We cannot directly tell that whether this succeeded!
  2025 	foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) {
  2370 	foreach ( $wpdb->get_col( "DESC $table_name", 0 ) as $column ) {
  2026 		if ($column == $column_name) {
  2371 		if ( $column == $column_name ) {
  2027 			return true;
  2372 			return true;
  2028 		}
  2373 		}
  2029 	}
  2374 	}
  2030 	return false;
  2375 	return false;
  2031 }
  2376 }
  2049 	}
  2394 	}
  2050 
  2395 
  2051 	foreach ( $results as $column ) {
  2396 	foreach ( $results as $column ) {
  2052 		if ( $column->Collation ) {
  2397 		if ( $column->Collation ) {
  2053 			list( $charset ) = explode( '_', $column->Collation );
  2398 			list( $charset ) = explode( '_', $column->Collation );
  2054 			$charset = strtolower( $charset );
  2399 			$charset         = strtolower( $charset );
  2055 			if ( 'utf8' !== $charset && 'utf8mb4' !== $charset ) {
  2400 			if ( 'utf8' !== $charset && 'utf8mb4' !== $charset ) {
  2056 				// Don't upgrade tables that have non-utf8 columns.
  2401 				// Don't upgrade tables that have non-utf8 columns.
  2057 				return false;
  2402 				return false;
  2058 			}
  2403 			}
  2059 		}
  2404 		}
  2063 	if ( ! $table_details ) {
  2408 	if ( ! $table_details ) {
  2064 		return false;
  2409 		return false;
  2065 	}
  2410 	}
  2066 
  2411 
  2067 	list( $table_charset ) = explode( '_', $table_details->Collation );
  2412 	list( $table_charset ) = explode( '_', $table_details->Collation );
  2068 	$table_charset = strtolower( $table_charset );
  2413 	$table_charset         = strtolower( $table_charset );
  2069 	if ( 'utf8mb4' === $table_charset ) {
  2414 	if ( 'utf8mb4' === $table_charset ) {
  2070 		return true;
  2415 		return true;
  2071 	}
  2416 	}
  2072 
  2417 
  2073 	return $wpdb->query( "ALTER TABLE $table CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci" );
  2418 	return $wpdb->query( "ALTER TABLE $table CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci" );
  2085 function get_alloptions_110() {
  2430 function get_alloptions_110() {
  2086 	global $wpdb;
  2431 	global $wpdb;
  2087 	$all_options = new stdClass;
  2432 	$all_options = new stdClass;
  2088 	if ( $options = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options" ) ) {
  2433 	if ( $options = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options" ) ) {
  2089 		foreach ( $options as $option ) {
  2434 		foreach ( $options as $option ) {
  2090 			if ( 'siteurl' == $option->option_name || 'home' == $option->option_name || 'category_base' == $option->option_name )
  2435 			if ( 'siteurl' == $option->option_name || 'home' == $option->option_name || 'category_base' == $option->option_name ) {
  2091 				$option->option_value = untrailingslashit( $option->option_value );
  2436 				$option->option_value = untrailingslashit( $option->option_value );
       
  2437 			}
  2092 			$all_options->{$option->option_name} = stripslashes( $option->option_value );
  2438 			$all_options->{$option->option_name} = stripslashes( $option->option_value );
  2093 		}
  2439 		}
  2094 	}
  2440 	}
  2095 	return $all_options;
  2441 	return $all_options;
  2096 }
  2442 }
  2105  * @global wpdb  $wpdb
  2451  * @global wpdb  $wpdb
  2106  *
  2452  *
  2107  * @param string $setting Option name.
  2453  * @param string $setting Option name.
  2108  * @return mixed
  2454  * @return mixed
  2109  */
  2455  */
  2110 function __get_option($setting) {
  2456 function __get_option( $setting ) {
  2111 	global $wpdb;
  2457 	global $wpdb;
  2112 
  2458 
  2113 	if ( $setting == 'home' && defined( 'WP_HOME' ) )
  2459 	if ( $setting == 'home' && defined( 'WP_HOME' ) ) {
  2114 		return untrailingslashit( WP_HOME );
  2460 		return untrailingslashit( WP_HOME );
  2115 
  2461 	}
  2116 	if ( $setting == 'siteurl' && defined( 'WP_SITEURL' ) )
  2462 
       
  2463 	if ( $setting == 'siteurl' && defined( 'WP_SITEURL' ) ) {
  2117 		return untrailingslashit( WP_SITEURL );
  2464 		return untrailingslashit( WP_SITEURL );
  2118 
  2465 	}
  2119 	$option = $wpdb->get_var( $wpdb->prepare("SELECT option_value FROM $wpdb->options WHERE option_name = %s", $setting ) );
  2466 
  2120 
  2467 	$option = $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM $wpdb->options WHERE option_name = %s", $setting ) );
  2121 	if ( 'home' == $setting && '' == $option )
  2468 
       
  2469 	if ( 'home' == $setting && '' == $option ) {
  2122 		return __get_option( 'siteurl' );
  2470 		return __get_option( 'siteurl' );
  2123 
  2471 	}
  2124 	if ( 'siteurl' == $setting || 'home' == $setting || 'category_base' == $setting || 'tag_base' == $setting )
  2472 
       
  2473 	if ( 'siteurl' == $setting || 'home' == $setting || 'category_base' == $setting || 'tag_base' == $setting ) {
  2125 		$option = untrailingslashit( $option );
  2474 		$option = untrailingslashit( $option );
       
  2475 	}
  2126 
  2476 
  2127 	return maybe_unserialize( $option );
  2477 	return maybe_unserialize( $option );
  2128 }
  2478 }
  2129 
  2479 
  2130 /**
  2480 /**
  2133  * @since 1.5.0
  2483  * @since 1.5.0
  2134  *
  2484  *
  2135  * @param string $content The content to modify.
  2485  * @param string $content The content to modify.
  2136  * @return string The de-slashed content.
  2486  * @return string The de-slashed content.
  2137  */
  2487  */
  2138 function deslash($content) {
  2488 function deslash( $content ) {
  2139 	// Note: \\\ inside a regex denotes a single backslash.
  2489 	// Note: \\\ inside a regex denotes a single backslash.
  2140 
  2490 
  2141 	/*
  2491 	/*
  2142 	 * Replace one or more backslashes followed by a single quote with
  2492 	 * Replace one or more backslashes followed by a single quote with
  2143 	 * a single quote.
  2493 	 * a single quote.
  2144 	 */
  2494 	 */
  2145 	$content = preg_replace("/\\\+'/", "'", $content);
  2495 	$content = preg_replace( "/\\\+'/", "'", $content );
  2146 
  2496 
  2147 	/*
  2497 	/*
  2148 	 * Replace one or more backslashes followed by a double quote with
  2498 	 * Replace one or more backslashes followed by a double quote with
  2149 	 * a double quote.
  2499 	 * a double quote.
  2150 	 */
  2500 	 */
  2151 	$content = preg_replace('/\\\+"/', '"', $content);
  2501 	$content = preg_replace( '/\\\+"/', '"', $content );
  2152 
  2502 
  2153 	// Replace one or more backslashes with one backslash.
  2503 	// Replace one or more backslashes with one backslash.
  2154 	$content = preg_replace("/\\\+/", "\\", $content);
  2504 	$content = preg_replace( '/\\\+/', '\\', $content );
  2155 
  2505 
  2156 	return $content;
  2506 	return $content;
  2157 }
  2507 }
  2158 
  2508 
  2159 /**
  2509 /**
  2163  *
  2513  *
  2164  * @since 1.5.0
  2514  * @since 1.5.0
  2165  *
  2515  *
  2166  * @global wpdb  $wpdb
  2516  * @global wpdb  $wpdb
  2167  *
  2517  *
  2168  * @param string|array $queries Optional. The query to run. Can be multiple queries
  2518  * @param string[]|string $queries Optional. The query to run. Can be multiple queries
  2169  *                              in an array, or a string of queries separated by
  2519  *                                 in an array, or a string of queries separated by
  2170  *                              semicolons. Default empty.
  2520  *                                 semicolons. Default empty string.
  2171  * @param bool         $execute Optional. Whether or not to execute the query right away.
  2521  * @param bool            $execute Optional. Whether or not to execute the query right away.
  2172  *                              Default true.
  2522  *                                 Default true.
  2173  * @return array Strings containing the results of the various update queries.
  2523  * @return array Strings containing the results of the various update queries.
  2174  */
  2524  */
  2175 function dbDelta( $queries = '', $execute = true ) {
  2525 function dbDelta( $queries = '', $execute = true ) {
  2176 	global $wpdb;
  2526 	global $wpdb;
  2177 
  2527 
  2178 	if ( in_array( $queries, array( '', 'all', 'blog', 'global', 'ms_global' ), true ) )
  2528 	if ( in_array( $queries, array( '', 'all', 'blog', 'global', 'ms_global' ), true ) ) {
  2179 	    $queries = wp_get_db_schema( $queries );
  2529 		$queries = wp_get_db_schema( $queries );
       
  2530 	}
  2180 
  2531 
  2181 	// Separate individual queries into an array
  2532 	// Separate individual queries into an array
  2182 	if ( !is_array($queries) ) {
  2533 	if ( ! is_array( $queries ) ) {
  2183 		$queries = explode( ';', $queries );
  2534 		$queries = explode( ';', $queries );
  2184 		$queries = array_filter( $queries );
  2535 		$queries = array_filter( $queries );
  2185 	}
  2536 	}
  2186 
  2537 
  2187 	/**
  2538 	/**
  2188 	 * Filters the dbDelta SQL queries.
  2539 	 * Filters the dbDelta SQL queries.
  2189 	 *
  2540 	 *
  2190 	 * @since 3.3.0
  2541 	 * @since 3.3.0
  2191 	 *
  2542 	 *
  2192 	 * @param array $queries An array of dbDelta SQL queries.
  2543 	 * @param string[] $queries An array of dbDelta SQL queries.
  2193 	 */
  2544 	 */
  2194 	$queries = apply_filters( 'dbdelta_queries', $queries );
  2545 	$queries = apply_filters( 'dbdelta_queries', $queries );
  2195 
  2546 
  2196 	$cqueries = array(); // Creation Queries
  2547 	$cqueries   = array(); // Creation Queries
  2197 	$iqueries = array(); // Insertion Queries
  2548 	$iqueries   = array(); // Insertion Queries
  2198 	$for_update = array();
  2549 	$for_update = array();
  2199 
  2550 
  2200 	// Create a tablename index for an array ($cqueries) of queries
  2551 	// Create a tablename index for an array ($cqueries) of queries
  2201 	foreach ($queries as $qry) {
  2552 	foreach ( $queries as $qry ) {
  2202 		if ( preg_match( "|CREATE TABLE ([^ ]*)|", $qry, $matches ) ) {
  2553 		if ( preg_match( '|CREATE TABLE ([^ ]*)|', $qry, $matches ) ) {
  2203 			$cqueries[ trim( $matches[1], '`' ) ] = $qry;
  2554 			$cqueries[ trim( $matches[1], '`' ) ] = $qry;
  2204 			$for_update[$matches[1]] = 'Created table '.$matches[1];
  2555 			$for_update[ $matches[1] ]            = 'Created table ' . $matches[1];
  2205 		} elseif ( preg_match( "|CREATE DATABASE ([^ ]*)|", $qry, $matches ) ) {
  2556 		} elseif ( preg_match( '|CREATE DATABASE ([^ ]*)|', $qry, $matches ) ) {
  2206 			array_unshift( $cqueries, $qry );
  2557 			array_unshift( $cqueries, $qry );
  2207 		} elseif ( preg_match( "|INSERT INTO ([^ ]*)|", $qry, $matches ) ) {
  2558 		} elseif ( preg_match( '|INSERT INTO ([^ ]*)|', $qry, $matches ) ) {
  2208 			$iqueries[] = $qry;
  2559 			$iqueries[] = $qry;
  2209 		} elseif ( preg_match( "|UPDATE ([^ ]*)|", $qry, $matches ) ) {
  2560 		} elseif ( preg_match( '|UPDATE ([^ ]*)|', $qry, $matches ) ) {
  2210 			$iqueries[] = $qry;
  2561 			$iqueries[] = $qry;
  2211 		} else {
  2562 		} else {
  2212 			// Unrecognized query type
  2563 			// Unrecognized query type
  2213 		}
  2564 		}
  2214 	}
  2565 	}
  2218 	 *
  2569 	 *
  2219 	 * Queries filterable via this hook contain "CREATE TABLE" or "CREATE DATABASE".
  2570 	 * Queries filterable via this hook contain "CREATE TABLE" or "CREATE DATABASE".
  2220 	 *
  2571 	 *
  2221 	 * @since 3.3.0
  2572 	 * @since 3.3.0
  2222 	 *
  2573 	 *
  2223 	 * @param array $cqueries An array of dbDelta create SQL queries.
  2574 	 * @param string[] $cqueries An array of dbDelta create SQL queries.
  2224 	 */
  2575 	 */
  2225 	$cqueries = apply_filters( 'dbdelta_create_queries', $cqueries );
  2576 	$cqueries = apply_filters( 'dbdelta_create_queries', $cqueries );
  2226 
  2577 
  2227 	/**
  2578 	/**
  2228 	 * Filters the dbDelta SQL queries for inserting or updating.
  2579 	 * Filters the dbDelta SQL queries for inserting or updating.
  2229 	 *
  2580 	 *
  2230 	 * Queries filterable via this hook contain "INSERT INTO" or "UPDATE".
  2581 	 * Queries filterable via this hook contain "INSERT INTO" or "UPDATE".
  2231 	 *
  2582 	 *
  2232 	 * @since 3.3.0
  2583 	 * @since 3.3.0
  2233 	 *
  2584 	 *
  2234 	 * @param array $iqueries An array of dbDelta insert or update SQL queries.
  2585 	 * @param string[] $iqueries An array of dbDelta insert or update SQL queries.
  2235 	 */
  2586 	 */
  2236 	$iqueries = apply_filters( 'dbdelta_insert_queries', $iqueries );
  2587 	$iqueries = apply_filters( 'dbdelta_insert_queries', $iqueries );
  2237 
  2588 
  2238 	$text_fields = array( 'tinytext', 'text', 'mediumtext', 'longtext' );
  2589 	$text_fields = array( 'tinytext', 'text', 'mediumtext', 'longtext' );
  2239 	$blob_fields = array( 'tinyblob', 'blob', 'mediumblob', 'longblob' );
  2590 	$blob_fields = array( 'tinyblob', 'blob', 'mediumblob', 'longblob' );
  2245 			unset( $cqueries[ $table ], $for_update[ $table ] );
  2596 			unset( $cqueries[ $table ], $for_update[ $table ] );
  2246 			continue;
  2597 			continue;
  2247 		}
  2598 		}
  2248 
  2599 
  2249 		// Fetch the table column structure from the database
  2600 		// Fetch the table column structure from the database
  2250 		$suppress = $wpdb->suppress_errors();
  2601 		$suppress    = $wpdb->suppress_errors();
  2251 		$tablefields = $wpdb->get_results("DESCRIBE {$table};");
  2602 		$tablefields = $wpdb->get_results( "DESCRIBE {$table};" );
  2252 		$wpdb->suppress_errors( $suppress );
  2603 		$wpdb->suppress_errors( $suppress );
  2253 
  2604 
  2254 		if ( ! $tablefields )
  2605 		if ( ! $tablefields ) {
  2255 			continue;
  2606 			continue;
       
  2607 		}
  2256 
  2608 
  2257 		// Clear the field and index arrays.
  2609 		// Clear the field and index arrays.
  2258 		$cfields = $indices = $indices_without_subparts = array();
  2610 		$cfields = $indices = $indices_without_subparts = array();
  2259 
  2611 
  2260 		// Get all of the field names in the query from between the parentheses.
  2612 		// Get all of the field names in the query from between the parentheses.
  2261 		preg_match("|\((.*)\)|ms", $qry, $match2);
  2613 		preg_match( '|\((.*)\)|ms', $qry, $match2 );
  2262 		$qryline = trim($match2[1]);
  2614 		$qryline = trim( $match2[1] );
  2263 
  2615 
  2264 		// Separate field lines into an array.
  2616 		// Separate field lines into an array.
  2265 		$flds = explode("\n", $qryline);
  2617 		$flds = explode( "\n", $qryline );
  2266 
  2618 
  2267 		// For every field line specified in the query.
  2619 		// For every field line specified in the query.
  2268 		foreach ( $flds as $fld ) {
  2620 		foreach ( $flds as $fld ) {
  2269 			$fld = trim( $fld, " \t\n\r\0\x0B," ); // Default trim characters, plus ','.
  2621 			$fld = trim( $fld, " \t\n\r\0\x0B," ); // Default trim characters, plus ','.
  2270 
  2622 
  2271 			// Extract the field name.
  2623 			// Extract the field name.
  2272 			preg_match( '|^([^ ]*)|', $fld, $fvals );
  2624 			preg_match( '|^([^ ]*)|', $fld, $fvals );
  2273 			$fieldname = trim( $fvals[1], '`' );
  2625 			$fieldname            = trim( $fvals[1], '`' );
  2274 			$fieldname_lowercased = strtolower( $fieldname );
  2626 			$fieldname_lowercased = strtolower( $fieldname );
  2275 
  2627 
  2276 			// Verify the found field name.
  2628 			// Verify the found field name.
  2277 			$validfield = true;
  2629 			$validfield = true;
  2278 			switch ( $fieldname_lowercased ) {
  2630 			switch ( $fieldname_lowercased ) {
  2292 					 * `SHOW INDEX FROM $table_name` query which returns the current table
  2644 					 * `SHOW INDEX FROM $table_name` query which returns the current table
  2293 					 * index information.
  2645 					 * index information.
  2294 					 */
  2646 					 */
  2295 
  2647 
  2296 					// Extract type, name and columns from the definition.
  2648 					// Extract type, name and columns from the definition.
       
  2649 					// phpcs:disable Squiz.Strings.ConcatenationSpacing.PaddingFound -- don't remove regex indentation
  2297 					preg_match(
  2650 					preg_match(
  2298 						  '/^'
  2651 						'/^'
  2299 						.   '(?P<index_type>'             // 1) Type of the index.
  2652 						.   '(?P<index_type>'             // 1) Type of the index.
  2300 						.       'PRIMARY\s+KEY|(?:UNIQUE|FULLTEXT|SPATIAL)\s+(?:KEY|INDEX)|KEY|INDEX'
  2653 						.       'PRIMARY\s+KEY|(?:UNIQUE|FULLTEXT|SPATIAL)\s+(?:KEY|INDEX)|KEY|INDEX'
  2301 						.   ')'
  2654 						.   ')'
  2302 						.   '\s+'                         // Followed by at least one white space character.
  2655 						.   '\s+'                         // Followed by at least one white space character.
  2303 						.   '(?:'                         // Name of the index. Optional if type is PRIMARY KEY.
  2656 						.   '(?:'                         // Name of the index. Optional if type is PRIMARY KEY.
  2315 						.   '\)'                          // Closing bracket for the columns.
  2668 						.   '\)'                          // Closing bracket for the columns.
  2316 						. '$/im',
  2669 						. '$/im',
  2317 						$fld,
  2670 						$fld,
  2318 						$index_matches
  2671 						$index_matches
  2319 					);
  2672 					);
       
  2673 					// phpcs:enable
  2320 
  2674 
  2321 					// Uppercase the index type and normalize space characters.
  2675 					// Uppercase the index type and normalize space characters.
  2322 					$index_type = strtoupper( preg_replace( '/\s+/', ' ', trim( $index_matches['index_type'] ) ) );
  2676 					$index_type = strtoupper( preg_replace( '/\s+/', ' ', trim( $index_matches['index_type'] ) ) );
  2323 
  2677 
  2324 					// 'INDEX' is a synonym for 'KEY', standardize on 'KEY'.
  2678 					// 'INDEX' is a synonym for 'KEY', standardize on 'KEY'.
  2332 
  2686 
  2333 					// Normalize columns.
  2687 					// Normalize columns.
  2334 					foreach ( $index_columns as $id => &$index_column ) {
  2688 					foreach ( $index_columns as $id => &$index_column ) {
  2335 						// Extract column name and number of indexed characters (sub_part).
  2689 						// Extract column name and number of indexed characters (sub_part).
  2336 						preg_match(
  2690 						preg_match(
  2337 							  '/'
  2691 							'/'
  2338 							.   '`?'                      // Name can be escaped with a backtick.
  2692 							. '`?'                      // Name can be escaped with a backtick.
  2339 							.       '(?P<column_name>'    // 1) Name of the column.
  2693 							. '(?P<column_name>'    // 1) Name of the column.
  2340 							.           '(?:[0-9a-zA-Z$_-]|[\xC2-\xDF][\x80-\xBF])+'
  2694 							. '(?:[0-9a-zA-Z$_-]|[\xC2-\xDF][\x80-\xBF])+'
  2341 							.       ')'
  2695 							. ')'
  2342 							.   '`?'                      // Name can be escaped with a backtick.
  2696 							. '`?'                      // Name can be escaped with a backtick.
  2343 							.   '(?:'                     // Optional sub part.
  2697 							. '(?:'                     // Optional sub part.
  2344 							.       '\s*'                 // Optional white space character between name and opening bracket.
  2698 							. '\s*'                 // Optional white space character between name and opening bracket.
  2345 							.       '\('                  // Opening bracket for the sub part.
  2699 							. '\('                  // Opening bracket for the sub part.
  2346 							.           '\s*'             // Optional white space character after opening bracket.
  2700 							. '\s*'             // Optional white space character after opening bracket.
  2347 							.           '(?P<sub_part>'
  2701 							. '(?P<sub_part>'
  2348 							.               '\d+'         // 2) Number of indexed characters.
  2702 							. '\d+'         // 2) Number of indexed characters.
  2349 							.           ')'
  2703 							. ')'
  2350 							.           '\s*'             // Optional white space character before closing bracket.
  2704 							. '\s*'             // Optional white space character before closing bracket.
  2351 							.        '\)'                 // Closing bracket for the sub part.
  2705 							. '\)'                 // Closing bracket for the sub part.
  2352 							.   ')?'
  2706 							. ')?'
  2353 							. '/',
  2707 							. '/',
  2354 							$index_column,
  2708 							$index_column,
  2355 							$index_column_matches
  2709 							$index_column_matches
  2356 						);
  2710 						);
  2357 
  2711 
  2366 							$index_column .= '(' . $index_column_matches['sub_part'] . ')';
  2720 							$index_column .= '(' . $index_column_matches['sub_part'] . ')';
  2367 						}
  2721 						}
  2368 					}
  2722 					}
  2369 
  2723 
  2370 					// Build the normalized index definition and add it to the list of indices.
  2724 					// Build the normalized index definition and add it to the list of indices.
  2371 					$indices[] = "{$index_type} {$index_name} (" . implode( ',', $index_columns ) . ")";
  2725 					$indices[]                  = "{$index_type} {$index_name} (" . implode( ',', $index_columns ) . ')';
  2372 					$indices_without_subparts[] = "{$index_type} {$index_name} (" . implode( ',', $index_columns_without_subparts ) . ")";
  2726 					$indices_without_subparts[] = "{$index_type} {$index_name} (" . implode( ',', $index_columns_without_subparts ) . ')';
  2373 
  2727 
  2374 					// Destroy no longer needed variables.
  2728 					// Destroy no longer needed variables.
  2375 					unset( $index_column, $index_column_matches, $index_matches, $index_type, $index_name, $index_columns, $index_columns_without_subparts );
  2729 					unset( $index_column, $index_column_matches, $index_matches, $index_type, $index_name, $index_columns, $index_columns_without_subparts );
  2376 
  2730 
  2377 					break;
  2731 					break;
  2384 		}
  2738 		}
  2385 
  2739 
  2386 		// For every field in the table.
  2740 		// For every field in the table.
  2387 		foreach ( $tablefields as $tablefield ) {
  2741 		foreach ( $tablefields as $tablefield ) {
  2388 			$tablefield_field_lowercased = strtolower( $tablefield->Field );
  2742 			$tablefield_field_lowercased = strtolower( $tablefield->Field );
  2389 			$tablefield_type_lowercased = strtolower( $tablefield->Type );
  2743 			$tablefield_type_lowercased  = strtolower( $tablefield->Type );
  2390 
  2744 
  2391 			// If the table field exists in the field array ...
  2745 			// If the table field exists in the field array ...
  2392 			if ( array_key_exists( $tablefield_field_lowercased, $cfields ) ) {
  2746 			if ( array_key_exists( $tablefield_field_lowercased, $cfields ) ) {
  2393 
  2747 
  2394 				// Get the field type from the query.
  2748 				// Get the field type from the query.
  2395 				preg_match( '|`?' . $tablefield->Field . '`? ([^ ]*( unsigned)?)|i', $cfields[ $tablefield_field_lowercased ], $matches );
  2749 				preg_match( '|`?' . $tablefield->Field . '`? ([^ ]*( unsigned)?)|i', $cfields[ $tablefield_field_lowercased ], $matches );
  2396 				$fieldtype = $matches[1];
  2750 				$fieldtype            = $matches[1];
  2397 				$fieldtype_lowercased = strtolower( $fieldtype );
  2751 				$fieldtype_lowercased = strtolower( $fieldtype );
  2398 
  2752 
  2399 				// Is actual field type different from the field type in query?
  2753 				// Is actual field type different from the field type in query?
  2400 				if ($tablefield->Type != $fieldtype) {
  2754 				if ( $tablefield->Type != $fieldtype ) {
  2401 					$do_change = true;
  2755 					$do_change = true;
  2402 					if ( in_array( $fieldtype_lowercased, $text_fields ) && in_array( $tablefield_type_lowercased, $text_fields ) ) {
  2756 					if ( in_array( $fieldtype_lowercased, $text_fields ) && in_array( $tablefield_type_lowercased, $text_fields ) ) {
  2403 						if ( array_search( $fieldtype_lowercased, $text_fields ) < array_search( $tablefield_type_lowercased, $text_fields ) ) {
  2757 						if ( array_search( $fieldtype_lowercased, $text_fields ) < array_search( $tablefield_type_lowercased, $text_fields ) ) {
  2404 							$do_change = false;
  2758 							$do_change = false;
  2405 						}
  2759 						}
  2411 						}
  2765 						}
  2412 					}
  2766 					}
  2413 
  2767 
  2414 					if ( $do_change ) {
  2768 					if ( $do_change ) {
  2415 						// Add a query to change the column type.
  2769 						// Add a query to change the column type.
  2416 						$cqueries[] = "ALTER TABLE {$table} CHANGE COLUMN `{$tablefield->Field}` " . $cfields[ $tablefield_field_lowercased ];
  2770 						$cqueries[]                                      = "ALTER TABLE {$table} CHANGE COLUMN `{$tablefield->Field}` " . $cfields[ $tablefield_field_lowercased ];
  2417 						$for_update[$table.'.'.$tablefield->Field] = "Changed type of {$table}.{$tablefield->Field} from {$tablefield->Type} to {$fieldtype}";
  2771 						$for_update[ $table . '.' . $tablefield->Field ] = "Changed type of {$table}.{$tablefield->Field} from {$tablefield->Type} to {$fieldtype}";
  2418 					}
  2772 					}
  2419 				}
  2773 				}
  2420 
  2774 
  2421 				// Get the default value from the array.
  2775 				// Get the default value from the array.
  2422 				if ( preg_match( "| DEFAULT '(.*?)'|i", $cfields[ $tablefield_field_lowercased ], $matches ) ) {
  2776 				if ( preg_match( "| DEFAULT '(.*?)'|i", $cfields[ $tablefield_field_lowercased ], $matches ) ) {
  2423 					$default_value = $matches[1];
  2777 					$default_value = $matches[1];
  2424 					if ($tablefield->Default != $default_value) {
  2778 					if ( $tablefield->Default != $default_value ) {
  2425 						// Add a query to change the column's default value
  2779 						// Add a query to change the column's default value
  2426 						$cqueries[] = "ALTER TABLE {$table} ALTER COLUMN `{$tablefield->Field}` SET DEFAULT '{$default_value}'";
  2780 						$cqueries[]                                      = "ALTER TABLE {$table} ALTER COLUMN `{$tablefield->Field}` SET DEFAULT '{$default_value}'";
  2427 						$for_update[$table.'.'.$tablefield->Field] = "Changed default value of {$table}.{$tablefield->Field} from {$tablefield->Default} to {$default_value}";
  2781 						$for_update[ $table . '.' . $tablefield->Field ] = "Changed default value of {$table}.{$tablefield->Field} from {$tablefield->Default} to {$default_value}";
  2428 					}
  2782 					}
  2429 				}
  2783 				}
  2430 
  2784 
  2431 				// Remove the field from the array (so it's not added).
  2785 				// Remove the field from the array (so it's not added).
  2432 				unset( $cfields[ $tablefield_field_lowercased ] );
  2786 				unset( $cfields[ $tablefield_field_lowercased ] );
  2434 				// This field exists in the table, but not in the creation queries?
  2788 				// This field exists in the table, but not in the creation queries?
  2435 			}
  2789 			}
  2436 		}
  2790 		}
  2437 
  2791 
  2438 		// For every remaining field specified for the table.
  2792 		// For every remaining field specified for the table.
  2439 		foreach ($cfields as $fieldname => $fielddef) {
  2793 		foreach ( $cfields as $fieldname => $fielddef ) {
  2440 			// Push a query line into $cqueries that adds the field to that table.
  2794 			// Push a query line into $cqueries that adds the field to that table.
  2441 			$cqueries[] = "ALTER TABLE {$table} ADD COLUMN $fielddef";
  2795 			$cqueries[]                              = "ALTER TABLE {$table} ADD COLUMN $fielddef";
  2442 			$for_update[$table.'.'.$fieldname] = 'Added column '.$table.'.'.$fieldname;
  2796 			$for_update[ $table . '.' . $fieldname ] = 'Added column ' . $table . '.' . $fieldname;
  2443 		}
  2797 		}
  2444 
  2798 
  2445 		// Index stuff goes here. Fetch the table index structure from the database.
  2799 		// Index stuff goes here. Fetch the table index structure from the database.
  2446 		$tableindices = $wpdb->get_results("SHOW INDEX FROM {$table};");
  2800 		$tableindices = $wpdb->get_results( "SHOW INDEX FROM {$table};" );
  2447 
  2801 
  2448 		if ($tableindices) {
  2802 		if ( $tableindices ) {
  2449 			// Clear the index array.
  2803 			// Clear the index array.
  2450 			$index_ary = array();
  2804 			$index_ary = array();
  2451 
  2805 
  2452 			// For every index in the table.
  2806 			// For every index in the table.
  2453 			foreach ($tableindices as $tableindex) {
  2807 			foreach ( $tableindices as $tableindex ) {
  2454 
  2808 
  2455 				// Add the index to the index data array.
  2809 				// Add the index to the index data array.
  2456 				$keyname = strtolower( $tableindex->Key_name );
  2810 				$keyname                             = strtolower( $tableindex->Key_name );
  2457 				$index_ary[$keyname]['columns'][] = array('fieldname' => $tableindex->Column_name, 'subpart' => $tableindex->Sub_part);
  2811 				$index_ary[ $keyname ]['columns'][]  = array(
  2458 				$index_ary[$keyname]['unique'] = ($tableindex->Non_unique == 0)?true:false;
  2812 					'fieldname' => $tableindex->Column_name,
  2459 				$index_ary[$keyname]['index_type'] = $tableindex->Index_type;
  2813 					'subpart'   => $tableindex->Sub_part,
       
  2814 				);
       
  2815 				$index_ary[ $keyname ]['unique']     = ( $tableindex->Non_unique == 0 ) ? true : false;
       
  2816 				$index_ary[ $keyname ]['index_type'] = $tableindex->Index_type;
  2460 			}
  2817 			}
  2461 
  2818 
  2462 			// For each actual index in the index array.
  2819 			// For each actual index in the index array.
  2463 			foreach ($index_ary as $index_name => $index_data) {
  2820 			foreach ( $index_ary as $index_name => $index_data ) {
  2464 
  2821 
  2465 				// Build a create string to compare to the query.
  2822 				// Build a create string to compare to the query.
  2466 				$index_string = '';
  2823 				$index_string = '';
  2467 				if ($index_name == 'primary') {
  2824 				if ( $index_name == 'primary' ) {
  2468 					$index_string .= 'PRIMARY ';
  2825 					$index_string .= 'PRIMARY ';
  2469 				} elseif ( $index_data['unique'] ) {
  2826 				} elseif ( $index_data['unique'] ) {
  2470 					$index_string .= 'UNIQUE ';
  2827 					$index_string .= 'UNIQUE ';
  2471 				}
  2828 				}
  2472 				if ( 'FULLTEXT' === strtoupper( $index_data['index_type'] ) ) {
  2829 				if ( 'FULLTEXT' === strtoupper( $index_data['index_type'] ) ) {
  2474 				}
  2831 				}
  2475 				if ( 'SPATIAL' === strtoupper( $index_data['index_type'] ) ) {
  2832 				if ( 'SPATIAL' === strtoupper( $index_data['index_type'] ) ) {
  2476 					$index_string .= 'SPATIAL ';
  2833 					$index_string .= 'SPATIAL ';
  2477 				}
  2834 				}
  2478 				$index_string .= 'KEY ';
  2835 				$index_string .= 'KEY ';
  2479 				if ( 'primary' !== $index_name  ) {
  2836 				if ( 'primary' !== $index_name ) {
  2480 					$index_string .= '`' . $index_name . '`';
  2837 					$index_string .= '`' . $index_name . '`';
  2481 				}
  2838 				}
  2482 				$index_columns = '';
  2839 				$index_columns = '';
  2483 
  2840 
  2484 				// For each column in the index.
  2841 				// For each column in the index.
  2485 				foreach ($index_data['columns'] as $column_data) {
  2842 				foreach ( $index_data['columns'] as $column_data ) {
  2486 					if ( $index_columns != '' ) {
  2843 					if ( $index_columns != '' ) {
  2487 						$index_columns .= ',';
  2844 						$index_columns .= ',';
  2488 					}
  2845 					}
  2489 
  2846 
  2490 					// Add the field to the column list string.
  2847 					// Add the field to the column list string.
  2504 		}
  2861 		}
  2505 
  2862 
  2506 		// For every remaining index specified for the table.
  2863 		// For every remaining index specified for the table.
  2507 		foreach ( (array) $indices as $index ) {
  2864 		foreach ( (array) $indices as $index ) {
  2508 			// Push a query line into $cqueries that adds the index to that table.
  2865 			// Push a query line into $cqueries that adds the index to that table.
  2509 			$cqueries[] = "ALTER TABLE {$table} ADD $index";
  2866 			$cqueries[]   = "ALTER TABLE {$table} ADD $index";
  2510 			$for_update[] = 'Added index ' . $table . ' ' . $index;
  2867 			$for_update[] = 'Added index ' . $table . ' ' . $index;
  2511 		}
  2868 		}
  2512 
  2869 
  2513 		// Remove the original table creation query from processing.
  2870 		// Remove the original table creation query from processing.
  2514 		unset( $cqueries[ $table ], $for_update[ $table ] );
  2871 		unset( $cqueries[ $table ], $for_update[ $table ] );
  2515 	}
  2872 	}
  2516 
  2873 
  2517 	$allqueries = array_merge($cqueries, $iqueries);
  2874 	$allqueries = array_merge( $cqueries, $iqueries );
  2518 	if ($execute) {
  2875 	if ( $execute ) {
  2519 		foreach ($allqueries as $query) {
  2876 		foreach ( $allqueries as $query ) {
  2520 			$wpdb->query($query);
  2877 			$wpdb->query( $query );
  2521 		}
  2878 		}
  2522 	}
  2879 	}
  2523 
  2880 
  2524 	return $for_update;
  2881 	return $for_update;
  2525 }
  2882 }
  2537  * @param string $tables Optional. Which set of tables to update. Default is 'all'.
  2894  * @param string $tables Optional. Which set of tables to update. Default is 'all'.
  2538  */
  2895  */
  2539 function make_db_current( $tables = 'all' ) {
  2896 function make_db_current( $tables = 'all' ) {
  2540 	$alterations = dbDelta( $tables );
  2897 	$alterations = dbDelta( $tables );
  2541 	echo "<ol>\n";
  2898 	echo "<ol>\n";
  2542 	foreach ($alterations as $alteration) echo "<li>$alteration</li>\n";
  2899 	foreach ( $alterations as $alteration ) {
       
  2900 		echo "<li>$alteration</li>\n";
       
  2901 	}
  2543 	echo "</ol>\n";
  2902 	echo "</ol>\n";
  2544 }
  2903 }
  2545 
  2904 
  2546 /**
  2905 /**
  2547  * Updates the database tables to a new schema, but without displaying results.
  2906  * Updates the database tables to a new schema, but without displaying results.
  2568  *
  2927  *
  2569  * @param string $theme_name The name of the theme.
  2928  * @param string $theme_name The name of the theme.
  2570  * @param string $template   The directory name of the theme.
  2929  * @param string $template   The directory name of the theme.
  2571  * @return bool
  2930  * @return bool
  2572  */
  2931  */
  2573 function make_site_theme_from_oldschool($theme_name, $template) {
  2932 function make_site_theme_from_oldschool( $theme_name, $template ) {
  2574 	$home_path = get_home_path();
  2933 	$home_path = get_home_path();
  2575 	$site_dir = WP_CONTENT_DIR . "/themes/$template";
  2934 	$site_dir  = WP_CONTENT_DIR . "/themes/$template";
  2576 
  2935 
  2577 	if (! file_exists("$home_path/index.php"))
  2936 	if ( ! file_exists( "$home_path/index.php" ) ) {
  2578 		return false;
  2937 		return false;
       
  2938 	}
  2579 
  2939 
  2580 	/*
  2940 	/*
  2581 	 * Copy files from the old locations to the site theme.
  2941 	 * Copy files from the old locations to the site theme.
  2582 	 * TODO: This does not copy arbitrary include dependencies. Only the standard WP files are copied.
  2942 	 * TODO: This does not copy arbitrary include dependencies. Only the standard WP files are copied.
  2583 	 */
  2943 	 */
  2584 	$files = array('index.php' => 'index.php', 'wp-layout.css' => 'style.css', 'wp-comments.php' => 'comments.php', 'wp-comments-popup.php' => 'comments-popup.php');
  2944 	$files = array(
  2585 
  2945 		'index.php'             => 'index.php',
  2586 	foreach ($files as $oldfile => $newfile) {
  2946 		'wp-layout.css'         => 'style.css',
  2587 		if ($oldfile == 'index.php')
  2947 		'wp-comments.php'       => 'comments.php',
       
  2948 		'wp-comments-popup.php' => 'comments-popup.php',
       
  2949 	);
       
  2950 
       
  2951 	foreach ( $files as $oldfile => $newfile ) {
       
  2952 		if ( $oldfile == 'index.php' ) {
  2588 			$oldpath = $home_path;
  2953 			$oldpath = $home_path;
  2589 		else
  2954 		} else {
  2590 			$oldpath = ABSPATH;
  2955 			$oldpath = ABSPATH;
       
  2956 		}
  2591 
  2957 
  2592 		// Check to make sure it's not a new index.
  2958 		// Check to make sure it's not a new index.
  2593 		if ($oldfile == 'index.php') {
  2959 		if ( $oldfile == 'index.php' ) {
  2594 			$index = implode('', file("$oldpath/$oldfile"));
  2960 			$index = implode( '', file( "$oldpath/$oldfile" ) );
  2595 			if (strpos($index, 'WP_USE_THEMES') !== false) {
  2961 			if ( strpos( $index, 'WP_USE_THEMES' ) !== false ) {
  2596 				if (! @copy(WP_CONTENT_DIR . '/themes/' . WP_DEFAULT_THEME . '/index.php', "$site_dir/$newfile"))
  2962 				if ( ! @copy( WP_CONTENT_DIR . '/themes/' . WP_DEFAULT_THEME . '/index.php', "$site_dir/$newfile" ) ) {
  2597 					return false;
  2963 					return false;
       
  2964 				}
  2598 
  2965 
  2599 				// Don't copy anything.
  2966 				// Don't copy anything.
  2600 				continue;
  2967 				continue;
  2601 			}
  2968 			}
  2602 		}
  2969 		}
  2603 
  2970 
  2604 		if (! @copy("$oldpath/$oldfile", "$site_dir/$newfile"))
  2971 		if ( ! @copy( "$oldpath/$oldfile", "$site_dir/$newfile" ) ) {
  2605 			return false;
  2972 			return false;
  2606 
  2973 		}
  2607 		chmod("$site_dir/$newfile", 0777);
  2974 
       
  2975 		chmod( "$site_dir/$newfile", 0777 );
  2608 
  2976 
  2609 		// Update the blog header include in each file.
  2977 		// Update the blog header include in each file.
  2610 		$lines = explode("\n", implode('', file("$site_dir/$newfile")));
  2978 		$lines = explode( "\n", implode( '', file( "$site_dir/$newfile" ) ) );
  2611 		if ($lines) {
  2979 		if ( $lines ) {
  2612 			$f = fopen("$site_dir/$newfile", 'w');
  2980 			$f = fopen( "$site_dir/$newfile", 'w' );
  2613 
  2981 
  2614 			foreach ($lines as $line) {
  2982 			foreach ( $lines as $line ) {
  2615 				if (preg_match('/require.*wp-blog-header/', $line))
  2983 				if ( preg_match( '/require.*wp-blog-header/', $line ) ) {
  2616 					$line = '//' . $line;
  2984 					$line = '//' . $line;
       
  2985 				}
  2617 
  2986 
  2618 				// Update stylesheet references.
  2987 				// Update stylesheet references.
  2619 				$line = str_replace("<?php echo __get_option('siteurl'); ?>/wp-layout.css", "<?php bloginfo('stylesheet_url'); ?>", $line);
  2988 				$line = str_replace( "<?php echo __get_option('siteurl'); ?>/wp-layout.css", "<?php bloginfo('stylesheet_url'); ?>", $line );
  2620 
  2989 
  2621 				// Update comments template inclusion.
  2990 				// Update comments template inclusion.
  2622 				$line = str_replace("<?php include(ABSPATH . 'wp-comments.php'); ?>", "<?php comments_template(); ?>", $line);
  2991 				$line = str_replace( "<?php include(ABSPATH . 'wp-comments.php'); ?>", '<?php comments_template(); ?>', $line );
  2623 
  2992 
  2624 				fwrite($f, "{$line}\n");
  2993 				fwrite( $f, "{$line}\n" );
  2625 			}
  2994 			}
  2626 			fclose($f);
  2995 			fclose( $f );
  2627 		}
  2996 		}
  2628 	}
  2997 	}
  2629 
  2998 
  2630 	// Add a theme header.
  2999 	// Add a theme header.
  2631 	$header = "/*\nTheme Name: $theme_name\nTheme URI: " . __get_option('siteurl') . "\nDescription: A theme automatically created by the update.\nVersion: 1.0\nAuthor: Moi\n*/\n";
  3000 	$header = "/*\nTheme Name: $theme_name\nTheme URI: " . __get_option( 'siteurl' ) . "\nDescription: A theme automatically created by the update.\nVersion: 1.0\nAuthor: Moi\n*/\n";
  2632 
  3001 
  2633 	$stylelines = file_get_contents("$site_dir/style.css");
  3002 	$stylelines = file_get_contents( "$site_dir/style.css" );
  2634 	if ($stylelines) {
  3003 	if ( $stylelines ) {
  2635 		$f = fopen("$site_dir/style.css", 'w');
  3004 		$f = fopen( "$site_dir/style.css", 'w' );
  2636 
  3005 
  2637 		fwrite($f, $header);
  3006 		fwrite( $f, $header );
  2638 		fwrite($f, $stylelines);
  3007 		fwrite( $f, $stylelines );
  2639 		fclose($f);
  3008 		fclose( $f );
  2640 	}
  3009 	}
  2641 
  3010 
  2642 	return true;
  3011 	return true;
  2643 }
  3012 }
  2644 
  3013 
  2651  *
  3020  *
  2652  * @param string $theme_name The name of the theme.
  3021  * @param string $theme_name The name of the theme.
  2653  * @param string $template   The directory name of the theme.
  3022  * @param string $template   The directory name of the theme.
  2654  * @return false|void
  3023  * @return false|void
  2655  */
  3024  */
  2656 function make_site_theme_from_default($theme_name, $template) {
  3025 function make_site_theme_from_default( $theme_name, $template ) {
  2657 	$site_dir = WP_CONTENT_DIR . "/themes/$template";
  3026 	$site_dir    = WP_CONTENT_DIR . "/themes/$template";
  2658 	$default_dir = WP_CONTENT_DIR . '/themes/' . WP_DEFAULT_THEME;
  3027 	$default_dir = WP_CONTENT_DIR . '/themes/' . WP_DEFAULT_THEME;
  2659 
  3028 
  2660 	// Copy files from the default theme to the site theme.
  3029 	// Copy files from the default theme to the site theme.
  2661 	//$files = array('index.php', 'comments.php', 'comments-popup.php', 'footer.php', 'header.php', 'sidebar.php', 'style.css');
  3030 	//$files = array('index.php', 'comments.php', 'comments-popup.php', 'footer.php', 'header.php', 'sidebar.php', 'style.css');
  2662 
  3031 
  2663 	$theme_dir = @ opendir($default_dir);
  3032 	$theme_dir = @ opendir( $default_dir );
  2664 	if ($theme_dir) {
  3033 	if ( $theme_dir ) {
  2665 		while(($theme_file = readdir( $theme_dir )) !== false) {
  3034 		while ( ( $theme_file = readdir( $theme_dir ) ) !== false ) {
  2666 			if (is_dir("$default_dir/$theme_file"))
  3035 			if ( is_dir( "$default_dir/$theme_file" ) ) {
  2667 				continue;
  3036 				continue;
  2668 			if (! @copy("$default_dir/$theme_file", "$site_dir/$theme_file"))
  3037 			}
       
  3038 			if ( ! @copy( "$default_dir/$theme_file", "$site_dir/$theme_file" ) ) {
  2669 				return;
  3039 				return;
  2670 			chmod("$site_dir/$theme_file", 0777);
  3040 			}
  2671 		}
  3041 			chmod( "$site_dir/$theme_file", 0777 );
  2672 	}
  3042 		}
  2673 	@closedir($theme_dir);
  3043 	}
       
  3044 	@closedir( $theme_dir );
  2674 
  3045 
  2675 	// Rewrite the theme header.
  3046 	// Rewrite the theme header.
  2676 	$stylelines = explode("\n", implode('', file("$site_dir/style.css")));
  3047 	$stylelines = explode( "\n", implode( '', file( "$site_dir/style.css" ) ) );
  2677 	if ($stylelines) {
  3048 	if ( $stylelines ) {
  2678 		$f = fopen("$site_dir/style.css", 'w');
  3049 		$f = fopen( "$site_dir/style.css", 'w' );
  2679 
  3050 
  2680 		foreach ($stylelines as $line) {
  3051 		foreach ( $stylelines as $line ) {
  2681 			if (strpos($line, 'Theme Name:') !== false) $line = 'Theme Name: ' . $theme_name;
  3052 			if ( strpos( $line, 'Theme Name:' ) !== false ) {
  2682 			elseif (strpos($line, 'Theme URI:') !== false) $line = 'Theme URI: ' . __get_option('url');
  3053 				$line = 'Theme Name: ' . $theme_name;
  2683 			elseif (strpos($line, 'Description:') !== false) $line = 'Description: Your theme.';
  3054 			} elseif ( strpos( $line, 'Theme URI:' ) !== false ) {
  2684 			elseif (strpos($line, 'Version:') !== false) $line = 'Version: 1';
  3055 				$line = 'Theme URI: ' . __get_option( 'url' );
  2685 			elseif (strpos($line, 'Author:') !== false) $line = 'Author: You';
  3056 			} elseif ( strpos( $line, 'Description:' ) !== false ) {
  2686 			fwrite($f, $line . "\n");
  3057 				$line = 'Description: Your theme.';
  2687 		}
  3058 			} elseif ( strpos( $line, 'Version:' ) !== false ) {
  2688 		fclose($f);
  3059 				$line = 'Version: 1';
       
  3060 			} elseif ( strpos( $line, 'Author:' ) !== false ) {
       
  3061 				$line = 'Author: You';
       
  3062 			}
       
  3063 			fwrite( $f, $line . "\n" );
       
  3064 		}
       
  3065 		fclose( $f );
  2689 	}
  3066 	}
  2690 
  3067 
  2691 	// Copy the images.
  3068 	// Copy the images.
  2692 	umask(0);
  3069 	umask( 0 );
  2693 	if (! mkdir("$site_dir/images", 0777)) {
  3070 	if ( ! mkdir( "$site_dir/images", 0777 ) ) {
  2694 		return false;
  3071 		return false;
  2695 	}
  3072 	}
  2696 
  3073 
  2697 	$images_dir = @ opendir("$default_dir/images");
  3074 	$images_dir = @ opendir( "$default_dir/images" );
  2698 	if ($images_dir) {
  3075 	if ( $images_dir ) {
  2699 		while(($image = readdir($images_dir)) !== false) {
  3076 		while ( ( $image = readdir( $images_dir ) ) !== false ) {
  2700 			if (is_dir("$default_dir/images/$image"))
  3077 			if ( is_dir( "$default_dir/images/$image" ) ) {
  2701 				continue;
  3078 				continue;
  2702 			if (! @copy("$default_dir/images/$image", "$site_dir/images/$image"))
  3079 			}
       
  3080 			if ( ! @copy( "$default_dir/images/$image", "$site_dir/images/$image" ) ) {
  2703 				return;
  3081 				return;
  2704 			chmod("$site_dir/images/$image", 0777);
  3082 			}
  2705 		}
  3083 			chmod( "$site_dir/images/$image", 0777 );
  2706 	}
  3084 		}
  2707 	@closedir($images_dir);
  3085 	}
       
  3086 	@closedir( $images_dir );
  2708 }
  3087 }
  2709 
  3088 
  2710 /**
  3089 /**
  2711  * Creates a site theme.
  3090  * Creates a site theme.
  2712  *
  3091  *
  2716  *
  3095  *
  2717  * @return false|string
  3096  * @return false|string
  2718  */
  3097  */
  2719 function make_site_theme() {
  3098 function make_site_theme() {
  2720 	// Name the theme after the blog.
  3099 	// Name the theme after the blog.
  2721 	$theme_name = __get_option('blogname');
  3100 	$theme_name = __get_option( 'blogname' );
  2722 	$template = sanitize_title($theme_name);
  3101 	$template   = sanitize_title( $theme_name );
  2723 	$site_dir = WP_CONTENT_DIR . "/themes/$template";
  3102 	$site_dir   = WP_CONTENT_DIR . "/themes/$template";
  2724 
  3103 
  2725 	// If the theme already exists, nothing to do.
  3104 	// If the theme already exists, nothing to do.
  2726 	if ( is_dir($site_dir)) {
  3105 	if ( is_dir( $site_dir ) ) {
  2727 		return false;
  3106 		return false;
  2728 	}
  3107 	}
  2729 
  3108 
  2730 	// We must be able to write to the themes dir.
  3109 	// We must be able to write to the themes dir.
  2731 	if (! is_writable(WP_CONTENT_DIR . "/themes")) {
  3110 	if ( ! is_writable( WP_CONTENT_DIR . '/themes' ) ) {
  2732 		return false;
  3111 		return false;
  2733 	}
  3112 	}
  2734 
  3113 
  2735 	umask(0);
  3114 	umask( 0 );
  2736 	if (! mkdir($site_dir, 0777)) {
  3115 	if ( ! mkdir( $site_dir, 0777 ) ) {
  2737 		return false;
  3116 		return false;
  2738 	}
  3117 	}
  2739 
  3118 
  2740 	if (file_exists(ABSPATH . 'wp-layout.css')) {
  3119 	if ( file_exists( ABSPATH . 'wp-layout.css' ) ) {
  2741 		if (! make_site_theme_from_oldschool($theme_name, $template)) {
  3120 		if ( ! make_site_theme_from_oldschool( $theme_name, $template ) ) {
  2742 			// TODO: rm -rf the site theme directory.
  3121 			// TODO: rm -rf the site theme directory.
  2743 			return false;
  3122 			return false;
  2744 		}
  3123 		}
  2745 	} else {
  3124 	} else {
  2746 		if (! make_site_theme_from_default($theme_name, $template))
  3125 		if ( ! make_site_theme_from_default( $theme_name, $template ) ) {
  2747 			// TODO: rm -rf the site theme directory.
  3126 			// TODO: rm -rf the site theme directory.
  2748 			return false;
  3127 			return false;
       
  3128 		}
  2749 	}
  3129 	}
  2750 
  3130 
  2751 	// Make the new site theme active.
  3131 	// Make the new site theme active.
  2752 	$current_template = __get_option('template');
  3132 	$current_template = __get_option( 'template' );
  2753 	if ($current_template == WP_DEFAULT_THEME) {
  3133 	if ( $current_template == WP_DEFAULT_THEME ) {
  2754 		update_option('template', $template);
  3134 		update_option( 'template', $template );
  2755 		update_option('stylesheet', $template);
  3135 		update_option( 'stylesheet', $template );
  2756 	}
  3136 	}
  2757 	return $template;
  3137 	return $template;
  2758 }
  3138 }
  2759 
  3139 
  2760 /**
  3140 /**
  2763  * @since 2.0.0
  3143  * @since 2.0.0
  2764  *
  3144  *
  2765  * @param int $level User level.
  3145  * @param int $level User level.
  2766  * @return string User role name.
  3146  * @return string User role name.
  2767  */
  3147  */
  2768 function translate_level_to_role($level) {
  3148 function translate_level_to_role( $level ) {
  2769 	switch ($level) {
  3149 	switch ( $level ) {
  2770 	case 10:
  3150 		case 10:
  2771 	case 9:
  3151 		case 9:
  2772 	case 8:
  3152 		case 8:
  2773 		return 'administrator';
  3153 			return 'administrator';
  2774 	case 7:
  3154 		case 7:
  2775 	case 6:
  3155 		case 6:
  2776 	case 5:
  3156 		case 5:
  2777 		return 'editor';
  3157 			return 'editor';
  2778 	case 4:
  3158 		case 4:
  2779 	case 3:
  3159 		case 3:
  2780 	case 2:
  3160 		case 2:
  2781 		return 'author';
  3161 			return 'author';
  2782 	case 1:
  3162 		case 1:
  2783 		return 'contributor';
  3163 			return 'contributor';
  2784 	case 0:
  3164 		case 0:
  2785 		return 'subscriber';
  3165 			return 'subscriber';
  2786 	}
  3166 	}
  2787 }
  3167 }
  2788 
  3168 
  2789 /**
  3169 /**
  2790  * Checks the version of the installed MySQL binary.
  3170  * Checks the version of the installed MySQL binary.
  2794  * @global wpdb  $wpdb
  3174  * @global wpdb  $wpdb
  2795  */
  3175  */
  2796 function wp_check_mysql_version() {
  3176 function wp_check_mysql_version() {
  2797 	global $wpdb;
  3177 	global $wpdb;
  2798 	$result = $wpdb->check_database_version();
  3178 	$result = $wpdb->check_database_version();
  2799 	if ( is_wp_error( $result ) )
  3179 	if ( is_wp_error( $result ) ) {
  2800 		die( $result->get_error_message() );
  3180 		wp_die( $result );
       
  3181 	}
  2801 }
  3182 }
  2802 
  3183 
  2803 /**
  3184 /**
  2804  * Disables the Automattic widgets plugin, which was merged into core.
  3185  * Disables the Automattic widgets plugin, which was merged into core.
  2805  *
  3186  *
  2826  * @global wpdb $wpdb WordPress database abstraction object.
  3207  * @global wpdb $wpdb WordPress database abstraction object.
  2827  */
  3208  */
  2828 function maybe_disable_link_manager() {
  3209 function maybe_disable_link_manager() {
  2829 	global $wp_current_db_version, $wpdb;
  3210 	global $wp_current_db_version, $wpdb;
  2830 
  3211 
  2831 	if ( $wp_current_db_version >= 22006 && get_option( 'link_manager_enabled' ) && ! $wpdb->get_var( "SELECT link_id FROM $wpdb->links LIMIT 1" ) )
  3212 	if ( $wp_current_db_version >= 22006 && get_option( 'link_manager_enabled' ) && ! $wpdb->get_var( "SELECT link_id FROM $wpdb->links LIMIT 1" ) ) {
  2832 		update_option( 'link_manager_enabled', 0 );
  3213 		update_option( 'link_manager_enabled', 0 );
       
  3214 	}
  2833 }
  3215 }
  2834 
  3216 
  2835 /**
  3217 /**
  2836  * Runs before the schema is upgraded.
  3218  * Runs before the schema is upgraded.
  2837  *
  3219  *
  2844 	global $wp_current_db_version, $wpdb;
  3226 	global $wp_current_db_version, $wpdb;
  2845 
  3227 
  2846 	// Upgrade versions prior to 2.9
  3228 	// Upgrade versions prior to 2.9
  2847 	if ( $wp_current_db_version < 11557 ) {
  3229 	if ( $wp_current_db_version < 11557 ) {
  2848 		// Delete duplicate options. Keep the option with the highest option_id.
  3230 		// Delete duplicate options. Keep the option with the highest option_id.
  2849 		$wpdb->query("DELETE o1 FROM $wpdb->options AS o1 JOIN $wpdb->options AS o2 USING (`option_name`) WHERE o2.option_id > o1.option_id");
  3231 		$wpdb->query( "DELETE o1 FROM $wpdb->options AS o1 JOIN $wpdb->options AS o2 USING (`option_name`) WHERE o2.option_id > o1.option_id" );
  2850 
  3232 
  2851 		// Drop the old primary key and add the new.
  3233 		// Drop the old primary key and add the new.
  2852 		$wpdb->query("ALTER TABLE $wpdb->options DROP PRIMARY KEY, ADD PRIMARY KEY(option_id)");
  3234 		$wpdb->query( "ALTER TABLE $wpdb->options DROP PRIMARY KEY, ADD PRIMARY KEY(option_id)" );
  2853 
  3235 
  2854 		// Drop the old option_name index. dbDelta() doesn't do the drop.
  3236 		// Drop the old option_name index. dbDelta() doesn't do the drop.
  2855 		$wpdb->query("ALTER TABLE $wpdb->options DROP INDEX option_name");
  3237 		$wpdb->query( "ALTER TABLE $wpdb->options DROP INDEX option_name" );
  2856 	}
  3238 	}
  2857 
  3239 
  2858 	// Multisite schema upgrades.
  3240 	// Multisite schema upgrades.
  2859 	if ( $wp_current_db_version < 25448 && is_multisite() && wp_should_upgrade_global_tables() ) {
  3241 	if ( $wp_current_db_version < 25448 && is_multisite() && wp_should_upgrade_global_tables() ) {
  2860 
  3242 
  2892 			maybe_convert_table_to_utf8mb4( $wpdb->termmeta );
  3274 			maybe_convert_table_to_utf8mb4( $wpdb->termmeta );
  2893 		}
  3275 		}
  2894 	}
  3276 	}
  2895 }
  3277 }
  2896 
  3278 
  2897 if ( !function_exists( 'install_global_terms' ) ) :
  3279 if ( ! function_exists( 'install_global_terms' ) ) :
  2898 /**
  3280 	/**
  2899  * Install global terms.
  3281 	 * Install global terms.
  2900  *
  3282 	 *
  2901  * @since 3.0.0
  3283 	 * @since 3.0.0
  2902  *
  3284 	 *
  2903  * @global wpdb   $wpdb
  3285 	 * @global wpdb   $wpdb
  2904  * @global string $charset_collate
  3286 	 * @global string $charset_collate
  2905  */
  3287 	 */
  2906 function install_global_terms() {
  3288 	function install_global_terms() {
  2907 	global $wpdb, $charset_collate;
  3289 		global $wpdb, $charset_collate;
  2908 	$ms_queries = "
  3290 		$ms_queries = "
  2909 CREATE TABLE $wpdb->sitecategories (
  3291 CREATE TABLE $wpdb->sitecategories (
  2910   cat_ID bigint(20) NOT NULL auto_increment,
  3292   cat_ID bigint(20) NOT NULL auto_increment,
  2911   cat_name varchar(55) NOT NULL default '',
  3293   cat_name varchar(55) NOT NULL default '',
  2912   category_nicename varchar(200) NOT NULL default '',
  3294   category_nicename varchar(200) NOT NULL default '',
  2913   last_updated timestamp NOT NULL,
  3295   last_updated timestamp NOT NULL,
  2914   PRIMARY KEY  (cat_ID),
  3296   PRIMARY KEY  (cat_ID),
  2915   KEY category_nicename (category_nicename),
  3297   KEY category_nicename (category_nicename),
  2916   KEY last_updated (last_updated)
  3298   KEY last_updated (last_updated)
  2917 ) $charset_collate;
  3299 ) $charset_collate;
  2918 ";
  3300 ";
  2919 // now create tables
  3301 		// now create tables
  2920 	dbDelta( $ms_queries );
  3302 		dbDelta( $ms_queries );
  2921 }
  3303 	}
  2922 endif;
  3304 endif;
  2923 
  3305 
  2924 /**
  3306 /**
  2925  * Determine if global tables should be upgraded.
  3307  * Determine if global tables should be upgraded.
  2926  *
  3308  *