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