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