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