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