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