wp/wp-admin/includes/upgrade.php
changeset 5 5e2f62d02dcd
parent 0 d970ebf37754
child 7 cf61fcea0001
equal deleted inserted replaced
4:346c88efed21 5:5e2f62d02dcd
     1 <?php
     1 <?php
     2 /**
     2 /**
     3  * WordPress Upgrade API
     3  * WordPress Upgrade API
     4  *
     4  *
     5  * Most of the functions are pluggable and can be overwritten
     5  * Most of the functions are pluggable and can be overwritten.
     6  *
     6  *
     7  * @package WordPress
     7  * @package WordPress
     8  * @subpackage Administration
     8  * @subpackage Administration
     9  */
     9  */
    10 
    10 
    18 /** WordPress Schema API */
    18 /** WordPress Schema API */
    19 require_once(ABSPATH . 'wp-admin/includes/schema.php');
    19 require_once(ABSPATH . 'wp-admin/includes/schema.php');
    20 
    20 
    21 if ( !function_exists('wp_install') ) :
    21 if ( !function_exists('wp_install') ) :
    22 /**
    22 /**
    23  * Installs the blog
    23  * Installs the site.
    24  *
    24  *
    25  * {@internal Missing Long Description}}
    25  * Runs the required functions to set up and populate the database,
       
    26  * including primary admin user and initial options.
    26  *
    27  *
    27  * @since 2.1.0
    28  * @since 2.1.0
    28  *
    29  *
    29  * @param string $blog_title Blog title.
    30  * @param string $blog_title    Blog title.
    30  * @param string $user_name User's username.
    31  * @param string $user_name     User's username.
    31  * @param string $user_email User's email.
    32  * @param string $user_email    User's email.
    32  * @param bool $public Whether blog is public.
    33  * @param bool   $public        Whether blog is public.
    33  * @param null $deprecated Optional. Not used.
    34  * @param string $deprecated    Optional. Not used.
    34  * @param string $user_password Optional. User's chosen password. Will default to a random password.
    35  * @param string $user_password Optional. User's chosen password. Default empty (random password).
    35  * @return array Array keys 'url', 'user_id', 'password', 'password_message'.
    36  * @param string $language      Optional. Language chosen. Default empty.
    36  */
    37  * @return array Array keys 'url', 'user_id', 'password', and 'password_message'.
    37 function wp_install( $blog_title, $user_name, $user_email, $public, $deprecated = '', $user_password = '' ) {
    38  */
       
    39 function wp_install( $blog_title, $user_name, $user_email, $public, $deprecated = '', $user_password = '', $language = '' ) {
    38 	if ( !empty( $deprecated ) )
    40 	if ( !empty( $deprecated ) )
    39 		_deprecated_argument( __FUNCTION__, '2.6' );
    41 		_deprecated_argument( __FUNCTION__, '2.6' );
    40 
    42 
    41 	wp_check_mysql_version();
    43 	wp_check_mysql_version();
    42 	wp_cache_flush();
    44 	wp_cache_flush();
    46 
    48 
    47 	update_option('blogname', $blog_title);
    49 	update_option('blogname', $blog_title);
    48 	update_option('admin_email', $user_email);
    50 	update_option('admin_email', $user_email);
    49 	update_option('blog_public', $public);
    51 	update_option('blog_public', $public);
    50 
    52 
       
    53 	if ( $language ) {
       
    54 		update_option( 'WPLANG', $language );
       
    55 	}
       
    56 
    51 	$guessurl = wp_guess_url();
    57 	$guessurl = wp_guess_url();
    52 
    58 
    53 	update_option('siteurl', $guessurl);
    59 	update_option('siteurl', $guessurl);
    54 
    60 
    55 	// If not a public blog, don't ping.
    61 	// If not a public blog, don't ping.
    56 	if ( ! $public )
    62 	if ( ! $public )
    57 		update_option('default_pingback_flag', 0);
    63 		update_option('default_pingback_flag', 0);
    58 
    64 
    59 	// Create default user. If the user already exists, the user tables are
    65 	/*
    60 	// being shared among blogs. Just set the role in that case.
    66 	 * Create default user. If the user already exists, the user tables are
       
    67 	 * being shared among blogs. Just set the role in that case.
       
    68 	 */
    61 	$user_id = username_exists($user_name);
    69 	$user_id = username_exists($user_name);
    62 	$user_password = trim($user_password);
    70 	$user_password = trim($user_password);
    63 	$email_password = false;
    71 	$email_password = false;
    64 	if ( !$user_id && empty($user_password) ) {
    72 	if ( !$user_id && empty($user_password) ) {
    65 		$user_password = wp_generate_password( 12, false );
    73 		$user_password = wp_generate_password( 12, false );
    66 		$message = __('<strong><em>Note that password</em></strong> carefully! It is a <em>random</em> password that was generated just for you.');
    74 		$message = __('<strong><em>Note that password</em></strong> carefully! It is a <em>random</em> password that was generated just for you.');
    67 		$user_id = wp_create_user($user_name, $user_password, $user_email);
    75 		$user_id = wp_create_user($user_name, $user_password, $user_email);
    68 		update_user_option($user_id, 'default_password_nag', true, true);
    76 		update_user_option($user_id, 'default_password_nag', true, true);
    69 		$email_password = true;
    77 		$email_password = true;
    70 	} else if ( !$user_id ) {
    78 	} elseif ( ! $user_id ) {
    71 		// Password has been provided
    79 		// Password has been provided
    72 		$message = '<em>'.__('Your chosen password.').'</em>';
    80 		$message = '<em>'.__('Your chosen password.').'</em>';
    73 		$user_id = wp_create_user($user_name, $user_password, $user_email);
    81 		$user_id = wp_create_user($user_name, $user_password, $user_email);
    74 	} else {
    82 	} else {
    75 		$message = __('User already exists. Password inherited.');
    83 		$message = __('User already exists. Password inherited.');
    78 	$user = new WP_User($user_id);
    86 	$user = new WP_User($user_id);
    79 	$user->set_role('administrator');
    87 	$user->set_role('administrator');
    80 
    88 
    81 	wp_install_defaults($user_id);
    89 	wp_install_defaults($user_id);
    82 
    90 
       
    91 	wp_install_maybe_enable_pretty_permalinks();
       
    92 
    83 	flush_rewrite_rules();
    93 	flush_rewrite_rules();
    84 
    94 
    85 	wp_new_blog_notification($blog_title, $guessurl, $user_id, ($email_password ? $user_password : __('The password you chose during the install.') ) );
    95 	wp_new_blog_notification($blog_title, $guessurl, $user_id, ($email_password ? $user_password : __('The password you chose during the install.') ) );
    86 
    96 
    87 	wp_cache_flush();
    97 	wp_cache_flush();
    88 
    98 
       
    99 	/**
       
   100 	 * Fires after a site is fully installed.
       
   101 	 *
       
   102 	 * @since 3.9.0
       
   103 	 *
       
   104 	 * @param WP_User $user The site owner.
       
   105 	 */
       
   106 	do_action( 'wp_install', $user );
       
   107 
    89 	return array('url' => $guessurl, 'user_id' => $user_id, 'password' => $user_password, 'password_message' => $message);
   108 	return array('url' => $guessurl, 'user_id' => $user_id, 'password' => $user_password, 'password_message' => $message);
    90 }
   109 }
    91 endif;
   110 endif;
    92 
   111 
    93 if ( !function_exists('wp_install_defaults') ) :
   112 if ( !function_exists('wp_install_defaults') ) :
    94 /**
   113 /**
    95  * {@internal Missing Short Description}}
   114  * Creates the initial content for a newly-installed site.
    96  *
   115  *
    97  * {@internal Missing Long Description}}
   116  * Adds the default "Uncategorized" category, the first post (with comment),
       
   117  * first page, and default widgets for default theme for the current version.
    98  *
   118  *
    99  * @since 2.1.0
   119  * @since 2.1.0
   100  *
   120  *
   101  * @param int $user_id User ID.
   121  * @param int $user_id User ID.
   102  */
   122  */
   103 function wp_install_defaults($user_id) {
   123 function wp_install_defaults( $user_id ) {
   104 	global $wpdb, $wp_rewrite, $current_site, $table_prefix;
   124 	global $wpdb, $wp_rewrite, $table_prefix;
   105 
   125 
   106 	// Default category
   126 	// Default category
   107 	$cat_name = __('Uncategorized');
   127 	$cat_name = __('Uncategorized');
   108 	/* translators: Default category slug */
   128 	/* translators: Default category slug */
   109 	$cat_slug = sanitize_title(_x('Uncategorized', 'Default category slug'));
   129 	$cat_slug = sanitize_title(_x('Uncategorized', 'Default category slug'));
   122 	$wpdb->insert( $wpdb->terms, array('term_id' => $cat_id, 'name' => $cat_name, 'slug' => $cat_slug, 'term_group' => 0) );
   142 	$wpdb->insert( $wpdb->terms, array('term_id' => $cat_id, 'name' => $cat_name, 'slug' => $cat_slug, 'term_group' => 0) );
   123 	$wpdb->insert( $wpdb->term_taxonomy, array('term_id' => $cat_id, 'taxonomy' => 'category', 'description' => '', 'parent' => 0, 'count' => 1));
   143 	$wpdb->insert( $wpdb->term_taxonomy, array('term_id' => $cat_id, 'taxonomy' => 'category', 'description' => '', 'parent' => 0, 'count' => 1));
   124 	$cat_tt_id = $wpdb->insert_id;
   144 	$cat_tt_id = $wpdb->insert_id;
   125 
   145 
   126 	// First post
   146 	// First post
   127 	$now = date('Y-m-d H:i:s');
   147 	$now = current_time( 'mysql' );
   128 	$now_gmt = gmdate('Y-m-d H:i:s');
   148 	$now_gmt = current_time( 'mysql', 1 );
   129 	$first_post_guid = get_option('home') . '/?p=1';
   149 	$first_post_guid = get_option( 'home' ) . '/?p=1';
   130 
   150 
   131 	if ( is_multisite() ) {
   151 	if ( is_multisite() ) {
   132 		$first_post = get_site_option( 'first_post' );
   152 		$first_post = get_site_option( 'first_post' );
   133 
   153 
   134 		if ( empty($first_post) )
   154 		if ( empty($first_post) )
   135 			$first_post = __( 'Welcome to <a href="SITE_URL">SITE_NAME</a>. This is your first post. Edit or delete it, then start blogging!' );
   155 			$first_post = __( 'Welcome to <a href="SITE_URL">SITE_NAME</a>. This is your first post. Edit or delete it, then start blogging!' );
   136 
   156 
   137 		$first_post = str_replace( "SITE_URL", esc_url( network_home_url() ), $first_post );
   157 		$first_post = str_replace( "SITE_URL", esc_url( network_home_url() ), $first_post );
   138 		$first_post = str_replace( "SITE_NAME", $current_site->site_name, $first_post );
   158 		$first_post = str_replace( "SITE_NAME", get_current_site()->site_name, $first_post );
   139 	} else {
   159 	} else {
   140 		$first_post = __('Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!');
   160 		$first_post = __('Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!');
   141 	}
   161 	}
   142 
   162 
   143 	$wpdb->insert( $wpdb->posts, array(
   163 	$wpdb->insert( $wpdb->posts, array(
   159 								));
   179 								));
   160 	$wpdb->insert( $wpdb->term_relationships, array('term_taxonomy_id' => $cat_tt_id, 'object_id' => 1) );
   180 	$wpdb->insert( $wpdb->term_relationships, array('term_taxonomy_id' => $cat_tt_id, 'object_id' => 1) );
   161 
   181 
   162 	// Default comment
   182 	// Default comment
   163 	$first_comment_author = __('Mr WordPress');
   183 	$first_comment_author = __('Mr WordPress');
   164 	$first_comment_url = 'http://wordpress.org/';
   184 	$first_comment_url = 'https://wordpress.org/';
   165 	$first_comment = __('Hi, this is a comment.
   185 	$first_comment = __('Hi, this is a comment.
   166 To delete a comment, just log in and view the post&#039;s comments. There you will have the option to edit or delete them.');
   186 To delete a comment, just log in and view the post&#039;s comments. There you will have the option to edit or delete them.');
   167 	if ( is_multisite() ) {
   187 	if ( is_multisite() ) {
   168 		$first_comment_author = get_site_option( 'first_comment_author', $first_comment_author );
   188 		$first_comment_author = get_site_option( 'first_comment_author', $first_comment_author );
   169 		$first_comment_url = get_site_option( 'first_comment_url', network_home_url() );
   189 		$first_comment_url = get_site_option( 'first_comment_url', network_home_url() );
   216 	update_option( 'widget_recent-posts', array ( 2 => array ( 'title' => '', 'number' => 5 ), '_multiwidget' => 1 ) );
   236 	update_option( 'widget_recent-posts', array ( 2 => array ( 'title' => '', 'number' => 5 ), '_multiwidget' => 1 ) );
   217 	update_option( 'widget_recent-comments', array ( 2 => array ( 'title' => '', 'number' => 5 ), '_multiwidget' => 1 ) );
   237 	update_option( 'widget_recent-comments', array ( 2 => array ( 'title' => '', 'number' => 5 ), '_multiwidget' => 1 ) );
   218 	update_option( 'widget_archives', array ( 2 => array ( 'title' => '', 'count' => 0, 'dropdown' => 0 ), '_multiwidget' => 1 ) );
   238 	update_option( 'widget_archives', array ( 2 => array ( 'title' => '', 'count' => 0, 'dropdown' => 0 ), '_multiwidget' => 1 ) );
   219 	update_option( 'widget_categories', array ( 2 => array ( 'title' => '', 'count' => 0, 'hierarchical' => 0, 'dropdown' => 0 ), '_multiwidget' => 1 ) );
   239 	update_option( 'widget_categories', array ( 2 => array ( 'title' => '', 'count' => 0, 'hierarchical' => 0, 'dropdown' => 0 ), '_multiwidget' => 1 ) );
   220 	update_option( 'widget_meta', array ( 2 => array ( 'title' => '' ), '_multiwidget' => 1 ) );
   240 	update_option( 'widget_meta', array ( 2 => array ( 'title' => '' ), '_multiwidget' => 1 ) );
   221 	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 (),'array_version' => 3 ) );
   241 	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', ), 'array_version' => 3 ) );
   222 
   242 
   223 	if ( ! is_multisite() )
   243 	if ( ! is_multisite() )
   224 		update_user_meta( $user_id, 'show_welcome_panel', 1 );
   244 		update_user_meta( $user_id, 'show_welcome_panel', 1 );
   225 	elseif ( ! is_super_admin( $user_id ) && ! metadata_exists( 'user', $user_id, 'show_welcome_panel' ) )
   245 	elseif ( ! is_super_admin( $user_id ) && ! metadata_exists( 'user', $user_id, 'show_welcome_panel' ) )
   226 		update_user_meta( $user_id, 'show_welcome_panel', 2 );
   246 		update_user_meta( $user_id, 'show_welcome_panel', 2 );
   242 			$wpdb->delete( $wpdb->usermeta, array( 'user_id' => $user_id , 'meta_key' => $wpdb->base_prefix.'1_capabilities' ) );
   262 			$wpdb->delete( $wpdb->usermeta, array( 'user_id' => $user_id , 'meta_key' => $wpdb->base_prefix.'1_capabilities' ) );
   243 	}
   263 	}
   244 }
   264 }
   245 endif;
   265 endif;
   246 
   266 
       
   267 /**
       
   268  * Maybe enable pretty permalinks on install.
       
   269  *
       
   270  * If after enabling pretty permalinks don't work, fallback to query-string permalinks.
       
   271  *
       
   272  * @since 4.2.0
       
   273  *
       
   274  * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
       
   275  *
       
   276  * @return bool Whether pretty permalinks are enabled. False otherwise.
       
   277  */
       
   278 function wp_install_maybe_enable_pretty_permalinks() {
       
   279 	global $wp_rewrite;
       
   280 
       
   281 	// Bail if a permalink structure is already enabled.
       
   282 	if ( get_option( 'permalink_structure' ) ) {
       
   283 		return true;
       
   284 	}
       
   285 
       
   286 	/*
       
   287 	 * The Permalink structures to attempt.
       
   288 	 *
       
   289 	 * The first is designed for mod_rewrite or nginx rewriting.
       
   290 	 *
       
   291 	 * The second is PATHINFO-based permalinks for web server configurations
       
   292 	 * without a true rewrite module enabled.
       
   293 	 */
       
   294 	$permalink_structures = array(
       
   295 		'/%year%/%monthnum%/%day%/%postname%/',
       
   296 		'/index.php/%year%/%monthnum%/%day%/%postname%/'
       
   297 	);
       
   298 
       
   299 	foreach ( (array) $permalink_structures as $permalink_structure ) {
       
   300 		$wp_rewrite->set_permalink_structure( $permalink_structure );
       
   301 
       
   302 		/*
       
   303 	 	 * Flush rules with the hard option to force refresh of the web-server's
       
   304 	 	 * rewrite config file (e.g. .htaccess or web.config).
       
   305 	 	 */
       
   306 		$wp_rewrite->flush_rules( true );
       
   307 
       
   308 		// Test against a real WordPress Post, or if none were created, a random 404 page.
       
   309 		$test_url = get_permalink( 1 );
       
   310 
       
   311 		if ( ! $test_url ) {
       
   312 			$test_url = home_url( '/wordpress-check-for-rewrites/' );
       
   313 		}
       
   314 
       
   315 		/*
       
   316 	 	 * Send a request to the site, and check whether
       
   317 	 	 * the 'x-pingback' header is returned as expected.
       
   318 	 	 *
       
   319 	 	 * Uses wp_remote_get() instead of wp_remote_head() because web servers
       
   320 	 	 * can block head requests.
       
   321 	 	 */
       
   322 		$response          = wp_remote_get( $test_url, array( 'timeout' => 5 ) );
       
   323 		$x_pingback_header = wp_remote_retrieve_header( $response, 'x-pingback' );
       
   324 		$pretty_permalinks = $x_pingback_header && $x_pingback_header === get_bloginfo( 'pingback_url' );
       
   325 
       
   326 		if ( $pretty_permalinks ) {
       
   327 			return true;
       
   328 		}
       
   329 	}
       
   330 
       
   331 	/*
       
   332 	 * If it makes it this far, pretty permalinks failed.
       
   333 	 * Fallback to query-string permalinks.
       
   334 	 */
       
   335 	$wp_rewrite->set_permalink_structure( '' );
       
   336 	$wp_rewrite->flush_rules( true );
       
   337 
       
   338 	return false;
       
   339 }
       
   340 
   247 if ( !function_exists('wp_new_blog_notification') ) :
   341 if ( !function_exists('wp_new_blog_notification') ) :
   248 /**
   342 /**
   249  * {@internal Missing Short Description}}
   343  * Notifies the site admin that the setup is complete.
   250  *
   344  *
   251  * {@internal Missing Long Description}}
   345  * Sends an email with wp_mail to the new administrator that the site setup is complete,
       
   346  * and provides them with a record of their login credentials.
   252  *
   347  *
   253  * @since 2.1.0
   348  * @since 2.1.0
   254  *
   349  *
   255  * @param string $blog_title Blog title.
   350  * @param string $blog_title Blog title.
   256  * @param string $blog_url Blog url.
   351  * @param string $blog_url   Blog url.
   257  * @param int $user_id User ID.
   352  * @param int    $user_id    User ID.
   258  * @param string $password User's Password.
   353  * @param string $password   User's Password.
   259  */
   354  */
   260 function wp_new_blog_notification($blog_title, $blog_url, $user_id, $password) {
   355 function wp_new_blog_notification($blog_title, $blog_url, $user_id, $password) {
   261 	$user = new WP_User( $user_id );
   356 	$user = new WP_User( $user_id );
   262 	$email = $user->user_email;
   357 	$email = $user->user_email;
   263 	$name = $user->user_login;
   358 	$name = $user->user_login;
   264 	$message = sprintf(__("Your new WordPress site has been successfully set up at:
   359 	$login_url = wp_login_url();
       
   360 	$message = sprintf( __( "Your new WordPress site has been successfully set up at:
   265 
   361 
   266 %1\$s
   362 %1\$s
   267 
   363 
   268 You can log in to the administrator account with the following information:
   364 You can log in to the administrator account with the following information:
   269 
   365 
   270 Username: %2\$s
   366 Username: %2\$s
   271 Password: %3\$s
   367 Password: %3\$s
       
   368 Log in here: %4\$s
   272 
   369 
   273 We hope you enjoy your new site. Thanks!
   370 We hope you enjoy your new site. Thanks!
   274 
   371 
   275 --The WordPress Team
   372 --The WordPress Team
   276 http://wordpress.org/
   373 https://wordpress.org/
   277 "), $blog_url, $name, $password);
   374 "), $blog_url, $name, $password, $login_url );
   278 
   375 
   279 	@wp_mail($email, __('New WordPress Site'), $message);
   376 	@wp_mail($email, __('New WordPress Site'), $message);
   280 }
   377 }
   281 endif;
   378 endif;
   282 
   379 
   283 if ( !function_exists('wp_upgrade') ) :
   380 if ( !function_exists('wp_upgrade') ) :
   284 /**
   381 /**
   285  * Run WordPress Upgrade functions.
   382  * Runs WordPress Upgrade functions.
   286  *
   383  *
   287  * {@internal Missing Long Description}}
   384  * Upgrades the database if needed during a site update.
   288  *
   385  *
   289  * @since 2.1.0
   386  * @since 2.1.0
   290  *
   387  *
   291  * @return null
   388  * @return null If no update is necessary or site isn't completely installed, null.
   292  */
   389  */
   293 function wp_upgrade() {
   390 function wp_upgrade() {
   294 	global $wp_current_db_version, $wp_db_version, $wpdb;
   391 	global $wp_current_db_version, $wp_db_version, $wpdb;
   295 
   392 
   296 	$wp_current_db_version = __get_option('db_version');
   393 	$wp_current_db_version = __get_option('db_version');
   315 		if ( $wpdb->get_row( "SELECT blog_id FROM {$wpdb->blog_versions} WHERE blog_id = '{$wpdb->blogid}'" ) )
   412 		if ( $wpdb->get_row( "SELECT blog_id FROM {$wpdb->blog_versions} WHERE blog_id = '{$wpdb->blogid}'" ) )
   316 			$wpdb->query( "UPDATE {$wpdb->blog_versions} SET db_version = '{$wp_db_version}' WHERE blog_id = '{$wpdb->blogid}'" );
   413 			$wpdb->query( "UPDATE {$wpdb->blog_versions} SET db_version = '{$wp_db_version}' WHERE blog_id = '{$wpdb->blogid}'" );
   317 		else
   414 		else
   318 			$wpdb->query( "INSERT INTO {$wpdb->blog_versions} ( `blog_id` , `db_version` , `last_updated` ) VALUES ( '{$wpdb->blogid}', '{$wp_db_version}', NOW());" );
   415 			$wpdb->query( "INSERT INTO {$wpdb->blog_versions} ( `blog_id` , `db_version` , `last_updated` ) VALUES ( '{$wpdb->blogid}', '{$wp_db_version}', NOW());" );
   319 	}
   416 	}
       
   417 
       
   418 	/**
       
   419 	 * Fires after a site is fully upgraded.
       
   420 	 *
       
   421 	 * @since 3.9.0
       
   422 	 *
       
   423 	 * @param int $wp_db_version         The new $wp_db_version.
       
   424 	 * @param int $wp_current_db_version The old (current) $wp_db_version.
       
   425 	 */
       
   426 	do_action( 'wp_upgrade', $wp_db_version, $wp_current_db_version );
   320 }
   427 }
   321 endif;
   428 endif;
   322 
   429 
   323 /**
   430 /**
   324  * Functions to be called in install and upgrade scripts.
   431  * Functions to be called in install and upgrade scripts.
   325  *
   432  *
   326  * {@internal Missing Long Description}}
   433  * Contains conditional checks to determine which upgrade scripts to run,
       
   434  * based on database version and WP version being updated-to.
   327  *
   435  *
   328  * @since 1.0.1
   436  * @since 1.0.1
       
   437  *
       
   438  * @return null If no update is necessary, null.
   329  */
   439  */
   330 function upgrade_all() {
   440 function upgrade_all() {
   331 	global $wp_current_db_version, $wp_db_version;
   441 	global $wp_current_db_version, $wp_db_version;
   332 	$wp_current_db_version = __get_option('db_version');
   442 	$wp_current_db_version = __get_option('db_version');
   333 
   443 
   402 	if ( $wp_current_db_version < 22422 )
   512 	if ( $wp_current_db_version < 22422 )
   403 		upgrade_350();
   513 		upgrade_350();
   404 
   514 
   405 	if ( $wp_current_db_version < 25824 )
   515 	if ( $wp_current_db_version < 25824 )
   406 		upgrade_370();
   516 		upgrade_370();
       
   517 
       
   518 	if ( $wp_current_db_version < 26148 )
       
   519 		upgrade_372();
       
   520 
       
   521 	if ( $wp_current_db_version < 26691 )
       
   522 		upgrade_380();
       
   523 
       
   524 	if ( $wp_current_db_version < 29630 )
       
   525 		upgrade_400();
       
   526 
       
   527 	// Don't harsh my mellow. upgrade_422() must be called before
       
   528 	// upgrade_420() to catch bad comments prior to any auto-expansion of
       
   529 	// MySQL column widths.
       
   530 	if ( $wp_current_db_version < 31534 )
       
   531 		upgrade_422();
       
   532 
       
   533 	if ( $wp_current_db_version < 31351 )
       
   534 		upgrade_420();
   407 
   535 
   408 	maybe_disable_link_manager();
   536 	maybe_disable_link_manager();
   409 
   537 
   410 	maybe_disable_automattic_widgets();
   538 	maybe_disable_automattic_widgets();
   411 
   539 
   438 			$newtitle = sanitize_title($category->cat_name);
   566 			$newtitle = sanitize_title($category->cat_name);
   439 			$wpdb->update( $wpdb->categories, array('category_nicename' => $newtitle), array('cat_ID' => $category->cat_ID) );
   567 			$wpdb->update( $wpdb->categories, array('category_nicename' => $newtitle), array('cat_ID' => $category->cat_ID) );
   440 		}
   568 		}
   441 	}
   569 	}
   442 
   570 
   443 	$wpdb->query("UPDATE $wpdb->options SET option_value = REPLACE(option_value, 'wp-links/links-images/', 'wp-images/links/')
   571 	$sql = "UPDATE $wpdb->options
   444 	WHERE option_name LIKE 'links_rating_image%'
   572 		SET option_value = REPLACE(option_value, 'wp-links/links-images/', 'wp-images/links/')
   445 	AND option_value LIKE 'wp-links/links-images/%'");
   573 		WHERE option_name LIKE %s
       
   574 		AND option_value LIKE %s";
       
   575 	$wpdb->query( $wpdb->prepare( $sql, $wpdb->esc_like( 'links_rating_image' ) . '%', $wpdb->esc_like( 'wp-links/links-images/' ) . '%' ) );
   446 
   576 
   447 	$done_ids = $wpdb->get_results("SELECT DISTINCT post_id FROM $wpdb->post2cat");
   577 	$done_ids = $wpdb->get_results("SELECT DISTINCT post_id FROM $wpdb->post2cat");
   448 	if ($done_ids) :
   578 	if ($done_ids) :
       
   579 		$done_posts = array();
   449 		foreach ($done_ids as $done_id) :
   580 		foreach ($done_ids as $done_id) :
   450 			$done_posts[] = $done_id->post_id;
   581 			$done_posts[] = $done_id->post_id;
   451 		endforeach;
   582 		endforeach;
   452 		$catwhere = ' AND ID NOT IN (' . implode(',', $done_posts) . ')';
   583 		$catwhere = ' AND ID NOT IN (' . implode(',', $done_posts) . ')';
   453 	else:
   584 	else:
   591 		}
   722 		}
   592 	}
   723 	}
   593 
   724 
   594 	$active_plugins = __get_option('active_plugins');
   725 	$active_plugins = __get_option('active_plugins');
   595 
   726 
   596 	// If plugins are not stored in an array, they're stored in the old
   727 	/*
   597 	// newline separated format. Convert to new format.
   728 	 * If plugins are not stored in an array, they're stored in the old
       
   729 	 * newline separated format. Convert to new format.
       
   730 	 */
   598 	if ( !is_array( $active_plugins ) ) {
   731 	if ( !is_array( $active_plugins ) ) {
   599 		$active_plugins = explode("\n", trim($active_plugins));
   732 		$active_plugins = explode("\n", trim($active_plugins));
   600 		update_option('active_plugins', $active_plugins);
   733 		update_option('active_plugins', $active_plugins);
   601 	}
   734 	}
   602 
   735 
   682 	$wpdb->hide_errors();
   815 	$wpdb->hide_errors();
   683 	foreach ( $old_user_fields as $old )
   816 	foreach ( $old_user_fields as $old )
   684 		$wpdb->query("ALTER TABLE $wpdb->users DROP $old");
   817 		$wpdb->query("ALTER TABLE $wpdb->users DROP $old");
   685 	$wpdb->show_errors();
   818 	$wpdb->show_errors();
   686 
   819 
   687 	// populate comment_count field of posts table
   820 	// Populate comment_count field of posts table.
   688 	$comments = $wpdb->get_results( "SELECT comment_post_ID, COUNT(*) as c FROM $wpdb->comments WHERE comment_approved = '1' GROUP BY comment_post_ID" );
   821 	$comments = $wpdb->get_results( "SELECT comment_post_ID, COUNT(*) as c FROM $wpdb->comments WHERE comment_approved = '1' GROUP BY comment_post_ID" );
   689 	if ( is_array( $comments ) )
   822 	if ( is_array( $comments ) )
   690 		foreach ($comments as $comment)
   823 		foreach ($comments as $comment)
   691 			$wpdb->update( $wpdb->posts, array('comment_count' => $comment->c), array('ID' => $comment->comment_post_ID) );
   824 			$wpdb->update( $wpdb->posts, array('comment_count' => $comment->c), array('ID' => $comment->comment_post_ID) );
   692 
   825 
   693 	// Some alpha versions used a post status of object instead of attachment and put
   826 	/*
   694 	// the mime type in post_type instead of post_mime_type.
   827 	 * Some alpha versions used a post status of object instead of attachment
       
   828 	 * and put the mime type in post_type instead of post_mime_type.
       
   829 	 */
   695 	if ( $wp_current_db_version > 2541 && $wp_current_db_version <= 3091 ) {
   830 	if ( $wp_current_db_version > 2541 && $wp_current_db_version <= 3091 ) {
   696 		$objects = $wpdb->get_results("SELECT ID, post_type FROM $wpdb->posts WHERE post_status = 'object'");
   831 		$objects = $wpdb->get_results("SELECT ID, post_type FROM $wpdb->posts WHERE post_status = 'object'");
   697 		foreach ($objects as $object) {
   832 		foreach ($objects as $object) {
   698 			$wpdb->update( $wpdb->posts, array(	'post_status' => 'attachment',
   833 			$wpdb->update( $wpdb->posts, array(	'post_status' => 'attachment',
   699 												'post_mime_type' => $object->post_type,
   834 												'post_mime_type' => $object->post_type,
   724 			$type = 'post';
   859 			$type = 'post';
   725 
   860 
   726 			if ( 'static' == $status ) {
   861 			if ( 'static' == $status ) {
   727 				$status = 'publish';
   862 				$status = 'publish';
   728 				$type = 'page';
   863 				$type = 'page';
   729 			} else if ( 'attachment' == $status ) {
   864 			} elseif ( 'attachment' == $status ) {
   730 				$status = 'inherit';
   865 				$status = 'inherit';
   731 				$type = 'attachment';
   866 				$type = 'attachment';
   732 			}
   867 			}
   733 
   868 
   734 			$wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_status = %s, post_type = %s WHERE ID = %d", $status, $type, $post->ID) );
   869 			$wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_status = %s, post_type = %s WHERE ID = %d", $status, $type, $post->ID) );
   846 		$wpdb->insert( $wpdb->term_relationships, array('object_id' => $post_id, 'term_taxonomy_id' => $tt_id) );
   981 		$wpdb->insert( $wpdb->term_relationships, array('object_id' => $post_id, 'term_taxonomy_id' => $tt_id) );
   847 	}
   982 	}
   848 
   983 
   849 	// < 3570 we used linkcategories. >= 3570 we used categories and link2cat.
   984 	// < 3570 we used linkcategories. >= 3570 we used categories and link2cat.
   850 	if ( $wp_current_db_version < 3570 ) {
   985 	if ( $wp_current_db_version < 3570 ) {
   851 		// Create link_category terms for link categories. Create a map of link cat IDs
   986 		/*
   852 		// to link_category terms.
   987 		 * Create link_category terms for link categories. Create a map of link
       
   988 		 * cat IDs to link_category terms.
       
   989 		 */
   853 		$link_cat_id_map = array();
   990 		$link_cat_id_map = array();
   854 		$default_link_cat = 0;
   991 		$default_link_cat = 0;
   855 		$tt_ids = array();
   992 		$tt_ids = array();
   856 		$link_cats = $wpdb->get_results("SELECT cat_id, cat_name FROM " . $wpdb->prefix . 'linkcategories');
   993 		$link_cats = $wpdb->get_results("SELECT cat_id, cat_name FROM " . $wpdb->prefix . 'linkcategories');
   857 		foreach ( $link_cats as $category) {
   994 		foreach ( $link_cats as $category) {
   955  * Upgrade old slugs made in version 2.2.
  1092  * Upgrade old slugs made in version 2.2.
   956  *
  1093  *
   957  * @since 2.2.0
  1094  * @since 2.2.0
   958  */
  1095  */
   959 function upgrade_old_slugs() {
  1096 function upgrade_old_slugs() {
   960 	// upgrade people who were using the Redirect Old Slugs plugin
  1097 	// Upgrade people who were using the Redirect Old Slugs plugin.
   961 	global $wpdb;
  1098 	global $wpdb;
   962 	$wpdb->query("UPDATE $wpdb->postmeta SET meta_key = '_wp_old_slug' WHERE meta_key = 'old_slug'");
  1099 	$wpdb->query("UPDATE $wpdb->postmeta SET meta_key = '_wp_old_slug' WHERE meta_key = 'old_slug'");
   963 }
  1100 }
   964 
  1101 
   965 /**
  1102 /**
  1073 	if ( $wp_current_db_version < 14139 && is_multisite() && is_main_site() && ! defined( 'MULTISITE' ) && get_site_option( 'siteurl' ) === false )
  1210 	if ( $wp_current_db_version < 14139 && is_multisite() && is_main_site() && ! defined( 'MULTISITE' ) && get_site_option( 'siteurl' ) === false )
  1074 		add_site_option( 'siteurl', '' );
  1211 		add_site_option( 'siteurl', '' );
  1075 
  1212 
  1076 	// 3.0 screen options key name changes.
  1213 	// 3.0 screen options key name changes.
  1077 	if ( is_main_site() && !defined('DO_NOT_UPGRADE_GLOBAL_TABLES') ) {
  1214 	if ( is_main_site() && !defined('DO_NOT_UPGRADE_GLOBAL_TABLES') ) {
  1078 		$prefix = like_escape($wpdb->base_prefix);
  1215 		$sql = "DELETE FROM $wpdb->usermeta
  1079 		$wpdb->query( "DELETE FROM $wpdb->usermeta WHERE meta_key LIKE '{$prefix}%meta-box-hidden%' OR meta_key LIKE '{$prefix}%closedpostboxes%' OR meta_key LIKE '{$prefix}%manage-%-columns-hidden%' OR meta_key LIKE '{$prefix}%meta-box-order%' OR meta_key LIKE '{$prefix}%metaboxorder%' OR meta_key LIKE '{$prefix}%screen_layout%'
  1216 			WHERE meta_key LIKE %s
  1080 					 OR meta_key = 'manageedittagscolumnshidden' OR meta_key='managecategoriescolumnshidden' OR meta_key = 'manageedit-tagscolumnshidden' OR meta_key = 'manageeditcolumnshidden' OR meta_key = 'categories_per_page' OR meta_key = 'edit_tags_per_page'" );
  1217 			OR meta_key LIKE %s
       
  1218 			OR meta_key LIKE %s
       
  1219 			OR meta_key LIKE %s
       
  1220 			OR meta_key LIKE %s
       
  1221 			OR meta_key LIKE %s
       
  1222 			OR meta_key = 'manageedittagscolumnshidden'
       
  1223 			OR meta_key = 'managecategoriescolumnshidden'
       
  1224 			OR meta_key = 'manageedit-tagscolumnshidden'
       
  1225 			OR meta_key = 'manageeditcolumnshidden'
       
  1226 			OR meta_key = 'categories_per_page'
       
  1227 			OR meta_key = 'edit_tags_per_page'";
       
  1228 		$prefix = $wpdb->esc_like( $wpdb->base_prefix );
       
  1229 		$wpdb->query( $wpdb->prepare( $sql,
       
  1230 			$prefix . '%' . $wpdb->esc_like( 'meta-box-hidden' ) . '%',
       
  1231 			$prefix . '%' . $wpdb->esc_like( 'closedpostboxes' ) . '%',
       
  1232 			$prefix . '%' . $wpdb->esc_like( 'manage-'	   ) . '%' . $wpdb->esc_like( '-columns-hidden' ) . '%',
       
  1233 			$prefix . '%' . $wpdb->esc_like( 'meta-box-order'  ) . '%',
       
  1234 			$prefix . '%' . $wpdb->esc_like( 'metaboxorder'    ) . '%',
       
  1235 			$prefix . '%' . $wpdb->esc_like( 'screen_layout'   ) . '%'
       
  1236 		) );
  1081 	}
  1237 	}
  1082 
  1238 
  1083 }
  1239 }
  1084 
  1240 
  1085 /**
  1241 /**
  1221 	if ( $wp_current_db_version < 25824 )
  1377 	if ( $wp_current_db_version < 25824 )
  1222 		wp_clear_scheduled_hook( 'wp_auto_updates_maybe_update' );
  1378 		wp_clear_scheduled_hook( 'wp_auto_updates_maybe_update' );
  1223 }
  1379 }
  1224 
  1380 
  1225 /**
  1381 /**
  1226  * Execute network level changes
  1382  * Execute changes made in WordPress 3.7.2.
       
  1383  *
       
  1384  * @since 3.7.2
       
  1385  * @since 3.8.0
       
  1386  */
       
  1387 function upgrade_372() {
       
  1388 	global $wp_current_db_version;
       
  1389 	if ( $wp_current_db_version < 26148 )
       
  1390 		wp_clear_scheduled_hook( 'wp_maybe_auto_update' );
       
  1391 }
       
  1392 
       
  1393 /**
       
  1394  * Execute changes made in WordPress 3.8.0.
       
  1395  *
       
  1396  * @since 3.8.0
       
  1397  */
       
  1398 function upgrade_380() {
       
  1399 	global $wp_current_db_version;
       
  1400 	if ( $wp_current_db_version < 26691 ) {
       
  1401 		deactivate_plugins( array( 'mp6/mp6.php' ), true );
       
  1402 	}
       
  1403 }
       
  1404 
       
  1405 /**
       
  1406  * Execute changes made in WordPress 4.0.0.
       
  1407  *
       
  1408  * @since 4.0.0
       
  1409  */
       
  1410 function upgrade_400() {
       
  1411 	global $wp_current_db_version;
       
  1412 	if ( $wp_current_db_version < 29630 ) {
       
  1413 		if ( ! is_multisite() && false === get_option( 'WPLANG' ) ) {
       
  1414 			if ( defined( 'WPLANG' ) && ( '' !== WPLANG ) && in_array( WPLANG, get_available_languages() ) ) {
       
  1415 				update_option( 'WPLANG', WPLANG );
       
  1416 			} else {
       
  1417 				update_option( 'WPLANG', '' );
       
  1418 			}
       
  1419 		}
       
  1420 	}
       
  1421 }
       
  1422 
       
  1423 /**
       
  1424  * Execute changes made in WordPress 4.2.0.
       
  1425  *
       
  1426  * @since 4.2.0
       
  1427  */
       
  1428 function upgrade_420() {
       
  1429 	global $wp_current_db_version, $wpdb;
       
  1430 
       
  1431 	if ( $wp_current_db_version < 31351 && $wpdb->charset === 'utf8mb4' ) {
       
  1432 		if ( is_multisite() ) {
       
  1433 			$tables = $wpdb->tables( 'blog' );
       
  1434 		} else {
       
  1435 			$tables = $wpdb->tables( 'all' );
       
  1436 		}
       
  1437 
       
  1438 		foreach ( $tables as $table ) {
       
  1439 			maybe_convert_table_to_utf8mb4( $table );
       
  1440 		}
       
  1441 	}
       
  1442 }
       
  1443 
       
  1444 /**
       
  1445  * Execute changes made in WordPress 4.2.1.
       
  1446  *
       
  1447  * @since 4.2.1
       
  1448  */
       
  1449 function upgrade_421() {
       
  1450 }
       
  1451 
       
  1452 /**
       
  1453  * Execute changes made in WordPress 4.2.2.
       
  1454  *
       
  1455  * @since 4.2.2
       
  1456  */
       
  1457 function upgrade_422() {
       
  1458 	global $wp_current_db_version, $wpdb;
       
  1459 
       
  1460 	if ( $wp_current_db_version < 31534 ) {
       
  1461 		$content_length = $wpdb->get_col_length( $wpdb->comments, 'comment_content' );
       
  1462 
       
  1463 		if ( is_wp_error( $content_length ) ) {
       
  1464 			return;
       
  1465 		}
       
  1466 
       
  1467 		if ( false === $content_length ) {
       
  1468 			$content_length = array(
       
  1469 				'type'   => 'byte',
       
  1470 				'length' => 65535,
       
  1471 			);
       
  1472 		} elseif ( ! is_array( $content_length ) ) {
       
  1473 			$length = (int) $content_length > 0 ? (int) $content_length : 65535;
       
  1474 			$content_length = array(
       
  1475 				'type'	 => 'byte',
       
  1476 				'length' => $length
       
  1477 			);
       
  1478 		}
       
  1479 
       
  1480 		if ( 'byte' !== $content_length['type'] || 0 === $content_length['length'] ) {
       
  1481 			// Sites with malformed DB schemas are on their own.
       
  1482 			return;
       
  1483 		}
       
  1484 
       
  1485 		$allowed_length = intval( $content_length['length'] ) - 10;
       
  1486 
       
  1487 		$comments = $wpdb->get_results(
       
  1488 			"SELECT `comment_ID` FROM `{$wpdb->comments}`
       
  1489 				WHERE `comment_date_gmt` > '2015-04-26'
       
  1490 				AND LENGTH( `comment_content` ) >= {$allowed_length}
       
  1491 				AND ( `comment_content` LIKE '%<%' OR `comment_content` LIKE '%>%' )"
       
  1492 		);
       
  1493 
       
  1494 		foreach ( $comments as $comment ) {
       
  1495 			wp_delete_comment( $comment->comment_ID, true );
       
  1496 		}
       
  1497 	}
       
  1498 }
       
  1499 
       
  1500 /**
       
  1501  * Executes network-level upgrade routines.
  1227  *
  1502  *
  1228  * @since 3.0.0
  1503  * @since 3.0.0
  1229  */
  1504  */
  1230 function upgrade_network() {
  1505 function upgrade_network() {
  1231 	global $wp_current_db_version, $wpdb;
  1506 	global $wp_current_db_version, $wpdb;
  1232 
  1507 
  1233 	// Always
  1508 	// Always.
  1234 	if ( is_main_network() ) {
  1509 	if ( is_main_network() ) {
  1235 		// Deletes all expired transients.
  1510 		/*
  1236 		// The multi-table delete syntax is used to delete the transient record from table a,
  1511 		 * Deletes all expired transients. The multi-table delete syntax is used
  1237 		// and the corresponding transient_timeout record from table b.
  1512 		 * to delete the transient record from table a, and the corresponding
       
  1513 		 * transient_timeout record from table b.
       
  1514 		 */
  1238 		$time = time();
  1515 		$time = time();
  1239 		$wpdb->query("DELETE a, b FROM $wpdb->sitemeta a, $wpdb->sitemeta b WHERE
  1516 		$sql = "DELETE a, b FROM $wpdb->sitemeta a, $wpdb->sitemeta b
  1240 			a.meta_key LIKE '\_site\_transient\_%' AND
  1517 			WHERE a.meta_key LIKE %s
  1241 			a.meta_key NOT LIKE '\_site\_transient\_timeout\_%' AND
  1518 			AND a.meta_key NOT LIKE %s
  1242 			b.meta_key = CONCAT( '_site_transient_timeout_', SUBSTRING( a.meta_key, 17 ) )
  1519 			AND b.meta_key = CONCAT( '_site_transient_timeout_', SUBSTRING( a.meta_key, 17 ) )
  1243 			AND b.meta_value < $time");
  1520 			AND b.meta_value < %d";
  1244 	}
  1521 		$wpdb->query( $wpdb->prepare( $sql, $wpdb->esc_like( '_site_transient_' ) . '%', $wpdb->esc_like ( '_site_transient_timeout_' ) . '%', $time ) );
  1245 
  1522 	}
  1246 	// 2.8
  1523 
       
  1524 	// 2.8.
  1247 	if ( $wp_current_db_version < 11549 ) {
  1525 	if ( $wp_current_db_version < 11549 ) {
  1248 		$wpmu_sitewide_plugins = get_site_option( 'wpmu_sitewide_plugins' );
  1526 		$wpmu_sitewide_plugins = get_site_option( 'wpmu_sitewide_plugins' );
  1249 		$active_sitewide_plugins = get_site_option( 'active_sitewide_plugins' );
  1527 		$active_sitewide_plugins = get_site_option( 'active_sitewide_plugins' );
  1250 		if ( $wpmu_sitewide_plugins ) {
  1528 		if ( $wpmu_sitewide_plugins ) {
  1251 			if ( !$active_sitewide_plugins )
  1529 			if ( !$active_sitewide_plugins )
  1313 			$illegal_name = reset( $illegal_names );
  1591 			$illegal_name = reset( $illegal_names );
  1314 			$illegal_names = explode( ' ', $illegal_name );
  1592 			$illegal_names = explode( ' ', $illegal_name );
  1315 			update_site_option( 'illegal_names', $illegal_names );
  1593 			update_site_option( 'illegal_names', $illegal_names );
  1316 		}
  1594 		}
  1317 	}
  1595 	}
  1318 }
  1596 
  1319 
  1597 	// 4.2
  1320 // The functions we use to actually do stuff
  1598 	if ( $wp_current_db_version < 31351 && $wpdb->charset === 'utf8mb4' ) {
  1321 
  1599 		if ( ! ( defined( 'DO_NOT_UPGRADE_GLOBAL_TABLES' ) && DO_NOT_UPGRADE_GLOBAL_TABLES ) ) {
  1322 // General
  1600 			$wpdb->query( "ALTER TABLE $wpdb->usermeta DROP INDEX meta_key, ADD INDEX meta_key(meta_key(191))" );
  1323 
  1601 			$wpdb->query( "ALTER TABLE $wpdb->site DROP INDEX domain, ADD INDEX domain(domain(140),path(51))" );
  1324 /**
  1602 			$wpdb->query( "ALTER TABLE $wpdb->sitemeta DROP INDEX meta_key, ADD INDEX meta_key(meta_key(191))" );
  1325  * {@internal Missing Short Description}}
  1603 			$wpdb->query( "ALTER TABLE $wpdb->signups DROP INDEX domain_path, ADD INDEX domain_path(domain(140),path(51))" );
  1326  *
  1604 
  1327  * {@internal Missing Long Description}}
  1605 			$tables = $wpdb->tables( 'global' );
       
  1606 
       
  1607 			foreach ( $tables as $table ) {
       
  1608 				maybe_convert_table_to_utf8mb4( $table );
       
  1609 			}
       
  1610 		}
       
  1611 	}
       
  1612 
       
  1613 	// 4.2.2
       
  1614 	if ( $wp_current_db_version < 31535 && 'utf8mb4' === $wpdb->charset ) {
       
  1615 		if ( ! ( defined( 'DO_NOT_UPGRADE_GLOBAL_TABLES' ) && DO_NOT_UPGRADE_GLOBAL_TABLES ) ) {
       
  1616 			$upgrade = false;
       
  1617 			$indexes = $wpdb->get_results( "SHOW INDEXES FROM $wpdb->signups" );
       
  1618 			foreach( $indexes as $index ) {
       
  1619 				if ( 'domain_path' == $index->Key_name && 'domain' == $index->Column_name && 140 != $index->Sub_part ) {
       
  1620 					$upgrade = true;
       
  1621 					break;
       
  1622 				}
       
  1623 			}
       
  1624 
       
  1625 			if ( $upgrade ) {
       
  1626 				$wpdb->query( "ALTER TABLE $wpdb->signups DROP INDEX domain_path, ADD INDEX domain_path(domain(140),path(51))" );
       
  1627 			}
       
  1628 		}
       
  1629 	}
       
  1630 }
       
  1631 
       
  1632 //
       
  1633 // General functions we use to actually do stuff
       
  1634 //
       
  1635 
       
  1636 /**
       
  1637  * Creates a table in the database if it doesn't already exist.
       
  1638  *
       
  1639  * This method checks for an existing database and creates a new one if it's not
       
  1640  * already present. It doesn't rely on MySQL's "IF NOT EXISTS" statement, but chooses
       
  1641  * to query all tables first and then run the SQL statement creating the table.
  1328  *
  1642  *
  1329  * @since 1.0.0
  1643  * @since 1.0.0
  1330  *
  1644  *
  1331  * @param string $table_name Database table name to create.
  1645  * @param string $table_name Database table name to create.
  1332  * @param string $create_ddl SQL statement to create table.
  1646  * @param string $create_ddl SQL statement to create table.
  1333  * @return bool If table already exists or was created by function.
  1647  * @return bool If table already exists or was created by function.
  1334  */
  1648  */
  1335 function maybe_create_table($table_name, $create_ddl) {
  1649 function maybe_create_table($table_name, $create_ddl) {
  1336 	global $wpdb;
  1650 	global $wpdb;
  1337 	if ( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") == $table_name )
  1651 
       
  1652 	$query = $wpdb->prepare( "SHOW TABLES LIKE %s", $wpdb->esc_like( $table_name ) );
       
  1653 
       
  1654 	if ( $wpdb->get_var( $query ) == $table_name ) {
  1338 		return true;
  1655 		return true;
  1339 	//didn't find it try to create it.
  1656 	}
  1340 	$q = $wpdb->query($create_ddl);
  1657 
  1341 	// we cannot directly tell that whether this succeeded!
  1658 	// Didn't find it try to create it..
  1342 	if ( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") == $table_name )
  1659 	$wpdb->query($create_ddl);
       
  1660 
       
  1661 	// We cannot directly tell that whether this succeeded!
       
  1662 	if ( $wpdb->get_var( $query ) == $table_name ) {
  1343 		return true;
  1663 		return true;
       
  1664 	}
  1344 	return false;
  1665 	return false;
  1345 }
  1666 }
  1346 
  1667 
  1347 /**
  1668 /**
  1348  * {@internal Missing Short Description}}
  1669  * Drops a specified index from a table.
  1349  *
       
  1350  * {@internal Missing Long Description}}
       
  1351  *
  1670  *
  1352  * @since 1.0.1
  1671  * @since 1.0.1
  1353  *
  1672  *
  1354  * @param string $table Database table name.
  1673  * @param string $table Database table name.
  1355  * @param string $index Index name to drop.
  1674  * @param string $index Index name to drop.
  1366 	$wpdb->show_errors();
  1685 	$wpdb->show_errors();
  1367 	return true;
  1686 	return true;
  1368 }
  1687 }
  1369 
  1688 
  1370 /**
  1689 /**
  1371  * {@internal Missing Short Description}}
  1690  * Adds an index to a specified table.
  1372  *
       
  1373  * {@internal Missing Long Description}}
       
  1374  *
  1691  *
  1375  * @since 1.0.1
  1692  * @since 1.0.1
  1376  *
  1693  *
  1377  * @param string $table Database table name.
  1694  * @param string $table Database table name.
  1378  * @param string $index Database table index column.
  1695  * @param string $index Database table index column.
  1384 	$wpdb->query("ALTER TABLE `$table` ADD INDEX ( `$index` )");
  1701 	$wpdb->query("ALTER TABLE `$table` ADD INDEX ( `$index` )");
  1385 	return true;
  1702 	return true;
  1386 }
  1703 }
  1387 
  1704 
  1388 /**
  1705 /**
  1389  ** maybe_add_column()
  1706  * Adds column to a database table if it doesn't already exist.
  1390  ** Add column to db table if it doesn't exist.
  1707  *
  1391  ** Returns:  true if already exists or on successful completion
  1708  * @since 1.3.0
  1392  **           false on error
  1709  *
       
  1710  * @param string $table_name  The table name to modify.
       
  1711  * @param string $column_name The column name to add to the table.
       
  1712  * @param string $create_ddl  The SQL statement used to add the column.
       
  1713  * @return True if already exists or on successful completion, false on error.
  1393  */
  1714  */
  1394 function maybe_add_column($table_name, $column_name, $create_ddl) {
  1715 function maybe_add_column($table_name, $column_name, $create_ddl) {
  1395 	global $wpdb;
  1716 	global $wpdb;
  1396 	foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) {
  1717 	foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) {
  1397 		if ($column == $column_name) {
  1718 		if ($column == $column_name) {
  1398 			return true;
  1719 			return true;
  1399 		}
  1720 		}
  1400 	}
  1721 	}
  1401 	//didn't find it try to create it.
  1722 
  1402 	$q = $wpdb->query($create_ddl);
  1723 	// Didn't find it try to create it.
  1403 	// we cannot directly tell that whether this succeeded!
  1724 	$wpdb->query($create_ddl);
       
  1725 
       
  1726 	// We cannot directly tell that whether this succeeded!
  1404 	foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) {
  1727 	foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) {
  1405 		if ($column == $column_name) {
  1728 		if ($column == $column_name) {
  1406 			return true;
  1729 			return true;
  1407 		}
  1730 		}
  1408 	}
  1731 	}
  1409 	return false;
  1732 	return false;
  1410 }
  1733 }
  1411 
  1734 
  1412 /**
  1735 /**
       
  1736  * If a table only contains utf8 or utf8mb4 columns, convert it to utf8mb4.
       
  1737  *
       
  1738  * @since 4.2.0
       
  1739  *
       
  1740  * @param string $table The table to convert.
       
  1741  * @return bool true if the table was converted, false if it wasn't.
       
  1742  */
       
  1743 function maybe_convert_table_to_utf8mb4( $table ) {
       
  1744 	global $wpdb;
       
  1745 
       
  1746 	$results = $wpdb->get_results( "SHOW FULL COLUMNS FROM `$table`" );
       
  1747 	if ( ! $results ) {
       
  1748 		return false;
       
  1749 	}
       
  1750 
       
  1751 	foreach ( $results as $column ) {
       
  1752 		if ( $column->Collation ) {
       
  1753 			list( $charset ) = explode( '_', $column->Collation );
       
  1754 			$charset = strtolower( $charset );
       
  1755 			if ( 'utf8' !== $charset && 'utf8mb4' !== $charset ) {
       
  1756 				// Don't upgrade tables that have non-utf8 columns.
       
  1757 				return false;
       
  1758 			}
       
  1759 		}
       
  1760 	}
       
  1761 
       
  1762 	return $wpdb->query( "ALTER TABLE $table CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci" );
       
  1763 }
       
  1764 
       
  1765 /**
  1413  * Retrieve all options as it was for 1.2.
  1766  * Retrieve all options as it was for 1.2.
  1414  *
  1767  *
  1415  * @since 1.2.0
  1768  * @since 1.2.0
  1416  *
  1769  *
  1417  * @return array List of options.
  1770  * @return stdClass List of options.
  1418  */
  1771  */
  1419 function get_alloptions_110() {
  1772 function get_alloptions_110() {
  1420 	global $wpdb;
  1773 	global $wpdb;
  1421 	$all_options = new stdClass;
  1774 	$all_options = new stdClass;
  1422 	if ( $options = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options" ) ) {
  1775 	if ( $options = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options" ) ) {
  1428 	}
  1781 	}
  1429 	return $all_options;
  1782 	return $all_options;
  1430 }
  1783 }
  1431 
  1784 
  1432 /**
  1785 /**
  1433  * Version of get_option that is private to install/upgrade.
  1786  * Utility version of get_option that is private to install/upgrade.
  1434  *
  1787  *
       
  1788  * @ignore
  1435  * @since 1.5.1
  1789  * @since 1.5.1
  1436  * @access private
  1790  * @access private
  1437  *
  1791  *
  1438  * @param string $setting Option name.
  1792  * @param string $setting Option name.
  1439  * @return mixed
  1793  * @return mixed
  1457 
  1811 
  1458 	return maybe_unserialize( $option );
  1812 	return maybe_unserialize( $option );
  1459 }
  1813 }
  1460 
  1814 
  1461 /**
  1815 /**
  1462  * {@internal Missing Short Description}}
  1816  * Filters for content to remove unnecessary slashes.
  1463  *
       
  1464  * {@internal Missing Long Description}}
       
  1465  *
  1817  *
  1466  * @since 1.5.0
  1818  * @since 1.5.0
  1467  *
  1819  *
  1468  * @param string $content
  1820  * @param string $content The content to modify.
  1469  * @return string
  1821  * @return string The de-slashed content.
  1470  */
  1822  */
  1471 function deslash($content) {
  1823 function deslash($content) {
  1472 	// Note: \\\ inside a regex denotes a single backslash.
  1824 	// Note: \\\ inside a regex denotes a single backslash.
  1473 
  1825 
  1474 	// Replace one or more backslashes followed by a single quote with
  1826 	/*
  1475 	// a single quote.
  1827 	 * Replace one or more backslashes followed by a single quote with
       
  1828 	 * a single quote.
       
  1829 	 */
  1476 	$content = preg_replace("/\\\+'/", "'", $content);
  1830 	$content = preg_replace("/\\\+'/", "'", $content);
  1477 
  1831 
  1478 	// Replace one or more backslashes followed by a double quote with
  1832 	/*
  1479 	// a double quote.
  1833 	 * Replace one or more backslashes followed by a double quote with
       
  1834 	 * a double quote.
       
  1835 	 */
  1480 	$content = preg_replace('/\\\+"/', '"', $content);
  1836 	$content = preg_replace('/\\\+"/', '"', $content);
  1481 
  1837 
  1482 	// Replace one or more backslashes with one backslash.
  1838 	// Replace one or more backslashes with one backslash.
  1483 	$content = preg_replace("/\\\+/", "\\", $content);
  1839 	$content = preg_replace("/\\\+/", "\\", $content);
  1484 
  1840 
  1485 	return $content;
  1841 	return $content;
  1486 }
  1842 }
  1487 
  1843 
  1488 /**
  1844 /**
  1489  * {@internal Missing Short Description}}
  1845  * Modifies the database based on specified SQL statements.
  1490  *
  1846  *
  1491  * {@internal Missing Long Description}}
  1847  * Useful for creating new tables and updating existing tables to a new structure.
  1492  *
  1848  *
  1493  * @since 1.5.0
  1849  * @since 1.5.0
  1494  *
  1850  *
  1495  * @param unknown_type $queries
  1851  * @param string|array $queries Optional. The query to run. Can be multiple queries
  1496  * @param unknown_type $execute
  1852  *                              in an array, or a string of queries separated by
  1497  * @return unknown
  1853  *                              semicolons. Default empty.
       
  1854  * @param bool         $execute Optional. Whether or not to execute the query right away.
       
  1855  *                              Default true.
       
  1856  * @return array Strings containing the results of the various update queries.
  1498  */
  1857  */
  1499 function dbDelta( $queries = '', $execute = true ) {
  1858 function dbDelta( $queries = '', $execute = true ) {
  1500 	global $wpdb;
  1859 	global $wpdb;
  1501 
  1860 
  1502 	if ( in_array( $queries, array( '', 'all', 'blog', 'global', 'ms_global' ), true ) )
  1861 	if ( in_array( $queries, array( '', 'all', 'blog', 'global', 'ms_global' ), true ) )
  1505 	// Separate individual queries into an array
  1864 	// Separate individual queries into an array
  1506 	if ( !is_array($queries) ) {
  1865 	if ( !is_array($queries) ) {
  1507 		$queries = explode( ';', $queries );
  1866 		$queries = explode( ';', $queries );
  1508 		$queries = array_filter( $queries );
  1867 		$queries = array_filter( $queries );
  1509 	}
  1868 	}
       
  1869 
       
  1870 	/**
       
  1871 	 * Filter the dbDelta SQL queries.
       
  1872 	 *
       
  1873 	 * @since 3.3.0
       
  1874 	 *
       
  1875 	 * @param array $queries An array of dbDelta SQL queries.
       
  1876 	 */
  1510 	$queries = apply_filters( 'dbdelta_queries', $queries );
  1877 	$queries = apply_filters( 'dbdelta_queries', $queries );
  1511 
  1878 
  1512 	$cqueries = array(); // Creation Queries
  1879 	$cqueries = array(); // Creation Queries
  1513 	$iqueries = array(); // Insertion Queries
  1880 	$iqueries = array(); // Insertion Queries
  1514 	$for_update = array();
  1881 	$for_update = array();
  1515 
  1882 
  1516 	// Create a tablename index for an array ($cqueries) of queries
  1883 	// Create a tablename index for an array ($cqueries) of queries
  1517 	foreach($queries as $qry) {
  1884 	foreach($queries as $qry) {
  1518 		if (preg_match("|CREATE TABLE ([^ ]*)|", $qry, $matches)) {
  1885 		if ( preg_match( "|CREATE TABLE ([^ ]*)|", $qry, $matches ) ) {
  1519 			$cqueries[ trim( $matches[1], '`' ) ] = $qry;
  1886 			$cqueries[ trim( $matches[1], '`' ) ] = $qry;
  1520 			$for_update[$matches[1]] = 'Created table '.$matches[1];
  1887 			$for_update[$matches[1]] = 'Created table '.$matches[1];
  1521 		} else if (preg_match("|CREATE DATABASE ([^ ]*)|", $qry, $matches)) {
  1888 		} elseif ( preg_match( "|CREATE DATABASE ([^ ]*)|", $qry, $matches ) ) {
  1522 			array_unshift($cqueries, $qry);
  1889 			array_unshift( $cqueries, $qry );
  1523 		} else if (preg_match("|INSERT INTO ([^ ]*)|", $qry, $matches)) {
  1890 		} elseif ( preg_match( "|INSERT INTO ([^ ]*)|", $qry, $matches ) ) {
  1524 			$iqueries[] = $qry;
  1891 			$iqueries[] = $qry;
  1525 		} else if (preg_match("|UPDATE ([^ ]*)|", $qry, $matches)) {
  1892 		} elseif ( preg_match( "|UPDATE ([^ ]*)|", $qry, $matches ) ) {
  1526 			$iqueries[] = $qry;
  1893 			$iqueries[] = $qry;
  1527 		} else {
  1894 		} else {
  1528 			// Unrecognized query type
  1895 			// Unrecognized query type
  1529 		}
  1896 		}
  1530 	}
  1897 	}
       
  1898 
       
  1899 	/**
       
  1900 	 * Filter the dbDelta SQL queries for creating tables and/or databases.
       
  1901 	 *
       
  1902 	 * Queries filterable via this hook contain "CREATE TABLE" or "CREATE DATABASE".
       
  1903 	 *
       
  1904 	 * @since 3.3.0
       
  1905 	 *
       
  1906 	 * @param array $cqueries An array of dbDelta create SQL queries.
       
  1907 	 */
  1531 	$cqueries = apply_filters( 'dbdelta_create_queries', $cqueries );
  1908 	$cqueries = apply_filters( 'dbdelta_create_queries', $cqueries );
       
  1909 
       
  1910 	/**
       
  1911 	 * Filter the dbDelta SQL queries for inserting or updating.
       
  1912 	 *
       
  1913 	 * Queries filterable via this hook contain "INSERT INTO" or "UPDATE".
       
  1914 	 *
       
  1915 	 * @since 3.3.0
       
  1916 	 *
       
  1917 	 * @param array $iqueries An array of dbDelta insert or update SQL queries.
       
  1918 	 */
  1532 	$iqueries = apply_filters( 'dbdelta_insert_queries', $iqueries );
  1919 	$iqueries = apply_filters( 'dbdelta_insert_queries', $iqueries );
  1533 
  1920 
  1534 	$global_tables = $wpdb->tables( 'global' );
  1921 	$global_tables = $wpdb->tables( 'global' );
  1535 	foreach ( $cqueries as $table => $qry ) {
  1922 	foreach ( $cqueries as $table => $qry ) {
  1536 		// Upgrade global tables only for the main site. Don't upgrade at all if DO_NOT_UPGRADE_GLOBAL_TABLES is defined.
  1923 		// Upgrade global tables only for the main site. Don't upgrade at all if DO_NOT_UPGRADE_GLOBAL_TABLES is defined.
  1537 		if ( in_array( $table, $global_tables ) && ( !is_main_site() || defined( 'DO_NOT_UPGRADE_GLOBAL_TABLES' ) ) )
  1924 		if ( in_array( $table, $global_tables ) && ( !is_main_site() || defined( 'DO_NOT_UPGRADE_GLOBAL_TABLES' ) ) ) {
       
  1925 			unset( $cqueries[ $table ], $for_update[ $table ] );
  1538 			continue;
  1926 			continue;
       
  1927 		}
  1539 
  1928 
  1540 		// Fetch the table column structure from the database
  1929 		// Fetch the table column structure from the database
  1541 		$wpdb->suppress_errors();
  1930 		$suppress = $wpdb->suppress_errors();
  1542 		$tablefields = $wpdb->get_results("DESCRIBE {$table};");
  1931 		$tablefields = $wpdb->get_results("DESCRIBE {$table};");
  1543 		$wpdb->suppress_errors( false );
  1932 		$wpdb->suppress_errors( $suppress );
  1544 
  1933 
  1545 		if ( ! $tablefields )
  1934 		if ( ! $tablefields )
  1546 			continue;
  1935 			continue;
  1547 
  1936 
  1548 		// Clear the field and index arrays
  1937 		// Clear the field and index arrays.
  1549 		$cfields = $indices = array();
  1938 		$cfields = $indices = array();
  1550 		// Get all of the field names in the query from between the parens
  1939 
       
  1940 		// Get all of the field names in the query from between the parentheses.
  1551 		preg_match("|\((.*)\)|ms", $qry, $match2);
  1941 		preg_match("|\((.*)\)|ms", $qry, $match2);
  1552 		$qryline = trim($match2[1]);
  1942 		$qryline = trim($match2[1]);
  1553 
  1943 
  1554 		// Separate field lines into an array
  1944 		// Separate field lines into an array.
  1555 		$flds = explode("\n", $qryline);
  1945 		$flds = explode("\n", $qryline);
  1556 
  1946 
       
  1947 		// todo: Remove this?
  1557 		//echo "<hr/><pre>\n".print_r(strtolower($table), true).":\n".print_r($cqueries, true)."</pre><hr/>";
  1948 		//echo "<hr/><pre>\n".print_r(strtolower($table), true).":\n".print_r($cqueries, true)."</pre><hr/>";
  1558 
  1949 
  1559 		// For every field line specified in the query
  1950 		// For every field line specified in the query.
  1560 		foreach ($flds as $fld) {
  1951 		foreach ($flds as $fld) {
  1561 			// Extract the field name
  1952 
       
  1953 			// Extract the field name.
  1562 			preg_match("|^([^ ]*)|", trim($fld), $fvals);
  1954 			preg_match("|^([^ ]*)|", trim($fld), $fvals);
  1563 			$fieldname = trim( $fvals[1], '`' );
  1955 			$fieldname = trim( $fvals[1], '`' );
  1564 
  1956 
  1565 			// Verify the found field name
  1957 			// Verify the found field name.
  1566 			$validfield = true;
  1958 			$validfield = true;
  1567 			switch (strtolower($fieldname)) {
  1959 			switch (strtolower($fieldname)) {
  1568 			case '':
  1960 			case '':
  1569 			case 'primary':
  1961 			case 'primary':
  1570 			case 'index':
  1962 			case 'index':
  1575 				$indices[] = trim(trim($fld), ", \n");
  1967 				$indices[] = trim(trim($fld), ", \n");
  1576 				break;
  1968 				break;
  1577 			}
  1969 			}
  1578 			$fld = trim($fld);
  1970 			$fld = trim($fld);
  1579 
  1971 
  1580 			// If it's a valid field, add it to the field array
  1972 			// If it's a valid field, add it to the field array.
  1581 			if ($validfield) {
  1973 			if ($validfield) {
  1582 				$cfields[strtolower($fieldname)] = trim($fld, ", \n");
  1974 				$cfields[strtolower($fieldname)] = trim($fld, ", \n");
  1583 			}
  1975 			}
  1584 		}
  1976 		}
  1585 
  1977 
  1586 		// For every field in the table
  1978 		// For every field in the table.
  1587 		foreach ($tablefields as $tablefield) {
  1979 		foreach ($tablefields as $tablefield) {
  1588 			// If the table field exists in the field array...
  1980 
       
  1981 			// If the table field exists in the field array ...
  1589 			if (array_key_exists(strtolower($tablefield->Field), $cfields)) {
  1982 			if (array_key_exists(strtolower($tablefield->Field), $cfields)) {
  1590 				// Get the field type from the query
  1983 
       
  1984 				// Get the field type from the query.
  1591 				preg_match("|".$tablefield->Field." ([^ ]*( unsigned)?)|i", $cfields[strtolower($tablefield->Field)], $matches);
  1985 				preg_match("|".$tablefield->Field." ([^ ]*( unsigned)?)|i", $cfields[strtolower($tablefield->Field)], $matches);
  1592 				$fieldtype = $matches[1];
  1986 				$fieldtype = $matches[1];
  1593 
  1987 
  1594 				// Is actual field type different from the field type in query?
  1988 				// Is actual field type different from the field type in query?
  1595 				if ($tablefield->Type != $fieldtype) {
  1989 				if ($tablefield->Type != $fieldtype) {
  1597 					$cqueries[] = "ALTER TABLE {$table} CHANGE COLUMN {$tablefield->Field} " . $cfields[strtolower($tablefield->Field)];
  1991 					$cqueries[] = "ALTER TABLE {$table} CHANGE COLUMN {$tablefield->Field} " . $cfields[strtolower($tablefield->Field)];
  1598 					$for_update[$table.'.'.$tablefield->Field] = "Changed type of {$table}.{$tablefield->Field} from {$tablefield->Type} to {$fieldtype}";
  1992 					$for_update[$table.'.'.$tablefield->Field] = "Changed type of {$table}.{$tablefield->Field} from {$tablefield->Type} to {$fieldtype}";
  1599 				}
  1993 				}
  1600 
  1994 
  1601 				// Get the default value from the array
  1995 				// Get the default value from the array
       
  1996 					// todo: Remove this?
  1602 					//echo "{$cfields[strtolower($tablefield->Field)]}<br>";
  1997 					//echo "{$cfields[strtolower($tablefield->Field)]}<br>";
  1603 				if (preg_match("| DEFAULT '(.*?)'|i", $cfields[strtolower($tablefield->Field)], $matches)) {
  1998 				if (preg_match("| DEFAULT '(.*?)'|i", $cfields[strtolower($tablefield->Field)], $matches)) {
  1604 					$default_value = $matches[1];
  1999 					$default_value = $matches[1];
  1605 					if ($tablefield->Default != $default_value) {
  2000 					if ($tablefield->Default != $default_value) {
  1606 						// Add a query to change the column's default value
  2001 						// Add a query to change the column's default value
  1607 						$cqueries[] = "ALTER TABLE {$table} ALTER COLUMN {$tablefield->Field} SET DEFAULT '{$default_value}'";
  2002 						$cqueries[] = "ALTER TABLE {$table} ALTER COLUMN {$tablefield->Field} SET DEFAULT '{$default_value}'";
  1608 						$for_update[$table.'.'.$tablefield->Field] = "Changed default value of {$table}.{$tablefield->Field} from {$tablefield->Default} to {$default_value}";
  2003 						$for_update[$table.'.'.$tablefield->Field] = "Changed default value of {$table}.{$tablefield->Field} from {$tablefield->Default} to {$default_value}";
  1609 					}
  2004 					}
  1610 				}
  2005 				}
  1611 
  2006 
  1612 				// Remove the field from the array (so it's not added)
  2007 				// Remove the field from the array (so it's not added).
  1613 				unset($cfields[strtolower($tablefield->Field)]);
  2008 				unset($cfields[strtolower($tablefield->Field)]);
  1614 			} else {
  2009 			} else {
  1615 				// This field exists in the table, but not in the creation queries?
  2010 				// This field exists in the table, but not in the creation queries?
  1616 			}
  2011 			}
  1617 		}
  2012 		}
  1618 
  2013 
  1619 		// For every remaining field specified for the table
  2014 		// For every remaining field specified for the table.
  1620 		foreach ($cfields as $fieldname => $fielddef) {
  2015 		foreach ($cfields as $fieldname => $fielddef) {
  1621 			// Push a query line into $cqueries that adds the field to that table
  2016 			// Push a query line into $cqueries that adds the field to that table.
  1622 			$cqueries[] = "ALTER TABLE {$table} ADD COLUMN $fielddef";
  2017 			$cqueries[] = "ALTER TABLE {$table} ADD COLUMN $fielddef";
  1623 			$for_update[$table.'.'.$fieldname] = 'Added column '.$table.'.'.$fieldname;
  2018 			$for_update[$table.'.'.$fieldname] = 'Added column '.$table.'.'.$fieldname;
  1624 		}
  2019 		}
  1625 
  2020 
  1626 		// Index stuff goes here
  2021 		// Index stuff goes here. Fetch the table index structure from the database.
  1627 		// Fetch the table index structure from the database
       
  1628 		$tableindices = $wpdb->get_results("SHOW INDEX FROM {$table};");
  2022 		$tableindices = $wpdb->get_results("SHOW INDEX FROM {$table};");
  1629 
  2023 
  1630 		if ($tableindices) {
  2024 		if ($tableindices) {
  1631 			// Clear the index array
  2025 			// Clear the index array.
  1632 			unset($index_ary);
  2026 			$index_ary = array();
  1633 
  2027 
  1634 			// For every index in the table
  2028 			// For every index in the table.
  1635 			foreach ($tableindices as $tableindex) {
  2029 			foreach ($tableindices as $tableindex) {
  1636 				// Add the index to the index data array
  2030 
       
  2031 				// Add the index to the index data array.
  1637 				$keyname = $tableindex->Key_name;
  2032 				$keyname = $tableindex->Key_name;
  1638 				$index_ary[$keyname]['columns'][] = array('fieldname' => $tableindex->Column_name, 'subpart' => $tableindex->Sub_part);
  2033 				$index_ary[$keyname]['columns'][] = array('fieldname' => $tableindex->Column_name, 'subpart' => $tableindex->Sub_part);
  1639 				$index_ary[$keyname]['unique'] = ($tableindex->Non_unique == 0)?true:false;
  2034 				$index_ary[$keyname]['unique'] = ($tableindex->Non_unique == 0)?true:false;
  1640 			}
  2035 			}
  1641 
  2036 
  1642 			// For each actual index in the index array
  2037 			// For each actual index in the index array.
  1643 			foreach ($index_ary as $index_name => $index_data) {
  2038 			foreach ($index_ary as $index_name => $index_data) {
  1644 				// Build a create string to compare to the query
  2039 
       
  2040 				// Build a create string to compare to the query.
  1645 				$index_string = '';
  2041 				$index_string = '';
  1646 				if ($index_name == 'PRIMARY') {
  2042 				if ($index_name == 'PRIMARY') {
  1647 					$index_string .= 'PRIMARY ';
  2043 					$index_string .= 'PRIMARY ';
  1648 				} else if($index_data['unique']) {
  2044 				} elseif ( $index_data['unique'] ) {
  1649 					$index_string .= 'UNIQUE ';
  2045 					$index_string .= 'UNIQUE ';
  1650 				}
  2046 				}
  1651 				$index_string .= 'KEY ';
  2047 				$index_string .= 'KEY ';
  1652 				if ($index_name != 'PRIMARY') {
  2048 				if ($index_name != 'PRIMARY') {
  1653 					$index_string .= $index_name;
  2049 					$index_string .= $index_name;
  1654 				}
  2050 				}
  1655 				$index_columns = '';
  2051 				$index_columns = '';
  1656 				// For each column in the index
  2052 
       
  2053 				// For each column in the index.
  1657 				foreach ($index_data['columns'] as $column_data) {
  2054 				foreach ($index_data['columns'] as $column_data) {
  1658 					if ($index_columns != '') $index_columns .= ',';
  2055 					if ($index_columns != '') $index_columns .= ',';
  1659 					// Add the field to the column list string
  2056 
       
  2057 					// Add the field to the column list string.
  1660 					$index_columns .= $column_data['fieldname'];
  2058 					$index_columns .= $column_data['fieldname'];
  1661 					if ($column_data['subpart'] != '') {
  2059 					if ($column_data['subpart'] != '') {
  1662 						$index_columns .= '('.$column_data['subpart'].')';
  2060 						$index_columns .= '('.$column_data['subpart'].')';
  1663 					}
  2061 					}
  1664 				}
  2062 				}
  1665 				// Add the column list to the index create string
  2063 
  1666 				$index_string .= ' ('.$index_columns.')';
  2064 				// The alternative index string doesn't care about subparts
  1667 				if (!(($aindex = array_search($index_string, $indices)) === false)) {
  2065 				$alt_index_columns = preg_replace( '/\([^)]*\)/', '', $index_columns );
  1668 					unset($indices[$aindex]);
  2066 
  1669 					//echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">{$table}:<br />Found index:".$index_string."</pre>\n";
  2067 				// Add the column list to the index create string.
       
  2068 				$index_strings = array(
       
  2069 					"$index_string ($index_columns)",
       
  2070 					"$index_string ($alt_index_columns)",
       
  2071 				);
       
  2072 
       
  2073 				foreach( $index_strings as $index_string ) {
       
  2074 					if ( ! ( ( $aindex = array_search( $index_string, $indices ) ) === false ) ) {
       
  2075 						unset( $indices[ $aindex ] );
       
  2076 						break;
       
  2077 						// todo: Remove this?
       
  2078 						//echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">{$table}:<br />Found index:".$index_string."</pre>\n";
       
  2079 					}
  1670 				}
  2080 				}
       
  2081 				// todo: Remove this?
  1671 				//else echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">{$table}:<br /><b>Did not find index:</b>".$index_string."<br />".print_r($indices, true)."</pre>\n";
  2082 				//else echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">{$table}:<br /><b>Did not find index:</b>".$index_string."<br />".print_r($indices, true)."</pre>\n";
  1672 			}
  2083 			}
  1673 		}
  2084 		}
  1674 
  2085 
  1675 		// For every remaining index specified for the table
  2086 		// For every remaining index specified for the table.
  1676 		foreach ( (array) $indices as $index ) {
  2087 		foreach ( (array) $indices as $index ) {
  1677 			// Push a query line into $cqueries that adds the index to that table
  2088 			// Push a query line into $cqueries that adds the index to that table.
  1678 			$cqueries[] = "ALTER TABLE {$table} ADD $index";
  2089 			$cqueries[] = "ALTER TABLE {$table} ADD $index";
  1679 			$for_update[] = 'Added index ' . $table . ' ' . $index;
  2090 			$for_update[] = 'Added index ' . $table . ' ' . $index;
  1680 		}
  2091 		}
  1681 
  2092 
  1682 		// Remove the original table creation query from processing
  2093 		// Remove the original table creation query from processing.
  1683 		unset( $cqueries[ $table ], $for_update[ $table ] );
  2094 		unset( $cqueries[ $table ], $for_update[ $table ] );
  1684 	}
  2095 	}
  1685 
  2096 
  1686 	$allqueries = array_merge($cqueries, $iqueries);
  2097 	$allqueries = array_merge($cqueries, $iqueries);
  1687 	if ($execute) {
  2098 	if ($execute) {
  1688 		foreach ($allqueries as $query) {
  2099 		foreach ($allqueries as $query) {
       
  2100 			// todo: Remove this?
  1689 			//echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">".print_r($query, true)."</pre>\n";
  2101 			//echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">".print_r($query, true)."</pre>\n";
  1690 			$wpdb->query($query);
  2102 			$wpdb->query($query);
  1691 		}
  2103 		}
  1692 	}
  2104 	}
  1693 
  2105 
  1694 	return $for_update;
  2106 	return $for_update;
  1695 }
  2107 }
  1696 
  2108 
  1697 /**
  2109 /**
  1698  * {@internal Missing Short Description}}
  2110  * Updates the database tables to a new schema.
  1699  *
  2111  *
  1700  * {@internal Missing Long Description}}
  2112  * By default, updates all the tables to use the latest defined schema, but can also
       
  2113  * be used to update a specific set of tables in wp_get_db_schema().
  1701  *
  2114  *
  1702  * @since 1.5.0
  2115  * @since 1.5.0
       
  2116  *
       
  2117  * @uses dbDelta
       
  2118  *
       
  2119  * @param string $tables Optional. Which set of tables to update. Default is 'all'.
  1703  */
  2120  */
  1704 function make_db_current( $tables = 'all' ) {
  2121 function make_db_current( $tables = 'all' ) {
  1705 	$alterations = dbDelta( $tables );
  2122 	$alterations = dbDelta( $tables );
  1706 	echo "<ol>\n";
  2123 	echo "<ol>\n";
  1707 	foreach($alterations as $alteration) echo "<li>$alteration</li>\n";
  2124 	foreach($alterations as $alteration) echo "<li>$alteration</li>\n";
  1708 	echo "</ol>\n";
  2125 	echo "</ol>\n";
  1709 }
  2126 }
  1710 
  2127 
  1711 /**
  2128 /**
  1712  * {@internal Missing Short Description}}
  2129  * Updates the database tables to a new schema, but without displaying results.
       
  2130  *
       
  2131  * By default, updates all the tables to use the latest defined schema, but can
       
  2132  * also be used to update a specific set of tables in wp_get_db_schema().
       
  2133  *
       
  2134  * @since 1.5.0
       
  2135  *
       
  2136  * @see make_db_current()
       
  2137  *
       
  2138  * @param string $tables Optional. Which set of tables to update. Default is 'all'.
       
  2139  */
       
  2140 function make_db_current_silent( $tables = 'all' ) {
       
  2141 	dbDelta( $tables );
       
  2142 }
       
  2143 
       
  2144 /**
       
  2145  * Creates a site theme from an existing theme.
  1713  *
  2146  *
  1714  * {@internal Missing Long Description}}
  2147  * {@internal Missing Long Description}}
  1715  *
  2148  *
  1716  * @since 1.5.0
  2149  * @since 1.5.0
  1717  */
  2150  *
  1718 function make_db_current_silent( $tables = 'all' ) {
  2151  * @param string $theme_name The name of the theme.
  1719 	$alterations = dbDelta( $tables );
  2152  * @param string $template   The directory name of the theme.
  1720 }
  2153  * @return bool
  1721 
       
  1722 /**
       
  1723  * {@internal Missing Short Description}}
       
  1724  *
       
  1725  * {@internal Missing Long Description}}
       
  1726  *
       
  1727  * @since 1.5.0
       
  1728  *
       
  1729  * @param unknown_type $theme_name
       
  1730  * @param unknown_type $template
       
  1731  * @return unknown
       
  1732  */
  2154  */
  1733 function make_site_theme_from_oldschool($theme_name, $template) {
  2155 function make_site_theme_from_oldschool($theme_name, $template) {
  1734 	$home_path = get_home_path();
  2156 	$home_path = get_home_path();
  1735 	$site_dir = WP_CONTENT_DIR . "/themes/$template";
  2157 	$site_dir = WP_CONTENT_DIR . "/themes/$template";
  1736 
  2158 
  1737 	if (! file_exists("$home_path/index.php"))
  2159 	if (! file_exists("$home_path/index.php"))
  1738 		return false;
  2160 		return false;
  1739 
  2161 
  1740 	// Copy files from the old locations to the site theme.
  2162 	/*
  1741 	// TODO: This does not copy arbitrary include dependencies. Only the
  2163 	 * Copy files from the old locations to the site theme.
  1742 	// standard WP files are copied.
  2164 	 * TODO: This does not copy arbitrary include dependencies. Only the standard WP files are copied.
       
  2165 	 */
  1743 	$files = array('index.php' => 'index.php', 'wp-layout.css' => 'style.css', 'wp-comments.php' => 'comments.php', 'wp-comments-popup.php' => 'comments-popup.php');
  2166 	$files = array('index.php' => 'index.php', 'wp-layout.css' => 'style.css', 'wp-comments.php' => 'comments.php', 'wp-comments-popup.php' => 'comments-popup.php');
  1744 
  2167 
  1745 	foreach ($files as $oldfile => $newfile) {
  2168 	foreach ($files as $oldfile => $newfile) {
  1746 		if ($oldfile == 'index.php')
  2169 		if ($oldfile == 'index.php')
  1747 			$oldpath = $home_path;
  2170 			$oldpath = $home_path;
  1748 		else
  2171 		else
  1749 			$oldpath = ABSPATH;
  2172 			$oldpath = ABSPATH;
  1750 
  2173 
  1751 		if ($oldfile == 'index.php') { // Check to make sure it's not a new index
  2174 		// Check to make sure it's not a new index.
       
  2175 		if ($oldfile == 'index.php') {
  1752 			$index = implode('', file("$oldpath/$oldfile"));
  2176 			$index = implode('', file("$oldpath/$oldfile"));
  1753 			if (strpos($index, 'WP_USE_THEMES') !== false) {
  2177 			if (strpos($index, 'WP_USE_THEMES') !== false) {
  1754 				if (! @copy(WP_CONTENT_DIR . '/themes/' . WP_DEFAULT_THEME . '/index.php', "$site_dir/$newfile"))
  2178 				if (! @copy(WP_CONTENT_DIR . '/themes/' . WP_DEFAULT_THEME . '/index.php', "$site_dir/$newfile"))
  1755 					return false;
  2179 					return false;
  1756 				continue; // Don't copy anything
  2180 
       
  2181 				// Don't copy anything.
       
  2182 				continue;
  1757 				}
  2183 				}
  1758 		}
  2184 		}
  1759 
  2185 
  1760 		if (! @copy("$oldpath/$oldfile", "$site_dir/$newfile"))
  2186 		if (! @copy("$oldpath/$oldfile", "$site_dir/$newfile"))
  1761 			return false;
  2187 			return false;
  1797 
  2223 
  1798 	return true;
  2224 	return true;
  1799 }
  2225 }
  1800 
  2226 
  1801 /**
  2227 /**
  1802  * {@internal Missing Short Description}}
  2228  * Creates a site theme from the default theme.
  1803  *
  2229  *
  1804  * {@internal Missing Long Description}}
  2230  * {@internal Missing Long Description}}
  1805  *
  2231  *
  1806  * @since 1.5.0
  2232  * @since 1.5.0
  1807  *
  2233  *
  1808  * @param unknown_type $theme_name
  2234  * @param string $theme_name The name of the theme.
  1809  * @param unknown_type $template
  2235  * @param string $template   The directory name of the theme.
  1810  * @return unknown
  2236  * @return null|false
  1811  */
  2237  */
  1812 function make_site_theme_from_default($theme_name, $template) {
  2238 function make_site_theme_from_default($theme_name, $template) {
  1813 	$site_dir = WP_CONTENT_DIR . "/themes/$template";
  2239 	$site_dir = WP_CONTENT_DIR . "/themes/$template";
  1814 	$default_dir = WP_CONTENT_DIR . '/themes/' . WP_DEFAULT_THEME;
  2240 	$default_dir = WP_CONTENT_DIR . '/themes/' . WP_DEFAULT_THEME;
  1815 
  2241 
  1861 		}
  2287 		}
  1862 	}
  2288 	}
  1863 	@closedir($images_dir);
  2289 	@closedir($images_dir);
  1864 }
  2290 }
  1865 
  2291 
  1866 // Create a site theme from the default theme.
  2292 /**
  1867 /**
  2293  * Creates a site theme.
  1868  * {@internal Missing Short Description}}
       
  1869  *
  2294  *
  1870  * {@internal Missing Long Description}}
  2295  * {@internal Missing Long Description}}
  1871  *
  2296  *
  1872  * @since 1.5.0
  2297  * @since 1.5.0
  1873  *
  2298  *
  1874  * @return unknown
  2299  * @return false|string
  1875  */
  2300  */
  1876 function make_site_theme() {
  2301 function make_site_theme() {
  1877 	// Name the theme after the blog.
  2302 	// Name the theme after the blog.
  1878 	$theme_name = __get_option('blogname');
  2303 	$theme_name = __get_option('blogname');
  1879 	$template = sanitize_title($theme_name);
  2304 	$template = sanitize_title($theme_name);
  1942 		return 'subscriber';
  2367 		return 'subscriber';
  1943 	}
  2368 	}
  1944 }
  2369 }
  1945 
  2370 
  1946 /**
  2371 /**
  1947  * {@internal Missing Short Description}}
  2372  * Checks the version of the installed MySQL binary.
  1948  *
       
  1949  * {@internal Missing Long Description}}
       
  1950  *
  2373  *
  1951  * @since 2.1.0
  2374  * @since 2.1.0
  1952  */
  2375  */
  1953 function wp_check_mysql_version() {
  2376 function wp_check_mysql_version() {
  1954 	global $wpdb;
  2377 	global $wpdb;
  1973 		}
  2396 		}
  1974 	}
  2397 	}
  1975 }
  2398 }
  1976 
  2399 
  1977 /**
  2400 /**
  1978  * Disables the Link Manager on upgrade, if at the time of upgrade, no links exist in the DB.
  2401  * Disables the Link Manager on upgrade if, at the time of upgrade, no links exist in the DB.
  1979  *
  2402  *
  1980  * @since 3.5.0
  2403  * @since 3.5.0
  1981  */
  2404  */
  1982 function maybe_disable_link_manager() {
  2405 function maybe_disable_link_manager() {
  1983 	global $wp_current_db_version, $wpdb;
  2406 	global $wp_current_db_version, $wpdb;
  1990  * Runs before the schema is upgraded.
  2413  * Runs before the schema is upgraded.
  1991  *
  2414  *
  1992  * @since 2.9.0
  2415  * @since 2.9.0
  1993  */
  2416  */
  1994 function pre_schema_upgrade() {
  2417 function pre_schema_upgrade() {
  1995 	global $wp_current_db_version, $wp_db_version, $wpdb;
  2418 	global $wp_current_db_version, $wpdb;
  1996 
  2419 
  1997 	// Upgrade versions prior to 2.9
  2420 	// Upgrade versions prior to 2.9
  1998 	if ( $wp_current_db_version < 11557 ) {
  2421 	if ( $wp_current_db_version < 11557 ) {
  1999 		// Delete duplicate options. Keep the option with the highest option_id.
  2422 		// Delete duplicate options. Keep the option with the highest option_id.
  2000 		$wpdb->query("DELETE o1 FROM $wpdb->options AS o1 JOIN $wpdb->options AS o2 USING (`option_name`) WHERE o2.option_id > o1.option_id");
  2423 		$wpdb->query("DELETE o1 FROM $wpdb->options AS o1 JOIN $wpdb->options AS o2 USING (`option_name`) WHERE o2.option_id > o1.option_id");
  2019 		if ( $wp_current_db_version < 25448 ) {
  2442 		if ( $wp_current_db_version < 25448 ) {
  2020 			// Convert archived from enum to tinyint.
  2443 			// Convert archived from enum to tinyint.
  2021 			$wpdb->query( "ALTER TABLE $wpdb->blogs CHANGE COLUMN archived archived varchar(1) NOT NULL default '0'" );
  2444 			$wpdb->query( "ALTER TABLE $wpdb->blogs CHANGE COLUMN archived archived varchar(1) NOT NULL default '0'" );
  2022 			$wpdb->query( "ALTER TABLE $wpdb->blogs CHANGE COLUMN archived archived tinyint(2) NOT NULL default 0" );
  2445 			$wpdb->query( "ALTER TABLE $wpdb->blogs CHANGE COLUMN archived archived tinyint(2) NOT NULL default 0" );
  2023 		}
  2446 		}
       
  2447 	}
       
  2448 
       
  2449 	if ( $wp_current_db_version < 30133 ) {
       
  2450 		// dbDelta() can recreate but can't drop the index.
       
  2451 		$wpdb->query( "ALTER TABLE $wpdb->terms DROP INDEX slug" );
       
  2452 	}
       
  2453 
       
  2454 	// Upgrade versions prior to 4.2.
       
  2455 	if ( $wp_current_db_version < 31351 ) {
       
  2456 		if ( ! is_multisite() ) {
       
  2457 			$wpdb->query( "ALTER TABLE $wpdb->usermeta DROP INDEX meta_key, ADD INDEX meta_key(meta_key(191))" );
       
  2458 		}
       
  2459 		$wpdb->query( "ALTER TABLE $wpdb->terms DROP INDEX slug, ADD INDEX slug(slug(191))" );
       
  2460 		$wpdb->query( "ALTER TABLE $wpdb->terms DROP INDEX name, ADD INDEX name(name(191))" );
       
  2461 		$wpdb->query( "ALTER TABLE $wpdb->commentmeta DROP INDEX meta_key, ADD INDEX meta_key(meta_key(191))" );
       
  2462 		$wpdb->query( "ALTER TABLE $wpdb->postmeta DROP INDEX meta_key, ADD INDEX meta_key(meta_key(191))" );
       
  2463 		$wpdb->query( "ALTER TABLE $wpdb->posts DROP INDEX post_name, ADD INDEX post_name(post_name(191))" );
  2024 	}
  2464 	}
  2025 }
  2465 }
  2026 
  2466 
  2027 /**
  2467 /**
  2028  * Install global terms.
  2468  * Install global terms.