]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-admin/includes/upgrade.php
WordPress 4.7.2
[autoinstalls/wordpress.git] / wp-admin / includes / upgrade.php
1 <?php
2 /**
3  * WordPress Upgrade API
4  *
5  * Most of the functions are pluggable and can be overwritten.
6  *
7  * @package WordPress
8  * @subpackage Administration
9  */
10
11 /** Include user install customize script. */
12 if ( file_exists(WP_CONTENT_DIR . '/install.php') )
13         require (WP_CONTENT_DIR . '/install.php');
14
15 /** WordPress Administration API */
16 require_once(ABSPATH . 'wp-admin/includes/admin.php');
17
18 /** WordPress Schema API */
19 require_once(ABSPATH . 'wp-admin/includes/schema.php');
20
21 if ( !function_exists('wp_install') ) :
22 /**
23  * Installs the site.
24  *
25  * Runs the required functions to set up and populate the database,
26  * including primary admin user and initial options.
27  *
28  * @since 2.1.0
29  *
30  * @param string $blog_title    Site title.
31  * @param string $user_name     User's username.
32  * @param string $user_email    User's email.
33  * @param bool   $public        Whether site is public.
34  * @param string $deprecated    Optional. Not used.
35  * @param string $user_password Optional. User's chosen password. Default empty (random password).
36  * @param string $language      Optional. Language chosen. Default empty.
37  * @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          */
72         $user_id = username_exists($user_name);
73         $user_password = trim($user_password);
74         $email_password = false;
75         if ( !$user_id && empty($user_password) ) {
76                 $user_password = wp_generate_password( 12, false );
77                 $message = __('<strong><em>Note that password</em></strong> carefully! It is a <em>random</em> password that was generated just for you.');
78                 $user_id = wp_create_user($user_name, $user_password, $user_email);
79                 update_user_option($user_id, 'default_password_nag', true, true);
80                 $email_password = true;
81         } elseif ( ! $user_id ) {
82                 // Password has been provided
83                 $message = '<em>'.__('Your chosen password.').'</em>';
84                 $user_id = wp_create_user($user_name, $user_password, $user_email);
85         } else {
86                 $message = __('User already exists. Password inherited.');
87         }
88
89         $user = new WP_User($user_id);
90         $user->set_role('administrator');
91
92         wp_install_defaults($user_id);
93
94         wp_install_maybe_enable_pretty_permalinks();
95
96         flush_rewrite_rules();
97
98         wp_new_blog_notification($blog_title, $guessurl, $user_id, ($email_password ? $user_password : __('The password you chose during the install.') ) );
99
100         wp_cache_flush();
101
102         /**
103          * Fires after a site is fully installed.
104          *
105          * @since 3.9.0
106          *
107          * @param WP_User $user The site owner.
108          */
109         do_action( 'wp_install', $user );
110
111         return array('url' => $guessurl, 'user_id' => $user_id, 'password' => $user_password, 'password_message' => $message);
112 }
113 endif;
114
115 if ( !function_exists('wp_install_defaults') ) :
116 /**
117  * Creates the initial content for a newly-installed site.
118  *
119  * Adds the default "Uncategorized" category, the first post (with comment),
120  * first page, and default widgets for default theme for the current version.
121  *
122  * @since 2.1.0
123  *
124  * @global wpdb       $wpdb
125  * @global WP_Rewrite $wp_rewrite
126  * @global string     $table_prefix
127  *
128  * @param int $user_id User ID.
129  */
130 function wp_install_defaults( $user_id ) {
131         global $wpdb, $wp_rewrite, $table_prefix;
132
133         // Default category
134         $cat_name = __('Uncategorized');
135         /* translators: Default category slug */
136         $cat_slug = sanitize_title(_x('Uncategorized', 'Default category slug'));
137
138         if ( global_terms_enabled() ) {
139                 $cat_id = $wpdb->get_var( $wpdb->prepare( "SELECT cat_ID FROM {$wpdb->sitecategories} WHERE category_nicename = %s", $cat_slug ) );
140                 if ( $cat_id == null ) {
141                         $wpdb->insert( $wpdb->sitecategories, array('cat_ID' => 0, 'cat_name' => $cat_name, 'category_nicename' => $cat_slug, 'last_updated' => current_time('mysql', true)) );
142                         $cat_id = $wpdb->insert_id;
143                 }
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                 );
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         $first_comment_author = __( 'A WordPress Commenter' );
198         $first_comment_email = 'wapuu@wordpress.example';
199         $first_comment_url = 'https://wordpress.org/';
200         $first_comment = __( 'Hi, this is a comment.
201 To get started with moderating, editing, and deleting comments, please visit the Comments screen in the dashboard.
202 Commenter avatars come from <a href="https://gravatar.com">Gravatar</a>.' );
203         if ( is_multisite() ) {
204                 $first_comment_author = get_site_option( 'first_comment_author', $first_comment_author );
205                 $first_comment_email = get_site_option( 'first_comment_email', $first_comment_email );
206                 $first_comment_url = get_site_option( 'first_comment_url', network_home_url() );
207                 $first_comment = get_site_option( 'first_comment', $first_comment );
208         }
209         $wpdb->insert( $wpdb->comments, array(
210                 'comment_post_ID' => 1,
211                 'comment_author' => $first_comment_author,
212                 'comment_author_email' => $first_comment_email,
213                 'comment_author_url' => $first_comment_url,
214                 'comment_date' => $now,
215                 'comment_date_gmt' => $now_gmt,
216                 'comment_content' => $first_comment
217         ));
218
219         // First Page
220         $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:
221
222 <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>
223
224 ...or something like this:
225
226 <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>
227
228 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() );
229         if ( is_multisite() )
230                 $first_page = get_site_option( 'first_page', $first_page );
231         $first_post_guid = get_option('home') . '/?page_id=2';
232         $wpdb->insert( $wpdb->posts, array(
233                 'post_author' => $user_id,
234                 'post_date' => $now,
235                 'post_date_gmt' => $now_gmt,
236                 'post_content' => $first_page,
237                 'post_excerpt' => '',
238                 'comment_status' => 'closed',
239                 'post_title' => __( 'Sample Page' ),
240                 /* translators: Default page slug */
241                 'post_name' => __( 'sample-page' ),
242                 'post_modified' => $now,
243                 'post_modified_gmt' => $now_gmt,
244                 'guid' => $first_post_guid,
245                 'post_type' => 'page',
246                 'to_ping' => '',
247                 'pinged' => '',
248                 'post_content_filtered' => ''
249         ));
250         $wpdb->insert( $wpdb->postmeta, array( 'post_id' => 2, 'meta_key' => '_wp_page_template', 'meta_value' => 'default' ) );
251
252         // Set up default widgets for default theme.
253         update_option( 'widget_search', array ( 2 => array ( 'title' => '' ), '_multiwidget' => 1 ) );
254         update_option( 'widget_recent-posts', array ( 2 => array ( 'title' => '', 'number' => 5 ), '_multiwidget' => 1 ) );
255         update_option( 'widget_recent-comments', array ( 2 => array ( 'title' => '', 'number' => 5 ), '_multiwidget' => 1 ) );
256         update_option( 'widget_archives', array ( 2 => array ( 'title' => '', 'count' => 0, 'dropdown' => 0 ), '_multiwidget' => 1 ) );
257         update_option( 'widget_categories', array ( 2 => array ( 'title' => '', 'count' => 0, 'hierarchical' => 0, 'dropdown' => 0 ), '_multiwidget' => 1 ) );
258         update_option( 'widget_meta', array ( 2 => array ( 'title' => '' ), '_multiwidget' => 1 ) );
259         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 ) );
260         if ( ! is_multisite() )
261                 update_user_meta( $user_id, 'show_welcome_panel', 1 );
262         elseif ( ! is_super_admin( $user_id ) && ! metadata_exists( 'user', $user_id, 'show_welcome_panel' ) )
263                 update_user_meta( $user_id, 'show_welcome_panel', 2 );
264
265         if ( is_multisite() ) {
266                 // Flush rules to pick up the new page.
267                 $wp_rewrite->init();
268                 $wp_rewrite->flush_rules();
269
270                 $user = new WP_User($user_id);
271                 $wpdb->update( $wpdb->options, array('option_value' => $user->user_email), array('option_name' => 'admin_email') );
272
273                 // Remove all perms except for the login user.
274                 $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id != %d AND meta_key = %s", $user_id, $table_prefix.'user_level') );
275                 $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id != %d AND meta_key = %s", $user_id, $table_prefix.'capabilities') );
276
277                 // Delete any caps that snuck into the previously active blog. (Hardcoded to blog 1 for now.) TODO: Get previous_blog_id.
278                 if ( !is_super_admin( $user_id ) && $user_id != 1 )
279                         $wpdb->delete( $wpdb->usermeta, array( 'user_id' => $user_id , 'meta_key' => $wpdb->base_prefix.'1_capabilities' ) );
280         }
281 }
282 endif;
283
284 /**
285  * Maybe enable pretty permalinks on install.
286  *
287  * If after enabling pretty permalinks don't work, fallback to query-string permalinks.
288  *
289  * @since 4.2.0
290  *
291  * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
292  *
293  * @return bool Whether pretty permalinks are enabled. False otherwise.
294  */
295 function wp_install_maybe_enable_pretty_permalinks() {
296         global $wp_rewrite;
297
298         // Bail if a permalink structure is already enabled.
299         if ( get_option( 'permalink_structure' ) ) {
300                 return true;
301         }
302
303         /*
304          * The Permalink structures to attempt.
305          *
306          * The first is designed for mod_rewrite or nginx rewriting.
307          *
308          * The second is PATHINFO-based permalinks for web server configurations
309          * without a true rewrite module enabled.
310          */
311         $permalink_structures = array(
312                 '/%year%/%monthnum%/%day%/%postname%/',
313                 '/index.php/%year%/%monthnum%/%day%/%postname%/'
314         );
315
316         foreach ( (array) $permalink_structures as $permalink_structure ) {
317                 $wp_rewrite->set_permalink_structure( $permalink_structure );
318
319                 /*
320                  * Flush rules with the hard option to force refresh of the web-server's
321                  * rewrite config file (e.g. .htaccess or web.config).
322                  */
323                 $wp_rewrite->flush_rules( true );
324
325                 $test_url = '';
326
327                 // Test against a real WordPress Post
328                 $first_post = get_page_by_path( sanitize_title( _x( 'hello-world', 'Default post slug' ) ), OBJECT, 'post' );
329                 if ( $first_post ) {
330                         $test_url = get_permalink( $first_post->ID );
331                 }
332
333                 /*
334                  * Send a request to the site, and check whether
335                  * the 'x-pingback' header is returned as expected.
336                  *
337                  * Uses wp_remote_get() instead of wp_remote_head() because web servers
338                  * can block head requests.
339                  */
340                 $response          = wp_remote_get( $test_url, array( 'timeout' => 5 ) );
341                 $x_pingback_header = wp_remote_retrieve_header( $response, 'x-pingback' );
342                 $pretty_permalinks = $x_pingback_header && $x_pingback_header === get_bloginfo( 'pingback_url' );
343
344                 if ( $pretty_permalinks ) {
345                         return true;
346                 }
347         }
348
349         /*
350          * If it makes it this far, pretty permalinks failed.
351          * Fallback to query-string permalinks.
352          */
353         $wp_rewrite->set_permalink_structure( '' );
354         $wp_rewrite->flush_rules( true );
355
356         return false;
357 }
358
359 if ( !function_exists('wp_new_blog_notification') ) :
360 /**
361  * Notifies the site admin that the setup is complete.
362  *
363  * Sends an email with wp_mail to the new administrator that the site setup is complete,
364  * and provides them with a record of their login credentials.
365  *
366  * @since 2.1.0
367  *
368  * @param string $blog_title Site title.
369  * @param string $blog_url   Site url.
370  * @param int    $user_id    User ID.
371  * @param string $password   User's Password.
372  */
373 function wp_new_blog_notification($blog_title, $blog_url, $user_id, $password) {
374         $user = new WP_User( $user_id );
375         $email = $user->user_email;
376         $name = $user->user_login;
377         $login_url = wp_login_url();
378         /* translators: New site notification email. 1: New site URL, 2: User login, 3: User password or password reset link, 4: Login URL */
379         $message = sprintf( __( "Your new WordPress site has been successfully set up at:
380
381 %1\$s
382
383 You can log in to the administrator account with the following information:
384
385 Username: %2\$s
386 Password: %3\$s
387 Log in here: %4\$s
388
389 We hope you enjoy your new site. Thanks!
390
391 --The WordPress Team
392 https://wordpress.org/
393 "), $blog_url, $name, $password, $login_url );
394
395         @wp_mail($email, __('New WordPress Site'), $message);
396 }
397 endif;
398
399 if ( !function_exists('wp_upgrade') ) :
400 /**
401  * Runs WordPress Upgrade functions.
402  *
403  * Upgrades the database if needed during a site update.
404  *
405  * @since 2.1.0
406  *
407  * @global int  $wp_current_db_version
408  * @global int  $wp_db_version
409  * @global wpdb $wpdb WordPress database abstraction object.
410  */
411 function wp_upgrade() {
412         global $wp_current_db_version, $wp_db_version, $wpdb;
413
414         $wp_current_db_version = __get_option('db_version');
415
416         // We are up-to-date. Nothing to do.
417         if ( $wp_db_version == $wp_current_db_version )
418                 return;
419
420         if ( ! is_blog_installed() )
421                 return;
422
423         wp_check_mysql_version();
424         wp_cache_flush();
425         pre_schema_upgrade();
426         make_db_current_silent();
427         upgrade_all();
428         if ( is_multisite() && is_main_site() )
429                 upgrade_network();
430         wp_cache_flush();
431
432         if ( is_multisite() ) {
433                 if ( $wpdb->get_row( "SELECT blog_id FROM {$wpdb->blog_versions} WHERE blog_id = '{$wpdb->blogid}'" ) )
434                         $wpdb->query( "UPDATE {$wpdb->blog_versions} SET db_version = '{$wp_db_version}' WHERE blog_id = '{$wpdb->blogid}'" );
435                 else
436                         $wpdb->query( "INSERT INTO {$wpdb->blog_versions} ( `blog_id` , `db_version` , `last_updated` ) VALUES ( '{$wpdb->blogid}', '{$wp_db_version}', NOW());" );
437         }
438
439         /**
440          * Fires after a site is fully upgraded.
441          *
442          * @since 3.9.0
443          *
444          * @param int $wp_db_version         The new $wp_db_version.
445          * @param int $wp_current_db_version The old (current) $wp_db_version.
446          */
447         do_action( 'wp_upgrade', $wp_db_version, $wp_current_db_version );
448 }
449 endif;
450
451 /**
452  * Functions to be called in install and upgrade scripts.
453  *
454  * Contains conditional checks to determine which upgrade scripts to run,
455  * based on database version and WP version being updated-to.
456  *
457  * @ignore
458  * @since 1.0.1
459  *
460  * @global int $wp_current_db_version
461  * @global int $wp_db_version
462  */
463 function upgrade_all() {
464         global $wp_current_db_version, $wp_db_version;
465         $wp_current_db_version = __get_option('db_version');
466
467         // We are up-to-date. Nothing to do.
468         if ( $wp_db_version == $wp_current_db_version )
469                 return;
470
471         // If the version is not set in the DB, try to guess the version.
472         if ( empty($wp_current_db_version) ) {
473                 $wp_current_db_version = 0;
474
475                 // If the template option exists, we have 1.5.
476                 $template = __get_option('template');
477                 if ( !empty($template) )
478                         $wp_current_db_version = 2541;
479         }
480
481         if ( $wp_current_db_version < 6039 )
482                 upgrade_230_options_table();
483
484         populate_options();
485
486         if ( $wp_current_db_version < 2541 ) {
487                 upgrade_100();
488                 upgrade_101();
489                 upgrade_110();
490                 upgrade_130();
491         }
492
493         if ( $wp_current_db_version < 3308 )
494                 upgrade_160();
495
496         if ( $wp_current_db_version < 4772 )
497                 upgrade_210();
498
499         if ( $wp_current_db_version < 4351 )
500                 upgrade_old_slugs();
501
502         if ( $wp_current_db_version < 5539 )
503                 upgrade_230();
504
505         if ( $wp_current_db_version < 6124 )
506                 upgrade_230_old_tables();
507
508         if ( $wp_current_db_version < 7499 )
509                 upgrade_250();
510
511         if ( $wp_current_db_version < 7935 )
512                 upgrade_252();
513
514         if ( $wp_current_db_version < 8201 )
515                 upgrade_260();
516
517         if ( $wp_current_db_version < 8989 )
518                 upgrade_270();
519
520         if ( $wp_current_db_version < 10360 )
521                 upgrade_280();
522
523         if ( $wp_current_db_version < 11958 )
524                 upgrade_290();
525
526         if ( $wp_current_db_version < 15260 )
527                 upgrade_300();
528
529         if ( $wp_current_db_version < 19389 )
530                 upgrade_330();
531
532         if ( $wp_current_db_version < 20080 )
533                 upgrade_340();
534
535         if ( $wp_current_db_version < 22422 )
536                 upgrade_350();
537
538         if ( $wp_current_db_version < 25824 )
539                 upgrade_370();
540
541         if ( $wp_current_db_version < 26148 )
542                 upgrade_372();
543
544         if ( $wp_current_db_version < 26691 )
545                 upgrade_380();
546
547         if ( $wp_current_db_version < 29630 )
548                 upgrade_400();
549
550         if ( $wp_current_db_version < 33055 )
551                 upgrade_430();
552
553         if ( $wp_current_db_version < 33056 )
554                 upgrade_431();
555
556         if ( $wp_current_db_version < 35700 )
557                 upgrade_440();
558
559         if ( $wp_current_db_version < 36686 )
560                 upgrade_450();
561
562         if ( $wp_current_db_version < 37965 )
563                 upgrade_460();
564
565         maybe_disable_link_manager();
566
567         maybe_disable_automattic_widgets();
568
569         update_option( 'db_version', $wp_db_version );
570         update_option( 'db_upgraded', true );
571 }
572
573 /**
574  * Execute changes made in WordPress 1.0.
575  *
576  * @ignore
577  * @since 1.0.0
578  *
579  * @global wpdb $wpdb WordPress database abstraction object.
580  */
581 function upgrade_100() {
582         global $wpdb;
583
584         // Get the title and ID of every post, post_name to check if it already has a value
585         $posts = $wpdb->get_results("SELECT ID, post_title, post_name FROM $wpdb->posts WHERE post_name = ''");
586         if ($posts) {
587                 foreach ($posts as $post) {
588                         if ('' == $post->post_name) {
589                                 $newtitle = sanitize_title($post->post_title);
590                                 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_name = %s WHERE ID = %d", $newtitle, $post->ID) );
591                         }
592                 }
593         }
594
595         $categories = $wpdb->get_results("SELECT cat_ID, cat_name, category_nicename FROM $wpdb->categories");
596         foreach ($categories as $category) {
597                 if ('' == $category->category_nicename) {
598                         $newtitle = sanitize_title($category->cat_name);
599                         $wpdb->update( $wpdb->categories, array('category_nicename' => $newtitle), array('cat_ID' => $category->cat_ID) );
600                 }
601         }
602
603         $sql = "UPDATE $wpdb->options
604                 SET option_value = REPLACE(option_value, 'wp-links/links-images/', 'wp-images/links/')
605                 WHERE option_name LIKE %s
606                 AND option_value LIKE %s";
607         $wpdb->query( $wpdb->prepare( $sql, $wpdb->esc_like( 'links_rating_image' ) . '%', $wpdb->esc_like( 'wp-links/links-images/' ) . '%' ) );
608
609         $done_ids = $wpdb->get_results("SELECT DISTINCT post_id FROM $wpdb->post2cat");
610         if ($done_ids) :
611                 $done_posts = array();
612                 foreach ($done_ids as $done_id) :
613                         $done_posts[] = $done_id->post_id;
614                 endforeach;
615                 $catwhere = ' AND ID NOT IN (' . implode(',', $done_posts) . ')';
616         else:
617                 $catwhere = '';
618         endif;
619
620         $allposts = $wpdb->get_results("SELECT ID, post_category FROM $wpdb->posts WHERE post_category != '0' $catwhere");
621         if ($allposts) :
622                 foreach ($allposts as $post) {
623                         // Check to see if it's already been imported
624                         $cat = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->post2cat WHERE post_id = %d AND category_id = %d", $post->ID, $post->post_category) );
625                         if (!$cat && 0 != $post->post_category) { // If there's no result
626                                 $wpdb->insert( $wpdb->post2cat, array('post_id' => $post->ID, 'category_id' => $post->post_category) );
627                         }
628                 }
629         endif;
630 }
631
632 /**
633  * Execute changes made in WordPress 1.0.1.
634  *
635  * @ignore
636  * @since 1.0.1
637  *
638  * @global wpdb $wpdb WordPress database abstraction object.
639  */
640 function upgrade_101() {
641         global $wpdb;
642
643         // Clean up indices, add a few
644         add_clean_index($wpdb->posts, 'post_name');
645         add_clean_index($wpdb->posts, 'post_status');
646         add_clean_index($wpdb->categories, 'category_nicename');
647         add_clean_index($wpdb->comments, 'comment_approved');
648         add_clean_index($wpdb->comments, 'comment_post_ID');
649         add_clean_index($wpdb->links , 'link_category');
650         add_clean_index($wpdb->links , 'link_visible');
651 }
652
653 /**
654  * Execute changes made in WordPress 1.2.
655  *
656  * @ignore
657  * @since 1.2.0
658  *
659  * @global wpdb $wpdb WordPress database abstraction object.
660  */
661 function upgrade_110() {
662         global $wpdb;
663
664         // Set user_nicename.
665         $users = $wpdb->get_results("SELECT ID, user_nickname, user_nicename FROM $wpdb->users");
666         foreach ($users as $user) {
667                 if ('' == $user->user_nicename) {
668                         $newname = sanitize_title($user->user_nickname);
669                         $wpdb->update( $wpdb->users, array('user_nicename' => $newname), array('ID' => $user->ID) );
670                 }
671         }
672
673         $users = $wpdb->get_results("SELECT ID, user_pass from $wpdb->users");
674         foreach ($users as $row) {
675                 if (!preg_match('/^[A-Fa-f0-9]{32}$/', $row->user_pass)) {
676                         $wpdb->update( $wpdb->users, array('user_pass' => md5($row->user_pass)), array('ID' => $row->ID) );
677                 }
678         }
679
680         // Get the GMT offset, we'll use that later on
681         $all_options = get_alloptions_110();
682
683         $time_difference = $all_options->time_difference;
684
685                 $server_time = time()+date('Z');
686         $weblogger_time = $server_time + $time_difference * HOUR_IN_SECONDS;
687         $gmt_time = time();
688
689         $diff_gmt_server = ($gmt_time - $server_time) / HOUR_IN_SECONDS;
690         $diff_weblogger_server = ($weblogger_time - $server_time) / HOUR_IN_SECONDS;
691         $diff_gmt_weblogger = $diff_gmt_server - $diff_weblogger_server;
692         $gmt_offset = -$diff_gmt_weblogger;
693
694         // Add a gmt_offset option, with value $gmt_offset
695         add_option('gmt_offset', $gmt_offset);
696
697         // Check if we already set the GMT fields (if we did, then
698         // MAX(post_date_gmt) can't be '0000-00-00 00:00:00'
699         // <michel_v> I just slapped myself silly for not thinking about it earlier
700         $got_gmt_fields = ! ($wpdb->get_var("SELECT MAX(post_date_gmt) FROM $wpdb->posts") == '0000-00-00 00:00:00');
701
702         if (!$got_gmt_fields) {
703
704                 // Add or subtract time to all dates, to get GMT dates
705                 $add_hours = intval($diff_gmt_weblogger);
706                 $add_minutes = intval(60 * ($diff_gmt_weblogger - $add_hours));
707                 $wpdb->query("UPDATE $wpdb->posts SET post_date_gmt = DATE_ADD(post_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
708                 $wpdb->query("UPDATE $wpdb->posts SET post_modified = post_date");
709                 $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'");
710                 $wpdb->query("UPDATE $wpdb->comments SET comment_date_gmt = DATE_ADD(comment_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
711                 $wpdb->query("UPDATE $wpdb->users SET user_registered = DATE_ADD(user_registered, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
712         }
713
714 }
715
716 /**
717  * Execute changes made in WordPress 1.5.
718  *
719  * @ignore
720  * @since 1.5.0
721  *
722  * @global wpdb $wpdb WordPress database abstraction object.
723  */
724 function upgrade_130() {
725         global $wpdb;
726
727         // Remove extraneous backslashes.
728         $posts = $wpdb->get_results("SELECT ID, post_title, post_content, post_excerpt, guid, post_date, post_name, post_status, post_author FROM $wpdb->posts");
729         if ($posts) {
730                 foreach ($posts as $post) {
731                         $post_content = addslashes(deslash($post->post_content));
732                         $post_title = addslashes(deslash($post->post_title));
733                         $post_excerpt = addslashes(deslash($post->post_excerpt));
734                         if ( empty($post->guid) )
735                                 $guid = get_permalink($post->ID);
736                         else
737                                 $guid = $post->guid;
738
739                         $wpdb->update( $wpdb->posts, compact('post_title', 'post_content', 'post_excerpt', 'guid'), array('ID' => $post->ID) );
740
741                 }
742         }
743
744         // Remove extraneous backslashes.
745         $comments = $wpdb->get_results("SELECT comment_ID, comment_author, comment_content FROM $wpdb->comments");
746         if ($comments) {
747                 foreach ($comments as $comment) {
748                         $comment_content = deslash($comment->comment_content);
749                         $comment_author = deslash($comment->comment_author);
750
751                         $wpdb->update($wpdb->comments, compact('comment_content', 'comment_author'), array('comment_ID' => $comment->comment_ID) );
752                 }
753         }
754
755         // Remove extraneous backslashes.
756         $links = $wpdb->get_results("SELECT link_id, link_name, link_description FROM $wpdb->links");
757         if ($links) {
758                 foreach ($links as $link) {
759                         $link_name = deslash($link->link_name);
760                         $link_description = deslash($link->link_description);
761
762                         $wpdb->update( $wpdb->links, compact('link_name', 'link_description'), array('link_id' => $link->link_id) );
763                 }
764         }
765
766         $active_plugins = __get_option('active_plugins');
767
768         /*
769          * If plugins are not stored in an array, they're stored in the old
770          * newline separated format. Convert to new format.
771          */
772         if ( !is_array( $active_plugins ) ) {
773                 $active_plugins = explode("\n", trim($active_plugins));
774                 update_option('active_plugins', $active_plugins);
775         }
776
777         // Obsolete tables
778         $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optionvalues');
779         $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiontypes');
780         $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiongroups');
781         $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiongroup_options');
782
783         // Update comments table to use comment_type
784         $wpdb->query("UPDATE $wpdb->comments SET comment_type='trackback', comment_content = REPLACE(comment_content, '<trackback />', '') WHERE comment_content LIKE '<trackback />%'");
785         $wpdb->query("UPDATE $wpdb->comments SET comment_type='pingback', comment_content = REPLACE(comment_content, '<pingback />', '') WHERE comment_content LIKE '<pingback />%'");
786
787         // Some versions have multiple duplicate option_name rows with the same values
788         $options = $wpdb->get_results("SELECT option_name, COUNT(option_name) AS dupes FROM `$wpdb->options` GROUP BY option_name");
789         foreach ( $options as $option ) {
790                 if ( 1 != $option->dupes ) { // Could this be done in the query?
791                         $limit = $option->dupes - 1;
792                         $dupe_ids = $wpdb->get_col( $wpdb->prepare("SELECT option_id FROM $wpdb->options WHERE option_name = %s LIMIT %d", $option->option_name, $limit) );
793                         if ( $dupe_ids ) {
794                                 $dupe_ids = join($dupe_ids, ',');
795                                 $wpdb->query("DELETE FROM $wpdb->options WHERE option_id IN ($dupe_ids)");
796                         }
797                 }
798         }
799
800         make_site_theme();
801 }
802
803 /**
804  * Execute changes made in WordPress 2.0.
805  *
806  * @ignore
807  * @since 2.0.0
808  *
809  * @global wpdb $wpdb WordPress database abstraction object.
810  * @global int  $wp_current_db_version
811  */
812 function upgrade_160() {
813         global $wpdb, $wp_current_db_version;
814
815         populate_roles_160();
816
817         $users = $wpdb->get_results("SELECT * FROM $wpdb->users");
818         foreach ( $users as $user ) :
819                 if ( !empty( $user->user_firstname ) )
820                         update_user_meta( $user->ID, 'first_name', wp_slash($user->user_firstname) );
821                 if ( !empty( $user->user_lastname ) )
822                         update_user_meta( $user->ID, 'last_name', wp_slash($user->user_lastname) );
823                 if ( !empty( $user->user_nickname ) )
824                         update_user_meta( $user->ID, 'nickname', wp_slash($user->user_nickname) );
825                 if ( !empty( $user->user_level ) )
826                         update_user_meta( $user->ID, $wpdb->prefix . 'user_level', $user->user_level );
827                 if ( !empty( $user->user_icq ) )
828                         update_user_meta( $user->ID, 'icq', wp_slash($user->user_icq) );
829                 if ( !empty( $user->user_aim ) )
830                         update_user_meta( $user->ID, 'aim', wp_slash($user->user_aim) );
831                 if ( !empty( $user->user_msn ) )
832                         update_user_meta( $user->ID, 'msn', wp_slash($user->user_msn) );
833                 if ( !empty( $user->user_yim ) )
834                         update_user_meta( $user->ID, 'yim', wp_slash($user->user_icq) );
835                 if ( !empty( $user->user_description ) )
836                         update_user_meta( $user->ID, 'description', wp_slash($user->user_description) );
837
838                 if ( isset( $user->user_idmode ) ):
839                         $idmode = $user->user_idmode;
840                         if ($idmode == 'nickname') $id = $user->user_nickname;
841                         if ($idmode == 'login') $id = $user->user_login;
842                         if ($idmode == 'firstname') $id = $user->user_firstname;
843                         if ($idmode == 'lastname') $id = $user->user_lastname;
844                         if ($idmode == 'namefl') $id = $user->user_firstname.' '.$user->user_lastname;
845                         if ($idmode == 'namelf') $id = $user->user_lastname.' '.$user->user_firstname;
846                         if (!$idmode) $id = $user->user_nickname;
847                         $wpdb->update( $wpdb->users, array('display_name' => $id), array('ID' => $user->ID) );
848                 endif;
849
850                 // FIXME: RESET_CAPS is temporary code to reset roles and caps if flag is set.
851                 $caps = get_user_meta( $user->ID, $wpdb->prefix . 'capabilities');
852                 if ( empty($caps) || defined('RESET_CAPS') ) {
853                         $level = get_user_meta($user->ID, $wpdb->prefix . 'user_level', true);
854                         $role = translate_level_to_role($level);
855                         update_user_meta( $user->ID, $wpdb->prefix . 'capabilities', array($role => true) );
856                 }
857
858         endforeach;
859         $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' );
860         $wpdb->hide_errors();
861         foreach ( $old_user_fields as $old )
862                 $wpdb->query("ALTER TABLE $wpdb->users DROP $old");
863         $wpdb->show_errors();
864
865         // Populate comment_count field of posts table.
866         $comments = $wpdb->get_results( "SELECT comment_post_ID, COUNT(*) as c FROM $wpdb->comments WHERE comment_approved = '1' GROUP BY comment_post_ID" );
867         if ( is_array( $comments ) )
868                 foreach ($comments as $comment)
869                         $wpdb->update( $wpdb->posts, array('comment_count' => $comment->c), array('ID' => $comment->comment_post_ID) );
870
871         /*
872          * Some alpha versions used a post status of object instead of attachment
873          * and put the mime type in post_type instead of post_mime_type.
874          */
875         if ( $wp_current_db_version > 2541 && $wp_current_db_version <= 3091 ) {
876                 $objects = $wpdb->get_results("SELECT ID, post_type FROM $wpdb->posts WHERE post_status = 'object'");
877                 foreach ($objects as $object) {
878                         $wpdb->update( $wpdb->posts, array(     'post_status' => 'attachment',
879                                                                                                 'post_mime_type' => $object->post_type,
880                                                                                                 'post_type' => ''),
881                                                                                  array( 'ID' => $object->ID ) );
882
883                         $meta = get_post_meta($object->ID, 'imagedata', true);
884                         if ( ! empty($meta['file']) )
885                                 update_attached_file( $object->ID, $meta['file'] );
886                 }
887         }
888 }
889
890 /**
891  * Execute changes made in WordPress 2.1.
892  *
893  * @ignore
894  * @since 2.1.0
895  *
896  * @global wpdb $wpdb WordPress database abstraction object.
897  * @global int  $wp_current_db_version
898  */
899 function upgrade_210() {
900         global $wpdb, $wp_current_db_version;
901
902         if ( $wp_current_db_version < 3506 ) {
903                 // Update status and type.
904                 $posts = $wpdb->get_results("SELECT ID, post_status FROM $wpdb->posts");
905
906                 if ( ! empty($posts) ) foreach ($posts as $post) {
907                         $status = $post->post_status;
908                         $type = 'post';
909
910                         if ( 'static' == $status ) {
911                                 $status = 'publish';
912                                 $type = 'page';
913                         } elseif ( 'attachment' == $status ) {
914                                 $status = 'inherit';
915                                 $type = 'attachment';
916                         }
917
918                         $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_status = %s, post_type = %s WHERE ID = %d", $status, $type, $post->ID) );
919                 }
920         }
921
922         if ( $wp_current_db_version < 3845 ) {
923                 populate_roles_210();
924         }
925
926         if ( $wp_current_db_version < 3531 ) {
927                 // Give future posts a post_status of future.
928                 $now = gmdate('Y-m-d H:i:59');
929                 $wpdb->query ("UPDATE $wpdb->posts SET post_status = 'future' WHERE post_status = 'publish' AND post_date_gmt > '$now'");
930
931                 $posts = $wpdb->get_results("SELECT ID, post_date FROM $wpdb->posts WHERE post_status ='future'");
932                 if ( !empty($posts) )
933                         foreach ( $posts as $post )
934                                 wp_schedule_single_event(mysql2date('U', $post->post_date, false), 'publish_future_post', array($post->ID));
935         }
936 }
937
938 /**
939  * Execute changes made in WordPress 2.3.
940  *
941  * @ignore
942  * @since 2.3.0
943  *
944  * @global wpdb $wpdb WordPress database abstraction object.
945  * @global int  $wp_current_db_version
946  */
947 function upgrade_230() {
948         global $wp_current_db_version, $wpdb;
949
950         if ( $wp_current_db_version < 5200 ) {
951                 populate_roles_230();
952         }
953
954         // Convert categories to terms.
955         $tt_ids = array();
956         $have_tags = false;
957         $categories = $wpdb->get_results("SELECT * FROM $wpdb->categories ORDER BY cat_ID");
958         foreach ($categories as $category) {
959                 $term_id = (int) $category->cat_ID;
960                 $name = $category->cat_name;
961                 $description = $category->category_description;
962                 $slug = $category->category_nicename;
963                 $parent = $category->category_parent;
964                 $term_group = 0;
965
966                 // Associate terms with the same slug in a term group and make slugs unique.
967                 if ( $exists = $wpdb->get_results( $wpdb->prepare("SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $slug) ) ) {
968                         $term_group = $exists[0]->term_group;
969                         $id = $exists[0]->term_id;
970                         $num = 2;
971                         do {
972                                 $alt_slug = $slug . "-$num";
973                                 $num++;
974                                 $slug_check = $wpdb->get_var( $wpdb->prepare("SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug) );
975                         } while ( $slug_check );
976
977                         $slug = $alt_slug;
978
979                         if ( empty( $term_group ) ) {
980                                 $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms GROUP BY term_group") + 1;
981                                 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->terms SET term_group = %d WHERE term_id = %d", $term_group, $id) );
982                         }
983                 }
984
985                 $wpdb->query( $wpdb->prepare("INSERT INTO $wpdb->terms (term_id, name, slug, term_group) VALUES
986                 (%d, %s, %s, %d)", $term_id, $name, $slug, $term_group) );
987
988                 $count = 0;
989                 if ( !empty($category->category_count) ) {
990                         $count = (int) $category->category_count;
991                         $taxonomy = 'category';
992                         $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) );
993                         $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
994                 }
995
996                 if ( !empty($category->link_count) ) {
997                         $count = (int) $category->link_count;
998                         $taxonomy = 'link_category';
999                         $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) );
1000                         $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
1001                 }
1002
1003                 if ( !empty($category->tag_count) ) {
1004                         $have_tags = true;
1005                         $count = (int) $category->tag_count;
1006                         $taxonomy = 'post_tag';
1007                         $wpdb->insert( $wpdb->term_taxonomy, compact('term_id', 'taxonomy', 'description', 'parent', 'count') );
1008                         $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
1009                 }
1010
1011                 if ( empty($count) ) {
1012                         $count = 0;
1013                         $taxonomy = 'category';
1014                         $wpdb->insert( $wpdb->term_taxonomy, compact('term_id', 'taxonomy', 'description', 'parent', 'count') );
1015                         $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
1016                 }
1017         }
1018
1019         $select = 'post_id, category_id';
1020         if ( $have_tags )
1021                 $select .= ', rel_type';
1022
1023         $posts = $wpdb->get_results("SELECT $select FROM $wpdb->post2cat GROUP BY post_id, category_id");
1024         foreach ( $posts as $post ) {
1025                 $post_id = (int) $post->post_id;
1026                 $term_id = (int) $post->category_id;
1027                 $taxonomy = 'category';
1028                 if ( !empty($post->rel_type) && 'tag' == $post->rel_type)
1029                         $taxonomy = 'tag';
1030                 $tt_id = $tt_ids[$term_id][$taxonomy];
1031                 if ( empty($tt_id) )
1032                         continue;
1033
1034                 $wpdb->insert( $wpdb->term_relationships, array('object_id' => $post_id, 'term_taxonomy_id' => $tt_id) );
1035         }
1036
1037         // < 3570 we used linkcategories. >= 3570 we used categories and link2cat.
1038         if ( $wp_current_db_version < 3570 ) {
1039                 /*
1040                  * Create link_category terms for link categories. Create a map of link
1041                  * cat IDs to link_category terms.
1042                  */
1043                 $link_cat_id_map = array();
1044                 $default_link_cat = 0;
1045                 $tt_ids = array();
1046                 $link_cats = $wpdb->get_results("SELECT cat_id, cat_name FROM " . $wpdb->prefix . 'linkcategories');
1047                 foreach ( $link_cats as $category) {
1048                         $cat_id = (int) $category->cat_id;
1049                         $term_id = 0;
1050                         $name = wp_slash($category->cat_name);
1051                         $slug = sanitize_title($name);
1052                         $term_group = 0;
1053
1054                         // Associate terms with the same slug in a term group and make slugs unique.
1055                         if ( $exists = $wpdb->get_results( $wpdb->prepare("SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $slug) ) ) {
1056                                 $term_group = $exists[0]->term_group;
1057                                 $term_id = $exists[0]->term_id;
1058                         }
1059
1060                         if ( empty($term_id) ) {
1061                                 $wpdb->insert( $wpdb->terms, compact('name', 'slug', 'term_group') );
1062                                 $term_id = (int) $wpdb->insert_id;
1063                         }
1064
1065                         $link_cat_id_map[$cat_id] = $term_id;
1066                         $default_link_cat = $term_id;
1067
1068                         $wpdb->insert( $wpdb->term_taxonomy, array('term_id' => $term_id, 'taxonomy' => 'link_category', 'description' => '', 'parent' => 0, 'count' => 0) );
1069                         $tt_ids[$term_id] = (int) $wpdb->insert_id;
1070                 }
1071
1072                 // Associate links to cats.
1073                 $links = $wpdb->get_results("SELECT link_id, link_category FROM $wpdb->links");
1074                 if ( !empty($links) ) foreach ( $links as $link ) {
1075                         if ( 0 == $link->link_category )
1076                                 continue;
1077                         if ( ! isset($link_cat_id_map[$link->link_category]) )
1078                                 continue;
1079                         $term_id = $link_cat_id_map[$link->link_category];
1080                         $tt_id = $tt_ids[$term_id];
1081                         if ( empty($tt_id) )
1082                                 continue;
1083
1084                         $wpdb->insert( $wpdb->term_relationships, array('object_id' => $link->link_id, 'term_taxonomy_id' => $tt_id) );
1085                 }
1086
1087                 // Set default to the last category we grabbed during the upgrade loop.
1088                 update_option('default_link_category', $default_link_cat);
1089         } else {
1090                 $links = $wpdb->get_results("SELECT link_id, category_id FROM $wpdb->link2cat GROUP BY link_id, category_id");
1091                 foreach ( $links as $link ) {
1092                         $link_id = (int) $link->link_id;
1093                         $term_id = (int) $link->category_id;
1094                         $taxonomy = 'link_category';
1095                         $tt_id = $tt_ids[$term_id][$taxonomy];
1096                         if ( empty($tt_id) )
1097                                 continue;
1098                         $wpdb->insert( $wpdb->term_relationships, array('object_id' => $link_id, 'term_taxonomy_id' => $tt_id) );
1099                 }
1100         }
1101
1102         if ( $wp_current_db_version < 4772 ) {
1103                 // Obsolete linkcategories table
1104                 $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'linkcategories');
1105         }
1106
1107         // Recalculate all counts
1108         $terms = $wpdb->get_results("SELECT term_taxonomy_id, taxonomy FROM $wpdb->term_taxonomy");
1109         foreach ( (array) $terms as $term ) {
1110                 if ( ('post_tag' == $term->taxonomy) || ('category' == $term->taxonomy) )
1111                         $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) );
1112                 else
1113                         $count = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term->term_taxonomy_id) );
1114                 $wpdb->update( $wpdb->term_taxonomy, array('count' => $count), array('term_taxonomy_id' => $term->term_taxonomy_id) );
1115         }
1116 }
1117
1118 /**
1119  * Remove old options from the database.
1120  *
1121  * @ignore
1122  * @since 2.3.0
1123  *
1124  * @global wpdb $wpdb WordPress database abstraction object.
1125  */
1126 function upgrade_230_options_table() {
1127         global $wpdb;
1128         $old_options_fields = array( 'option_can_override', 'option_type', 'option_width', 'option_height', 'option_description', 'option_admin_level' );
1129         $wpdb->hide_errors();
1130         foreach ( $old_options_fields as $old )
1131                 $wpdb->query("ALTER TABLE $wpdb->options DROP $old");
1132         $wpdb->show_errors();
1133 }
1134
1135 /**
1136  * Remove old categories, link2cat, and post2cat database tables.
1137  *
1138  * @ignore
1139  * @since 2.3.0
1140  *
1141  * @global wpdb $wpdb WordPress database abstraction object.
1142  */
1143 function upgrade_230_old_tables() {
1144         global $wpdb;
1145         $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'categories');
1146         $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'link2cat');
1147         $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'post2cat');
1148 }
1149
1150 /**
1151  * Upgrade old slugs made in version 2.2.
1152  *
1153  * @ignore
1154  * @since 2.2.0
1155  *
1156  * @global wpdb $wpdb WordPress database abstraction object.
1157  */
1158 function upgrade_old_slugs() {
1159         // Upgrade people who were using the Redirect Old Slugs plugin.
1160         global $wpdb;
1161         $wpdb->query("UPDATE $wpdb->postmeta SET meta_key = '_wp_old_slug' WHERE meta_key = 'old_slug'");
1162 }
1163
1164 /**
1165  * Execute changes made in WordPress 2.5.0.
1166  *
1167  * @ignore
1168  * @since 2.5.0
1169  *
1170  * @global int $wp_current_db_version
1171  */
1172 function upgrade_250() {
1173         global $wp_current_db_version;
1174
1175         if ( $wp_current_db_version < 6689 ) {
1176                 populate_roles_250();
1177         }
1178
1179 }
1180
1181 /**
1182  * Execute changes made in WordPress 2.5.2.
1183  *
1184  * @ignore
1185  * @since 2.5.2
1186  *
1187  * @global wpdb $wpdb WordPress database abstraction object.
1188  */
1189 function upgrade_252() {
1190         global $wpdb;
1191
1192         $wpdb->query("UPDATE $wpdb->users SET user_activation_key = ''");
1193 }
1194
1195 /**
1196  * Execute changes made in WordPress 2.6.
1197  *
1198  * @ignore
1199  * @since 2.6.0
1200  *
1201  * @global int $wp_current_db_version
1202  */
1203 function upgrade_260() {
1204         global $wp_current_db_version;
1205
1206         if ( $wp_current_db_version < 8000 )
1207                 populate_roles_260();
1208 }
1209
1210 /**
1211  * Execute changes made in WordPress 2.7.
1212  *
1213  * @ignore
1214  * @since 2.7.0
1215  *
1216  * @global wpdb $wpdb WordPress database abstraction object.
1217  * @global int  $wp_current_db_version
1218  */
1219 function upgrade_270() {
1220         global $wpdb, $wp_current_db_version;
1221
1222         if ( $wp_current_db_version < 8980 )
1223                 populate_roles_270();
1224
1225         // Update post_date for unpublished posts with empty timestamp
1226         if ( $wp_current_db_version < 8921 )
1227                 $wpdb->query( "UPDATE $wpdb->posts SET post_date = post_modified WHERE post_date = '0000-00-00 00:00:00'" );
1228 }
1229
1230 /**
1231  * Execute changes made in WordPress 2.8.
1232  *
1233  * @ignore
1234  * @since 2.8.0
1235  *
1236  * @global int  $wp_current_db_version
1237  * @global wpdb $wpdb WordPress database abstraction object.
1238  */
1239 function upgrade_280() {
1240         global $wp_current_db_version, $wpdb;
1241
1242         if ( $wp_current_db_version < 10360 )
1243                 populate_roles_280();
1244         if ( is_multisite() ) {
1245                 $start = 0;
1246                 while( $rows = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options ORDER BY option_id LIMIT $start, 20" ) ) {
1247                         foreach ( $rows as $row ) {
1248                                 $value = $row->option_value;
1249                                 if ( !@unserialize( $value ) )
1250                                         $value = stripslashes( $value );
1251                                 if ( $value !== $row->option_value ) {
1252                                         update_option( $row->option_name, $value );
1253                                 }
1254                         }
1255                         $start += 20;
1256                 }
1257                 refresh_blog_details( $wpdb->blogid );
1258         }
1259 }
1260
1261 /**
1262  * Execute changes made in WordPress 2.9.
1263  *
1264  * @ignore
1265  * @since 2.9.0
1266  *
1267  * @global int $wp_current_db_version
1268  */
1269 function upgrade_290() {
1270         global $wp_current_db_version;
1271
1272         if ( $wp_current_db_version < 11958 ) {
1273                 // Previously, setting depth to 1 would redundantly disable threading, but now 2 is the minimum depth to avoid confusion
1274                 if ( get_option( 'thread_comments_depth' ) == '1' ) {
1275                         update_option( 'thread_comments_depth', 2 );
1276                         update_option( 'thread_comments', 0 );
1277                 }
1278         }
1279 }
1280
1281 /**
1282  * Execute changes made in WordPress 3.0.
1283  *
1284  * @ignore
1285  * @since 3.0.0
1286  *
1287  * @global int  $wp_current_db_version
1288  * @global wpdb $wpdb WordPress database abstraction object.
1289  */
1290 function upgrade_300() {
1291         global $wp_current_db_version, $wpdb;
1292
1293         if ( $wp_current_db_version < 15093 )
1294                 populate_roles_300();
1295
1296         if ( $wp_current_db_version < 14139 && is_multisite() && is_main_site() && ! defined( 'MULTISITE' ) && get_site_option( 'siteurl' ) === false )
1297                 add_site_option( 'siteurl', '' );
1298
1299         // 3.0 screen options key name changes.
1300         if ( wp_should_upgrade_global_tables() ) {
1301                 $sql = "DELETE FROM $wpdb->usermeta
1302                         WHERE meta_key LIKE %s
1303                         OR meta_key LIKE %s
1304                         OR meta_key LIKE %s
1305                         OR meta_key LIKE %s
1306                         OR meta_key LIKE %s
1307                         OR meta_key LIKE %s
1308                         OR meta_key = 'manageedittagscolumnshidden'
1309                         OR meta_key = 'managecategoriescolumnshidden'
1310                         OR meta_key = 'manageedit-tagscolumnshidden'
1311                         OR meta_key = 'manageeditcolumnshidden'
1312                         OR meta_key = 'categories_per_page'
1313                         OR meta_key = 'edit_tags_per_page'";
1314                 $prefix = $wpdb->esc_like( $wpdb->base_prefix );
1315                 $wpdb->query( $wpdb->prepare( $sql,
1316                         $prefix . '%' . $wpdb->esc_like( 'meta-box-hidden' ) . '%',
1317                         $prefix . '%' . $wpdb->esc_like( 'closedpostboxes' ) . '%',
1318                         $prefix . '%' . $wpdb->esc_like( 'manage-'         ) . '%' . $wpdb->esc_like( '-columns-hidden' ) . '%',
1319                         $prefix . '%' . $wpdb->esc_like( 'meta-box-order'  ) . '%',
1320                         $prefix . '%' . $wpdb->esc_like( 'metaboxorder'    ) . '%',
1321                         $prefix . '%' . $wpdb->esc_like( 'screen_layout'   ) . '%'
1322                 ) );
1323         }
1324
1325 }
1326
1327 /**
1328  * Execute changes made in WordPress 3.3.
1329  *
1330  * @ignore
1331  * @since 3.3.0
1332  *
1333  * @global int   $wp_current_db_version
1334  * @global wpdb  $wpdb
1335  * @global array $wp_registered_widgets
1336  * @global array $sidebars_widgets
1337  */
1338 function upgrade_330() {
1339         global $wp_current_db_version, $wpdb, $wp_registered_widgets, $sidebars_widgets;
1340
1341         if ( $wp_current_db_version < 19061 && wp_should_upgrade_global_tables() ) {
1342                 $wpdb->query( "DELETE FROM $wpdb->usermeta WHERE meta_key IN ('show_admin_bar_admin', 'plugins_last_view')" );
1343         }
1344
1345         if ( $wp_current_db_version >= 11548 )
1346                 return;
1347
1348         $sidebars_widgets = get_option( 'sidebars_widgets', array() );
1349         $_sidebars_widgets = array();
1350
1351         if ( isset($sidebars_widgets['wp_inactive_widgets']) || empty($sidebars_widgets) )
1352                 $sidebars_widgets['array_version'] = 3;
1353         elseif ( !isset($sidebars_widgets['array_version']) )
1354                 $sidebars_widgets['array_version'] = 1;
1355
1356         switch ( $sidebars_widgets['array_version'] ) {
1357                 case 1 :
1358                         foreach ( (array) $sidebars_widgets as $index => $sidebar )
1359                         if ( is_array($sidebar) )
1360                         foreach ( (array) $sidebar as $i => $name ) {
1361                                 $id = strtolower($name);
1362                                 if ( isset($wp_registered_widgets[$id]) ) {
1363                                         $_sidebars_widgets[$index][$i] = $id;
1364                                         continue;
1365                                 }
1366                                 $id = sanitize_title($name);
1367                                 if ( isset($wp_registered_widgets[$id]) ) {
1368                                         $_sidebars_widgets[$index][$i] = $id;
1369                                         continue;
1370                                 }
1371
1372                                 $found = false;
1373
1374                                 foreach ( $wp_registered_widgets as $widget_id => $widget ) {
1375                                         if ( strtolower($widget['name']) == strtolower($name) ) {
1376                                                 $_sidebars_widgets[$index][$i] = $widget['id'];
1377                                                 $found = true;
1378                                                 break;
1379                                         } elseif ( sanitize_title($widget['name']) == sanitize_title($name) ) {
1380                                                 $_sidebars_widgets[$index][$i] = $widget['id'];
1381                                                 $found = true;
1382                                                 break;
1383                                         }
1384                                 }
1385
1386                                 if ( $found )
1387                                         continue;
1388
1389                                 unset($_sidebars_widgets[$index][$i]);
1390                         }
1391                         $_sidebars_widgets['array_version'] = 2;
1392                         $sidebars_widgets = $_sidebars_widgets;
1393                         unset($_sidebars_widgets);
1394
1395                 case 2 :
1396                         $sidebars_widgets = retrieve_widgets();
1397                         $sidebars_widgets['array_version'] = 3;
1398                         update_option( 'sidebars_widgets', $sidebars_widgets );
1399         }
1400 }
1401
1402 /**
1403  * Execute changes made in WordPress 3.4.
1404  *
1405  * @ignore
1406  * @since 3.4.0
1407  *
1408  * @global int   $wp_current_db_version
1409  * @global wpdb  $wpdb
1410  */
1411 function upgrade_340() {
1412         global $wp_current_db_version, $wpdb;
1413
1414         if ( $wp_current_db_version < 19798 ) {
1415                 $wpdb->hide_errors();
1416                 $wpdb->query( "ALTER TABLE $wpdb->options DROP COLUMN blog_id" );
1417                 $wpdb->show_errors();
1418         }
1419
1420         if ( $wp_current_db_version < 19799 ) {
1421                 $wpdb->hide_errors();
1422                 $wpdb->query("ALTER TABLE $wpdb->comments DROP INDEX comment_approved");
1423                 $wpdb->show_errors();
1424         }
1425
1426         if ( $wp_current_db_version < 20022 && wp_should_upgrade_global_tables() ) {
1427                 $wpdb->query( "DELETE FROM $wpdb->usermeta WHERE meta_key = 'themes_last_view'" );
1428         }
1429
1430         if ( $wp_current_db_version < 20080 ) {
1431                 if ( 'yes' == $wpdb->get_var( "SELECT autoload FROM $wpdb->options WHERE option_name = 'uninstall_plugins'" ) ) {
1432                         $uninstall_plugins = get_option( 'uninstall_plugins' );
1433                         delete_option( 'uninstall_plugins' );
1434                         add_option( 'uninstall_plugins', $uninstall_plugins, null, 'no' );
1435                 }
1436         }
1437 }
1438
1439 /**
1440  * Execute changes made in WordPress 3.5.
1441  *
1442  * @ignore
1443  * @since 3.5.0
1444  *
1445  * @global int   $wp_current_db_version
1446  * @global wpdb  $wpdb
1447  */
1448 function upgrade_350() {
1449         global $wp_current_db_version, $wpdb;
1450
1451         if ( $wp_current_db_version < 22006 && $wpdb->get_var( "SELECT link_id FROM $wpdb->links LIMIT 1" ) )
1452                 update_option( 'link_manager_enabled', 1 ); // Previously set to 0 by populate_options()
1453
1454         if ( $wp_current_db_version < 21811 && wp_should_upgrade_global_tables() ) {
1455                 $meta_keys = array();
1456                 foreach ( array_merge( get_post_types(), get_taxonomies() ) as $name ) {
1457                         if ( false !== strpos( $name, '-' ) )
1458                         $meta_keys[] = 'edit_' . str_replace( '-', '_', $name ) . '_per_page';
1459                 }
1460                 if ( $meta_keys ) {
1461                         $meta_keys = implode( "', '", $meta_keys );
1462                         $wpdb->query( "DELETE FROM $wpdb->usermeta WHERE meta_key IN ('$meta_keys')" );
1463                 }
1464         }
1465
1466         if ( $wp_current_db_version < 22422 && $term = get_term_by( 'slug', 'post-format-standard', 'post_format' ) )
1467                 wp_delete_term( $term->term_id, 'post_format' );
1468 }
1469
1470 /**
1471  * Execute changes made in WordPress 3.7.
1472  *
1473  * @ignore
1474  * @since 3.7.0
1475  *
1476  * @global int $wp_current_db_version
1477  */
1478 function upgrade_370() {
1479         global $wp_current_db_version;
1480         if ( $wp_current_db_version < 25824 )
1481                 wp_clear_scheduled_hook( 'wp_auto_updates_maybe_update' );
1482 }
1483
1484 /**
1485  * Execute changes made in WordPress 3.7.2.
1486  *
1487  * @ignore
1488  * @since 3.7.2
1489  * @since 3.8.0
1490  *
1491  * @global int $wp_current_db_version
1492  */
1493 function upgrade_372() {
1494         global $wp_current_db_version;
1495         if ( $wp_current_db_version < 26148 )
1496                 wp_clear_scheduled_hook( 'wp_maybe_auto_update' );
1497 }
1498
1499 /**
1500  * Execute changes made in WordPress 3.8.0.
1501  *
1502  * @ignore
1503  * @since 3.8.0
1504  *
1505  * @global int $wp_current_db_version
1506  */
1507 function upgrade_380() {
1508         global $wp_current_db_version;
1509         if ( $wp_current_db_version < 26691 ) {
1510                 deactivate_plugins( array( 'mp6/mp6.php' ), true );
1511         }
1512 }
1513
1514 /**
1515  * Execute changes made in WordPress 4.0.0.
1516  *
1517  * @ignore
1518  * @since 4.0.0
1519  *
1520  * @global int $wp_current_db_version
1521  */
1522 function upgrade_400() {
1523         global $wp_current_db_version;
1524         if ( $wp_current_db_version < 29630 ) {
1525                 if ( ! is_multisite() && false === get_option( 'WPLANG' ) ) {
1526                         if ( defined( 'WPLANG' ) && ( '' !== WPLANG ) && in_array( WPLANG, get_available_languages() ) ) {
1527                                 update_option( 'WPLANG', WPLANG );
1528                         } else {
1529                                 update_option( 'WPLANG', '' );
1530                         }
1531                 }
1532         }
1533 }
1534
1535 /**
1536  * Execute changes made in WordPress 4.2.0.
1537  *
1538  * @ignore
1539  * @since 4.2.0
1540  *
1541  * @global int   $wp_current_db_version
1542  * @global wpdb  $wpdb
1543  */
1544 function upgrade_420() {}
1545
1546 /**
1547  * Executes changes made in WordPress 4.3.0.
1548  *
1549  * @ignore
1550  * @since 4.3.0
1551  *
1552  * @global int  $wp_current_db_version Current version.
1553  * @global wpdb $wpdb                  WordPress database abstraction object.
1554  */
1555 function upgrade_430() {
1556         global $wp_current_db_version, $wpdb;
1557
1558         if ( $wp_current_db_version < 32364 ) {
1559                 upgrade_430_fix_comments();
1560         }
1561
1562         // Shared terms are split in a separate process.
1563         if ( $wp_current_db_version < 32814 ) {
1564                 update_option( 'finished_splitting_shared_terms', 0 );
1565                 wp_schedule_single_event( time() + ( 1 * MINUTE_IN_SECONDS ), 'wp_split_shared_term_batch' );
1566         }
1567
1568         if ( $wp_current_db_version < 33055 && 'utf8mb4' === $wpdb->charset ) {
1569                 if ( is_multisite() ) {
1570                         $tables = $wpdb->tables( 'blog' );
1571                 } else {
1572                         $tables = $wpdb->tables( 'all' );
1573                         if ( ! wp_should_upgrade_global_tables() ) {
1574                                 $global_tables = $wpdb->tables( 'global' );
1575                                 $tables = array_diff_assoc( $tables, $global_tables );
1576                         }
1577                 }
1578
1579                 foreach ( $tables as $table ) {
1580                         maybe_convert_table_to_utf8mb4( $table );
1581                 }
1582         }
1583 }
1584
1585 /**
1586  * Executes comments changes made in WordPress 4.3.0.
1587  *
1588  * @ignore
1589  * @since 4.3.0
1590  *
1591  * @global int  $wp_current_db_version Current version.
1592  * @global wpdb $wpdb                  WordPress database abstraction object.
1593  */
1594 function upgrade_430_fix_comments() {
1595         global $wp_current_db_version, $wpdb;
1596
1597         $content_length = $wpdb->get_col_length( $wpdb->comments, 'comment_content' );
1598
1599         if ( is_wp_error( $content_length ) ) {
1600                 return;
1601         }
1602
1603         if ( false === $content_length ) {
1604                 $content_length = array(
1605                         'type'   => 'byte',
1606                         'length' => 65535,
1607                 );
1608         } elseif ( ! is_array( $content_length ) ) {
1609                 $length = (int) $content_length > 0 ? (int) $content_length : 65535;
1610                 $content_length = array(
1611                         'type'   => 'byte',
1612                         'length' => $length
1613                 );
1614         }
1615
1616         if ( 'byte' !== $content_length['type'] || 0 === $content_length['length'] ) {
1617                 // Sites with malformed DB schemas are on their own.
1618                 return;
1619         }
1620
1621         $allowed_length = intval( $content_length['length'] ) - 10;
1622
1623         $comments = $wpdb->get_results(
1624                 "SELECT `comment_ID` FROM `{$wpdb->comments}`
1625                         WHERE `comment_date_gmt` > '2015-04-26'
1626                         AND LENGTH( `comment_content` ) >= {$allowed_length}
1627                         AND ( `comment_content` LIKE '%<%' OR `comment_content` LIKE '%>%' )"
1628         );
1629
1630         foreach ( $comments as $comment ) {
1631                 wp_delete_comment( $comment->comment_ID, true );
1632         }
1633 }
1634
1635 /**
1636  * Executes changes made in WordPress 4.3.1.
1637  *
1638  * @ignore
1639  * @since 4.3.1
1640  */
1641 function upgrade_431() {
1642         // Fix incorrect cron entries for term splitting
1643         $cron_array = _get_cron_array();
1644         if ( isset( $cron_array['wp_batch_split_terms'] ) ) {
1645                 unset( $cron_array['wp_batch_split_terms'] );
1646                 _set_cron_array( $cron_array );
1647         }
1648 }
1649
1650 /**
1651  * Executes changes made in WordPress 4.4.0.
1652  *
1653  * @ignore
1654  * @since 4.4.0
1655  *
1656  * @global int  $wp_current_db_version Current version.
1657  * @global wpdb $wpdb                  WordPress database abstraction object.
1658  */
1659 function upgrade_440() {
1660         global $wp_current_db_version, $wpdb;
1661
1662         if ( $wp_current_db_version < 34030 ) {
1663                 $wpdb->query( "ALTER TABLE {$wpdb->options} MODIFY option_name VARCHAR(191)" );
1664         }
1665
1666         // Remove the unused 'add_users' role.
1667         $roles = wp_roles();
1668         foreach ( $roles->role_objects as $role ) {
1669                 if ( $role->has_cap( 'add_users' ) ) {
1670                         $role->remove_cap( 'add_users' );
1671                 }
1672         }
1673 }
1674
1675 /**
1676  * Executes changes made in WordPress 4.5.0.
1677  *
1678  * @ignore
1679  * @since 4.5.0
1680  *
1681  * @global int  $wp_current_db_version Current database version.
1682  * @global wpdb $wpdb                  WordPress database abstraction object.
1683  */
1684 function upgrade_450() {
1685         global $wp_current_db_version, $wpdb;
1686
1687         if ( $wp_current_db_version < 36180 ) {
1688                 wp_clear_scheduled_hook( 'wp_maybe_auto_update' );
1689         }
1690
1691         // Remove unused email confirmation options, moved to usermeta.
1692         if ( $wp_current_db_version < 36679 && is_multisite() ) {
1693                 $wpdb->query( "DELETE FROM $wpdb->options WHERE option_name REGEXP '^[0-9]+_new_email$'" );
1694         }
1695
1696         // Remove unused user setting for wpLink.
1697         delete_user_setting( 'wplink' );
1698 }
1699
1700 /**
1701  * Executes changes made in WordPress 4.6.0.
1702  *
1703  * @ignore
1704  * @since 4.6.0
1705  *
1706  * @global int $wp_current_db_version Current database version.
1707  */
1708 function upgrade_460() {
1709         global $wp_current_db_version;
1710
1711         // Remove unused post meta.
1712         if ( $wp_current_db_version < 37854 ) {
1713                 delete_post_meta_by_key( '_post_restored_from' );
1714         }
1715
1716         // Remove plugins with callback as an array object/method as the uninstall hook, see #13786.
1717         if ( $wp_current_db_version < 37965 ) {
1718                 $uninstall_plugins = get_option( 'uninstall_plugins', array() );
1719
1720                 if ( ! empty( $uninstall_plugins ) ) {
1721                         foreach ( $uninstall_plugins as $basename => $callback ) {
1722                                 if ( is_array( $callback ) && is_object( $callback[0] ) ) {
1723                                         unset( $uninstall_plugins[ $basename ] );
1724                                 }
1725                         }
1726
1727                         update_option( 'uninstall_plugins', $uninstall_plugins );
1728                 }
1729         }
1730 }
1731
1732 /**
1733  * Executes network-level upgrade routines.
1734  *
1735  * @since 3.0.0
1736  *
1737  * @global int   $wp_current_db_version
1738  * @global wpdb  $wpdb
1739  */
1740 function upgrade_network() {
1741         global $wp_current_db_version, $wpdb;
1742
1743         // Always.
1744         if ( is_main_network() ) {
1745                 /*
1746                  * Deletes all expired transients. The multi-table delete syntax is used
1747                  * to delete the transient record from table a, and the corresponding
1748                  * transient_timeout record from table b.
1749                  */
1750                 $time = time();
1751                 $sql = "DELETE a, b FROM $wpdb->sitemeta a, $wpdb->sitemeta b
1752                         WHERE a.meta_key LIKE %s
1753                         AND a.meta_key NOT LIKE %s
1754                         AND b.meta_key = CONCAT( '_site_transient_timeout_', SUBSTRING( a.meta_key, 17 ) )
1755                         AND b.meta_value < %d";
1756                 $wpdb->query( $wpdb->prepare( $sql, $wpdb->esc_like( '_site_transient_' ) . '%', $wpdb->esc_like ( '_site_transient_timeout_' ) . '%', $time ) );
1757         }
1758
1759         // 2.8.
1760         if ( $wp_current_db_version < 11549 ) {
1761                 $wpmu_sitewide_plugins = get_site_option( 'wpmu_sitewide_plugins' );
1762                 $active_sitewide_plugins = get_site_option( 'active_sitewide_plugins' );
1763                 if ( $wpmu_sitewide_plugins ) {
1764                         if ( !$active_sitewide_plugins )
1765                                 $sitewide_plugins = (array) $wpmu_sitewide_plugins;
1766                         else
1767                                 $sitewide_plugins = array_merge( (array) $active_sitewide_plugins, (array) $wpmu_sitewide_plugins );
1768
1769                         update_site_option( 'active_sitewide_plugins', $sitewide_plugins );
1770                 }
1771                 delete_site_option( 'wpmu_sitewide_plugins' );
1772                 delete_site_option( 'deactivated_sitewide_plugins' );
1773
1774                 $start = 0;
1775                 while( $rows = $wpdb->get_results( "SELECT meta_key, meta_value FROM {$wpdb->sitemeta} ORDER BY meta_id LIMIT $start, 20" ) ) {
1776                         foreach ( $rows as $row ) {
1777                                 $value = $row->meta_value;
1778                                 if ( !@unserialize( $value ) )
1779                                         $value = stripslashes( $value );
1780                                 if ( $value !== $row->meta_value ) {
1781                                         update_site_option( $row->meta_key, $value );
1782                                 }
1783                         }
1784                         $start += 20;
1785                 }
1786         }
1787
1788         // 3.0
1789         if ( $wp_current_db_version < 13576 )
1790                 update_site_option( 'global_terms_enabled', '1' );
1791
1792         // 3.3
1793         if ( $wp_current_db_version < 19390 )
1794                 update_site_option( 'initial_db_version', $wp_current_db_version );
1795
1796         if ( $wp_current_db_version < 19470 ) {
1797                 if ( false === get_site_option( 'active_sitewide_plugins' ) )
1798                         update_site_option( 'active_sitewide_plugins', array() );
1799         }
1800
1801         // 3.4
1802         if ( $wp_current_db_version < 20148 ) {
1803                 // 'allowedthemes' keys things by stylesheet. 'allowed_themes' keyed things by name.
1804                 $allowedthemes  = get_site_option( 'allowedthemes'  );
1805                 $allowed_themes = get_site_option( 'allowed_themes' );
1806                 if ( false === $allowedthemes && is_array( $allowed_themes ) && $allowed_themes ) {
1807                         $converted = array();
1808                         $themes = wp_get_themes();
1809                         foreach ( $themes as $stylesheet => $theme_data ) {
1810                                 if ( isset( $allowed_themes[ $theme_data->get('Name') ] ) )
1811                                         $converted[ $stylesheet ] = true;
1812                         }
1813                         update_site_option( 'allowedthemes', $converted );
1814                         delete_site_option( 'allowed_themes' );
1815                 }
1816         }
1817
1818         // 3.5
1819         if ( $wp_current_db_version < 21823 )
1820                 update_site_option( 'ms_files_rewriting', '1' );
1821
1822         // 3.5.2
1823         if ( $wp_current_db_version < 24448 ) {
1824                 $illegal_names = get_site_option( 'illegal_names' );
1825                 if ( is_array( $illegal_names ) && count( $illegal_names ) === 1 ) {
1826                         $illegal_name = reset( $illegal_names );
1827                         $illegal_names = explode( ' ', $illegal_name );
1828                         update_site_option( 'illegal_names', $illegal_names );
1829                 }
1830         }
1831
1832         // 4.2
1833         if ( $wp_current_db_version < 31351 && $wpdb->charset === 'utf8mb4' ) {
1834                 if ( wp_should_upgrade_global_tables() ) {
1835                         $wpdb->query( "ALTER TABLE $wpdb->usermeta DROP INDEX meta_key, ADD INDEX meta_key(meta_key(191))" );
1836                         $wpdb->query( "ALTER TABLE $wpdb->site DROP INDEX domain, ADD INDEX domain(domain(140),path(51))" );
1837                         $wpdb->query( "ALTER TABLE $wpdb->sitemeta DROP INDEX meta_key, ADD INDEX meta_key(meta_key(191))" );
1838                         $wpdb->query( "ALTER TABLE $wpdb->signups DROP INDEX domain_path, ADD INDEX domain_path(domain(140),path(51))" );
1839
1840                         $tables = $wpdb->tables( 'global' );
1841
1842                         // sitecategories may not exist.
1843                         if ( ! $wpdb->get_var( "SHOW TABLES LIKE '{$tables['sitecategories']}'" ) ) {
1844                                 unset( $tables['sitecategories'] );
1845                         }
1846
1847                         foreach ( $tables as $table ) {
1848                                 maybe_convert_table_to_utf8mb4( $table );
1849                         }
1850                 }
1851         }
1852
1853         // 4.3
1854         if ( $wp_current_db_version < 33055 && 'utf8mb4' === $wpdb->charset ) {
1855                 if ( wp_should_upgrade_global_tables() ) {
1856                         $upgrade = false;
1857                         $indexes = $wpdb->get_results( "SHOW INDEXES FROM $wpdb->signups" );
1858                         foreach ( $indexes as $index ) {
1859                                 if ( 'domain_path' == $index->Key_name && 'domain' == $index->Column_name && 140 != $index->Sub_part ) {
1860                                         $upgrade = true;
1861                                         break;
1862                                 }
1863                         }
1864
1865                         if ( $upgrade ) {
1866                                 $wpdb->query( "ALTER TABLE $wpdb->signups DROP INDEX domain_path, ADD INDEX domain_path(domain(140),path(51))" );
1867                         }
1868
1869                         $tables = $wpdb->tables( 'global' );
1870
1871                         // sitecategories may not exist.
1872                         if ( ! $wpdb->get_var( "SHOW TABLES LIKE '{$tables['sitecategories']}'" ) ) {
1873                                 unset( $tables['sitecategories'] );
1874                         }
1875
1876                         foreach ( $tables as $table ) {
1877                                 maybe_convert_table_to_utf8mb4( $table );
1878                         }
1879                 }
1880         }
1881 }
1882
1883 //
1884 // General functions we use to actually do stuff
1885 //
1886
1887 /**
1888  * Creates a table in the database if it doesn't already exist.
1889  *
1890  * This method checks for an existing database and creates a new one if it's not
1891  * already present. It doesn't rely on MySQL's "IF NOT EXISTS" statement, but chooses
1892  * to query all tables first and then run the SQL statement creating the table.
1893  *
1894  * @since 1.0.0
1895  *
1896  * @global wpdb  $wpdb
1897  *
1898  * @param string $table_name Database table name to create.
1899  * @param string $create_ddl SQL statement to create table.
1900  * @return bool If table already exists or was created by function.
1901  */
1902 function maybe_create_table($table_name, $create_ddl) {
1903         global $wpdb;
1904
1905         $query = $wpdb->prepare( "SHOW TABLES LIKE %s", $wpdb->esc_like( $table_name ) );
1906
1907         if ( $wpdb->get_var( $query ) == $table_name ) {
1908                 return true;
1909         }
1910
1911         // Didn't find it try to create it..
1912         $wpdb->query($create_ddl);
1913
1914         // We cannot directly tell that whether this succeeded!
1915         if ( $wpdb->get_var( $query ) == $table_name ) {
1916                 return true;
1917         }
1918         return false;
1919 }
1920
1921 /**
1922  * Drops a specified index from a table.
1923  *
1924  * @since 1.0.1
1925  *
1926  * @global wpdb  $wpdb
1927  *
1928  * @param string $table Database table name.
1929  * @param string $index Index name to drop.
1930  * @return true True, when finished.
1931  */
1932 function drop_index($table, $index) {
1933         global $wpdb;
1934         $wpdb->hide_errors();
1935         $wpdb->query("ALTER TABLE `$table` DROP INDEX `$index`");
1936         // Now we need to take out all the extra ones we may have created
1937         for ($i = 0; $i < 25; $i++) {
1938                 $wpdb->query("ALTER TABLE `$table` DROP INDEX `{$index}_$i`");
1939         }
1940         $wpdb->show_errors();
1941         return true;
1942 }
1943
1944 /**
1945  * Adds an index to a specified table.
1946  *
1947  * @since 1.0.1
1948  *
1949  * @global wpdb  $wpdb
1950  *
1951  * @param string $table Database table name.
1952  * @param string $index Database table index column.
1953  * @return true True, when done with execution.
1954  */
1955 function add_clean_index($table, $index) {
1956         global $wpdb;
1957         drop_index($table, $index);
1958         $wpdb->query("ALTER TABLE `$table` ADD INDEX ( `$index` )");
1959         return true;
1960 }
1961
1962 /**
1963  * Adds column to a database table if it doesn't already exist.
1964  *
1965  * @since 1.3.0
1966  *
1967  * @global wpdb  $wpdb
1968  *
1969  * @param string $table_name  The table name to modify.
1970  * @param string $column_name The column name to add to the table.
1971  * @param string $create_ddl  The SQL statement used to add the column.
1972  * @return bool True if already exists or on successful completion, false on error.
1973  */
1974 function maybe_add_column($table_name, $column_name, $create_ddl) {
1975         global $wpdb;
1976         foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) {
1977                 if ($column == $column_name) {
1978                         return true;
1979                 }
1980         }
1981
1982         // Didn't find it try to create it.
1983         $wpdb->query($create_ddl);
1984
1985         // We cannot directly tell that whether this succeeded!
1986         foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) {
1987                 if ($column == $column_name) {
1988                         return true;
1989                 }
1990         }
1991         return false;
1992 }
1993
1994 /**
1995  * If a table only contains utf8 or utf8mb4 columns, convert it to utf8mb4.
1996  *
1997  * @since 4.2.0
1998  *
1999  * @global wpdb  $wpdb
2000  *
2001  * @param string $table The table to convert.
2002  * @return bool true if the table was converted, false if it wasn't.
2003  */
2004 function maybe_convert_table_to_utf8mb4( $table ) {
2005         global $wpdb;
2006
2007         $results = $wpdb->get_results( "SHOW FULL COLUMNS FROM `$table`" );
2008         if ( ! $results ) {
2009                 return false;
2010         }
2011
2012         foreach ( $results as $column ) {
2013                 if ( $column->Collation ) {
2014                         list( $charset ) = explode( '_', $column->Collation );
2015                         $charset = strtolower( $charset );
2016                         if ( 'utf8' !== $charset && 'utf8mb4' !== $charset ) {
2017                                 // Don't upgrade tables that have non-utf8 columns.
2018                                 return false;
2019                         }
2020                 }
2021         }
2022
2023         $table_details = $wpdb->get_row( "SHOW TABLE STATUS LIKE '$table'" );
2024         if ( ! $table_details ) {
2025                 return false;
2026         }
2027
2028         list( $table_charset ) = explode( '_', $table_details->Collation );
2029         $table_charset = strtolower( $table_charset );
2030         if ( 'utf8mb4' === $table_charset ) {
2031                 return true;
2032         }
2033
2034         return $wpdb->query( "ALTER TABLE $table CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci" );
2035 }
2036
2037 /**
2038  * Retrieve all options as it was for 1.2.
2039  *
2040  * @since 1.2.0
2041  *
2042  * @global wpdb  $wpdb
2043  *
2044  * @return stdClass List of options.
2045  */
2046 function get_alloptions_110() {
2047         global $wpdb;
2048         $all_options = new stdClass;
2049         if ( $options = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options" ) ) {
2050                 foreach ( $options as $option ) {
2051                         if ( 'siteurl' == $option->option_name || 'home' == $option->option_name || 'category_base' == $option->option_name )
2052                                 $option->option_value = untrailingslashit( $option->option_value );
2053                         $all_options->{$option->option_name} = stripslashes( $option->option_value );
2054                 }
2055         }
2056         return $all_options;
2057 }
2058
2059 /**
2060  * Utility version of get_option that is private to install/upgrade.
2061  *
2062  * @ignore
2063  * @since 1.5.1
2064  * @access private
2065  *
2066  * @global wpdb  $wpdb
2067  *
2068  * @param string $setting Option name.
2069  * @return mixed
2070  */
2071 function __get_option($setting) {
2072         global $wpdb;
2073
2074         if ( $setting == 'home' && defined( 'WP_HOME' ) )
2075                 return untrailingslashit( WP_HOME );
2076
2077         if ( $setting == 'siteurl' && defined( 'WP_SITEURL' ) )
2078                 return untrailingslashit( WP_SITEURL );
2079
2080         $option = $wpdb->get_var( $wpdb->prepare("SELECT option_value FROM $wpdb->options WHERE option_name = %s", $setting ) );
2081
2082         if ( 'home' == $setting && '' == $option )
2083                 return __get_option( 'siteurl' );
2084
2085         if ( 'siteurl' == $setting || 'home' == $setting || 'category_base' == $setting || 'tag_base' == $setting )
2086                 $option = untrailingslashit( $option );
2087
2088         return maybe_unserialize( $option );
2089 }
2090
2091 /**
2092  * Filters for content to remove unnecessary slashes.
2093  *
2094  * @since 1.5.0
2095  *
2096  * @param string $content The content to modify.
2097  * @return string The de-slashed content.
2098  */
2099 function deslash($content) {
2100         // Note: \\\ inside a regex denotes a single backslash.
2101
2102         /*
2103          * Replace one or more backslashes followed by a single quote with
2104          * a single quote.
2105          */
2106         $content = preg_replace("/\\\+'/", "'", $content);
2107
2108         /*
2109          * Replace one or more backslashes followed by a double quote with
2110          * a double quote.
2111          */
2112         $content = preg_replace('/\\\+"/', '"', $content);
2113
2114         // Replace one or more backslashes with one backslash.
2115         $content = preg_replace("/\\\+/", "\\", $content);
2116
2117         return $content;
2118 }
2119
2120 /**
2121  * Modifies the database based on specified SQL statements.
2122  *
2123  * Useful for creating new tables and updating existing tables to a new structure.
2124  *
2125  * @since 1.5.0
2126  *
2127  * @global wpdb  $wpdb
2128  *
2129  * @param string|array $queries Optional. The query to run. Can be multiple queries
2130  *                              in an array, or a string of queries separated by
2131  *                              semicolons. Default empty.
2132  * @param bool         $execute Optional. Whether or not to execute the query right away.
2133  *                              Default true.
2134  * @return array Strings containing the results of the various update queries.
2135  */
2136 function dbDelta( $queries = '', $execute = true ) {
2137         global $wpdb;
2138
2139         if ( in_array( $queries, array( '', 'all', 'blog', 'global', 'ms_global' ), true ) )
2140             $queries = wp_get_db_schema( $queries );
2141
2142         // Separate individual queries into an array
2143         if ( !is_array($queries) ) {
2144                 $queries = explode( ';', $queries );
2145                 $queries = array_filter( $queries );
2146         }
2147
2148         /**
2149          * Filters the dbDelta SQL queries.
2150          *
2151          * @since 3.3.0
2152          *
2153          * @param array $queries An array of dbDelta SQL queries.
2154          */
2155         $queries = apply_filters( 'dbdelta_queries', $queries );
2156
2157         $cqueries = array(); // Creation Queries
2158         $iqueries = array(); // Insertion Queries
2159         $for_update = array();
2160
2161         // Create a tablename index for an array ($cqueries) of queries
2162         foreach ($queries as $qry) {
2163                 if ( preg_match( "|CREATE TABLE ([^ ]*)|", $qry, $matches ) ) {
2164                         $cqueries[ trim( $matches[1], '`' ) ] = $qry;
2165                         $for_update[$matches[1]] = 'Created table '.$matches[1];
2166                 } elseif ( preg_match( "|CREATE DATABASE ([^ ]*)|", $qry, $matches ) ) {
2167                         array_unshift( $cqueries, $qry );
2168                 } elseif ( preg_match( "|INSERT INTO ([^ ]*)|", $qry, $matches ) ) {
2169                         $iqueries[] = $qry;
2170                 } elseif ( preg_match( "|UPDATE ([^ ]*)|", $qry, $matches ) ) {
2171                         $iqueries[] = $qry;
2172                 } else {
2173                         // Unrecognized query type
2174                 }
2175         }
2176
2177         /**
2178          * Filters the dbDelta SQL queries for creating tables and/or databases.
2179          *
2180          * Queries filterable via this hook contain "CREATE TABLE" or "CREATE DATABASE".
2181          *
2182          * @since 3.3.0
2183          *
2184          * @param array $cqueries An array of dbDelta create SQL queries.
2185          */
2186         $cqueries = apply_filters( 'dbdelta_create_queries', $cqueries );
2187
2188         /**
2189          * Filters the dbDelta SQL queries for inserting or updating.
2190          *
2191          * Queries filterable via this hook contain "INSERT INTO" or "UPDATE".
2192          *
2193          * @since 3.3.0
2194          *
2195          * @param array $iqueries An array of dbDelta insert or update SQL queries.
2196          */
2197         $iqueries = apply_filters( 'dbdelta_insert_queries', $iqueries );
2198
2199         $text_fields = array( 'tinytext', 'text', 'mediumtext', 'longtext' );
2200         $blob_fields = array( 'tinyblob', 'blob', 'mediumblob', 'longblob' );
2201
2202         $global_tables = $wpdb->tables( 'global' );
2203         foreach ( $cqueries as $table => $qry ) {
2204                 // Upgrade global tables only for the main site. Don't upgrade at all if conditions are not optimal.
2205                 if ( in_array( $table, $global_tables ) && ! wp_should_upgrade_global_tables() ) {
2206                         unset( $cqueries[ $table ], $for_update[ $table ] );
2207                         continue;
2208                 }
2209
2210                 // Fetch the table column structure from the database
2211                 $suppress = $wpdb->suppress_errors();
2212                 $tablefields = $wpdb->get_results("DESCRIBE {$table};");
2213                 $wpdb->suppress_errors( $suppress );
2214
2215                 if ( ! $tablefields )
2216                         continue;
2217
2218                 // Clear the field and index arrays.
2219                 $cfields = $indices = array();
2220
2221                 // Get all of the field names in the query from between the parentheses.
2222                 preg_match("|\((.*)\)|ms", $qry, $match2);
2223                 $qryline = trim($match2[1]);
2224
2225                 // Separate field lines into an array.
2226                 $flds = explode("\n", $qryline);
2227
2228                 // For every field line specified in the query.
2229                 foreach ( $flds as $fld ) {
2230                         $fld = trim( $fld, " \t\n\r\0\x0B," ); // Default trim characters, plus ','.
2231
2232                         // Extract the field name.
2233                         preg_match( '|^([^ ]*)|', $fld, $fvals );
2234                         $fieldname = trim( $fvals[1], '`' );
2235                         $fieldname_lowercased = strtolower( $fieldname );
2236
2237                         // Verify the found field name.
2238                         $validfield = true;
2239                         switch ( $fieldname_lowercased ) {
2240                                 case '':
2241                                 case 'primary':
2242                                 case 'index':
2243                                 case 'fulltext':
2244                                 case 'unique':
2245                                 case 'key':
2246                                 case 'spatial':
2247                                         $validfield = false;
2248
2249                                         /*
2250                                          * Normalize the index definition.
2251                                          *
2252                                          * This is done so the definition can be compared against the result of a
2253                                          * `SHOW INDEX FROM $table_name` query which returns the current table
2254                                          * index information.
2255                                          */
2256
2257                                         // Extract type, name and columns from the definition.
2258                                         preg_match(
2259                                                   '/^'
2260                                                 .   '(?P<index_type>'             // 1) Type of the index.
2261                                                 .       'PRIMARY\s+KEY|(?:UNIQUE|FULLTEXT|SPATIAL)\s+(?:KEY|INDEX)|KEY|INDEX'
2262                                                 .   ')'
2263                                                 .   '\s+'                         // Followed by at least one white space character.
2264                                                 .   '(?:'                         // Name of the index. Optional if type is PRIMARY KEY.
2265                                                 .       '`?'                      // Name can be escaped with a backtick.
2266                                                 .           '(?P<index_name>'     // 2) Name of the index.
2267                                                 .               '(?:[0-9a-zA-Z$_-]|[\xC2-\xDF][\x80-\xBF])+'
2268                                                 .           ')'
2269                                                 .       '`?'                      // Name can be escaped with a backtick.
2270                                                 .       '\s+'                     // Followed by at least one white space character.
2271                                                 .   ')*'
2272                                                 .   '\('                          // Opening bracket for the columns.
2273                                                 .       '(?P<index_columns>'
2274                                                 .           '.+?'                 // 3) Column names, index prefixes, and orders.
2275                                                 .       ')'
2276                                                 .   '\)'                          // Closing bracket for the columns.
2277                                                 . '$/im',
2278                                                 $fld,
2279                                                 $index_matches
2280                                         );
2281
2282                                         // Uppercase the index type and normalize space characters.
2283                                         $index_type = strtoupper( preg_replace( '/\s+/', ' ', trim( $index_matches['index_type'] ) ) );
2284
2285                                         // 'INDEX' is a synonym for 'KEY', standardize on 'KEY'.
2286                                         $index_type = str_replace( 'INDEX', 'KEY', $index_type );
2287
2288                                         // Escape the index name with backticks. An index for a primary key has no name.
2289                                         $index_name = ( 'PRIMARY KEY' === $index_type ) ? '' : '`' . strtolower( $index_matches['index_name'] ) . '`';
2290
2291                                         // Parse the columns. Multiple columns are separated by a comma.
2292                                         $index_columns = array_map( 'trim', explode( ',', $index_matches['index_columns'] ) );
2293
2294                                         // Normalize columns.
2295                                         foreach ( $index_columns as &$index_column ) {
2296                                                 // Extract column name and number of indexed characters (sub_part).
2297                                                 preg_match(
2298                                                           '/'
2299                                                         .   '`?'                      // Name can be escaped with a backtick.
2300                                                         .       '(?P<column_name>'    // 1) Name of the column.
2301                                                         .           '(?:[0-9a-zA-Z$_-]|[\xC2-\xDF][\x80-\xBF])+'
2302                                                         .       ')'
2303                                                         .   '`?'                      // Name can be escaped with a backtick.
2304                                                         .   '(?:'                     // Optional sub part.
2305                                                         .       '\s*'                 // Optional white space character between name and opening bracket.
2306                                                         .       '\('                  // Opening bracket for the sub part.
2307                                                         .           '\s*'             // Optional white space character after opening bracket.
2308                                                         .           '(?P<sub_part>'
2309                                                         .               '\d+'         // 2) Number of indexed characters.
2310                                                         .           ')'
2311                                                         .           '\s*'             // Optional white space character before closing bracket.
2312                                                         .        '\)'                 // Closing bracket for the sub part.
2313                                                         .   ')?'
2314                                                         . '/',
2315                                                         $index_column,
2316                                                         $index_column_matches
2317                                                 );
2318
2319                                                 // Escape the column name with backticks.
2320                                                 $index_column = '`' . $index_column_matches['column_name'] . '`';
2321
2322                                                 // Append the optional sup part with the number of indexed characters.
2323                                                 if ( isset( $index_column_matches['sub_part'] ) ) {
2324                                                         $index_column .= '(' . $index_column_matches['sub_part'] . ')';
2325                                                 }
2326                                         }
2327
2328                                         // Build the normalized index definition and add it to the list of indices.
2329                                         $indices[] = "{$index_type} {$index_name} (" . implode( ',', $index_columns ) . ")";
2330
2331                                         // Destroy no longer needed variables.
2332                                         unset( $index_column, $index_column_matches, $index_matches, $index_type, $index_name, $index_columns );
2333
2334                                         break;
2335                         }
2336
2337                         // If it's a valid field, add it to the field array.
2338                         if ( $validfield ) {
2339                                 $cfields[ $fieldname_lowercased ] = $fld;
2340                         }
2341                 }
2342
2343                 // For every field in the table.
2344                 foreach ( $tablefields as $tablefield ) {
2345                         $tablefield_field_lowercased = strtolower( $tablefield->Field );
2346                         $tablefield_type_lowercased = strtolower( $tablefield->Type );
2347
2348                         // If the table field exists in the field array ...
2349                         if ( array_key_exists( $tablefield_field_lowercased, $cfields ) ) {
2350
2351                                 // Get the field type from the query.
2352                                 preg_match( '|`?' . $tablefield->Field . '`? ([^ ]*( unsigned)?)|i', $cfields[ $tablefield_field_lowercased ], $matches );
2353                                 $fieldtype = $matches[1];
2354                                 $fieldtype_lowercased = strtolower( $fieldtype );
2355
2356                                 // Is actual field type different from the field type in query?
2357                                 if ($tablefield->Type != $fieldtype) {
2358                                         $do_change = true;
2359                                         if ( in_array( $fieldtype_lowercased, $text_fields ) && in_array( $tablefield_type_lowercased, $text_fields ) ) {
2360                                                 if ( array_search( $fieldtype_lowercased, $text_fields ) < array_search( $tablefield_type_lowercased, $text_fields ) ) {
2361                                                         $do_change = false;
2362                                                 }
2363                                         }
2364
2365                                         if ( in_array( $fieldtype_lowercased, $blob_fields ) && in_array( $tablefield_type_lowercased, $blob_fields ) ) {
2366                                                 if ( array_search( $fieldtype_lowercased, $blob_fields ) < array_search( $tablefield_type_lowercased, $blob_fields ) ) {
2367                                                         $do_change = false;
2368                                                 }
2369                                         }
2370
2371                                         if ( $do_change ) {
2372                                                 // Add a query to change the column type.
2373                                                 $cqueries[] = "ALTER TABLE {$table} CHANGE COLUMN `{$tablefield->Field}` " . $cfields[ $tablefield_field_lowercased ];
2374                                                 $for_update[$table.'.'.$tablefield->Field] = "Changed type of {$table}.{$tablefield->Field} from {$tablefield->Type} to {$fieldtype}";
2375                                         }
2376                                 }
2377
2378                                 // Get the default value from the array.
2379                                 if ( preg_match( "| DEFAULT '(.*?)'|i", $cfields[ $tablefield_field_lowercased ], $matches ) ) {
2380                                         $default_value = $matches[1];
2381                                         if ($tablefield->Default != $default_value) {
2382                                                 // Add a query to change the column's default value
2383                                                 $cqueries[] = "ALTER TABLE {$table} ALTER COLUMN `{$tablefield->Field}` SET DEFAULT '{$default_value}'";
2384                                                 $for_update[$table.'.'.$tablefield->Field] = "Changed default value of {$table}.{$tablefield->Field} from {$tablefield->Default} to {$default_value}";
2385                                         }
2386                                 }
2387
2388                                 // Remove the field from the array (so it's not added).
2389                                 unset( $cfields[ $tablefield_field_lowercased ] );
2390                         } else {
2391                                 // This field exists in the table, but not in the creation queries?
2392                         }
2393                 }
2394
2395                 // For every remaining field specified for the table.
2396                 foreach ($cfields as $fieldname => $fielddef) {
2397                         // Push a query line into $cqueries that adds the field to that table.
2398                         $cqueries[] = "ALTER TABLE {$table} ADD COLUMN $fielddef";
2399                         $for_update[$table.'.'.$fieldname] = 'Added column '.$table.'.'.$fieldname;
2400                 }
2401
2402                 // Index stuff goes here. Fetch the table index structure from the database.
2403                 $tableindices = $wpdb->get_results("SHOW INDEX FROM {$table};");
2404
2405                 if ($tableindices) {
2406                         // Clear the index array.
2407                         $index_ary = array();
2408
2409                         // For every index in the table.
2410                         foreach ($tableindices as $tableindex) {
2411
2412                                 // Add the index to the index data array.
2413                                 $keyname = strtolower( $tableindex->Key_name );
2414                                 $index_ary[$keyname]['columns'][] = array('fieldname' => $tableindex->Column_name, 'subpart' => $tableindex->Sub_part);
2415                                 $index_ary[$keyname]['unique'] = ($tableindex->Non_unique == 0)?true:false;
2416                                 $index_ary[$keyname]['index_type'] = $tableindex->Index_type;
2417                         }
2418
2419                         // For each actual index in the index array.
2420                         foreach ($index_ary as $index_name => $index_data) {
2421
2422                                 // Build a create string to compare to the query.
2423                                 $index_string = '';
2424                                 if ($index_name == 'primary') {
2425                                         $index_string .= 'PRIMARY ';
2426                                 } elseif ( $index_data['unique'] ) {
2427                                         $index_string .= 'UNIQUE ';
2428                                 }
2429                                 if ( 'FULLTEXT' === strtoupper( $index_data['index_type'] ) ) {
2430                                         $index_string .= 'FULLTEXT ';
2431                                 }
2432                                 if ( 'SPATIAL' === strtoupper( $index_data['index_type'] ) ) {
2433                                         $index_string .= 'SPATIAL ';
2434                                 }
2435                                 $index_string .= 'KEY ';
2436                                 if ( 'primary' !== $index_name  ) {
2437                                         $index_string .= '`' . $index_name . '`';
2438                                 }
2439                                 $index_columns = '';
2440
2441                                 // For each column in the index.
2442                                 foreach ($index_data['columns'] as $column_data) {
2443                                         if ( $index_columns != '' ) {
2444                                                 $index_columns .= ',';
2445                                         }
2446
2447                                         // Add the field to the column list string.
2448                                         $index_columns .= '`' . $column_data['fieldname'] . '`';
2449                                         if ($column_data['subpart'] != '') {
2450                                                 $index_columns .= '('.$column_data['subpart'].')';
2451                                         }
2452                                 }
2453
2454                                 // The alternative index string doesn't care about subparts
2455                                 $alt_index_columns = preg_replace( '/\([^)]*\)/', '', $index_columns );
2456
2457                                 // Add the column list to the index create string.
2458                                 $index_strings = array(
2459                                         "$index_string ($index_columns)",
2460                                         "$index_string ($alt_index_columns)",
2461                                 );
2462
2463                                 foreach ( $index_strings as $index_string ) {
2464                                         if ( ! ( ( $aindex = array_search( $index_string, $indices ) ) === false ) ) {
2465                                                 unset( $indices[ $aindex ] );
2466                                                 break;
2467                                         }
2468                                 }
2469                         }
2470                 }
2471
2472                 // For every remaining index specified for the table.
2473                 foreach ( (array) $indices as $index ) {
2474                         // Push a query line into $cqueries that adds the index to that table.
2475                         $cqueries[] = "ALTER TABLE {$table} ADD $index";
2476                         $for_update[] = 'Added index ' . $table . ' ' . $index;
2477                 }
2478
2479                 // Remove the original table creation query from processing.
2480                 unset( $cqueries[ $table ], $for_update[ $table ] );
2481         }
2482
2483         $allqueries = array_merge($cqueries, $iqueries);
2484         if ($execute) {
2485                 foreach ($allqueries as $query) {
2486                         $wpdb->query($query);
2487                 }
2488         }
2489
2490         return $for_update;
2491 }
2492
2493 /**
2494  * Updates the database tables to a new schema.
2495  *
2496  * By default, updates all the tables to use the latest defined schema, but can also
2497  * be used to update a specific set of tables in wp_get_db_schema().
2498  *
2499  * @since 1.5.0
2500  *
2501  * @uses dbDelta
2502  *
2503  * @param string $tables Optional. Which set of tables to update. Default is 'all'.
2504  */
2505 function make_db_current( $tables = 'all' ) {
2506         $alterations = dbDelta( $tables );
2507         echo "<ol>\n";
2508         foreach ($alterations as $alteration) echo "<li>$alteration</li>\n";
2509         echo "</ol>\n";
2510 }
2511
2512 /**
2513  * Updates the database tables to a new schema, but without displaying results.
2514  *
2515  * By default, updates all the tables to use the latest defined schema, but can
2516  * also be used to update a specific set of tables in wp_get_db_schema().
2517  *
2518  * @since 1.5.0
2519  *
2520  * @see make_db_current()
2521  *
2522  * @param string $tables Optional. Which set of tables to update. Default is 'all'.
2523  */
2524 function make_db_current_silent( $tables = 'all' ) {
2525         dbDelta( $tables );
2526 }
2527
2528 /**
2529  * Creates a site theme from an existing theme.
2530  *
2531  * {@internal Missing Long Description}}
2532  *
2533  * @since 1.5.0
2534  *
2535  * @param string $theme_name The name of the theme.
2536  * @param string $template   The directory name of the theme.
2537  * @return bool
2538  */
2539 function make_site_theme_from_oldschool($theme_name, $template) {
2540         $home_path = get_home_path();
2541         $site_dir = WP_CONTENT_DIR . "/themes/$template";
2542
2543         if (! file_exists("$home_path/index.php"))
2544                 return false;
2545
2546         /*
2547          * Copy files from the old locations to the site theme.
2548          * TODO: This does not copy arbitrary include dependencies. Only the standard WP files are copied.
2549          */
2550         $files = array('index.php' => 'index.php', 'wp-layout.css' => 'style.css', 'wp-comments.php' => 'comments.php', 'wp-comments-popup.php' => 'comments-popup.php');
2551
2552         foreach ($files as $oldfile => $newfile) {
2553                 if ($oldfile == 'index.php')
2554                         $oldpath = $home_path;
2555                 else
2556                         $oldpath = ABSPATH;
2557
2558                 // Check to make sure it's not a new index.
2559                 if ($oldfile == 'index.php') {
2560                         $index = implode('', file("$oldpath/$oldfile"));
2561                         if (strpos($index, 'WP_USE_THEMES') !== false) {
2562                                 if (! @copy(WP_CONTENT_DIR . '/themes/' . WP_DEFAULT_THEME . '/index.php', "$site_dir/$newfile"))
2563                                         return false;
2564
2565                                 // Don't copy anything.
2566                                 continue;
2567                         }
2568                 }
2569
2570                 if (! @copy("$oldpath/$oldfile", "$site_dir/$newfile"))
2571                         return false;
2572
2573                 chmod("$site_dir/$newfile", 0777);
2574
2575                 // Update the blog header include in each file.
2576                 $lines = explode("\n", implode('', file("$site_dir/$newfile")));
2577                 if ($lines) {
2578                         $f = fopen("$site_dir/$newfile", 'w');
2579
2580                         foreach ($lines as $line) {
2581                                 if (preg_match('/require.*wp-blog-header/', $line))
2582                                         $line = '//' . $line;
2583
2584                                 // Update stylesheet references.
2585                                 $line = str_replace("<?php echo __get_option('siteurl'); ?>/wp-layout.css", "<?php bloginfo('stylesheet_url'); ?>", $line);
2586
2587                                 // Update comments template inclusion.
2588                                 $line = str_replace("<?php include(ABSPATH . 'wp-comments.php'); ?>", "<?php comments_template(); ?>", $line);
2589
2590                                 fwrite($f, "{$line}\n");
2591                         }
2592                         fclose($f);
2593                 }
2594         }
2595
2596         // Add a theme header.
2597         $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";
2598
2599         $stylelines = file_get_contents("$site_dir/style.css");
2600         if ($stylelines) {
2601                 $f = fopen("$site_dir/style.css", 'w');
2602
2603                 fwrite($f, $header);
2604                 fwrite($f, $stylelines);
2605                 fclose($f);
2606         }
2607
2608         return true;
2609 }
2610
2611 /**
2612  * Creates a site theme from the default theme.
2613  *
2614  * {@internal Missing Long Description}}
2615  *
2616  * @since 1.5.0
2617  *
2618  * @param string $theme_name The name of the theme.
2619  * @param string $template   The directory name of the theme.
2620  * @return false|void
2621  */
2622 function make_site_theme_from_default($theme_name, $template) {
2623         $site_dir = WP_CONTENT_DIR . "/themes/$template";
2624         $default_dir = WP_CONTENT_DIR . '/themes/' . WP_DEFAULT_THEME;
2625
2626         // Copy files from the default theme to the site theme.
2627         //$files = array('index.php', 'comments.php', 'comments-popup.php', 'footer.php', 'header.php', 'sidebar.php', 'style.css');
2628
2629         $theme_dir = @ opendir($default_dir);
2630         if ($theme_dir) {
2631                 while(($theme_file = readdir( $theme_dir )) !== false) {
2632                         if (is_dir("$default_dir/$theme_file"))
2633                                 continue;
2634                         if (! @copy("$default_dir/$theme_file", "$site_dir/$theme_file"))
2635                                 return;
2636                         chmod("$site_dir/$theme_file", 0777);
2637                 }
2638         }
2639         @closedir($theme_dir);
2640
2641         // Rewrite the theme header.
2642         $stylelines = explode("\n", implode('', file("$site_dir/style.css")));
2643         if ($stylelines) {
2644                 $f = fopen("$site_dir/style.css", 'w');
2645
2646                 foreach ($stylelines as $line) {
2647                         if (strpos($line, 'Theme Name:') !== false) $line = 'Theme Name: ' . $theme_name;
2648                         elseif (strpos($line, 'Theme URI:') !== false) $line = 'Theme URI: ' . __get_option('url');
2649                         elseif (strpos($line, 'Description:') !== false) $line = 'Description: Your theme.';
2650                         elseif (strpos($line, 'Version:') !== false) $line = 'Version: 1';
2651                         elseif (strpos($line, 'Author:') !== false) $line = 'Author: You';
2652                         fwrite($f, $line . "\n");
2653                 }
2654                 fclose($f);
2655         }
2656
2657         // Copy the images.
2658         umask(0);
2659         if (! mkdir("$site_dir/images", 0777)) {
2660                 return false;
2661         }
2662
2663         $images_dir = @ opendir("$default_dir/images");
2664         if ($images_dir) {
2665                 while(($image = readdir($images_dir)) !== false) {
2666                         if (is_dir("$default_dir/images/$image"))
2667                                 continue;
2668                         if (! @copy("$default_dir/images/$image", "$site_dir/images/$image"))
2669                                 return;
2670                         chmod("$site_dir/images/$image", 0777);
2671                 }
2672         }
2673         @closedir($images_dir);
2674 }
2675
2676 /**
2677  * Creates a site theme.
2678  *
2679  * {@internal Missing Long Description}}
2680  *
2681  * @since 1.5.0
2682  *
2683  * @return false|string
2684  */
2685 function make_site_theme() {
2686         // Name the theme after the blog.
2687         $theme_name = __get_option('blogname');
2688         $template = sanitize_title($theme_name);
2689         $site_dir = WP_CONTENT_DIR . "/themes/$template";
2690
2691         // If the theme already exists, nothing to do.
2692         if ( is_dir($site_dir)) {
2693                 return false;
2694         }
2695
2696         // We must be able to write to the themes dir.
2697         if (! is_writable(WP_CONTENT_DIR . "/themes")) {
2698                 return false;
2699         }
2700
2701         umask(0);
2702         if (! mkdir($site_dir, 0777)) {
2703                 return false;
2704         }
2705
2706         if (file_exists(ABSPATH . 'wp-layout.css')) {
2707                 if (! make_site_theme_from_oldschool($theme_name, $template)) {
2708                         // TODO: rm -rf the site theme directory.
2709                         return false;
2710                 }
2711         } else {
2712                 if (! make_site_theme_from_default($theme_name, $template))
2713                         // TODO: rm -rf the site theme directory.
2714                         return false;
2715         }
2716
2717         // Make the new site theme active.
2718         $current_template = __get_option('template');
2719         if ($current_template == WP_DEFAULT_THEME) {
2720                 update_option('template', $template);
2721                 update_option('stylesheet', $template);
2722         }
2723         return $template;
2724 }
2725
2726 /**
2727  * Translate user level to user role name.
2728  *
2729  * @since 2.0.0
2730  *
2731  * @param int $level User level.
2732  * @return string User role name.
2733  */
2734 function translate_level_to_role($level) {
2735         switch ($level) {
2736         case 10:
2737         case 9:
2738         case 8:
2739                 return 'administrator';
2740         case 7:
2741         case 6:
2742         case 5:
2743                 return 'editor';
2744         case 4:
2745         case 3:
2746         case 2:
2747                 return 'author';
2748         case 1:
2749                 return 'contributor';
2750         case 0:
2751                 return 'subscriber';
2752         }
2753 }
2754
2755 /**
2756  * Checks the version of the installed MySQL binary.
2757  *
2758  * @since 2.1.0
2759  *
2760  * @global wpdb  $wpdb
2761  */
2762 function wp_check_mysql_version() {
2763         global $wpdb;
2764         $result = $wpdb->check_database_version();
2765         if ( is_wp_error( $result ) )
2766                 die( $result->get_error_message() );
2767 }
2768
2769 /**
2770  * Disables the Automattic widgets plugin, which was merged into core.
2771  *
2772  * @since 2.2.0
2773  */
2774 function maybe_disable_automattic_widgets() {
2775         $plugins = __get_option( 'active_plugins' );
2776
2777         foreach ( (array) $plugins as $plugin ) {
2778                 if ( basename( $plugin ) == 'widgets.php' ) {
2779                         array_splice( $plugins, array_search( $plugin, $plugins ), 1 );
2780                         update_option( 'active_plugins', $plugins );
2781                         break;
2782                 }
2783         }
2784 }
2785
2786 /**
2787  * Disables the Link Manager on upgrade if, at the time of upgrade, no links exist in the DB.
2788  *
2789  * @since 3.5.0
2790  *
2791  * @global int  $wp_current_db_version
2792  * @global wpdb $wpdb WordPress database abstraction object.
2793  */
2794 function maybe_disable_link_manager() {
2795         global $wp_current_db_version, $wpdb;
2796
2797         if ( $wp_current_db_version >= 22006 && get_option( 'link_manager_enabled' ) && ! $wpdb->get_var( "SELECT link_id FROM $wpdb->links LIMIT 1" ) )
2798                 update_option( 'link_manager_enabled', 0 );
2799 }
2800
2801 /**
2802  * Runs before the schema is upgraded.
2803  *
2804  * @since 2.9.0
2805  *
2806  * @global int  $wp_current_db_version
2807  * @global wpdb $wpdb WordPress database abstraction object.
2808  */
2809 function pre_schema_upgrade() {
2810         global $wp_current_db_version, $wpdb;
2811
2812         // Upgrade versions prior to 2.9
2813         if ( $wp_current_db_version < 11557 ) {
2814                 // Delete duplicate options. Keep the option with the highest option_id.
2815                 $wpdb->query("DELETE o1 FROM $wpdb->options AS o1 JOIN $wpdb->options AS o2 USING (`option_name`) WHERE o2.option_id > o1.option_id");
2816
2817                 // Drop the old primary key and add the new.
2818                 $wpdb->query("ALTER TABLE $wpdb->options DROP PRIMARY KEY, ADD PRIMARY KEY(option_id)");
2819
2820                 // Drop the old option_name index. dbDelta() doesn't do the drop.
2821                 $wpdb->query("ALTER TABLE $wpdb->options DROP INDEX option_name");
2822         }
2823
2824         // Multisite schema upgrades.
2825         if ( $wp_current_db_version < 25448 && is_multisite() && wp_should_upgrade_global_tables() ) {
2826
2827                 // Upgrade versions prior to 3.7
2828                 if ( $wp_current_db_version < 25179 ) {
2829                         // New primary key for signups.
2830                         $wpdb->query( "ALTER TABLE $wpdb->signups ADD signup_id BIGINT(20) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST" );
2831                         $wpdb->query( "ALTER TABLE $wpdb->signups DROP INDEX domain" );
2832                 }
2833
2834                 if ( $wp_current_db_version < 25448 ) {
2835                         // Convert archived from enum to tinyint.
2836                         $wpdb->query( "ALTER TABLE $wpdb->blogs CHANGE COLUMN archived archived varchar(1) NOT NULL default '0'" );
2837                         $wpdb->query( "ALTER TABLE $wpdb->blogs CHANGE COLUMN archived archived tinyint(2) NOT NULL default 0" );
2838                 }
2839         }
2840
2841         // Upgrade versions prior to 4.2.
2842         if ( $wp_current_db_version < 31351 ) {
2843                 if ( ! is_multisite() && wp_should_upgrade_global_tables() ) {
2844                         $wpdb->query( "ALTER TABLE $wpdb->usermeta DROP INDEX meta_key, ADD INDEX meta_key(meta_key(191))" );
2845                 }
2846                 $wpdb->query( "ALTER TABLE $wpdb->terms DROP INDEX slug, ADD INDEX slug(slug(191))" );
2847                 $wpdb->query( "ALTER TABLE $wpdb->terms DROP INDEX name, ADD INDEX name(name(191))" );
2848                 $wpdb->query( "ALTER TABLE $wpdb->commentmeta DROP INDEX meta_key, ADD INDEX meta_key(meta_key(191))" );
2849                 $wpdb->query( "ALTER TABLE $wpdb->postmeta DROP INDEX meta_key, ADD INDEX meta_key(meta_key(191))" );
2850                 $wpdb->query( "ALTER TABLE $wpdb->posts DROP INDEX post_name, ADD INDEX post_name(post_name(191))" );
2851         }
2852
2853         // Upgrade versions prior to 4.4.
2854         if ( $wp_current_db_version < 34978 ) {
2855                 // If compatible termmeta table is found, use it, but enforce a proper index and update collation.
2856                 if ( $wpdb->get_var( "SHOW TABLES LIKE '{$wpdb->termmeta}'" ) && $wpdb->get_results( "SHOW INDEX FROM {$wpdb->termmeta} WHERE Column_name = 'meta_key'" ) ) {
2857                         $wpdb->query( "ALTER TABLE $wpdb->termmeta DROP INDEX meta_key, ADD INDEX meta_key(meta_key(191))" );
2858                         maybe_convert_table_to_utf8mb4( $wpdb->termmeta );
2859                 }
2860         }
2861 }
2862
2863 /**
2864  * Install global terms.
2865  *
2866  * @since 3.0.0
2867  *
2868  * @global wpdb   $wpdb
2869  * @global string $charset_collate
2870  */
2871 if ( !function_exists( 'install_global_terms' ) ) :
2872 function install_global_terms() {
2873         global $wpdb, $charset_collate;
2874         $ms_queries = "
2875 CREATE TABLE $wpdb->sitecategories (
2876   cat_ID bigint(20) NOT NULL auto_increment,
2877   cat_name varchar(55) NOT NULL default '',
2878   category_nicename varchar(200) NOT NULL default '',
2879   last_updated timestamp NOT NULL,
2880   PRIMARY KEY  (cat_ID),
2881   KEY category_nicename (category_nicename),
2882   KEY last_updated (last_updated)
2883 ) $charset_collate;
2884 ";
2885 // now create tables
2886         dbDelta( $ms_queries );
2887 }
2888 endif;
2889
2890 /**
2891  * Determine if global tables should be upgraded.
2892  *
2893  * This function performs a series of checks to ensure the environment allows
2894  * for the safe upgrading of global WordPress database tables. It is necessary
2895  * because global tables will commonly grow to millions of rows on large
2896  * installations, and the ability to control their upgrade routines can be
2897  * critical to the operation of large networks.
2898  *
2899  * In a future iteration, this function may use `wp_is_large_network()` to more-
2900  * intelligently prevent global table upgrades. Until then, we make sure
2901  * WordPress is on the main site of the main network, to avoid running queries
2902  * more than once in multi-site or multi-network environments.
2903  *
2904  * @since 4.3.0
2905  *
2906  * @return bool Whether to run the upgrade routines on global tables.
2907  */
2908 function wp_should_upgrade_global_tables() {
2909
2910         // Return false early if explicitly not upgrading
2911         if ( defined( 'DO_NOT_UPGRADE_GLOBAL_TABLES' ) ) {
2912                 return false;
2913         }
2914
2915         // Assume global tables should be upgraded
2916         $should_upgrade = true;
2917
2918         // Set to false if not on main network (does not matter if not multi-network)
2919         if ( ! is_main_network() ) {
2920                 $should_upgrade = false;
2921         }
2922
2923         // Set to false if not on main site of current network (does not matter if not multi-site)
2924         if ( ! is_main_site() ) {
2925                 $should_upgrade = false;
2926         }
2927
2928         /**
2929          * Filters if upgrade routines should be run on global tables.
2930          *
2931          * @param bool $should_upgrade Whether to run the upgrade routines on global tables.
2932          */
2933         return apply_filters( 'wp_should_upgrade_global_tables', $should_upgrade );
2934 }