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