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