]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-admin/includes/upgrade.php
Wordpress 2.6.2
[autoinstalls/wordpress.git] / wp-admin / includes / upgrade.php
1 <?php
2
3 if ( file_exists(WP_CONTENT_DIR . '/install.php') )
4         require (WP_CONTENT_DIR . '/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
22         $guessurl = wp_guess_url();
23
24         update_option('siteurl', $guessurl);
25
26         // If not a public blog, don't ping.
27         if ( ! $public )
28                 update_option('default_pingback_flag', 0);
29
30         // Create default user.  If the user already exists, the user tables are
31         // being shared among blogs.  Just set the role in that case.
32         $user_id = username_exists($user_name);
33         if ( !$user_id ) {
34                 $random_password = wp_generate_password();
35                 $user_id = wp_create_user($user_name, $random_password, $user_email);
36         } else {
37                 $random_password = __('User already exists.  Password inherited.');
38         }
39
40         $user = new WP_User($user_id);
41         $user->set_role('administrator');
42
43         wp_install_defaults($user_id);
44
45         $wp_rewrite->flush_rules();
46
47         wp_new_blog_notification($blog_title, $guessurl, $user_id, $random_password);
48
49         wp_cache_flush();
50
51         return array('url' => $guessurl, 'user_id' => $user_id, 'password' => $random_password);
52 }
53 endif;
54
55 if ( !function_exists('wp_install_defaults') ) :
56 function wp_install_defaults($user_id) {
57         global $wpdb;
58
59         // Default category
60         $cat_name = $wpdb->escape(__('Uncategorized'));
61         $cat_slug = sanitize_title(_c('Uncategorized|Default category slug'));
62         $wpdb->query("INSERT INTO $wpdb->terms (name, slug, term_group) VALUES ('$cat_name', '$cat_slug', '0')");
63         $wpdb->query("INSERT INTO $wpdb->term_taxonomy (term_id, taxonomy, description, parent, count) VALUES ('1', 'category', '', '0', '1')");
64
65         // Default link category
66         $cat_name = $wpdb->escape(__('Blogroll'));
67         $cat_slug = sanitize_title(_c('Blogroll|Default link category slug'));
68         $wpdb->query("INSERT INTO $wpdb->terms (name, slug, term_group) VALUES ('$cat_name', '$cat_slug', '0')");
69         $wpdb->query("INSERT INTO $wpdb->term_taxonomy (term_id, taxonomy, description, parent, count) VALUES ('2', 'link_category', '', '0', '7')");
70
71         // Now drop in some default links
72         $wpdb->query("INSERT INTO $wpdb->links (link_url, link_name, link_category, link_rss, link_notes) VALUES ('http://codex.wordpress.org/', 'Documentation', 0, '', '');");
73         $wpdb->query( "INSERT INTO $wpdb->term_relationships (`object_id`, `term_taxonomy_id`) VALUES (1, 2)" );
74
75         $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/', '');");
76         $wpdb->query( "INSERT INTO $wpdb->term_relationships (`object_id`, `term_taxonomy_id`) VALUES (2, 2)" );
77
78         $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, '', '');");
79         $wpdb->query( "INSERT INTO $wpdb->term_relationships (`object_id`, `term_taxonomy_id`) VALUES (3, 2)" );
80
81         $wpdb->query("INSERT INTO $wpdb->links (link_url, link_name, link_category, link_rss, link_notes) VALUES ('http://wordpress.org/support/', 'Support Forum', 0, '', '');");
82         $wpdb->query( "INSERT INTO $wpdb->term_relationships (`object_id`, `term_taxonomy_id`) VALUES (4, 2)" );
83
84         $wpdb->query("INSERT INTO $wpdb->links (link_url, link_name, link_category, link_rss, link_notes) VALUES ('http://wordpress.org/extend/plugins/', 'Plugins', 0, '', '');");
85         $wpdb->query( "INSERT INTO $wpdb->term_relationships (`object_id`, `term_taxonomy_id`) VALUES (5, 2)" );
86
87         $wpdb->query("INSERT INTO $wpdb->links (link_url, link_name, link_category, link_rss, link_notes) VALUES ('http://wordpress.org/extend/themes/', 'Themes', 0, '', '');");
88         $wpdb->query( "INSERT INTO $wpdb->term_relationships (`object_id`, `term_taxonomy_id`) VALUES (6, 2)" );
89
90         $wpdb->query("INSERT INTO $wpdb->links (link_url, link_name, link_category, link_rss, link_notes) VALUES ('http://planet.wordpress.org/', 'WordPress Planet', 0, '', '');");
91         $wpdb->query( "INSERT INTO $wpdb->term_relationships (`object_id`, `term_taxonomy_id`) VALUES (7, 2)" );
92
93         // First post
94         $now = date('Y-m-d H:i:s');
95         $now_gmt = gmdate('Y-m-d H:i:s');
96         $first_post_guid = get_option('home') . '/?p=1';
97         $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', '', '', '')");
98         $wpdb->query( "INSERT INTO $wpdb->term_relationships (`object_id`, `term_taxonomy_id`) VALUES (1, 1)" );
99
100         // Default comment
101         $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.'))."')");
102
103         // First Page
104         $first_post_guid = get_option('home') . '/?page_id=2';
105         $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', '', '', '')");
106 }
107 endif;
108
109 if ( !function_exists('wp_new_blog_notification') ) :
110 function wp_new_blog_notification($blog_title, $blog_url, $user_id, $password) {
111         $user = new WP_User($user_id);
112         $email = $user->user_email;
113         $name = $user->user_login;
114         $message_headers = 'From: "' . $blog_title . '" <wordpress@' . $_SERVER['SERVER_NAME'] . '>';
115         $message = sprintf(__("Your new WordPress blog has been successfully set up at:
116
117 %1\$s
118
119 You can log in to the administrator account with the following information:
120
121 Username: %2\$s
122 Password: %3\$s
123
124 We hope you enjoy your new blog. Thanks!
125
126 --The WordPress Team
127 http://wordpress.org/
128 "), $blog_url, $name, $password);
129
130         @wp_mail($email, __('New WordPress Blog'), $message, $message_headers);
131 }
132 endif;
133
134 if ( !function_exists('wp_upgrade') ) :
135 function wp_upgrade() {
136         global $wp_current_db_version, $wp_db_version;
137
138         $wp_current_db_version = __get_option('db_version');
139
140         // We are up-to-date.  Nothing to do.
141         if ( $wp_db_version == $wp_current_db_version )
142                 return;
143
144         wp_check_mysql_version();
145         wp_cache_flush();
146         make_db_current_silent();
147         upgrade_all();
148         wp_cache_flush();
149 }
150 endif;
151
152 // Functions to be called in install and upgrade scripts
153 function upgrade_all() {
154         global $wp_current_db_version, $wp_db_version, $wp_rewrite;
155         $wp_current_db_version = __get_option('db_version');
156
157         // We are up-to-date.  Nothing to do.
158         if ( $wp_db_version == $wp_current_db_version )
159                 return;
160
161         // If the version is not set in the DB, try to guess the version.
162         if ( empty($wp_current_db_version) ) {
163                 $wp_current_db_version = 0;
164
165                 // If the template option exists, we have 1.5.
166                 $template = __get_option('template');
167                 if ( !empty($template) )
168                         $wp_current_db_version = 2541;
169         }
170
171         if ( $wp_current_db_version < 6039 )
172                 upgrade_230_options_table();
173
174         populate_options();
175
176         if ( $wp_current_db_version < 2541 ) {
177                 upgrade_100();
178                 upgrade_101();
179                 upgrade_110();
180                 upgrade_130();
181         }
182
183         if ( $wp_current_db_version < 3308 )
184                 upgrade_160();
185
186         if ( $wp_current_db_version < 4772 )
187                 upgrade_210();
188
189         if ( $wp_current_db_version < 4351 )
190                 upgrade_old_slugs();
191
192         if ( $wp_current_db_version < 5539 )
193                 upgrade_230();
194
195         if ( $wp_current_db_version < 6124 )
196                 upgrade_230_old_tables();
197
198         if ( $wp_current_db_version < 7499 )
199                 upgrade_250();
200
201         if ( $wp_current_db_version < 7796 )
202                 upgrade_251();
203
204         if ( $wp_current_db_version < 7935 )
205                 upgrade_252();
206
207         if ( $wp_current_db_version < 8201 )
208                 upgrade_260();
209
210         maybe_disable_automattic_widgets();
211
212         $wp_rewrite->flush_rules();
213
214         update_option('db_version', $wp_db_version);
215 }
216
217 function upgrade_100() {
218         global $wpdb;
219
220         // Get the title and ID of every post, post_name to check if it already has a value
221         $posts = $wpdb->get_results("SELECT ID, post_title, post_name FROM $wpdb->posts WHERE post_name = ''");
222         if ($posts) {
223                 foreach($posts as $post) {
224                         if ('' == $post->post_name) {
225                                 $newtitle = sanitize_title($post->post_title);
226                                 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_name = %s WHERE ID = %d", $newtitle, $post->ID) );
227                         }
228                 }
229         }
230
231         $categories = $wpdb->get_results("SELECT cat_ID, cat_name, category_nicename FROM $wpdb->categories");
232         foreach ($categories as $category) {
233                 if ('' == $category->category_nicename) {
234                         $newtitle = sanitize_title($category->cat_name);
235                         $wpdb->query( $wpdb->prepare("UPDATE $wpdb->categories SET category_nicename = %s WHERE cat_ID = %d", $newtitle, $category->cat_ID) );
236                 }
237         }
238
239
240         $wpdb->query("UPDATE $wpdb->options SET option_value = REPLACE(option_value, 'wp-links/links-images/', 'wp-images/links/')
241         WHERE option_name LIKE 'links_rating_image%'
242         AND option_value LIKE 'wp-links/links-images/%'");
243
244         $done_ids = $wpdb->get_results("SELECT DISTINCT post_id FROM $wpdb->post2cat");
245         if ($done_ids) :
246                 foreach ($done_ids as $done_id) :
247                         $done_posts[] = $done_id->post_id;
248                 endforeach;
249                 $catwhere = ' AND ID NOT IN (' . implode(',', $done_posts) . ')';
250         else:
251                 $catwhere = '';
252         endif;
253
254         $allposts = $wpdb->get_results("SELECT ID, post_category FROM $wpdb->posts WHERE post_category != '0' $catwhere");
255         if ($allposts) :
256                 foreach ($allposts as $post) {
257                         // Check to see if it's already been imported
258                         $cat = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->post2cat WHERE post_id = %d AND category_id = %d", $post->ID, $post->post_category) );
259                         if (!$cat && 0 != $post->post_category) { // If there's no result
260                                 $wpdb->query( $wpdb->prepare("INSERT INTO $wpdb->post2cat
261                                         (post_id, category_id)
262                                         VALUES (%s, %s)
263                                         ", $post->ID, $post->post_category) );
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( $wpdb->prepare("UPDATE $wpdb->users SET user_nicename = %s WHERE ID = %d", $newname, $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( $wpdb->prepare("SELECT option_id FROM $wpdb->options WHERE option_name = %s LIMIT %d", $option->option_name, $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                         $wpdb->query( $wpdb->prepare("UPDATE $wpdb->users SET display_name = %s WHERE ID = %d", $id, $user->ID) );
452                 endif;
453
454                 // FIXME: RESET_CAPS is temporary code to reset roles and caps if flag is set.
455                 $caps = get_usermeta( $user->ID, $wpdb->prefix . 'capabilities');
456                 if ( empty($caps) || defined('RESET_CAPS') ) {
457                         $level = get_usermeta($user->ID, $wpdb->prefix . 'user_level');
458                         $role = translate_level_to_role($level);
459                         update_usermeta( $user->ID, $wpdb->prefix . 'capabilities', array($role => true) );
460                 }
461
462         endforeach;
463         $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' );
464         $wpdb->hide_errors();
465         foreach ( $old_user_fields as $old )
466                 $wpdb->query("ALTER TABLE $wpdb->users DROP $old");
467         $wpdb->show_errors();
468
469         // populate comment_count field of posts table
470         $comments = $wpdb->get_results( "SELECT comment_post_ID, COUNT(*) as c FROM $wpdb->comments WHERE comment_approved = '1' GROUP BY comment_post_ID" );
471         if( is_array( $comments ) ) {
472                 foreach ($comments as $comment) {
473                         $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET comment_count = %d WHERE ID = %d", $comment->c, $comment->comment_post_ID) );
474                 }
475         }
476
477         // Some alpha versions used a post status of object instead of attachment and put
478         // the mime type in post_type instead of post_mime_type.
479         if ( $wp_current_db_version > 2541 && $wp_current_db_version <= 3091 ) {
480                 $objects = $wpdb->get_results("SELECT ID, post_type FROM $wpdb->posts WHERE post_status = 'object'");
481                 foreach ($objects as $object) {
482                         $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_status = 'attachment',
483                         post_mime_type = %s,
484                         post_type = ''
485                         WHERE ID = %d", $object->post_type, $object->ID) );
486
487                         $meta = get_post_meta($object->ID, 'imagedata', true);
488                         if ( ! empty($meta['file']) )
489                                 update_attached_file( $object->ID, $meta['file'] );
490                 }
491         }
492 }
493
494 function upgrade_210() {
495         global $wpdb, $wp_current_db_version;
496
497         if ( $wp_current_db_version < 3506 ) {
498                 // Update status and type.
499                 $posts = $wpdb->get_results("SELECT ID, post_status FROM $wpdb->posts");
500
501                 if ( ! empty($posts) ) foreach ($posts as $post) {
502                         $status = $post->post_status;
503                         $type = 'post';
504
505                         if ( 'static' == $status ) {
506                                 $status = 'publish';
507                                 $type = 'page';
508                         } else if ( 'attachment' == $status ) {
509                                 $status = 'inherit';
510                                 $type = 'attachment';
511                         }
512
513                         $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_status = %s, post_type = %s WHERE ID = %d", $status, $type, $post->ID) );
514                 }
515         }
516
517         if ( $wp_current_db_version < 3845 ) {
518                 populate_roles_210();
519         }
520
521         if ( $wp_current_db_version < 3531 ) {
522                 // Give future posts a post_status of future.
523                 $now = gmdate('Y-m-d H:i:59');
524                 $wpdb->query ("UPDATE $wpdb->posts SET post_status = 'future' WHERE post_status = 'publish' AND post_date_gmt > '$now'");
525
526                 $posts = $wpdb->get_results("SELECT ID, post_date FROM $wpdb->posts WHERE post_status ='future'");
527                 if ( !empty($posts) )
528                         foreach ( $posts as $post )
529                                 wp_schedule_single_event(mysql2date('U', $post->post_date), 'publish_future_post', array($post->ID));
530         }
531 }
532
533 function upgrade_230() {
534         global $wp_current_db_version, $wpdb;
535
536         if ( $wp_current_db_version < 5200 ) {
537                 populate_roles_230();
538         }
539
540         // Convert categories to terms.
541         $tt_ids = array();
542         $have_tags = false;
543         $categories = $wpdb->get_results("SELECT * FROM $wpdb->categories ORDER BY cat_ID");
544         foreach ($categories as $category) {
545                 $term_id = (int) $category->cat_ID;
546                 $name = $category->cat_name;
547                 $description = $category->category_description;
548                 $slug = $category->category_nicename;
549                 $parent = $category->category_parent;
550                 $term_group = 0;
551
552                 // Associate terms with the same slug in a term group and make slugs unique.
553                 if ( $exists = $wpdb->get_results( $wpdb->prepare("SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $slug) ) ) {
554                         $term_group = $exists[0]->term_group;
555                         $id = $exists[0]->term_id;
556                         $num = 2;
557                         do {
558                                 $alt_slug = $slug . "-$num";
559                                 $num++;
560                                 $slug_check = $wpdb->get_var( $wpdb->prepare("SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug) );
561                         } while ( $slug_check );
562
563                         $slug = $alt_slug;
564
565                         if ( empty( $term_group ) ) {
566                                 $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms GROUP BY term_group") + 1;
567                                 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->terms SET term_group = %d WHERE term_id = %d", $term_group, $id) );
568                         }
569                 }
570
571                 $wpdb->query( $wpdb->prepare("INSERT INTO $wpdb->terms (term_id, name, slug, term_group) VALUES 
572                 (%d, %s, %s, %d)", $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( $wpdb->prepare("INSERT INTO $wpdb->term_taxonomy (term_id, taxonomy, description, parent, count) VALUES ( %d, %s, %s, %d, %d)", $term_id, $taxonomy, $description, $parent, $count) );
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( $wpdb->prepare("INSERT INTO $wpdb->term_taxonomy (term_id, taxonomy, description, parent, count) VALUES ( %d, %s, %s, %d, %d)", $term_id, $taxonomy, $description, $parent, $count) );
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( $wpdb->prepare("INSERT INTO $wpdb->term_taxonomy (term_id, taxonomy, description, parent, count) VALUES ( %d, %s, %s, %d, %d)", $term_id, $taxonomy, $description, $parent, $count) );
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( $wpdb->prepare("INSERT INTO $wpdb->term_taxonomy (term_id, taxonomy, description, parent, count) VALUES ( %d, %s, %s, %d, %d)", $term_id, $taxonomy, $description, $parent, $count) );
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( $wpdb->prepare("INSERT INTO $wpdb->term_relationships (object_id, term_taxonomy_id) VALUES ( %d, %d)", $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( $wpdb->prepare("SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $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( $wpdb->prepare("INSERT INTO $wpdb->terms (name, slug, term_group) VALUES (%s, %s, %d)", $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( $wpdb->prepare("INSERT INTO $wpdb->term_taxonomy (term_id, taxonomy, description, parent, count) VALUES (%d, 'link_category', '', '0', '0')", $term_id) );
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( $wpdb->prepare("INSERT INTO $wpdb->term_relationships (object_id, term_taxonomy_id) VALUES ( %d, %d)", $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( $wpdb->prepare("INSERT INTO $wpdb->term_relationships (object_id, term_taxonomy_id) VALUES ( %d, %d)", $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( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->term_relationships, $wpdb->posts WHERE $wpdb->posts.ID = $wpdb->term_relationships.object_id AND post_status = 'publish' AND post_type = 'post' AND term_taxonomy_id = %d", $term->term_taxonomy_id) );
697                 else
698                         $count = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term->term_taxonomy_id) );
699                 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->term_taxonomy SET count = %d WHERE term_taxonomy_id = %d", $count, $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 function upgrade_252() {
743         global $wpdb;
744
745         $wpdb->query("UPDATE $wpdb->users SET user_activation_key = ''");
746 }
747
748 function upgrade_260() {
749         if ( $wp_current_db_version < 8000 )
750                 populate_roles_260();
751
752         if ( $wp_current_db_version < 8201 ) {
753                 update_option('enable_app', 1);
754                 update_option('enable_xmlrpc', 1);
755         }
756 }
757
758 // The functions we use to actually do stuff
759
760 // General
761 function maybe_create_table($table_name, $create_ddl) {
762         global $wpdb;
763         foreach ($wpdb->get_col("SHOW TABLES",0) as $table ) {
764                 if ($table == $table_name) {
765                         return true;
766                 }
767         }
768         //didn't find it try to create it.
769         $q = $wpdb->query($create_ddl);
770         // we cannot directly tell that whether this succeeded!
771         foreach ($wpdb->get_col("SHOW TABLES",0) as $table ) {
772                 if ($table == $table_name) {
773                         return true;
774                 }
775         }
776         return false;
777 }
778
779 function drop_index($table, $index) {
780         global $wpdb;
781         $wpdb->hide_errors();
782         $wpdb->query("ALTER TABLE `$table` DROP INDEX `$index`");
783         // Now we need to take out all the extra ones we may have created
784         for ($i = 0; $i < 25; $i++) {
785                 $wpdb->query("ALTER TABLE `$table` DROP INDEX `{$index}_$i`");
786         }
787         $wpdb->show_errors();
788         return true;
789 }
790
791 function add_clean_index($table, $index) {
792         global $wpdb;
793         drop_index($table, $index);
794         $wpdb->query("ALTER TABLE `$table` ADD INDEX ( `$index` )");
795         return true;
796 }
797
798 /**
799  ** maybe_add_column()
800  ** Add column to db table if it doesn't exist.
801  ** Returns:  true if already exists or on successful completion
802  **           false on error
803  */
804 function maybe_add_column($table_name, $column_name, $create_ddl) {
805         global $wpdb, $debug;
806         foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) {
807                 if ($debug) echo("checking $column == $column_name<br />");
808                 if ($column == $column_name) {
809                         return true;
810                 }
811         }
812         //didn't find it try to create it.
813         $q = $wpdb->query($create_ddl);
814         // we cannot directly tell that whether this succeeded!
815         foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) {
816                 if ($column == $column_name) {
817                         return true;
818                 }
819         }
820         return false;
821 }
822
823
824 // get_alloptions as it was for 1.2.
825 function get_alloptions_110() {
826         global $wpdb;
827         if ($options = $wpdb->get_results("SELECT option_name, option_value FROM $wpdb->options")) {
828                 foreach ($options as $option) {
829                         // "When trying to design a foolproof system,
830                         //  never underestimate the ingenuity of the fools :)" -- Dougal
831                         if ('siteurl' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value);
832                         if ('home' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value);
833                         if ('category_base' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value);
834                         $all_options->{$option->option_name} = stripslashes($option->option_value);
835                 }
836         }
837         return $all_options;
838 }
839
840 // Version of get_option that is private to install/upgrade.
841 function __get_option($setting) {
842         global $wpdb;
843
844         if ( $setting == 'home' && defined( 'WP_HOME' ) ) {
845                 return preg_replace( '|/+$|', '', constant( 'WP_HOME' ) );
846         }
847
848         if ( $setting == 'siteurl' && defined( 'WP_SITEURL' ) ) {
849                 return preg_replace( '|/+$|', '', constant( 'WP_SITEURL' ) );
850         }
851
852         $option = $wpdb->get_var( $wpdb->prepare("SELECT option_value FROM $wpdb->options WHERE option_name = %s", $setting) );
853
854         if ( 'home' == $setting && '' == $option )
855                 return __get_option('siteurl');
856
857         if ( 'siteurl' == $setting || 'home' == $setting || 'category_base' == $setting )
858                 $option = preg_replace('|/+$|', '', $option);
859
860         @ $kellogs = unserialize($option);
861         if ($kellogs !== FALSE)
862                 return $kellogs;
863         else
864                 return $option;
865 }
866
867 function deslash($content) {
868         // Note: \\\ inside a regex denotes a single backslash.
869
870         // Replace one or more backslashes followed by a single quote with
871         // a single quote.
872         $content = preg_replace("/\\\+'/", "'", $content);
873
874         // Replace one or more backslashes followed by a double quote with
875         // a double quote.
876         $content = preg_replace('/\\\+"/', '"', $content);
877
878         // Replace one or more backslashes with one backslash.
879         $content = preg_replace("/\\\+/", "\\", $content);
880
881         return $content;
882 }
883
884 function dbDelta($queries, $execute = true) {
885         global $wpdb;
886
887         // Separate individual queries into an array
888         if( !is_array($queries) ) {
889                 $queries = explode( ';', $queries );
890                 if('' == $queries[count($queries) - 1]) array_pop($queries);
891         }
892
893         $cqueries = array(); // Creation Queries
894         $iqueries = array(); // Insertion Queries
895         $for_update = array();
896
897         // Create a tablename index for an array ($cqueries) of queries
898         foreach($queries as $qry) {
899                 if(preg_match("|CREATE TABLE ([^ ]*)|", $qry, $matches)) {
900                         $cqueries[strtolower($matches[1])] = $qry;
901                         $for_update[$matches[1]] = 'Created table '.$matches[1];
902                 }
903                 else if(preg_match("|CREATE DATABASE ([^ ]*)|", $qry, $matches)) {
904                         array_unshift($cqueries, $qry);
905                 }
906                 else if(preg_match("|INSERT INTO ([^ ]*)|", $qry, $matches)) {
907                         $iqueries[] = $qry;
908                 }
909                 else if(preg_match("|UPDATE ([^ ]*)|", $qry, $matches)) {
910                         $iqueries[] = $qry;
911                 }
912                 else {
913                         // Unrecognized query type
914                 }
915         }
916
917         // Check to see which tables and fields exist
918         if($tables = $wpdb->get_col('SHOW TABLES;')) {
919                 // For every table in the database
920                 foreach($tables as $table) {
921                         // If a table query exists for the database table...
922                         if( array_key_exists(strtolower($table), $cqueries) ) {
923                                 // Clear the field and index arrays
924                                 unset($cfields);
925                                 unset($indices);
926                                 // Get all of the field names in the query from between the parens
927                                 preg_match("|\((.*)\)|ms", $cqueries[strtolower($table)], $match2);
928                                 $qryline = trim($match2[1]);
929
930                                 // Separate field lines into an array
931                                 $flds = explode("\n", $qryline);
932
933                                 //echo "<hr/><pre>\n".print_r(strtolower($table), true).":\n".print_r($cqueries, true)."</pre><hr/>";
934
935                                 // For every field line specified in the query
936                                 foreach($flds as $fld) {
937                                         // Extract the field name
938                                         preg_match("|^([^ ]*)|", trim($fld), $fvals);
939                                         $fieldname = $fvals[1];
940
941                                         // Verify the found field name
942                                         $validfield = true;
943                                         switch(strtolower($fieldname))
944                                         {
945                                         case '':
946                                         case 'primary':
947                                         case 'index':
948                                         case 'fulltext':
949                                         case 'unique':
950                                         case 'key':
951                                                 $validfield = false;
952                                                 $indices[] = trim(trim($fld), ", \n");
953                                                 break;
954                                         }
955                                         $fld = trim($fld);
956
957                                         // If it's a valid field, add it to the field array
958                                         if($validfield) {
959                                                 $cfields[strtolower($fieldname)] = trim($fld, ", \n");
960                                         }
961                                 }
962
963                                 // Fetch the table column structure from the database
964                                 $tablefields = $wpdb->get_results("DESCRIBE {$table};");
965
966                                 // For every field in the table
967                                 foreach($tablefields as $tablefield) {
968                                         // If the table field exists in the field array...
969                                         if(array_key_exists(strtolower($tablefield->Field), $cfields)) {
970                                                 // Get the field type from the query
971                                                 preg_match("|".$tablefield->Field." ([^ ]*( unsigned)?)|i", $cfields[strtolower($tablefield->Field)], $matches);
972                                                 $fieldtype = $matches[1];
973
974                                                 // Is actual field type different from the field type in query?
975                                                 if($tablefield->Type != $fieldtype) {
976                                                         // Add a query to change the column type
977                                                         $cqueries[] = "ALTER TABLE {$table} CHANGE COLUMN {$tablefield->Field} " . $cfields[strtolower($tablefield->Field)];
978                                                         $for_update[$table.'.'.$tablefield->Field] = "Changed type of {$table}.{$tablefield->Field} from {$tablefield->Type} to {$fieldtype}";
979                                                 }
980
981                                                 // Get the default value from the array
982                                                         //echo "{$cfields[strtolower($tablefield->Field)]}<br>";
983                                                 if(preg_match("| DEFAULT '(.*)'|i", $cfields[strtolower($tablefield->Field)], $matches)) {
984                                                         $default_value = $matches[1];
985                                                         if($tablefield->Default != $default_value)
986                                                         {
987                                                                 // Add a query to change the column's default value
988                                                                 $cqueries[] = "ALTER TABLE {$table} ALTER COLUMN {$tablefield->Field} SET DEFAULT '{$default_value}'";
989                                                                 $for_update[$table.'.'.$tablefield->Field] = "Changed default value of {$table}.{$tablefield->Field} from {$tablefield->Default} to {$default_value}";
990                                                         }
991                                                 }
992
993                                                 // Remove the field from the array (so it's not added)
994                                                 unset($cfields[strtolower($tablefield->Field)]);
995                                         }
996                                         else {
997                                                 // This field exists in the table, but not in the creation queries?
998                                         }
999                                 }
1000
1001                                 // For every remaining field specified for the table
1002                                 foreach($cfields as $fieldname => $fielddef) {
1003                                         // Push a query line into $cqueries that adds the field to that table
1004                                         $cqueries[] = "ALTER TABLE {$table} ADD COLUMN $fielddef";
1005                                         $for_update[$table.'.'.$fieldname] = 'Added column '.$table.'.'.$fieldname;
1006                                 }
1007
1008                                 // Index stuff goes here
1009                                 // Fetch the table index structure from the database
1010                                 $tableindices = $wpdb->get_results("SHOW INDEX FROM {$table};");
1011
1012                                 if($tableindices) {
1013                                         // Clear the index array
1014                                         unset($index_ary);
1015
1016                                         // For every index in the table
1017                                         foreach($tableindices as $tableindex) {
1018                                                 // Add the index to the index data array
1019                                                 $keyname = $tableindex->Key_name;
1020                                                 $index_ary[$keyname]['columns'][] = array('fieldname' => $tableindex->Column_name, 'subpart' => $tableindex->Sub_part);
1021                                                 $index_ary[$keyname]['unique'] = ($tableindex->Non_unique == 0)?true:false;
1022                                         }
1023
1024                                         // For each actual index in the index array
1025                                         foreach($index_ary as $index_name => $index_data) {
1026                                                 // Build a create string to compare to the query
1027                                                 $index_string = '';
1028                                                 if($index_name == 'PRIMARY') {
1029                                                         $index_string .= 'PRIMARY ';
1030                                                 }
1031                                                 else if($index_data['unique']) {
1032                                                         $index_string .= 'UNIQUE ';
1033                                                 }
1034                                                 $index_string .= 'KEY ';
1035                                                 if($index_name != 'PRIMARY') {
1036                                                         $index_string .= $index_name;
1037                                                 }
1038                                                 $index_columns = '';
1039                                                 // For each column in the index
1040                                                 foreach($index_data['columns'] as $column_data) {
1041                                                         if($index_columns != '') $index_columns .= ',';
1042                                                         // Add the field to the column list string
1043                                                         $index_columns .= $column_data['fieldname'];
1044                                                         if($column_data['subpart'] != '') {
1045                                                                 $index_columns .= '('.$column_data['subpart'].')';
1046                                                         }
1047                                                 }
1048                                                 // Add the column list to the index create string
1049                                                 $index_string .= ' ('.$index_columns.')';
1050                                                 if(!(($aindex = array_search($index_string, $indices)) === false)) {
1051                                                         unset($indices[$aindex]);
1052                                                         //echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">{$table}:<br />Found index:".$index_string."</pre>\n";
1053                                                 }
1054                                                 //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";
1055                                         }
1056                                 }
1057
1058                                 // For every remaining index specified for the table
1059                                 foreach ( (array) $indices as $index ) {
1060                                         // Push a query line into $cqueries that adds the index to that table
1061                                         $cqueries[] = "ALTER TABLE {$table} ADD $index";
1062                                         $for_update[$table.'.'.$fieldname] = 'Added index '.$table.' '.$index;
1063                                 }
1064
1065                                 // Remove the original table creation query from processing
1066                                 unset($cqueries[strtolower($table)]);
1067                                 unset($for_update[strtolower($table)]);
1068                         } else {
1069                                 // This table exists in the database, but not in the creation queries?
1070                         }
1071                 }
1072         }
1073
1074         $allqueries = array_merge($cqueries, $iqueries);
1075         if($execute) {
1076                 foreach($allqueries as $query) {
1077                         //echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">".print_r($query, true)."</pre>\n";
1078                         $wpdb->query($query);
1079                 }
1080         }
1081
1082         return $for_update;
1083 }
1084
1085 function make_db_current() {
1086         global $wp_queries;
1087
1088         $alterations = dbDelta($wp_queries);
1089         echo "<ol>\n";
1090         foreach($alterations as $alteration) echo "<li>$alteration</li>\n";
1091         echo "</ol>\n";
1092 }
1093
1094 function make_db_current_silent() {
1095         global $wp_queries;
1096
1097         $alterations = dbDelta($wp_queries);
1098 }
1099
1100 function make_site_theme_from_oldschool($theme_name, $template) {
1101         $home_path = get_home_path();
1102         $site_dir = WP_CONTENT_DIR . "/themes/$template";
1103
1104         if (! file_exists("$home_path/index.php"))
1105                 return false;
1106
1107         // Copy files from the old locations to the site theme.
1108         // TODO: This does not copy arbitarary include dependencies.  Only the
1109         // standard WP files are copied.
1110         $files = array('index.php' => 'index.php', 'wp-layout.css' => 'style.css', 'wp-comments.php' => 'comments.php', 'wp-comments-popup.php' => 'comments-popup.php');
1111
1112         foreach ($files as $oldfile => $newfile) {
1113                 if ($oldfile == 'index.php')
1114                         $oldpath = $home_path;
1115                 else
1116                         $oldpath = ABSPATH;
1117
1118                 if ($oldfile == 'index.php') { // Check to make sure it's not a new index
1119                         $index = implode('', file("$oldpath/$oldfile"));
1120                         if (strpos($index, 'WP_USE_THEMES') !== false) {
1121                                 if (! @copy(WP_CONTENT_DIR . '/themes/default/index.php', "$site_dir/$newfile"))
1122                                         return false;
1123                                 continue; // Don't copy anything
1124                                 }
1125                 }
1126
1127                 if (! @copy("$oldpath/$oldfile", "$site_dir/$newfile"))
1128                         return false;
1129
1130                 chmod("$site_dir/$newfile", 0777);
1131
1132                 // Update the blog header include in each file.
1133                 $lines = explode("\n", implode('', file("$site_dir/$newfile")));
1134                 if ($lines) {
1135                         $f = fopen("$site_dir/$newfile", 'w');
1136
1137                         foreach ($lines as $line) {
1138                                 if (preg_match('/require.*wp-blog-header/', $line))
1139                                         $line = '//' . $line;
1140
1141                                 // Update stylesheet references.
1142                                 $line = str_replace("<?php echo __get_option('siteurl'); ?>/wp-layout.css", "<?php bloginfo('stylesheet_url'); ?>", $line);
1143
1144                                 // Update comments template inclusion.
1145                                 $line = str_replace("<?php include(ABSPATH . 'wp-comments.php'); ?>", "<?php comments_template(); ?>", $line);
1146
1147                                 fwrite($f, "{$line}\n");
1148                         }
1149                         fclose($f);
1150                 }
1151         }
1152
1153         // Add a theme header.
1154         $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";
1155
1156         $stylelines = file_get_contents("$site_dir/style.css");
1157         if ($stylelines) {
1158                 $f = fopen("$site_dir/style.css", 'w');
1159
1160                 fwrite($f, $header);
1161                 fwrite($f, $stylelines);
1162                 fclose($f);
1163         }
1164
1165         return true;
1166 }
1167
1168 function make_site_theme_from_default($theme_name, $template) {
1169         $site_dir = WP_CONTENT_DIR . "/themes/$template";
1170         $default_dir = WP_CONTENT_DIR . '/themes/default';
1171
1172         // Copy files from the default theme to the site theme.
1173         //$files = array('index.php', 'comments.php', 'comments-popup.php', 'footer.php', 'header.php', 'sidebar.php', 'style.css');
1174
1175         $theme_dir = @ opendir("$default_dir");
1176         if ($theme_dir) {
1177                 while(($theme_file = readdir( $theme_dir )) !== false) {
1178                         if (is_dir("$default_dir/$theme_file"))
1179                                 continue;
1180                         if (! @copy("$default_dir/$theme_file", "$site_dir/$theme_file"))
1181                                 return;
1182                         chmod("$site_dir/$theme_file", 0777);
1183                 }
1184         }
1185         @closedir($theme_dir);
1186
1187         // Rewrite the theme header.
1188         $stylelines = explode("\n", implode('', file("$site_dir/style.css")));
1189         if ($stylelines) {
1190                 $f = fopen("$site_dir/style.css", 'w');
1191
1192                 foreach ($stylelines as $line) {
1193                         if (strpos($line, 'Theme Name:') !== false) $line = 'Theme Name: ' . $theme_name;
1194                         elseif (strpos($line, 'Theme URI:') !== false) $line = 'Theme URI: ' . __get_option('url');
1195                         elseif (strpos($line, 'Description:') !== false) $line = 'Description: Your theme.';
1196                         elseif (strpos($line, 'Version:') !== false) $line = 'Version: 1';
1197                         elseif (strpos($line, 'Author:') !== false) $line = 'Author: You';
1198                         fwrite($f, $line . "\n");
1199                 }
1200                 fclose($f);
1201         }
1202
1203         // Copy the images.
1204         umask(0);
1205         if (! mkdir("$site_dir/images", 0777)) {
1206                 return false;
1207         }
1208
1209         $images_dir = @ opendir("$default_dir/images");
1210         if ($images_dir) {
1211                 while(($image = readdir($images_dir)) !== false) {
1212                         if (is_dir("$default_dir/images/$image"))
1213                                 continue;
1214                         if (! @copy("$default_dir/images/$image", "$site_dir/images/$image"))
1215                                 return;
1216                         chmod("$site_dir/images/$image", 0777);
1217                 }
1218         }
1219         @closedir($images_dir);
1220 }
1221
1222 // Create a site theme from the default theme.
1223 function make_site_theme() {
1224         // Name the theme after the blog.
1225         $theme_name = __get_option('blogname');
1226         $template = sanitize_title($theme_name);
1227         $site_dir = WP_CONTENT_DIR . "/themes/$template";
1228
1229         // If the theme already exists, nothing to do.
1230         if ( is_dir($site_dir)) {
1231                 return false;
1232         }
1233
1234         // We must be able to write to the themes dir.
1235         if (! is_writable(WP_CONTENT_DIR . "/themes")) {
1236                 return false;
1237         }
1238
1239         umask(0);
1240         if (! mkdir($site_dir, 0777)) {
1241                 return false;
1242         }
1243
1244         if (file_exists(ABSPATH . 'wp-layout.css')) {
1245                 if (! make_site_theme_from_oldschool($theme_name, $template)) {
1246                         // TODO:  rm -rf the site theme directory.
1247                         return false;
1248                 }
1249         } else {
1250                 if (! make_site_theme_from_default($theme_name, $template))
1251                         // TODO:  rm -rf the site theme directory.
1252                         return false;
1253         }
1254
1255         // Make the new site theme active.
1256         $current_template = __get_option('template');
1257         if ($current_template == 'default') {
1258                 update_option('template', $template);
1259                 update_option('stylesheet', $template);
1260         }
1261         return $template;
1262 }
1263
1264 function translate_level_to_role($level) {
1265         switch ($level) {
1266         case 10:
1267         case 9:
1268         case 8:
1269                 return 'administrator';
1270         case 7:
1271         case 6:
1272         case 5:
1273                 return 'editor';
1274         case 4:
1275         case 3:
1276         case 2:
1277                 return 'author';
1278         case 1:
1279                 return 'contributor';
1280         case 0:
1281                 return 'subscriber';
1282         }
1283 }
1284
1285 function wp_check_mysql_version() {
1286         global $wpdb;
1287         $result = $wpdb->check_database_version();
1288         if ( is_wp_error( $result ) )
1289                 die( $result->get_error_message() );
1290 }
1291
1292 function maybe_disable_automattic_widgets() {
1293         $plugins = __get_option( 'active_plugins' );
1294
1295         foreach ( (array) $plugins as $plugin ) {
1296                 if ( basename( $plugin ) == 'widgets.php' ) {
1297                         array_splice( $plugins, array_search( $plugin, $plugins ), 1 );
1298                         update_option( 'active_plugins', $plugins );
1299                         break;
1300                 }
1301         }
1302 }
1303
1304 ?>