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