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