]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-admin/includes/upgrade.php
WordPress 4.1.4-scripts
[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 blog
24  *
25  * {@internal Missing Long Description}}
26  *
27  * @since 2.1.0
28  *
29  * @param string $blog_title Blog title.
30  * @param string $user_name User's username.
31  * @param string $user_email User's email.
32  * @param bool $public Whether blog is public.
33  * @param string $deprecated Optional. Not used.
34  * @param string $user_password Optional. User's chosen password. Will default to a random password.
35  * @param string $language Optional. Language chosen.
36  * @return array Array keys 'url', 'user_id', 'password', 'password_message'.
37  */
38 function wp_install( $blog_title, $user_name, $user_email, $public, $deprecated = '', $user_password = '', $language = '' ) {
39         if ( !empty( $deprecated ) )
40                 _deprecated_argument( __FUNCTION__, '2.6' );
41
42         wp_check_mysql_version();
43         wp_cache_flush();
44         make_db_current_silent();
45         populate_options();
46         populate_roles();
47
48         update_option('blogname', $blog_title);
49         update_option('admin_email', $user_email);
50         update_option('blog_public', $public);
51
52         if ( $language ) {
53                 update_option( 'WPLANG', $language );
54         }
55
56         $guessurl = wp_guess_url();
57
58         update_option('siteurl', $guessurl);
59
60         // If not a public blog, don't ping.
61         if ( ! $public )
62                 update_option('default_pingback_flag', 0);
63
64         /*
65          * Create default user. If the user already exists, the user tables are
66          * being shared among blogs. Just set the role in that case.
67          */
68         $user_id = username_exists($user_name);
69         $user_password = trim($user_password);
70         $email_password = false;
71         if ( !$user_id && empty($user_password) ) {
72                 $user_password = wp_generate_password( 12, false );
73                 $message = __('<strong><em>Note that password</em></strong> carefully! It is a <em>random</em> password that was generated just for you.');
74                 $user_id = wp_create_user($user_name, $user_password, $user_email);
75                 update_user_option($user_id, 'default_password_nag', true, true);
76                 $email_password = true;
77         } else if ( !$user_id ) {
78                 // Password has been provided
79                 $message = '<em>'.__('Your chosen password.').'</em>';
80                 $user_id = wp_create_user($user_name, $user_password, $user_email);
81         } else {
82                 $message = __('User already exists. Password inherited.');
83         }
84
85         $user = new WP_User($user_id);
86         $user->set_role('administrator');
87
88         wp_install_defaults($user_id);
89
90         flush_rewrite_rules();
91
92         wp_new_blog_notification($blog_title, $guessurl, $user_id, ($email_password ? $user_password : __('The password you chose during the install.') ) );
93
94         wp_cache_flush();
95
96         /**
97          * Fires after a site is fully installed.
98          *
99          * @since 3.9.0
100          *
101          * @param WP_User $user The site owner.
102          */
103         do_action( 'wp_install', $user );
104
105         return array('url' => $guessurl, 'user_id' => $user_id, 'password' => $user_password, 'password_message' => $message);
106 }
107 endif;
108
109 if ( !function_exists('wp_install_defaults') ) :
110 /**
111  * {@internal Missing Short Description}}
112  *
113  * {@internal Missing Long Description}}
114  *
115  * @since 2.1.0
116  *
117  * @param int $user_id User ID.
118  */
119 function wp_install_defaults( $user_id ) {
120         global $wpdb, $wp_rewrite, $table_prefix;
121
122         // Default category
123         $cat_name = __('Uncategorized');
124         /* translators: Default category slug */
125         $cat_slug = sanitize_title(_x('Uncategorized', 'Default category slug'));
126
127         if ( global_terms_enabled() ) {
128                 $cat_id = $wpdb->get_var( $wpdb->prepare( "SELECT cat_ID FROM {$wpdb->sitecategories} WHERE category_nicename = %s", $cat_slug ) );
129                 if ( $cat_id == null ) {
130                         $wpdb->insert( $wpdb->sitecategories, array('cat_ID' => 0, 'cat_name' => $cat_name, 'category_nicename' => $cat_slug, 'last_updated' => current_time('mysql', true)) );
131                         $cat_id = $wpdb->insert_id;
132                 }
133                 update_option('default_category', $cat_id);
134         } else {
135                 $cat_id = 1;
136         }
137
138         $wpdb->insert( $wpdb->terms, array('term_id' => $cat_id, 'name' => $cat_name, 'slug' => $cat_slug, 'term_group' => 0) );
139         $wpdb->insert( $wpdb->term_taxonomy, array('term_id' => $cat_id, 'taxonomy' => 'category', 'description' => '', 'parent' => 0, 'count' => 1));
140         $cat_tt_id = $wpdb->insert_id;
141
142         // First post
143         $now = date('Y-m-d H:i:s');
144         $now_gmt = gmdate('Y-m-d H:i:s');
145         $first_post_guid = get_option('home') . '/?p=1';
146
147         if ( is_multisite() ) {
148                 $first_post = get_site_option( 'first_post' );
149
150                 if ( empty($first_post) )
151                         $first_post = __( 'Welcome to <a href="SITE_URL">SITE_NAME</a>. This is your first post. Edit or delete it, then start blogging!' );
152
153                 $first_post = str_replace( "SITE_URL", esc_url( network_home_url() ), $first_post );
154                 $first_post = str_replace( "SITE_NAME", get_current_site()->site_name, $first_post );
155         } else {
156                 $first_post = __('Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!');
157         }
158
159         $wpdb->insert( $wpdb->posts, array(
160                                                                 'post_author' => $user_id,
161                                                                 'post_date' => $now,
162                                                                 'post_date_gmt' => $now_gmt,
163                                                                 'post_content' => $first_post,
164                                                                 'post_excerpt' => '',
165                                                                 'post_title' => __('Hello world!'),
166                                                                 /* translators: Default post slug */
167                                                                 'post_name' => sanitize_title( _x('hello-world', 'Default post slug') ),
168                                                                 'post_modified' => $now,
169                                                                 'post_modified_gmt' => $now_gmt,
170                                                                 'guid' => $first_post_guid,
171                                                                 'comment_count' => 1,
172                                                                 'to_ping' => '',
173                                                                 'pinged' => '',
174                                                                 'post_content_filtered' => ''
175                                                                 ));
176         $wpdb->insert( $wpdb->term_relationships, array('term_taxonomy_id' => $cat_tt_id, 'object_id' => 1) );
177
178         // Default comment
179         $first_comment_author = __('Mr WordPress');
180         $first_comment_url = 'https://wordpress.org/';
181         $first_comment = __('Hi, this is a comment.
182 To delete a comment, just log in and view the post&#039;s comments. There you will have the option to edit or delete them.');
183         if ( is_multisite() ) {
184                 $first_comment_author = get_site_option( 'first_comment_author', $first_comment_author );
185                 $first_comment_url = get_site_option( 'first_comment_url', network_home_url() );
186                 $first_comment = get_site_option( 'first_comment', $first_comment );
187         }
188         $wpdb->insert( $wpdb->comments, array(
189                                                                 'comment_post_ID' => 1,
190                                                                 'comment_author' => $first_comment_author,
191                                                                 'comment_author_email' => '',
192                                                                 'comment_author_url' => $first_comment_url,
193                                                                 'comment_date' => $now,
194                                                                 'comment_date_gmt' => $now_gmt,
195                                                                 'comment_content' => $first_comment
196                                                                 ));
197
198         // First Page
199         $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:
200
201 <blockquote>Hi there! I'm a bike messenger by day, aspiring actor by night, and this is my blog. 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>
202
203 ...or something like this:
204
205 <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>
206
207 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() );
208         if ( is_multisite() )
209                 $first_page = get_site_option( 'first_page', $first_page );
210         $first_post_guid = get_option('home') . '/?page_id=2';
211         $wpdb->insert( $wpdb->posts, array(
212                                                                 'post_author' => $user_id,
213                                                                 'post_date' => $now,
214                                                                 'post_date_gmt' => $now_gmt,
215                                                                 'post_content' => $first_page,
216                                                                 'post_excerpt' => '',
217                                                                 'post_title' => __( 'Sample Page' ),
218                                                                 /* translators: Default page slug */
219                                                                 'post_name' => __( 'sample-page' ),
220                                                                 'post_modified' => $now,
221                                                                 'post_modified_gmt' => $now_gmt,
222                                                                 'guid' => $first_post_guid,
223                                                                 'post_type' => 'page',
224                                                                 'to_ping' => '',
225                                                                 'pinged' => '',
226                                                                 'post_content_filtered' => ''
227                                                                 ));
228         $wpdb->insert( $wpdb->postmeta, array( 'post_id' => 2, 'meta_key' => '_wp_page_template', 'meta_value' => 'default' ) );
229
230         // Set up default widgets for default theme.
231         update_option( 'widget_search', array ( 2 => array ( 'title' => '' ), '_multiwidget' => 1 ) );
232         update_option( 'widget_recent-posts', array ( 2 => array ( 'title' => '', 'number' => 5 ), '_multiwidget' => 1 ) );
233         update_option( 'widget_recent-comments', array ( 2 => array ( 'title' => '', 'number' => 5 ), '_multiwidget' => 1 ) );
234         update_option( 'widget_archives', array ( 2 => array ( 'title' => '', 'count' => 0, 'dropdown' => 0 ), '_multiwidget' => 1 ) );
235         update_option( 'widget_categories', array ( 2 => array ( 'title' => '', 'count' => 0, 'hierarchical' => 0, 'dropdown' => 0 ), '_multiwidget' => 1 ) );
236         update_option( 'widget_meta', array ( 2 => array ( 'title' => '' ), '_multiwidget' => 1 ) );
237         update_option( 'sidebars_widgets', array ( 'wp_inactive_widgets' => array (), 'sidebar-1' => array ( 0 => 'search-2', 1 => 'recent-posts-2', 2 => 'recent-comments-2', 3 => 'archives-2', 4 => 'categories-2', 5 => 'meta-2', ), 'array_version' => 3 ) );
238
239         if ( ! is_multisite() )
240                 update_user_meta( $user_id, 'show_welcome_panel', 1 );
241         elseif ( ! is_super_admin( $user_id ) && ! metadata_exists( 'user', $user_id, 'show_welcome_panel' ) )
242                 update_user_meta( $user_id, 'show_welcome_panel', 2 );
243
244         if ( is_multisite() ) {
245                 // Flush rules to pick up the new page.
246                 $wp_rewrite->init();
247                 $wp_rewrite->flush_rules();
248
249                 $user = new WP_User($user_id);
250                 $wpdb->update( $wpdb->options, array('option_value' => $user->user_email), array('option_name' => 'admin_email') );
251
252                 // Remove all perms except for the login user.
253                 $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id != %d AND meta_key = %s", $user_id, $table_prefix.'user_level') );
254                 $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id != %d AND meta_key = %s", $user_id, $table_prefix.'capabilities') );
255
256                 // Delete any caps that snuck into the previously active blog. (Hardcoded to blog 1 for now.) TODO: Get previous_blog_id.
257                 if ( !is_super_admin( $user_id ) && $user_id != 1 )
258                         $wpdb->delete( $wpdb->usermeta, array( 'user_id' => $user_id , 'meta_key' => $wpdb->base_prefix.'1_capabilities' ) );
259         }
260 }
261 endif;
262
263 if ( !function_exists('wp_new_blog_notification') ) :
264 /**
265  * {@internal Missing Short Description}}
266  *
267  * {@internal Missing Long Description}}
268  *
269  * @since 2.1.0
270  *
271  * @param string $blog_title Blog title.
272  * @param string $blog_url Blog url.
273  * @param int $user_id User ID.
274  * @param string $password User's Password.
275  */
276 function wp_new_blog_notification($blog_title, $blog_url, $user_id, $password) {
277         $user = new WP_User( $user_id );
278         $email = $user->user_email;
279         $name = $user->user_login;
280         $login_url = wp_login_url();
281         $message = sprintf( __( "Your new WordPress site has been successfully set up at:
282
283 %1\$s
284
285 You can log in to the administrator account with the following information:
286
287 Username: %2\$s
288 Password: %3\$s
289 Log in here: %4\$s
290
291 We hope you enjoy your new site. Thanks!
292
293 --The WordPress Team
294 https://wordpress.org/
295 "), $blog_url, $name, $password, $login_url );
296
297         @wp_mail($email, __('New WordPress Site'), $message);
298 }
299 endif;
300
301 if ( !function_exists('wp_upgrade') ) :
302 /**
303  * Run WordPress Upgrade functions.
304  *
305  * {@internal Missing Long Description}}
306  *
307  * @since 2.1.0
308  *
309  * @return null
310  */
311 function wp_upgrade() {
312         global $wp_current_db_version, $wp_db_version, $wpdb;
313
314         $wp_current_db_version = __get_option('db_version');
315
316         // We are up-to-date. Nothing to do.
317         if ( $wp_db_version == $wp_current_db_version )
318                 return;
319
320         if ( ! is_blog_installed() )
321                 return;
322
323         wp_check_mysql_version();
324         wp_cache_flush();
325         pre_schema_upgrade();
326         make_db_current_silent();
327         upgrade_all();
328         if ( is_multisite() && is_main_site() )
329                 upgrade_network();
330         wp_cache_flush();
331
332         if ( is_multisite() ) {
333                 if ( $wpdb->get_row( "SELECT blog_id FROM {$wpdb->blog_versions} WHERE blog_id = '{$wpdb->blogid}'" ) )
334                         $wpdb->query( "UPDATE {$wpdb->blog_versions} SET db_version = '{$wp_db_version}' WHERE blog_id = '{$wpdb->blogid}'" );
335                 else
336                         $wpdb->query( "INSERT INTO {$wpdb->blog_versions} ( `blog_id` , `db_version` , `last_updated` ) VALUES ( '{$wpdb->blogid}', '{$wp_db_version}', NOW());" );
337         }
338
339         /**
340          * Fires after a site is fully upgraded.
341          *
342          * @since 3.9.0
343          *
344          * @param int $wp_db_version         The new $wp_db_version.
345          * @param int $wp_current_db_version The old (current) $wp_db_version.
346          */
347         do_action( 'wp_upgrade', $wp_db_version, $wp_current_db_version );
348 }
349 endif;
350
351 /**
352  * Functions to be called in install and upgrade scripts.
353  *
354  * {@internal Missing Long Description}}
355  *
356  * @since 1.0.1
357  */
358 function upgrade_all() {
359         global $wp_current_db_version, $wp_db_version;
360         $wp_current_db_version = __get_option('db_version');
361
362         // We are up-to-date. Nothing to do.
363         if ( $wp_db_version == $wp_current_db_version )
364                 return;
365
366         // If the version is not set in the DB, try to guess the version.
367         if ( empty($wp_current_db_version) ) {
368                 $wp_current_db_version = 0;
369
370                 // If the template option exists, we have 1.5.
371                 $template = __get_option('template');
372                 if ( !empty($template) )
373                         $wp_current_db_version = 2541;
374         }
375
376         if ( $wp_current_db_version < 6039 )
377                 upgrade_230_options_table();
378
379         populate_options();
380
381         if ( $wp_current_db_version < 2541 ) {
382                 upgrade_100();
383                 upgrade_101();
384                 upgrade_110();
385                 upgrade_130();
386         }
387
388         if ( $wp_current_db_version < 3308 )
389                 upgrade_160();
390
391         if ( $wp_current_db_version < 4772 )
392                 upgrade_210();
393
394         if ( $wp_current_db_version < 4351 )
395                 upgrade_old_slugs();
396
397         if ( $wp_current_db_version < 5539 )
398                 upgrade_230();
399
400         if ( $wp_current_db_version < 6124 )
401                 upgrade_230_old_tables();
402
403         if ( $wp_current_db_version < 7499 )
404                 upgrade_250();
405
406         if ( $wp_current_db_version < 7935 )
407                 upgrade_252();
408
409         if ( $wp_current_db_version < 8201 )
410                 upgrade_260();
411
412         if ( $wp_current_db_version < 8989 )
413                 upgrade_270();
414
415         if ( $wp_current_db_version < 10360 )
416                 upgrade_280();
417
418         if ( $wp_current_db_version < 11958 )
419                 upgrade_290();
420
421         if ( $wp_current_db_version < 15260 )
422                 upgrade_300();
423
424         if ( $wp_current_db_version < 19389 )
425                 upgrade_330();
426
427         if ( $wp_current_db_version < 20080 )
428                 upgrade_340();
429
430         if ( $wp_current_db_version < 22422 )
431                 upgrade_350();
432
433         if ( $wp_current_db_version < 25824 )
434                 upgrade_370();
435
436         if ( $wp_current_db_version < 26148 )
437                 upgrade_372();
438
439         if ( $wp_current_db_version < 26691 )
440                 upgrade_380();
441
442         if ( $wp_current_db_version < 29630 )
443                 upgrade_400();
444
445         if ( $wp_current_db_version < 30134 )
446                 upgrade_414();
447
448         maybe_disable_link_manager();
449
450         maybe_disable_automattic_widgets();
451
452         update_option( 'db_version', $wp_db_version );
453         update_option( 'db_upgraded', true );
454 }
455
456 /**
457  * Execute changes made in WordPress 1.0.
458  *
459  * @since 1.0.0
460  */
461 function upgrade_100() {
462         global $wpdb;
463
464         // Get the title and ID of every post, post_name to check if it already has a value
465         $posts = $wpdb->get_results("SELECT ID, post_title, post_name FROM $wpdb->posts WHERE post_name = ''");
466         if ($posts) {
467                 foreach($posts as $post) {
468                         if ('' == $post->post_name) {
469                                 $newtitle = sanitize_title($post->post_title);
470                                 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_name = %s WHERE ID = %d", $newtitle, $post->ID) );
471                         }
472                 }
473         }
474
475         $categories = $wpdb->get_results("SELECT cat_ID, cat_name, category_nicename FROM $wpdb->categories");
476         foreach ($categories as $category) {
477                 if ('' == $category->category_nicename) {
478                         $newtitle = sanitize_title($category->cat_name);
479                         $wpdb->update( $wpdb->categories, array('category_nicename' => $newtitle), array('cat_ID' => $category->cat_ID) );
480                 }
481         }
482
483         $sql = "UPDATE $wpdb->options
484                 SET option_value = REPLACE(option_value, 'wp-links/links-images/', 'wp-images/links/')
485                 WHERE option_name LIKE %s
486                 AND option_value LIKE %s";
487         $wpdb->query( $wpdb->prepare( $sql, $wpdb->esc_like( 'links_rating_image' ) . '%', $wpdb->esc_like( 'wp-links/links-images/' ) . '%' ) );
488
489         $done_ids = $wpdb->get_results("SELECT DISTINCT post_id FROM $wpdb->post2cat");
490         if ($done_ids) :
491                 foreach ($done_ids as $done_id) :
492                         $done_posts[] = $done_id->post_id;
493                 endforeach;
494                 $catwhere = ' AND ID NOT IN (' . implode(',', $done_posts) . ')';
495         else:
496                 $catwhere = '';
497         endif;
498
499         $allposts = $wpdb->get_results("SELECT ID, post_category FROM $wpdb->posts WHERE post_category != '0' $catwhere");
500         if ($allposts) :
501                 foreach ($allposts as $post) {
502                         // Check to see if it's already been imported
503                         $cat = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->post2cat WHERE post_id = %d AND category_id = %d", $post->ID, $post->post_category) );
504                         if (!$cat && 0 != $post->post_category) { // If there's no result
505                                 $wpdb->insert( $wpdb->post2cat, array('post_id' => $post->ID, 'category_id' => $post->post_category) );
506                         }
507                 }
508         endif;
509 }
510
511 /**
512  * Execute changes made in WordPress 1.0.1.
513  *
514  * @since 1.0.1
515  */
516 function upgrade_101() {
517         global $wpdb;
518
519         // Clean up indices, add a few
520         add_clean_index($wpdb->posts, 'post_name');
521         add_clean_index($wpdb->posts, 'post_status');
522         add_clean_index($wpdb->categories, 'category_nicename');
523         add_clean_index($wpdb->comments, 'comment_approved');
524         add_clean_index($wpdb->comments, 'comment_post_ID');
525         add_clean_index($wpdb->links , 'link_category');
526         add_clean_index($wpdb->links , 'link_visible');
527 }
528
529 /**
530  * Execute changes made in WordPress 1.2.
531  *
532  * @since 1.2.0
533  */
534 function upgrade_110() {
535         global $wpdb;
536
537         // Set user_nicename.
538         $users = $wpdb->get_results("SELECT ID, user_nickname, user_nicename FROM $wpdb->users");
539         foreach ($users as $user) {
540                 if ('' == $user->user_nicename) {
541                         $newname = sanitize_title($user->user_nickname);
542                         $wpdb->update( $wpdb->users, array('user_nicename' => $newname), array('ID' => $user->ID) );
543                 }
544         }
545
546         $users = $wpdb->get_results("SELECT ID, user_pass from $wpdb->users");
547         foreach ($users as $row) {
548                 if (!preg_match('/^[A-Fa-f0-9]{32}$/', $row->user_pass)) {
549                         $wpdb->update( $wpdb->users, array('user_pass' => md5($row->user_pass)), array('ID' => $row->ID) );
550                 }
551         }
552
553         // Get the GMT offset, we'll use that later on
554         $all_options = get_alloptions_110();
555
556         $time_difference = $all_options->time_difference;
557
558                 $server_time = time()+date('Z');
559         $weblogger_time = $server_time + $time_difference * HOUR_IN_SECONDS;
560         $gmt_time = time();
561
562         $diff_gmt_server = ($gmt_time - $server_time) / HOUR_IN_SECONDS;
563         $diff_weblogger_server = ($weblogger_time - $server_time) / HOUR_IN_SECONDS;
564         $diff_gmt_weblogger = $diff_gmt_server - $diff_weblogger_server;
565         $gmt_offset = -$diff_gmt_weblogger;
566
567         // Add a gmt_offset option, with value $gmt_offset
568         add_option('gmt_offset', $gmt_offset);
569
570         // Check if we already set the GMT fields (if we did, then
571         // MAX(post_date_gmt) can't be '0000-00-00 00:00:00'
572         // <michel_v> I just slapped myself silly for not thinking about it earlier
573         $got_gmt_fields = ! ($wpdb->get_var("SELECT MAX(post_date_gmt) FROM $wpdb->posts") == '0000-00-00 00:00:00');
574
575         if (!$got_gmt_fields) {
576
577                 // Add or subtract time to all dates, to get GMT dates
578                 $add_hours = intval($diff_gmt_weblogger);
579                 $add_minutes = intval(60 * ($diff_gmt_weblogger - $add_hours));
580                 $wpdb->query("UPDATE $wpdb->posts SET post_date_gmt = DATE_ADD(post_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
581                 $wpdb->query("UPDATE $wpdb->posts SET post_modified = post_date");
582                 $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'");
583                 $wpdb->query("UPDATE $wpdb->comments SET comment_date_gmt = DATE_ADD(comment_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
584                 $wpdb->query("UPDATE $wpdb->users SET user_registered = DATE_ADD(user_registered, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
585         }
586
587 }
588
589 /**
590  * Execute changes made in WordPress 1.5.
591  *
592  * @since 1.5.0
593  */
594 function upgrade_130() {
595         global $wpdb;
596
597         // Remove extraneous backslashes.
598         $posts = $wpdb->get_results("SELECT ID, post_title, post_content, post_excerpt, guid, post_date, post_name, post_status, post_author FROM $wpdb->posts");
599         if ($posts) {
600                 foreach($posts as $post) {
601                         $post_content = addslashes(deslash($post->post_content));
602                         $post_title = addslashes(deslash($post->post_title));
603                         $post_excerpt = addslashes(deslash($post->post_excerpt));
604                         if ( empty($post->guid) )
605                                 $guid = get_permalink($post->ID);
606                         else
607                                 $guid = $post->guid;
608
609                         $wpdb->update( $wpdb->posts, compact('post_title', 'post_content', 'post_excerpt', 'guid'), array('ID' => $post->ID) );
610
611                 }
612         }
613
614         // Remove extraneous backslashes.
615         $comments = $wpdb->get_results("SELECT comment_ID, comment_author, comment_content FROM $wpdb->comments");
616         if ($comments) {
617                 foreach($comments as $comment) {
618                         $comment_content = deslash($comment->comment_content);
619                         $comment_author = deslash($comment->comment_author);
620
621                         $wpdb->update($wpdb->comments, compact('comment_content', 'comment_author'), array('comment_ID' => $comment->comment_ID) );
622                 }
623         }
624
625         // Remove extraneous backslashes.
626         $links = $wpdb->get_results("SELECT link_id, link_name, link_description FROM $wpdb->links");
627         if ($links) {
628                 foreach($links as $link) {
629                         $link_name = deslash($link->link_name);
630                         $link_description = deslash($link->link_description);
631
632                         $wpdb->update( $wpdb->links, compact('link_name', 'link_description'), array('link_id' => $link->link_id) );
633                 }
634         }
635
636         $active_plugins = __get_option('active_plugins');
637
638         /*
639          * If plugins are not stored in an array, they're stored in the old
640          * newline separated format. Convert to new format.
641          */
642         if ( !is_array( $active_plugins ) ) {
643                 $active_plugins = explode("\n", trim($active_plugins));
644                 update_option('active_plugins', $active_plugins);
645         }
646
647         // Obsolete tables
648         $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optionvalues');
649         $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiontypes');
650         $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiongroups');
651         $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiongroup_options');
652
653         // Update comments table to use comment_type
654         $wpdb->query("UPDATE $wpdb->comments SET comment_type='trackback', comment_content = REPLACE(comment_content, '<trackback />', '') WHERE comment_content LIKE '<trackback />%'");
655         $wpdb->query("UPDATE $wpdb->comments SET comment_type='pingback', comment_content = REPLACE(comment_content, '<pingback />', '') WHERE comment_content LIKE '<pingback />%'");
656
657         // Some versions have multiple duplicate option_name rows with the same values
658         $options = $wpdb->get_results("SELECT option_name, COUNT(option_name) AS dupes FROM `$wpdb->options` GROUP BY option_name");
659         foreach ( $options as $option ) {
660                 if ( 1 != $option->dupes ) { // Could this be done in the query?
661                         $limit = $option->dupes - 1;
662                         $dupe_ids = $wpdb->get_col( $wpdb->prepare("SELECT option_id FROM $wpdb->options WHERE option_name = %s LIMIT %d", $option->option_name, $limit) );
663                         if ( $dupe_ids ) {
664                                 $dupe_ids = join($dupe_ids, ',');
665                                 $wpdb->query("DELETE FROM $wpdb->options WHERE option_id IN ($dupe_ids)");
666                         }
667                 }
668         }
669
670         make_site_theme();
671 }
672
673 /**
674  * Execute changes made in WordPress 2.0.
675  *
676  * @since 2.0.0
677  */
678 function upgrade_160() {
679         global $wpdb, $wp_current_db_version;
680
681         populate_roles_160();
682
683         $users = $wpdb->get_results("SELECT * FROM $wpdb->users");
684         foreach ( $users as $user ) :
685                 if ( !empty( $user->user_firstname ) )
686                         update_user_meta( $user->ID, 'first_name', wp_slash($user->user_firstname) );
687                 if ( !empty( $user->user_lastname ) )
688                         update_user_meta( $user->ID, 'last_name', wp_slash($user->user_lastname) );
689                 if ( !empty( $user->user_nickname ) )
690                         update_user_meta( $user->ID, 'nickname', wp_slash($user->user_nickname) );
691                 if ( !empty( $user->user_level ) )
692                         update_user_meta( $user->ID, $wpdb->prefix . 'user_level', $user->user_level );
693                 if ( !empty( $user->user_icq ) )
694                         update_user_meta( $user->ID, 'icq', wp_slash($user->user_icq) );
695                 if ( !empty( $user->user_aim ) )
696                         update_user_meta( $user->ID, 'aim', wp_slash($user->user_aim) );
697                 if ( !empty( $user->user_msn ) )
698                         update_user_meta( $user->ID, 'msn', wp_slash($user->user_msn) );
699                 if ( !empty( $user->user_yim ) )
700                         update_user_meta( $user->ID, 'yim', wp_slash($user->user_icq) );
701                 if ( !empty( $user->user_description ) )
702                         update_user_meta( $user->ID, 'description', wp_slash($user->user_description) );
703
704                 if ( isset( $user->user_idmode ) ):
705                         $idmode = $user->user_idmode;
706                         if ($idmode == 'nickname') $id = $user->user_nickname;
707                         if ($idmode == 'login') $id = $user->user_login;
708                         if ($idmode == 'firstname') $id = $user->user_firstname;
709                         if ($idmode == 'lastname') $id = $user->user_lastname;
710                         if ($idmode == 'namefl') $id = $user->user_firstname.' '.$user->user_lastname;
711                         if ($idmode == 'namelf') $id = $user->user_lastname.' '.$user->user_firstname;
712                         if (!$idmode) $id = $user->user_nickname;
713                         $wpdb->update( $wpdb->users, array('display_name' => $id), array('ID' => $user->ID) );
714                 endif;
715
716                 // FIXME: RESET_CAPS is temporary code to reset roles and caps if flag is set.
717                 $caps = get_user_meta( $user->ID, $wpdb->prefix . 'capabilities');
718                 if ( empty($caps) || defined('RESET_CAPS') ) {
719                         $level = get_user_meta($user->ID, $wpdb->prefix . 'user_level', true);
720                         $role = translate_level_to_role($level);
721                         update_user_meta( $user->ID, $wpdb->prefix . 'capabilities', array($role => true) );
722                 }
723
724         endforeach;
725         $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' );
726         $wpdb->hide_errors();
727         foreach ( $old_user_fields as $old )
728                 $wpdb->query("ALTER TABLE $wpdb->users DROP $old");
729         $wpdb->show_errors();
730
731         // Populate comment_count field of posts table.
732         $comments = $wpdb->get_results( "SELECT comment_post_ID, COUNT(*) as c FROM $wpdb->comments WHERE comment_approved = '1' GROUP BY comment_post_ID" );
733         if ( is_array( $comments ) )
734                 foreach ($comments as $comment)
735                         $wpdb->update( $wpdb->posts, array('comment_count' => $comment->c), array('ID' => $comment->comment_post_ID) );
736
737         /*
738          * Some alpha versions used a post status of object instead of attachment
739          * and put the mime type in post_type instead of post_mime_type.
740          */
741         if ( $wp_current_db_version > 2541 && $wp_current_db_version <= 3091 ) {
742                 $objects = $wpdb->get_results("SELECT ID, post_type FROM $wpdb->posts WHERE post_status = 'object'");
743                 foreach ($objects as $object) {
744                         $wpdb->update( $wpdb->posts, array(     'post_status' => 'attachment',
745                                                                                                 'post_mime_type' => $object->post_type,
746                                                                                                 'post_type' => ''),
747                                                                                  array( 'ID' => $object->ID ) );
748
749                         $meta = get_post_meta($object->ID, 'imagedata', true);
750                         if ( ! empty($meta['file']) )
751                                 update_attached_file( $object->ID, $meta['file'] );
752                 }
753         }
754 }
755
756 /**
757  * Execute changes made in WordPress 2.1.
758  *
759  * @since 2.1.0
760  */
761 function upgrade_210() {
762         global $wpdb, $wp_current_db_version;
763
764         if ( $wp_current_db_version < 3506 ) {
765                 // Update status and type.
766                 $posts = $wpdb->get_results("SELECT ID, post_status FROM $wpdb->posts");
767
768                 if ( ! empty($posts) ) foreach ($posts as $post) {
769                         $status = $post->post_status;
770                         $type = 'post';
771
772                         if ( 'static' == $status ) {
773                                 $status = 'publish';
774                                 $type = 'page';
775                         } else if ( 'attachment' == $status ) {
776                                 $status = 'inherit';
777                                 $type = 'attachment';
778                         }
779
780                         $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_status = %s, post_type = %s WHERE ID = %d", $status, $type, $post->ID) );
781                 }
782         }
783
784         if ( $wp_current_db_version < 3845 ) {
785                 populate_roles_210();
786         }
787
788         if ( $wp_current_db_version < 3531 ) {
789                 // Give future posts a post_status of future.
790                 $now = gmdate('Y-m-d H:i:59');
791                 $wpdb->query ("UPDATE $wpdb->posts SET post_status = 'future' WHERE post_status = 'publish' AND post_date_gmt > '$now'");
792
793                 $posts = $wpdb->get_results("SELECT ID, post_date FROM $wpdb->posts WHERE post_status ='future'");
794                 if ( !empty($posts) )
795                         foreach ( $posts as $post )
796                                 wp_schedule_single_event(mysql2date('U', $post->post_date, false), 'publish_future_post', array($post->ID));
797         }
798 }
799
800 /**
801  * Execute changes made in WordPress 2.3.
802  *
803  * @since 2.3.0
804  */
805 function upgrade_230() {
806         global $wp_current_db_version, $wpdb;
807
808         if ( $wp_current_db_version < 5200 ) {
809                 populate_roles_230();
810         }
811
812         // Convert categories to terms.
813         $tt_ids = array();
814         $have_tags = false;
815         $categories = $wpdb->get_results("SELECT * FROM $wpdb->categories ORDER BY cat_ID");
816         foreach ($categories as $category) {
817                 $term_id = (int) $category->cat_ID;
818                 $name = $category->cat_name;
819                 $description = $category->category_description;
820                 $slug = $category->category_nicename;
821                 $parent = $category->category_parent;
822                 $term_group = 0;
823
824                 // Associate terms with the same slug in a term group and make slugs unique.
825                 if ( $exists = $wpdb->get_results( $wpdb->prepare("SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $slug) ) ) {
826                         $term_group = $exists[0]->term_group;
827                         $id = $exists[0]->term_id;
828                         $num = 2;
829                         do {
830                                 $alt_slug = $slug . "-$num";
831                                 $num++;
832                                 $slug_check = $wpdb->get_var( $wpdb->prepare("SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug) );
833                         } while ( $slug_check );
834
835                         $slug = $alt_slug;
836
837                         if ( empty( $term_group ) ) {
838                                 $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms GROUP BY term_group") + 1;
839                                 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->terms SET term_group = %d WHERE term_id = %d", $term_group, $id) );
840                         }
841                 }
842
843                 $wpdb->query( $wpdb->prepare("INSERT INTO $wpdb->terms (term_id, name, slug, term_group) VALUES
844                 (%d, %s, %s, %d)", $term_id, $name, $slug, $term_group) );
845
846                 $count = 0;
847                 if ( !empty($category->category_count) ) {
848                         $count = (int) $category->category_count;
849                         $taxonomy = 'category';
850                         $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) );
851                         $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
852                 }
853
854                 if ( !empty($category->link_count) ) {
855                         $count = (int) $category->link_count;
856                         $taxonomy = 'link_category';
857                         $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) );
858                         $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
859                 }
860
861                 if ( !empty($category->tag_count) ) {
862                         $have_tags = true;
863                         $count = (int) $category->tag_count;
864                         $taxonomy = 'post_tag';
865                         $wpdb->insert( $wpdb->term_taxonomy, compact('term_id', 'taxonomy', 'description', 'parent', 'count') );
866                         $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
867                 }
868
869                 if ( empty($count) ) {
870                         $count = 0;
871                         $taxonomy = 'category';
872                         $wpdb->insert( $wpdb->term_taxonomy, compact('term_id', 'taxonomy', 'description', 'parent', 'count') );
873                         $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
874                 }
875         }
876
877         $select = 'post_id, category_id';
878         if ( $have_tags )
879                 $select .= ', rel_type';
880
881         $posts = $wpdb->get_results("SELECT $select FROM $wpdb->post2cat GROUP BY post_id, category_id");
882         foreach ( $posts as $post ) {
883                 $post_id = (int) $post->post_id;
884                 $term_id = (int) $post->category_id;
885                 $taxonomy = 'category';
886                 if ( !empty($post->rel_type) && 'tag' == $post->rel_type)
887                         $taxonomy = 'tag';
888                 $tt_id = $tt_ids[$term_id][$taxonomy];
889                 if ( empty($tt_id) )
890                         continue;
891
892                 $wpdb->insert( $wpdb->term_relationships, array('object_id' => $post_id, 'term_taxonomy_id' => $tt_id) );
893         }
894
895         // < 3570 we used linkcategories. >= 3570 we used categories and link2cat.
896         if ( $wp_current_db_version < 3570 ) {
897                 /*
898                  * Create link_category terms for link categories. Create a map of link
899                  * cat IDs to link_category terms.
900                  */
901                 $link_cat_id_map = array();
902                 $default_link_cat = 0;
903                 $tt_ids = array();
904                 $link_cats = $wpdb->get_results("SELECT cat_id, cat_name FROM " . $wpdb->prefix . 'linkcategories');
905                 foreach ( $link_cats as $category) {
906                         $cat_id = (int) $category->cat_id;
907                         $term_id = 0;
908                         $name = wp_slash($category->cat_name);
909                         $slug = sanitize_title($name);
910                         $term_group = 0;
911
912                         // Associate terms with the same slug in a term group and make slugs unique.
913                         if ( $exists = $wpdb->get_results( $wpdb->prepare("SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $slug) ) ) {
914                                 $term_group = $exists[0]->term_group;
915                                 $term_id = $exists[0]->term_id;
916                         }
917
918                         if ( empty($term_id) ) {
919                                 $wpdb->insert( $wpdb->terms, compact('name', 'slug', 'term_group') );
920                                 $term_id = (int) $wpdb->insert_id;
921                         }
922
923                         $link_cat_id_map[$cat_id] = $term_id;
924                         $default_link_cat = $term_id;
925
926                         $wpdb->insert( $wpdb->term_taxonomy, array('term_id' => $term_id, 'taxonomy' => 'link_category', 'description' => '', 'parent' => 0, 'count' => 0) );
927                         $tt_ids[$term_id] = (int) $wpdb->insert_id;
928                 }
929
930                 // Associate links to cats.
931                 $links = $wpdb->get_results("SELECT link_id, link_category FROM $wpdb->links");
932                 if ( !empty($links) ) foreach ( $links as $link ) {
933                         if ( 0 == $link->link_category )
934                                 continue;
935                         if ( ! isset($link_cat_id_map[$link->link_category]) )
936                                 continue;
937                         $term_id = $link_cat_id_map[$link->link_category];
938                         $tt_id = $tt_ids[$term_id];
939                         if ( empty($tt_id) )
940                                 continue;
941
942                         $wpdb->insert( $wpdb->term_relationships, array('object_id' => $link->link_id, 'term_taxonomy_id' => $tt_id) );
943                 }
944
945                 // Set default to the last category we grabbed during the upgrade loop.
946                 update_option('default_link_category', $default_link_cat);
947         } else {
948                 $links = $wpdb->get_results("SELECT link_id, category_id FROM $wpdb->link2cat GROUP BY link_id, category_id");
949                 foreach ( $links as $link ) {
950                         $link_id = (int) $link->link_id;
951                         $term_id = (int) $link->category_id;
952                         $taxonomy = 'link_category';
953                         $tt_id = $tt_ids[$term_id][$taxonomy];
954                         if ( empty($tt_id) )
955                                 continue;
956                         $wpdb->insert( $wpdb->term_relationships, array('object_id' => $link_id, 'term_taxonomy_id' => $tt_id) );
957                 }
958         }
959
960         if ( $wp_current_db_version < 4772 ) {
961                 // Obsolete linkcategories table
962                 $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'linkcategories');
963         }
964
965         // Recalculate all counts
966         $terms = $wpdb->get_results("SELECT term_taxonomy_id, taxonomy FROM $wpdb->term_taxonomy");
967         foreach ( (array) $terms as $term ) {
968                 if ( ('post_tag' == $term->taxonomy) || ('category' == $term->taxonomy) )
969                         $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) );
970                 else
971                         $count = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term->term_taxonomy_id) );
972                 $wpdb->update( $wpdb->term_taxonomy, array('count' => $count), array('term_taxonomy_id' => $term->term_taxonomy_id) );
973         }
974 }
975
976 /**
977  * Remove old options from the database.
978  *
979  * @since 2.3.0
980  */
981 function upgrade_230_options_table() {
982         global $wpdb;
983         $old_options_fields = array( 'option_can_override', 'option_type', 'option_width', 'option_height', 'option_description', 'option_admin_level' );
984         $wpdb->hide_errors();
985         foreach ( $old_options_fields as $old )
986                 $wpdb->query("ALTER TABLE $wpdb->options DROP $old");
987         $wpdb->show_errors();
988 }
989
990 /**
991  * Remove old categories, link2cat, and post2cat database tables.
992  *
993  * @since 2.3.0
994  */
995 function upgrade_230_old_tables() {
996         global $wpdb;
997         $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'categories');
998         $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'link2cat');
999         $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'post2cat');
1000 }
1001
1002 /**
1003  * Upgrade old slugs made in version 2.2.
1004  *
1005  * @since 2.2.0
1006  */
1007 function upgrade_old_slugs() {
1008         // Upgrade people who were using the Redirect Old Slugs plugin.
1009         global $wpdb;
1010         $wpdb->query("UPDATE $wpdb->postmeta SET meta_key = '_wp_old_slug' WHERE meta_key = 'old_slug'");
1011 }
1012
1013 /**
1014  * Execute changes made in WordPress 2.5.0.
1015  *
1016  * @since 2.5.0
1017  */
1018 function upgrade_250() {
1019         global $wp_current_db_version;
1020
1021         if ( $wp_current_db_version < 6689 ) {
1022                 populate_roles_250();
1023         }
1024
1025 }
1026
1027 /**
1028  * Execute changes made in WordPress 2.5.2.
1029  *
1030  * @since 2.5.2
1031  */
1032 function upgrade_252() {
1033         global $wpdb;
1034
1035         $wpdb->query("UPDATE $wpdb->users SET user_activation_key = ''");
1036 }
1037
1038 /**
1039  * Execute changes made in WordPress 2.6.
1040  *
1041  * @since 2.6.0
1042  */
1043 function upgrade_260() {
1044         global $wp_current_db_version;
1045
1046         if ( $wp_current_db_version < 8000 )
1047                 populate_roles_260();
1048 }
1049
1050 /**
1051  * Execute changes made in WordPress 2.7.
1052  *
1053  * @since 2.7.0
1054  */
1055 function upgrade_270() {
1056         global $wpdb, $wp_current_db_version;
1057
1058         if ( $wp_current_db_version < 8980 )
1059                 populate_roles_270();
1060
1061         // Update post_date for unpublished posts with empty timestamp
1062         if ( $wp_current_db_version < 8921 )
1063                 $wpdb->query( "UPDATE $wpdb->posts SET post_date = post_modified WHERE post_date = '0000-00-00 00:00:00'" );
1064 }
1065
1066 /**
1067  * Execute changes made in WordPress 2.8.
1068  *
1069  * @since 2.8.0
1070  */
1071 function upgrade_280() {
1072         global $wp_current_db_version, $wpdb;
1073
1074         if ( $wp_current_db_version < 10360 )
1075                 populate_roles_280();
1076         if ( is_multisite() ) {
1077                 $start = 0;
1078                 while( $rows = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options ORDER BY option_id LIMIT $start, 20" ) ) {
1079                         foreach( $rows as $row ) {
1080                                 $value = $row->option_value;
1081                                 if ( !@unserialize( $value ) )
1082                                         $value = stripslashes( $value );
1083                                 if ( $value !== $row->option_value ) {
1084                                         update_option( $row->option_name, $value );
1085                                 }
1086                         }
1087                         $start += 20;
1088                 }
1089                 refresh_blog_details( $wpdb->blogid );
1090         }
1091 }
1092
1093 /**
1094  * Execute changes made in WordPress 2.9.
1095  *
1096  * @since 2.9.0
1097  */
1098 function upgrade_290() {
1099         global $wp_current_db_version;
1100
1101         if ( $wp_current_db_version < 11958 ) {
1102                 // Previously, setting depth to 1 would redundantly disable threading, but now 2 is the minimum depth to avoid confusion
1103                 if ( get_option( 'thread_comments_depth' ) == '1' ) {
1104                         update_option( 'thread_comments_depth', 2 );
1105                         update_option( 'thread_comments', 0 );
1106                 }
1107         }
1108 }
1109
1110 /**
1111  * Execute changes made in WordPress 3.0.
1112  *
1113  * @since 3.0.0
1114  */
1115 function upgrade_300() {
1116         global $wp_current_db_version, $wpdb;
1117
1118         if ( $wp_current_db_version < 15093 )
1119                 populate_roles_300();
1120
1121         if ( $wp_current_db_version < 14139 && is_multisite() && is_main_site() && ! defined( 'MULTISITE' ) && get_site_option( 'siteurl' ) === false )
1122                 add_site_option( 'siteurl', '' );
1123
1124         // 3.0 screen options key name changes.
1125         if ( is_main_site() && !defined('DO_NOT_UPGRADE_GLOBAL_TABLES') ) {
1126                 $sql = "DELETE FROM $wpdb->usermeta
1127                         WHERE meta_key LIKE %s
1128                         OR meta_key LIKE %s
1129                         OR meta_key LIKE %s
1130                         OR meta_key LIKE %s
1131                         OR meta_key LIKE %s
1132                         OR meta_key LIKE %s
1133                         OR meta_key = 'manageedittagscolumnshidden'
1134                         OR meta_key = 'managecategoriescolumnshidden'
1135                         OR meta_key = 'manageedit-tagscolumnshidden'
1136                         OR meta_key = 'manageeditcolumnshidden'
1137                         OR meta_key = 'categories_per_page'
1138                         OR meta_key = 'edit_tags_per_page'";
1139                 $prefix = $wpdb->esc_like( $wpdb->base_prefix );
1140                 $wpdb->query( $wpdb->prepare( $sql,
1141                         $prefix . '%' . $wpdb->esc_like( 'meta-box-hidden' ) . '%',
1142                         $prefix . '%' . $wpdb->esc_like( 'closedpostboxes' ) . '%',
1143                         $prefix . '%' . $wpdb->esc_like( 'manage-'         ) . '%' . $wpdb->esc_like( '-columns-hidden' ) . '%',
1144                         $prefix . '%' . $wpdb->esc_like( 'meta-box-order'  ) . '%',
1145                         $prefix . '%' . $wpdb->esc_like( 'metaboxorder'    ) . '%',
1146                         $prefix . '%' . $wpdb->esc_like( 'screen_layout'   ) . '%'
1147                 ) );
1148         }
1149
1150 }
1151
1152 /**
1153  * Execute changes made in WordPress 3.3.
1154  *
1155  * @since 3.3.0
1156  */
1157 function upgrade_330() {
1158         global $wp_current_db_version, $wpdb, $wp_registered_widgets, $sidebars_widgets;
1159
1160         if ( $wp_current_db_version < 19061 && is_main_site() && ! defined( 'DO_NOT_UPGRADE_GLOBAL_TABLES' ) ) {
1161                 $wpdb->query( "DELETE FROM $wpdb->usermeta WHERE meta_key IN ('show_admin_bar_admin', 'plugins_last_view')" );
1162         }
1163
1164         if ( $wp_current_db_version >= 11548 )
1165                 return;
1166
1167         $sidebars_widgets = get_option( 'sidebars_widgets', array() );
1168         $_sidebars_widgets = array();
1169
1170         if ( isset($sidebars_widgets['wp_inactive_widgets']) || empty($sidebars_widgets) )
1171                 $sidebars_widgets['array_version'] = 3;
1172         elseif ( !isset($sidebars_widgets['array_version']) )
1173                 $sidebars_widgets['array_version'] = 1;
1174
1175         switch ( $sidebars_widgets['array_version'] ) {
1176                 case 1 :
1177                         foreach ( (array) $sidebars_widgets as $index => $sidebar )
1178                         if ( is_array($sidebar) )
1179                         foreach ( (array) $sidebar as $i => $name ) {
1180                                 $id = strtolower($name);
1181                                 if ( isset($wp_registered_widgets[$id]) ) {
1182                                         $_sidebars_widgets[$index][$i] = $id;
1183                                         continue;
1184                                 }
1185                                 $id = sanitize_title($name);
1186                                 if ( isset($wp_registered_widgets[$id]) ) {
1187                                         $_sidebars_widgets[$index][$i] = $id;
1188                                         continue;
1189                                 }
1190
1191                                 $found = false;
1192
1193                                 foreach ( $wp_registered_widgets as $widget_id => $widget ) {
1194                                         if ( strtolower($widget['name']) == strtolower($name) ) {
1195                                                 $_sidebars_widgets[$index][$i] = $widget['id'];
1196                                                 $found = true;
1197                                                 break;
1198                                         } elseif ( sanitize_title($widget['name']) == sanitize_title($name) ) {
1199                                                 $_sidebars_widgets[$index][$i] = $widget['id'];
1200                                                 $found = true;
1201                                                 break;
1202                                         }
1203                                 }
1204
1205                                 if ( $found )
1206                                         continue;
1207
1208                                 unset($_sidebars_widgets[$index][$i]);
1209                         }
1210                         $_sidebars_widgets['array_version'] = 2;
1211                         $sidebars_widgets = $_sidebars_widgets;
1212                         unset($_sidebars_widgets);
1213
1214                 case 2 :
1215                         $sidebars_widgets = retrieve_widgets();
1216                         $sidebars_widgets['array_version'] = 3;
1217                         update_option( 'sidebars_widgets', $sidebars_widgets );
1218         }
1219 }
1220
1221 /**
1222  * Execute changes made in WordPress 3.4.
1223  *
1224  * @since 3.4.0
1225  */
1226 function upgrade_340() {
1227         global $wp_current_db_version, $wpdb;
1228
1229         if ( $wp_current_db_version < 19798 ) {
1230                 $wpdb->hide_errors();
1231                 $wpdb->query( "ALTER TABLE $wpdb->options DROP COLUMN blog_id" );
1232                 $wpdb->show_errors();
1233         }
1234
1235         if ( $wp_current_db_version < 19799 ) {
1236                 $wpdb->hide_errors();
1237                 $wpdb->query("ALTER TABLE $wpdb->comments DROP INDEX comment_approved");
1238                 $wpdb->show_errors();
1239         }
1240
1241         if ( $wp_current_db_version < 20022 && is_main_site() && ! defined( 'DO_NOT_UPGRADE_GLOBAL_TABLES' ) ) {
1242                 $wpdb->query( "DELETE FROM $wpdb->usermeta WHERE meta_key = 'themes_last_view'" );
1243         }
1244
1245         if ( $wp_current_db_version < 20080 ) {
1246                 if ( 'yes' == $wpdb->get_var( "SELECT autoload FROM $wpdb->options WHERE option_name = 'uninstall_plugins'" ) ) {
1247                         $uninstall_plugins = get_option( 'uninstall_plugins' );
1248                         delete_option( 'uninstall_plugins' );
1249                         add_option( 'uninstall_plugins', $uninstall_plugins, null, 'no' );
1250                 }
1251         }
1252 }
1253
1254 /**
1255  * Execute changes made in WordPress 3.5.
1256  *
1257  * @since 3.5.0
1258  */
1259 function upgrade_350() {
1260         global $wp_current_db_version, $wpdb;
1261
1262         if ( $wp_current_db_version < 22006 && $wpdb->get_var( "SELECT link_id FROM $wpdb->links LIMIT 1" ) )
1263                 update_option( 'link_manager_enabled', 1 ); // Previously set to 0 by populate_options()
1264
1265         if ( $wp_current_db_version < 21811 && is_main_site() && ! defined( 'DO_NOT_UPGRADE_GLOBAL_TABLES' ) ) {
1266                 $meta_keys = array();
1267                 foreach ( array_merge( get_post_types(), get_taxonomies() ) as $name ) {
1268                         if ( false !== strpos( $name, '-' ) )
1269                         $meta_keys[] = 'edit_' . str_replace( '-', '_', $name ) . '_per_page';
1270                 }
1271                 if ( $meta_keys ) {
1272                         $meta_keys = implode( "', '", $meta_keys );
1273                         $wpdb->query( "DELETE FROM $wpdb->usermeta WHERE meta_key IN ('$meta_keys')" );
1274                 }
1275         }
1276
1277         if ( $wp_current_db_version < 22422 && $term = get_term_by( 'slug', 'post-format-standard', 'post_format' ) )
1278                 wp_delete_term( $term->term_id, 'post_format' );
1279 }
1280
1281 /**
1282  * Execute changes made in WordPress 3.7.
1283  *
1284  * @since 3.7.0
1285  */
1286 function upgrade_370() {
1287         global $wp_current_db_version;
1288         if ( $wp_current_db_version < 25824 )
1289                 wp_clear_scheduled_hook( 'wp_auto_updates_maybe_update' );
1290 }
1291
1292 /**
1293  * Execute changes made in WordPress 3.7.2.
1294  *
1295  * @since 3.7.2
1296  * @since 3.8.0
1297  */
1298 function upgrade_372() {
1299         global $wp_current_db_version;
1300         if ( $wp_current_db_version < 26148 )
1301                 wp_clear_scheduled_hook( 'wp_maybe_auto_update' );
1302 }
1303
1304 /**
1305  * Execute changes made in WordPress 3.8.0.
1306  *
1307  * @since 3.8.0
1308  */
1309 function upgrade_380() {
1310         global $wp_current_db_version;
1311         if ( $wp_current_db_version < 26691 ) {
1312                 deactivate_plugins( array( 'mp6/mp6.php' ), true );
1313         }
1314 }
1315
1316 /**
1317  * Execute changes made in WordPress 4.0.0.
1318  *
1319  * @since 4.0.0
1320  */
1321 function upgrade_400() {
1322         global $wp_current_db_version;
1323         if ( $wp_current_db_version < 29630 ) {
1324                 if ( ! is_multisite() && false === get_option( 'WPLANG' ) ) {
1325                         if ( defined( 'WPLANG' ) && ( '' !== WPLANG ) && in_array( WPLANG, get_available_languages() ) ) {
1326                                 update_option( 'WPLANG', WPLANG );
1327                         } else {
1328                                 update_option( 'WPLANG', '' );
1329                         }
1330                 }
1331         }
1332 }
1333
1334 /**
1335  * Execute changes made in WordPress 4.1.4.
1336  *
1337  * @since 4.1.3
1338  */
1339 function upgrade_414() {
1340         global $wp_current_db_version, $wpdb;
1341
1342         if ( $wp_current_db_version < 30134 ) {
1343                 $content_length = $wpdb->get_col_length( $wpdb->comments, 'comment_content' );
1344                 if ( ! $content_length ) {
1345                         $content_length = 65535;
1346                 }
1347
1348                 $comments = $wpdb->get_results(
1349                         "SELECT comment_ID FROM $wpdb->comments
1350                         WHERE comment_date_gmt > '2015-04-26'
1351                         AND CHAR_LENGTH( comment_content ) >= $content_length
1352                         AND ( comment_content LIKE '%<%' OR comment_content LIKE '%>%' )"
1353                 );
1354
1355                 foreach ( $comments as $comment ) {
1356                         wp_delete_comment( $comment->comment_ID, true );
1357                 }
1358         }
1359 }
1360
1361 /**
1362  * Execute network level changes
1363  *
1364  * @since 3.0.0
1365  */
1366 function upgrade_network() {
1367         global $wp_current_db_version, $wpdb;
1368
1369         // Always.
1370         if ( is_main_network() ) {
1371                 /*
1372                  * Deletes all expired transients. The multi-table delete syntax is used
1373                  * to delete the transient record from table a, and the corresponding
1374                  * transient_timeout record from table b.
1375                  */
1376                 $time = time();
1377                 $sql = "DELETE a, b FROM $wpdb->sitemeta a, $wpdb->sitemeta b
1378                         WHERE a.meta_key LIKE %s
1379                         AND a.meta_key NOT LIKE %s
1380                         AND b.meta_key = CONCAT( '_site_transient_timeout_', SUBSTRING( a.meta_key, 17 ) )
1381                         AND b.meta_value < %d";
1382                 $wpdb->query( $wpdb->prepare( $sql, $wpdb->esc_like( '_site_transient_' ) . '%', $wpdb->esc_like ( '_site_transient_timeout_' ) . '%', $time ) );
1383         }
1384
1385         // 2.8.
1386         if ( $wp_current_db_version < 11549 ) {
1387                 $wpmu_sitewide_plugins = get_site_option( 'wpmu_sitewide_plugins' );
1388                 $active_sitewide_plugins = get_site_option( 'active_sitewide_plugins' );
1389                 if ( $wpmu_sitewide_plugins ) {
1390                         if ( !$active_sitewide_plugins )
1391                                 $sitewide_plugins = (array) $wpmu_sitewide_plugins;
1392                         else
1393                                 $sitewide_plugins = array_merge( (array) $active_sitewide_plugins, (array) $wpmu_sitewide_plugins );
1394
1395                         update_site_option( 'active_sitewide_plugins', $sitewide_plugins );
1396                 }
1397                 delete_site_option( 'wpmu_sitewide_plugins' );
1398                 delete_site_option( 'deactivated_sitewide_plugins' );
1399
1400                 $start = 0;
1401                 while( $rows = $wpdb->get_results( "SELECT meta_key, meta_value FROM {$wpdb->sitemeta} ORDER BY meta_id LIMIT $start, 20" ) ) {
1402                         foreach( $rows as $row ) {
1403                                 $value = $row->meta_value;
1404                                 if ( !@unserialize( $value ) )
1405                                         $value = stripslashes( $value );
1406                                 if ( $value !== $row->meta_value ) {
1407                                         update_site_option( $row->meta_key, $value );
1408                                 }
1409                         }
1410                         $start += 20;
1411                 }
1412         }
1413
1414         // 3.0
1415         if ( $wp_current_db_version < 13576 )
1416                 update_site_option( 'global_terms_enabled', '1' );
1417
1418         // 3.3
1419         if ( $wp_current_db_version < 19390 )
1420                 update_site_option( 'initial_db_version', $wp_current_db_version );
1421
1422         if ( $wp_current_db_version < 19470 ) {
1423                 if ( false === get_site_option( 'active_sitewide_plugins' ) )
1424                         update_site_option( 'active_sitewide_plugins', array() );
1425         }
1426
1427         // 3.4
1428         if ( $wp_current_db_version < 20148 ) {
1429                 // 'allowedthemes' keys things by stylesheet. 'allowed_themes' keyed things by name.
1430                 $allowedthemes  = get_site_option( 'allowedthemes'  );
1431                 $allowed_themes = get_site_option( 'allowed_themes' );
1432                 if ( false === $allowedthemes && is_array( $allowed_themes ) && $allowed_themes ) {
1433                         $converted = array();
1434                         $themes = wp_get_themes();
1435                         foreach ( $themes as $stylesheet => $theme_data ) {
1436                                 if ( isset( $allowed_themes[ $theme_data->get('Name') ] ) )
1437                                         $converted[ $stylesheet ] = true;
1438                         }
1439                         update_site_option( 'allowedthemes', $converted );
1440                         delete_site_option( 'allowed_themes' );
1441                 }
1442         }
1443
1444         // 3.5
1445         if ( $wp_current_db_version < 21823 )
1446                 update_site_option( 'ms_files_rewriting', '1' );
1447
1448         // 3.5.2
1449         if ( $wp_current_db_version < 24448 ) {
1450                 $illegal_names = get_site_option( 'illegal_names' );
1451                 if ( is_array( $illegal_names ) && count( $illegal_names ) === 1 ) {
1452                         $illegal_name = reset( $illegal_names );
1453                         $illegal_names = explode( ' ', $illegal_name );
1454                         update_site_option( 'illegal_names', $illegal_names );
1455                 }
1456         }
1457 }
1458
1459 // The functions we use to actually do stuff
1460
1461 // General
1462
1463 /**
1464  * {@internal Missing Short Description}}
1465  *
1466  * {@internal Missing Long Description}}
1467  *
1468  * @since 1.0.0
1469  *
1470  * @param string $table_name Database table name to create.
1471  * @param string $create_ddl SQL statement to create table.
1472  * @return bool If table already exists or was created by function.
1473  */
1474 function maybe_create_table($table_name, $create_ddl) {
1475         global $wpdb;
1476
1477         $query = $wpdb->prepare( "SHOW TABLES LIKE %s", $wpdb->esc_like( $table_name ) );
1478
1479         if ( $wpdb->get_var( $query ) == $table_name ) {
1480                 return true;
1481         }
1482
1483         // Didn't find it try to create it..
1484         $wpdb->query($create_ddl);
1485
1486         // We cannot directly tell that whether this succeeded!
1487         if ( $wpdb->get_var( $query ) == $table_name ) {
1488                 return true;
1489         }
1490         return false;
1491 }
1492
1493 /**
1494  * {@internal Missing Short Description}}
1495  *
1496  * {@internal Missing Long Description}}
1497  *
1498  * @since 1.0.1
1499  *
1500  * @param string $table Database table name.
1501  * @param string $index Index name to drop.
1502  * @return bool True, when finished.
1503  */
1504 function drop_index($table, $index) {
1505         global $wpdb;
1506         $wpdb->hide_errors();
1507         $wpdb->query("ALTER TABLE `$table` DROP INDEX `$index`");
1508         // Now we need to take out all the extra ones we may have created
1509         for ($i = 0; $i < 25; $i++) {
1510                 $wpdb->query("ALTER TABLE `$table` DROP INDEX `{$index}_$i`");
1511         }
1512         $wpdb->show_errors();
1513         return true;
1514 }
1515
1516 /**
1517  * {@internal Missing Short Description}}
1518  *
1519  * {@internal Missing Long Description}}
1520  *
1521  * @since 1.0.1
1522  *
1523  * @param string $table Database table name.
1524  * @param string $index Database table index column.
1525  * @return bool True, when done with execution.
1526  */
1527 function add_clean_index($table, $index) {
1528         global $wpdb;
1529         drop_index($table, $index);
1530         $wpdb->query("ALTER TABLE `$table` ADD INDEX ( `$index` )");
1531         return true;
1532 }
1533
1534 /**
1535  ** maybe_add_column()
1536  ** Add column to db table if it doesn't exist.
1537  ** Returns:  true if already exists or on successful completion
1538  **           false on error
1539  */
1540 function maybe_add_column($table_name, $column_name, $create_ddl) {
1541         global $wpdb;
1542         foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) {
1543                 if ($column == $column_name) {
1544                         return true;
1545                 }
1546         }
1547
1548         // Didn't find it try to create it.
1549         $wpdb->query($create_ddl);
1550
1551         // We cannot directly tell that whether this succeeded!
1552         foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) {
1553                 if ($column == $column_name) {
1554                         return true;
1555                 }
1556         }
1557         return false;
1558 }
1559
1560 /**
1561  * Retrieve all options as it was for 1.2.
1562  *
1563  * @since 1.2.0
1564  *
1565  * @return stdClass List of options.
1566  */
1567 function get_alloptions_110() {
1568         global $wpdb;
1569         $all_options = new stdClass;
1570         if ( $options = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options" ) ) {
1571                 foreach ( $options as $option ) {
1572                         if ( 'siteurl' == $option->option_name || 'home' == $option->option_name || 'category_base' == $option->option_name )
1573                                 $option->option_value = untrailingslashit( $option->option_value );
1574                         $all_options->{$option->option_name} = stripslashes( $option->option_value );
1575                 }
1576         }
1577         return $all_options;
1578 }
1579
1580 /**
1581  * Version of get_option that is private to install/upgrade.
1582  *
1583  * @since 1.5.1
1584  * @access private
1585  *
1586  * @param string $setting Option name.
1587  * @return mixed
1588  */
1589 function __get_option($setting) {
1590         global $wpdb;
1591
1592         if ( $setting == 'home' && defined( 'WP_HOME' ) )
1593                 return untrailingslashit( WP_HOME );
1594
1595         if ( $setting == 'siteurl' && defined( 'WP_SITEURL' ) )
1596                 return untrailingslashit( WP_SITEURL );
1597
1598         $option = $wpdb->get_var( $wpdb->prepare("SELECT option_value FROM $wpdb->options WHERE option_name = %s", $setting ) );
1599
1600         if ( 'home' == $setting && '' == $option )
1601                 return __get_option( 'siteurl' );
1602
1603         if ( 'siteurl' == $setting || 'home' == $setting || 'category_base' == $setting || 'tag_base' == $setting )
1604                 $option = untrailingslashit( $option );
1605
1606         return maybe_unserialize( $option );
1607 }
1608
1609 /**
1610  * {@internal Missing Short Description}}
1611  *
1612  * {@internal Missing Long Description}}
1613  *
1614  * @since 1.5.0
1615  *
1616  * @param string $content
1617  * @return string
1618  */
1619 function deslash($content) {
1620         // Note: \\\ inside a regex denotes a single backslash.
1621
1622         /*
1623          * Replace one or more backslashes followed by a single quote with
1624          * a single quote.
1625          */
1626         $content = preg_replace("/\\\+'/", "'", $content);
1627
1628         /*
1629          * Replace one or more backslashes followed by a double quote with
1630          * a double quote.
1631          */
1632         $content = preg_replace('/\\\+"/', '"', $content);
1633
1634         // Replace one or more backslashes with one backslash.
1635         $content = preg_replace("/\\\+/", "\\", $content);
1636
1637         return $content;
1638 }
1639
1640 /**
1641  * {@internal Missing Short Description}}
1642  *
1643  * {@internal Missing Long Description}}
1644  *
1645  * @since 1.5.0
1646  *
1647  * @param string $queries
1648  * @param bool   $execute
1649  * @return array
1650  */
1651 function dbDelta( $queries = '', $execute = true ) {
1652         global $wpdb;
1653
1654         if ( in_array( $queries, array( '', 'all', 'blog', 'global', 'ms_global' ), true ) )
1655             $queries = wp_get_db_schema( $queries );
1656
1657         // Separate individual queries into an array
1658         if ( !is_array($queries) ) {
1659                 $queries = explode( ';', $queries );
1660                 $queries = array_filter( $queries );
1661         }
1662
1663         /**
1664          * Filter the dbDelta SQL queries.
1665          *
1666          * @since 3.3.0
1667          *
1668          * @param array $queries An array of dbDelta SQL queries.
1669          */
1670         $queries = apply_filters( 'dbdelta_queries', $queries );
1671
1672         $cqueries = array(); // Creation Queries
1673         $iqueries = array(); // Insertion Queries
1674         $for_update = array();
1675
1676         // Create a tablename index for an array ($cqueries) of queries
1677         foreach($queries as $qry) {
1678                 if (preg_match("|CREATE TABLE ([^ ]*)|", $qry, $matches)) {
1679                         $cqueries[ trim( $matches[1], '`' ) ] = $qry;
1680                         $for_update[$matches[1]] = 'Created table '.$matches[1];
1681                 } else if (preg_match("|CREATE DATABASE ([^ ]*)|", $qry, $matches)) {
1682                         array_unshift($cqueries, $qry);
1683                 } else if (preg_match("|INSERT INTO ([^ ]*)|", $qry, $matches)) {
1684                         $iqueries[] = $qry;
1685                 } else if (preg_match("|UPDATE ([^ ]*)|", $qry, $matches)) {
1686                         $iqueries[] = $qry;
1687                 } else {
1688                         // Unrecognized query type
1689                 }
1690         }
1691
1692         /**
1693          * Filter the dbDelta SQL queries for creating tables and/or databases.
1694          *
1695          * Queries filterable via this hook contain "CREATE TABLE" or "CREATE DATABASE".
1696          *
1697          * @since 3.3.0
1698          *
1699          * @param array $cqueries An array of dbDelta create SQL queries.
1700          */
1701         $cqueries = apply_filters( 'dbdelta_create_queries', $cqueries );
1702
1703         /**
1704          * Filter the dbDelta SQL queries for inserting or updating.
1705          *
1706          * Queries filterable via this hook contain "INSERT INTO" or "UPDATE".
1707          *
1708          * @since 3.3.0
1709          *
1710          * @param array $iqueries An array of dbDelta insert or update SQL queries.
1711          */
1712         $iqueries = apply_filters( 'dbdelta_insert_queries', $iqueries );
1713
1714         $global_tables = $wpdb->tables( 'global' );
1715         foreach ( $cqueries as $table => $qry ) {
1716                 // Upgrade global tables only for the main site. Don't upgrade at all if DO_NOT_UPGRADE_GLOBAL_TABLES is defined.
1717                 if ( in_array( $table, $global_tables ) && ( !is_main_site() || defined( 'DO_NOT_UPGRADE_GLOBAL_TABLES' ) ) ) {
1718                         unset( $cqueries[ $table ], $for_update[ $table ] );
1719                         continue;
1720                 }
1721
1722                 // Fetch the table column structure from the database
1723                 $suppress = $wpdb->suppress_errors();
1724                 $tablefields = $wpdb->get_results("DESCRIBE {$table};");
1725                 $wpdb->suppress_errors( $suppress );
1726
1727                 if ( ! $tablefields )
1728                         continue;
1729
1730                 // Clear the field and index arrays.
1731                 $cfields = $indices = array();
1732
1733                 // Get all of the field names in the query from between the parentheses.
1734                 preg_match("|\((.*)\)|ms", $qry, $match2);
1735                 $qryline = trim($match2[1]);
1736
1737                 // Separate field lines into an array.
1738                 $flds = explode("\n", $qryline);
1739
1740                 // todo: Remove this?
1741                 //echo "<hr/><pre>\n".print_r(strtolower($table), true).":\n".print_r($cqueries, true)."</pre><hr/>";
1742
1743                 // For every field line specified in the query.
1744                 foreach ($flds as $fld) {
1745
1746                         // Extract the field name.
1747                         preg_match("|^([^ ]*)|", trim($fld), $fvals);
1748                         $fieldname = trim( $fvals[1], '`' );
1749
1750                         // Verify the found field name.
1751                         $validfield = true;
1752                         switch (strtolower($fieldname)) {
1753                         case '':
1754                         case 'primary':
1755                         case 'index':
1756                         case 'fulltext':
1757                         case 'unique':
1758                         case 'key':
1759                                 $validfield = false;
1760                                 $indices[] = trim(trim($fld), ", \n");
1761                                 break;
1762                         }
1763                         $fld = trim($fld);
1764
1765                         // If it's a valid field, add it to the field array.
1766                         if ($validfield) {
1767                                 $cfields[strtolower($fieldname)] = trim($fld, ", \n");
1768                         }
1769                 }
1770
1771                 // For every field in the table.
1772                 foreach ($tablefields as $tablefield) {
1773
1774                         // If the table field exists in the field array ...
1775                         if (array_key_exists(strtolower($tablefield->Field), $cfields)) {
1776
1777                                 // Get the field type from the query.
1778                                 preg_match("|".$tablefield->Field." ([^ ]*( unsigned)?)|i", $cfields[strtolower($tablefield->Field)], $matches);
1779                                 $fieldtype = $matches[1];
1780
1781                                 // Is actual field type different from the field type in query?
1782                                 if ($tablefield->Type != $fieldtype) {
1783                                         // Add a query to change the column type
1784                                         $cqueries[] = "ALTER TABLE {$table} CHANGE COLUMN {$tablefield->Field} " . $cfields[strtolower($tablefield->Field)];
1785                                         $for_update[$table.'.'.$tablefield->Field] = "Changed type of {$table}.{$tablefield->Field} from {$tablefield->Type} to {$fieldtype}";
1786                                 }
1787
1788                                 // Get the default value from the array
1789                                         // todo: Remove this?
1790                                         //echo "{$cfields[strtolower($tablefield->Field)]}<br>";
1791                                 if (preg_match("| DEFAULT '(.*?)'|i", $cfields[strtolower($tablefield->Field)], $matches)) {
1792                                         $default_value = $matches[1];
1793                                         if ($tablefield->Default != $default_value) {
1794                                                 // Add a query to change the column's default value
1795                                                 $cqueries[] = "ALTER TABLE {$table} ALTER COLUMN {$tablefield->Field} SET DEFAULT '{$default_value}'";
1796                                                 $for_update[$table.'.'.$tablefield->Field] = "Changed default value of {$table}.{$tablefield->Field} from {$tablefield->Default} to {$default_value}";
1797                                         }
1798                                 }
1799
1800                                 // Remove the field from the array (so it's not added).
1801                                 unset($cfields[strtolower($tablefield->Field)]);
1802                         } else {
1803                                 // This field exists in the table, but not in the creation queries?
1804                         }
1805                 }
1806
1807                 // For every remaining field specified for the table.
1808                 foreach ($cfields as $fieldname => $fielddef) {
1809                         // Push a query line into $cqueries that adds the field to that table.
1810                         $cqueries[] = "ALTER TABLE {$table} ADD COLUMN $fielddef";
1811                         $for_update[$table.'.'.$fieldname] = 'Added column '.$table.'.'.$fieldname;
1812                 }
1813
1814                 // Index stuff goes here. Fetch the table index structure from the database.
1815                 $tableindices = $wpdb->get_results("SHOW INDEX FROM {$table};");
1816
1817                 if ($tableindices) {
1818                         // Clear the index array.
1819                         unset($index_ary);
1820
1821                         // For every index in the table.
1822                         foreach ($tableindices as $tableindex) {
1823
1824                                 // Add the index to the index data array.
1825                                 $keyname = $tableindex->Key_name;
1826                                 $index_ary[$keyname]['columns'][] = array('fieldname' => $tableindex->Column_name, 'subpart' => $tableindex->Sub_part);
1827                                 $index_ary[$keyname]['unique'] = ($tableindex->Non_unique == 0)?true:false;
1828                         }
1829
1830                         // For each actual index in the index array.
1831                         foreach ($index_ary as $index_name => $index_data) {
1832
1833                                 // Build a create string to compare to the query.
1834                                 $index_string = '';
1835                                 if ($index_name == 'PRIMARY') {
1836                                         $index_string .= 'PRIMARY ';
1837                                 } else if($index_data['unique']) {
1838                                         $index_string .= 'UNIQUE ';
1839                                 }
1840                                 $index_string .= 'KEY ';
1841                                 if ($index_name != 'PRIMARY') {
1842                                         $index_string .= $index_name;
1843                                 }
1844                                 $index_columns = '';
1845
1846                                 // For each column in the index.
1847                                 foreach ($index_data['columns'] as $column_data) {
1848                                         if ($index_columns != '') $index_columns .= ',';
1849
1850                                         // Add the field to the column list string.
1851                                         $index_columns .= $column_data['fieldname'];
1852                                         if ($column_data['subpart'] != '') {
1853                                                 $index_columns .= '('.$column_data['subpart'].')';
1854                                         }
1855                                 }
1856                                 // Add the column list to the index create string.
1857                                 $index_string .= ' ('.$index_columns.')';
1858                                 if (!(($aindex = array_search($index_string, $indices)) === false)) {
1859                                         unset($indices[$aindex]);
1860                                         // todo: Remove this?
1861                                         //echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">{$table}:<br />Found index:".$index_string."</pre>\n";
1862                                 }
1863                                 // todo: Remove this?
1864                                 //else echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">{$table}:<br /><b>Did not find index:</b>".$index_string."<br />".print_r($indices, true)."</pre>\n";
1865                         }
1866                 }
1867
1868                 // For every remaining index specified for the table.
1869                 foreach ( (array) $indices as $index ) {
1870                         // Push a query line into $cqueries that adds the index to that table.
1871                         $cqueries[] = "ALTER TABLE {$table} ADD $index";
1872                         $for_update[] = 'Added index ' . $table . ' ' . $index;
1873                 }
1874
1875                 // Remove the original table creation query from processing.
1876                 unset( $cqueries[ $table ], $for_update[ $table ] );
1877         }
1878
1879         $allqueries = array_merge($cqueries, $iqueries);
1880         if ($execute) {
1881                 foreach ($allqueries as $query) {
1882                         // todo: Remove this?
1883                         //echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">".print_r($query, true)."</pre>\n";
1884                         $wpdb->query($query);
1885                 }
1886         }
1887
1888         return $for_update;
1889 }
1890
1891 /**
1892  * {@internal Missing Short Description}}
1893  *
1894  * {@internal Missing Long Description}}
1895  *
1896  * @since 1.5.0
1897  */
1898 function make_db_current( $tables = 'all' ) {
1899         $alterations = dbDelta( $tables );
1900         echo "<ol>\n";
1901         foreach($alterations as $alteration) echo "<li>$alteration</li>\n";
1902         echo "</ol>\n";
1903 }
1904
1905 /**
1906  * {@internal Missing Short Description}}
1907  *
1908  * {@internal Missing Long Description}}
1909  *
1910  * @since 1.5.0
1911  */
1912 function make_db_current_silent( $tables = 'all' ) {
1913         dbDelta( $tables );
1914 }
1915
1916 /**
1917  * {@internal Missing Short Description}}
1918  *
1919  * {@internal Missing Long Description}}
1920  *
1921  * @since 1.5.0
1922  *
1923  * @param string $theme_name
1924  * @param string $template
1925  * @return bool
1926  */
1927 function make_site_theme_from_oldschool($theme_name, $template) {
1928         $home_path = get_home_path();
1929         $site_dir = WP_CONTENT_DIR . "/themes/$template";
1930
1931         if (! file_exists("$home_path/index.php"))
1932                 return false;
1933
1934         /*
1935          * Copy files from the old locations to the site theme.
1936          * TODO: This does not copy arbitrary include dependencies. Only the standard WP files are copied.
1937          */
1938         $files = array('index.php' => 'index.php', 'wp-layout.css' => 'style.css', 'wp-comments.php' => 'comments.php', 'wp-comments-popup.php' => 'comments-popup.php');
1939
1940         foreach ($files as $oldfile => $newfile) {
1941                 if ($oldfile == 'index.php')
1942                         $oldpath = $home_path;
1943                 else
1944                         $oldpath = ABSPATH;
1945
1946                 // Check to make sure it's not a new index.
1947                 if ($oldfile == 'index.php') {
1948                         $index = implode('', file("$oldpath/$oldfile"));
1949                         if (strpos($index, 'WP_USE_THEMES') !== false) {
1950                                 if (! @copy(WP_CONTENT_DIR . '/themes/' . WP_DEFAULT_THEME . '/index.php', "$site_dir/$newfile"))
1951                                         return false;
1952
1953                                 // Don't copy anything.
1954                                 continue;
1955                                 }
1956                 }
1957
1958                 if (! @copy("$oldpath/$oldfile", "$site_dir/$newfile"))
1959                         return false;
1960
1961                 chmod("$site_dir/$newfile", 0777);
1962
1963                 // Update the blog header include in each file.
1964                 $lines = explode("\n", implode('', file("$site_dir/$newfile")));
1965                 if ($lines) {
1966                         $f = fopen("$site_dir/$newfile", 'w');
1967
1968                         foreach ($lines as $line) {
1969                                 if (preg_match('/require.*wp-blog-header/', $line))
1970                                         $line = '//' . $line;
1971
1972                                 // Update stylesheet references.
1973                                 $line = str_replace("<?php echo __get_option('siteurl'); ?>/wp-layout.css", "<?php bloginfo('stylesheet_url'); ?>", $line);
1974
1975                                 // Update comments template inclusion.
1976                                 $line = str_replace("<?php include(ABSPATH . 'wp-comments.php'); ?>", "<?php comments_template(); ?>", $line);
1977
1978                                 fwrite($f, "{$line}\n");
1979                         }
1980                         fclose($f);
1981                 }
1982         }
1983
1984         // Add a theme header.
1985         $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";
1986
1987         $stylelines = file_get_contents("$site_dir/style.css");
1988         if ($stylelines) {
1989                 $f = fopen("$site_dir/style.css", 'w');
1990
1991                 fwrite($f, $header);
1992                 fwrite($f, $stylelines);
1993                 fclose($f);
1994         }
1995
1996         return true;
1997 }
1998
1999 /**
2000  * {@internal Missing Short Description}}
2001  *
2002  * {@internal Missing Long Description}}
2003  *
2004  * @since 1.5.0
2005  *
2006  * @param string $theme_name
2007  * @param string $template
2008  * @return null|false
2009  */
2010 function make_site_theme_from_default($theme_name, $template) {
2011         $site_dir = WP_CONTENT_DIR . "/themes/$template";
2012         $default_dir = WP_CONTENT_DIR . '/themes/' . WP_DEFAULT_THEME;
2013
2014         // Copy files from the default theme to the site theme.
2015         //$files = array('index.php', 'comments.php', 'comments-popup.php', 'footer.php', 'header.php', 'sidebar.php', 'style.css');
2016
2017         $theme_dir = @ opendir($default_dir);
2018         if ($theme_dir) {
2019                 while(($theme_file = readdir( $theme_dir )) !== false) {
2020                         if (is_dir("$default_dir/$theme_file"))
2021                                 continue;
2022                         if (! @copy("$default_dir/$theme_file", "$site_dir/$theme_file"))
2023                                 return;
2024                         chmod("$site_dir/$theme_file", 0777);
2025                 }
2026         }
2027         @closedir($theme_dir);
2028
2029         // Rewrite the theme header.
2030         $stylelines = explode("\n", implode('', file("$site_dir/style.css")));
2031         if ($stylelines) {
2032                 $f = fopen("$site_dir/style.css", 'w');
2033
2034                 foreach ($stylelines as $line) {
2035                         if (strpos($line, 'Theme Name:') !== false) $line = 'Theme Name: ' . $theme_name;
2036                         elseif (strpos($line, 'Theme URI:') !== false) $line = 'Theme URI: ' . __get_option('url');
2037                         elseif (strpos($line, 'Description:') !== false) $line = 'Description: Your theme.';
2038                         elseif (strpos($line, 'Version:') !== false) $line = 'Version: 1';
2039                         elseif (strpos($line, 'Author:') !== false) $line = 'Author: You';
2040                         fwrite($f, $line . "\n");
2041                 }
2042                 fclose($f);
2043         }
2044
2045         // Copy the images.
2046         umask(0);
2047         if (! mkdir("$site_dir/images", 0777)) {
2048                 return false;
2049         }
2050
2051         $images_dir = @ opendir("$default_dir/images");
2052         if ($images_dir) {
2053                 while(($image = readdir($images_dir)) !== false) {
2054                         if (is_dir("$default_dir/images/$image"))
2055                                 continue;
2056                         if (! @copy("$default_dir/images/$image", "$site_dir/images/$image"))
2057                                 return;
2058                         chmod("$site_dir/images/$image", 0777);
2059                 }
2060         }
2061         @closedir($images_dir);
2062 }
2063
2064 // Create a site theme from the default theme.
2065 /**
2066  * {@internal Missing Short Description}}
2067  *
2068  * {@internal Missing Long Description}}
2069  *
2070  * @since 1.5.0
2071  *
2072  * @return false|string
2073  */
2074 function make_site_theme() {
2075         // Name the theme after the blog.
2076         $theme_name = __get_option('blogname');
2077         $template = sanitize_title($theme_name);
2078         $site_dir = WP_CONTENT_DIR . "/themes/$template";
2079
2080         // If the theme already exists, nothing to do.
2081         if ( is_dir($site_dir)) {
2082                 return false;
2083         }
2084
2085         // We must be able to write to the themes dir.
2086         if (! is_writable(WP_CONTENT_DIR . "/themes")) {
2087                 return false;
2088         }
2089
2090         umask(0);
2091         if (! mkdir($site_dir, 0777)) {
2092                 return false;
2093         }
2094
2095         if (file_exists(ABSPATH . 'wp-layout.css')) {
2096                 if (! make_site_theme_from_oldschool($theme_name, $template)) {
2097                         // TODO: rm -rf the site theme directory.
2098                         return false;
2099                 }
2100         } else {
2101                 if (! make_site_theme_from_default($theme_name, $template))
2102                         // TODO: rm -rf the site theme directory.
2103                         return false;
2104         }
2105
2106         // Make the new site theme active.
2107         $current_template = __get_option('template');
2108         if ($current_template == WP_DEFAULT_THEME) {
2109                 update_option('template', $template);
2110                 update_option('stylesheet', $template);
2111         }
2112         return $template;
2113 }
2114
2115 /**
2116  * Translate user level to user role name.
2117  *
2118  * @since 2.0.0
2119  *
2120  * @param int $level User level.
2121  * @return string User role name.
2122  */
2123 function translate_level_to_role($level) {
2124         switch ($level) {
2125         case 10:
2126         case 9:
2127         case 8:
2128                 return 'administrator';
2129         case 7:
2130         case 6:
2131         case 5:
2132                 return 'editor';
2133         case 4:
2134         case 3:
2135         case 2:
2136                 return 'author';
2137         case 1:
2138                 return 'contributor';
2139         case 0:
2140                 return 'subscriber';
2141         }
2142 }
2143
2144 /**
2145  * {@internal Missing Short Description}}
2146  *
2147  * {@internal Missing Long Description}}
2148  *
2149  * @since 2.1.0
2150  */
2151 function wp_check_mysql_version() {
2152         global $wpdb;
2153         $result = $wpdb->check_database_version();
2154         if ( is_wp_error( $result ) )
2155                 die( $result->get_error_message() );
2156 }
2157
2158 /**
2159  * Disables the Automattic widgets plugin, which was merged into core.
2160  *
2161  * @since 2.2.0
2162  */
2163 function maybe_disable_automattic_widgets() {
2164         $plugins = __get_option( 'active_plugins' );
2165
2166         foreach ( (array) $plugins as $plugin ) {
2167                 if ( basename( $plugin ) == 'widgets.php' ) {
2168                         array_splice( $plugins, array_search( $plugin, $plugins ), 1 );
2169                         update_option( 'active_plugins', $plugins );
2170                         break;
2171                 }
2172         }
2173 }
2174
2175 /**
2176  * Disables the Link Manager on upgrade, if at the time of upgrade, no links exist in the DB.
2177  *
2178  * @since 3.5.0
2179  */
2180 function maybe_disable_link_manager() {
2181         global $wp_current_db_version, $wpdb;
2182
2183         if ( $wp_current_db_version >= 22006 && get_option( 'link_manager_enabled' ) && ! $wpdb->get_var( "SELECT link_id FROM $wpdb->links LIMIT 1" ) )
2184                 update_option( 'link_manager_enabled', 0 );
2185 }
2186
2187 /**
2188  * Runs before the schema is upgraded.
2189  *
2190  * @since 2.9.0
2191  */
2192 function pre_schema_upgrade() {
2193         global $wp_current_db_version, $wpdb;
2194
2195         // Upgrade versions prior to 2.9
2196         if ( $wp_current_db_version < 11557 ) {
2197                 // Delete duplicate options. Keep the option with the highest option_id.
2198                 $wpdb->query("DELETE o1 FROM $wpdb->options AS o1 JOIN $wpdb->options AS o2 USING (`option_name`) WHERE o2.option_id > o1.option_id");
2199
2200                 // Drop the old primary key and add the new.
2201                 $wpdb->query("ALTER TABLE $wpdb->options DROP PRIMARY KEY, ADD PRIMARY KEY(option_id)");
2202
2203                 // Drop the old option_name index. dbDelta() doesn't do the drop.
2204                 $wpdb->query("ALTER TABLE $wpdb->options DROP INDEX option_name");
2205         }
2206
2207         // Multisite schema upgrades.
2208         if ( $wp_current_db_version < 25448 && is_multisite() && ! defined( 'DO_NOT_UPGRADE_GLOBAL_TABLES' ) && is_main_network() ) {
2209
2210                 // Upgrade verions prior to 3.7
2211                 if ( $wp_current_db_version < 25179 ) {
2212                         // New primary key for signups.
2213                         $wpdb->query( "ALTER TABLE $wpdb->signups ADD signup_id BIGINT(20) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST" );
2214                         $wpdb->query( "ALTER TABLE $wpdb->signups DROP INDEX domain" );
2215                 }
2216
2217                 if ( $wp_current_db_version < 25448 ) {
2218                         // Convert archived from enum to tinyint.
2219                         $wpdb->query( "ALTER TABLE $wpdb->blogs CHANGE COLUMN archived archived varchar(1) NOT NULL default '0'" );
2220                         $wpdb->query( "ALTER TABLE $wpdb->blogs CHANGE COLUMN archived archived tinyint(2) NOT NULL default 0" );
2221                 }
2222         }
2223
2224         if ( $wp_current_db_version < 30133 ) {
2225                 // dbDelta() can recreate but can't drop the index.
2226                 $wpdb->query( "ALTER TABLE $wpdb->terms DROP INDEX slug" );
2227         }
2228 }
2229
2230 /**
2231  * Install global terms.
2232  *
2233  * @since 3.0.0
2234  *
2235  */
2236 if ( !function_exists( 'install_global_terms' ) ) :
2237 function install_global_terms() {
2238         global $wpdb, $charset_collate;
2239         $ms_queries = "
2240 CREATE TABLE $wpdb->sitecategories (
2241   cat_ID bigint(20) NOT NULL auto_increment,
2242   cat_name varchar(55) NOT NULL default '',
2243   category_nicename varchar(200) NOT NULL default '',
2244   last_updated timestamp NOT NULL,
2245   PRIMARY KEY  (cat_ID),
2246   KEY category_nicename (category_nicename),
2247   KEY last_updated (last_updated)
2248 ) $charset_collate;
2249 ";
2250 // now create tables
2251         dbDelta( $ms_queries );
2252 }
2253 endif;