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