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