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