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