3 * WordPress Upgrade API
5 * Most of the functions are pluggable and can be overwritten
8 * @subpackage Administration
11 /** Include user install customize script. */
12 if ( file_exists(WP_CONTENT_DIR . '/install.php') )
13 require (WP_CONTENT_DIR . '/install.php');
15 /** WordPress Administration API */
16 require_once(ABSPATH . 'wp-admin/includes/admin.php');
18 /** WordPress Schema API */
19 require_once(ABSPATH . 'wp-admin/includes/schema.php');
21 if ( !function_exists('wp_install') ) :
25 * {@internal Missing Long Description}}
29 * @param string $blog_title Blog title.
30 * @param string $user_name User's username.
31 * @param string $user_email User's email.
32 * @param bool $public Whether blog is public.
33 * @param null $deprecated Optional. Not used.
34 * @param string $user_password Optional. User's chosen password. Will default to a random password.
35 * @return array Array keys 'url', 'user_id', 'password', 'password_message'.
37 function wp_install( $blog_title, $user_name, $user_email, $public, $deprecated = '', $user_password = '' ) {
38 if ( !empty( $deprecated ) )
39 _deprecated_argument( __FUNCTION__, '2.6' );
41 wp_check_mysql_version();
43 make_db_current_silent();
47 update_option('blogname', $blog_title);
48 update_option('admin_email', $user_email);
49 update_option('blog_public', $public);
51 $guessurl = wp_guess_url();
53 update_option('siteurl', $guessurl);
55 // If not a public blog, don't ping.
57 update_option('default_pingback_flag', 0);
59 // Create default user. If the user already exists, the user tables are
60 // being shared among blogs. Just set the role in that case.
61 $user_id = username_exists($user_name);
62 $user_password = trim($user_password);
63 $email_password = false;
64 if ( !$user_id && empty($user_password) ) {
65 $user_password = wp_generate_password( 12, false );
66 $message = __('<strong><em>Note that password</em></strong> carefully! It is a <em>random</em> password that was generated just for you.');
67 $user_id = wp_create_user($user_name, $user_password, $user_email);
68 update_user_option($user_id, 'default_password_nag', true, true);
69 $email_password = true;
70 } else if ( !$user_id ) {
71 // Password has been provided
72 $message = '<em>'.__('Your chosen password.').'</em>';
73 $user_id = wp_create_user($user_name, $user_password, $user_email);
75 $message = __('User already exists. Password inherited.');
78 $user = new WP_User($user_id);
79 $user->set_role('administrator');
81 wp_install_defaults($user_id);
83 flush_rewrite_rules();
85 wp_new_blog_notification($blog_title, $guessurl, $user_id, ($email_password ? $user_password : __('The password you chose during the install.') ) );
89 return array('url' => $guessurl, 'user_id' => $user_id, 'password' => $user_password, 'password_message' => $message);
93 if ( !function_exists('wp_install_defaults') ) :
95 * {@internal Missing Short Description}}
97 * {@internal Missing Long Description}}
101 * @param int $user_id User ID.
103 function wp_install_defaults($user_id) {
104 global $wpdb, $wp_rewrite, $current_site, $table_prefix;
107 $cat_name = __('Uncategorized');
108 /* translators: Default category slug */
109 $cat_slug = sanitize_title(_x('Uncategorized', 'Default category slug'));
111 if ( global_terms_enabled() ) {
112 $cat_id = $wpdb->get_var( $wpdb->prepare( "SELECT cat_ID FROM {$wpdb->sitecategories} WHERE category_nicename = %s", $cat_slug ) );
113 if ( $cat_id == null ) {
114 $wpdb->insert( $wpdb->sitecategories, array('cat_ID' => 0, 'cat_name' => $cat_name, 'category_nicename' => $cat_slug, 'last_updated' => current_time('mysql', true)) );
115 $cat_id = $wpdb->insert_id;
117 update_option('default_category', $cat_id);
122 $wpdb->insert( $wpdb->terms, array('term_id' => $cat_id, 'name' => $cat_name, 'slug' => $cat_slug, 'term_group' => 0) );
123 $wpdb->insert( $wpdb->term_taxonomy, array('term_id' => $cat_id, 'taxonomy' => 'category', 'description' => '', 'parent' => 0, 'count' => 1));
124 $cat_tt_id = $wpdb->insert_id;
126 // Default link category
127 $cat_name = __('Blogroll');
128 /* translators: Default link category slug */
129 $cat_slug = sanitize_title(_x('Blogroll', 'Default link category slug'));
131 if ( global_terms_enabled() ) {
132 $blogroll_id = $wpdb->get_var( $wpdb->prepare( "SELECT cat_ID FROM {$wpdb->sitecategories} WHERE category_nicename = %s", $cat_slug ) );
133 if ( $blogroll_id == null ) {
134 $wpdb->insert( $wpdb->sitecategories, array('cat_ID' => 0, 'cat_name' => $cat_name, 'category_nicename' => $cat_slug, 'last_updated' => current_time('mysql', true)) );
135 $blogroll_id = $wpdb->insert_id;
137 update_option('default_link_category', $blogroll_id);
142 $wpdb->insert( $wpdb->terms, array('term_id' => $blogroll_id, 'name' => $cat_name, 'slug' => $cat_slug, 'term_group' => 0) );
143 $wpdb->insert( $wpdb->term_taxonomy, array('term_id' => $blogroll_id, 'taxonomy' => 'link_category', 'description' => '', 'parent' => 0, 'count' => 7));
144 $blogroll_tt_id = $wpdb->insert_id;
146 // Now drop in some default links
147 $default_links = array();
148 $default_links[] = array( 'link_url' => __( 'http://codex.wordpress.org/' ),
149 'link_name' => __( 'Documentation' ),
153 $default_links[] = array( 'link_url' => __( 'http://wordpress.org/news/' ),
154 'link_name' => __( 'WordPress Blog' ),
155 'link_rss' => __( 'http://wordpress.org/news/feed/' ),
158 $default_links[] = array( 'link_url' => __( 'http://wordpress.org/support/' ),
159 'link_name' => _x( 'Support Forums', 'default link' ),
163 $default_links[] = array( 'link_url' => 'http://wordpress.org/extend/plugins/',
164 'link_name' => _x( 'Plugins', 'Default link to wordpress.org/extend/plugins/' ),
168 $default_links[] = array( 'link_url' => 'http://wordpress.org/extend/themes/',
169 'link_name' => _x( 'Themes', 'Default link to wordpress.org/extend/themes/' ),
173 $default_links[] = array( 'link_url' => __( 'http://wordpress.org/support/forum/requests-and-feedback' ),
174 'link_name' => __( 'Feedback' ),
178 $default_links[] = array( 'link_url' => __( 'http://planet.wordpress.org/' ),
179 'link_name' => __( 'WordPress Planet' ),
183 foreach ( $default_links as $link ) {
184 $wpdb->insert( $wpdb->links, $link);
185 $wpdb->insert( $wpdb->term_relationships, array('term_taxonomy_id' => $blogroll_tt_id, 'object_id' => $wpdb->insert_id) );
189 $now = date('Y-m-d H:i:s');
190 $now_gmt = gmdate('Y-m-d H:i:s');
191 $first_post_guid = get_option('home') . '/?p=1';
193 if ( is_multisite() ) {
194 $first_post = get_site_option( 'first_post' );
196 if ( empty($first_post) )
197 $first_post = stripslashes( __( 'Welcome to <a href="SITE_URL">SITE_NAME</a>. This is your first post. Edit or delete it, then start blogging!' ) );
199 $first_post = str_replace( "SITE_URL", esc_url( network_home_url() ), $first_post );
200 $first_post = str_replace( "SITE_NAME", $current_site->site_name, $first_post );
202 $first_post = __('Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!');
205 $wpdb->insert( $wpdb->posts, array(
206 'post_author' => $user_id,
208 'post_date_gmt' => $now_gmt,
209 'post_content' => $first_post,
210 'post_excerpt' => '',
211 'post_title' => __('Hello world!'),
212 /* translators: Default post slug */
213 'post_name' => sanitize_title( _x('hello-world', 'Default post slug') ),
214 'post_modified' => $now,
215 'post_modified_gmt' => $now_gmt,
216 'guid' => $first_post_guid,
217 'comment_count' => 1,
220 'post_content_filtered' => ''
222 $wpdb->insert( $wpdb->term_relationships, array('term_taxonomy_id' => $cat_tt_id, 'object_id' => 1) );
225 $first_comment_author = __('Mr WordPress');
226 $first_comment_url = 'http://wordpress.org/';
227 $first_comment = __('Hi, this is a comment.<br />To delete a comment, just log in and view the post's comments. There you will have the option to edit or delete them.');
228 if ( is_multisite() ) {
229 $first_comment_author = get_site_option( 'first_comment_author', $first_comment_author );
230 $first_comment_url = get_site_option( 'first_comment_url', network_home_url() );
231 $first_comment = get_site_option( 'first_comment', $first_comment );
233 $wpdb->insert( $wpdb->comments, array(
234 'comment_post_ID' => 1,
235 'comment_author' => $first_comment_author,
236 'comment_author_email' => '',
237 'comment_author_url' => $first_comment_url,
238 'comment_date' => $now,
239 'comment_date_gmt' => $now_gmt,
240 'comment_content' => $first_comment
244 $first_page = sprintf( __( "This is an example page. It's different from a blog post because it will stay in one place and will show up in your site navigation (in most themes). Most people start with an About page that introduces them to potential site visitors. It might say something like this:
246 <blockquote>Hi there! I'm a bike messenger by day, aspiring actor by night, and this is my blog. I live in Los Angeles, have a great dog named Jack, and I like piña coladas. (And gettin' caught in the rain.)</blockquote>
248 ...or something like this:
250 <blockquote>The XYZ Doohickey Company was founded in 1971, and has been providing quality doohickies to the public ever since. Located in Gotham City, XYZ employs over 2,000 people and does all kinds of awesome things for the Gotham community.</blockquote>
252 As a new WordPress user, you should go to <a href=\"%s\">your dashboard</a> to delete this page and create new pages for your content. Have fun!" ), admin_url() );
253 if ( is_multisite() )
254 $first_page = get_site_option( 'first_page', $first_page );
255 $first_post_guid = get_option('home') . '/?page_id=2';
256 $wpdb->insert( $wpdb->posts, array(
257 'post_author' => $user_id,
259 'post_date_gmt' => $now_gmt,
260 'post_content' => $first_page,
261 'post_excerpt' => '',
262 'post_title' => __( 'Sample Page' ),
263 /* translators: Default page slug */
264 'post_name' => __( 'sample-page' ),
265 'post_modified' => $now,
266 'post_modified_gmt' => $now_gmt,
267 'guid' => $first_post_guid,
268 'post_type' => 'page',
271 'post_content_filtered' => ''
273 $wpdb->insert( $wpdb->postmeta, array( 'post_id' => 2, 'meta_key' => '_wp_page_template', 'meta_value' => 'default' ) );
275 // Set up default widgets for default theme.
276 update_option( 'widget_search', array ( 2 => array ( 'title' => '' ), '_multiwidget' => 1 ) );
277 update_option( 'widget_recent-posts', array ( 2 => array ( 'title' => '', 'number' => 5 ), '_multiwidget' => 1 ) );
278 update_option( 'widget_recent-comments', array ( 2 => array ( 'title' => '', 'number' => 5 ), '_multiwidget' => 1 ) );
279 update_option( 'widget_archives', array ( 2 => array ( 'title' => '', 'count' => 0, 'dropdown' => 0 ), '_multiwidget' => 1 ) );
280 update_option( 'widget_categories', array ( 2 => array ( 'title' => '', 'count' => 0, 'hierarchical' => 0, 'dropdown' => 0 ), '_multiwidget' => 1 ) );
281 update_option( 'widget_meta', array ( 2 => array ( 'title' => '' ), '_multiwidget' => 1 ) );
282 update_option( 'sidebars_widgets', array ( 'wp_inactive_widgets' => array ( ), 'sidebar-1' => array ( 0 => 'search-2', 1 => 'recent-posts-2', 2 => 'recent-comments-2', 3 => 'archives-2', 4 => 'categories-2', 5 => 'meta-2', ), 'sidebar-2' => array ( ), 'sidebar-3' => array ( ), 'sidebar-4' => array ( ), 'sidebar-5' => array ( ), 'array_version' => 3 ) );
284 if ( ! is_multisite() )
285 update_user_meta( $user_id, 'show_welcome_panel', 1 );
286 elseif ( ! is_super_admin( $user_id ) && ! metadata_exists( 'user', $user_id, 'show_welcome_panel' ) )
287 update_user_meta( $user_id, 'show_welcome_panel', 2 );
289 if ( is_multisite() ) {
290 // Flush rules to pick up the new page.
292 $wp_rewrite->flush_rules();
294 $user = new WP_User($user_id);
295 $wpdb->update( $wpdb->options, array('option_value' => $user->user_email), array('option_name' => 'admin_email') );
297 // Remove all perms except for the login user.
298 $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id != %d AND meta_key = %s", $user_id, $table_prefix.'user_level') );
299 $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id != %d AND meta_key = %s", $user_id, $table_prefix.'capabilities') );
301 // Delete any caps that snuck into the previously active blog. (Hardcoded to blog 1 for now.) TODO: Get previous_blog_id.
302 if ( !is_super_admin( $user_id ) && $user_id != 1 )
303 $wpdb->delete( $wpdb->usermeta, array( 'user_id' => $user_id , 'meta_key' => $wpdb->base_prefix.'1_capabilities' ) );
308 if ( !function_exists('wp_new_blog_notification') ) :
310 * {@internal Missing Short Description}}
312 * {@internal Missing Long Description}}
316 * @param string $blog_title Blog title.
317 * @param string $blog_url Blog url.
318 * @param int $user_id User ID.
319 * @param string $password User's Password.
321 function wp_new_blog_notification($blog_title, $blog_url, $user_id, $password) {
322 $user = new WP_User($user_id);
323 $email = $user->user_email;
324 $name = $user->user_login;
325 $message = sprintf(__("Your new WordPress site has been successfully set up at:
329 You can log in to the administrator account with the following information:
334 We hope you enjoy your new site. Thanks!
337 http://wordpress.org/
338 "), $blog_url, $name, $password);
340 @wp_mail($email, __('New WordPress Site'), $message);
344 if ( !function_exists('wp_upgrade') ) :
346 * Run WordPress Upgrade functions.
348 * {@internal Missing Long Description}}
354 function wp_upgrade() {
355 global $wp_current_db_version, $wp_db_version, $wpdb;
357 $wp_current_db_version = __get_option('db_version');
359 // We are up-to-date. Nothing to do.
360 if ( $wp_db_version == $wp_current_db_version )
363 if ( ! is_blog_installed() )
366 wp_check_mysql_version();
368 pre_schema_upgrade();
369 make_db_current_silent();
371 if ( is_multisite() && is_main_site() )
375 if ( is_multisite() ) {
376 if ( $wpdb->get_row( "SELECT blog_id FROM {$wpdb->blog_versions} WHERE blog_id = '{$wpdb->blogid}'" ) )
377 $wpdb->query( "UPDATE {$wpdb->blog_versions} SET db_version = '{$wp_db_version}' WHERE blog_id = '{$wpdb->blogid}'" );
379 $wpdb->query( "INSERT INTO {$wpdb->blog_versions} ( `blog_id` , `db_version` , `last_updated` ) VALUES ( '{$wpdb->blogid}', '{$wp_db_version}', NOW());" );
385 * Functions to be called in install and upgrade scripts.
387 * {@internal Missing Long Description}}
391 function upgrade_all() {
392 global $wp_current_db_version, $wp_db_version;
393 $wp_current_db_version = __get_option('db_version');
395 // We are up-to-date. Nothing to do.
396 if ( $wp_db_version == $wp_current_db_version )
399 // If the version is not set in the DB, try to guess the version.
400 if ( empty($wp_current_db_version) ) {
401 $wp_current_db_version = 0;
403 // If the template option exists, we have 1.5.
404 $template = __get_option('template');
405 if ( !empty($template) )
406 $wp_current_db_version = 2541;
409 if ( $wp_current_db_version < 6039 )
410 upgrade_230_options_table();
414 if ( $wp_current_db_version < 2541 ) {
421 if ( $wp_current_db_version < 3308 )
424 if ( $wp_current_db_version < 4772 )
427 if ( $wp_current_db_version < 4351 )
430 if ( $wp_current_db_version < 5539 )
433 if ( $wp_current_db_version < 6124 )
434 upgrade_230_old_tables();
436 if ( $wp_current_db_version < 7499 )
439 if ( $wp_current_db_version < 7935 )
442 if ( $wp_current_db_version < 8201 )
445 if ( $wp_current_db_version < 8989 )
448 if ( $wp_current_db_version < 10360 )
451 if ( $wp_current_db_version < 11958 )
454 if ( $wp_current_db_version < 15260 )
457 if ( $wp_current_db_version < 19389 )
460 if ( $wp_current_db_version < 20080 )
463 maybe_disable_automattic_widgets();
465 update_option( 'db_version', $wp_db_version );
466 update_option( 'db_upgraded', true );
470 * Execute changes made in WordPress 1.0.
474 function upgrade_100() {
477 // Get the title and ID of every post, post_name to check if it already has a value
478 $posts = $wpdb->get_results("SELECT ID, post_title, post_name FROM $wpdb->posts WHERE post_name = ''");
480 foreach($posts as $post) {
481 if ('' == $post->post_name) {
482 $newtitle = sanitize_title($post->post_title);
483 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_name = %s WHERE ID = %d", $newtitle, $post->ID) );
488 $categories = $wpdb->get_results("SELECT cat_ID, cat_name, category_nicename FROM $wpdb->categories");
489 foreach ($categories as $category) {
490 if ('' == $category->category_nicename) {
491 $newtitle = sanitize_title($category->cat_name);
492 $wpdb>update( $wpdb->categories, array('category_nicename' => $newtitle), array('cat_ID' => $category->cat_ID) );
496 $wpdb->query("UPDATE $wpdb->options SET option_value = REPLACE(option_value, 'wp-links/links-images/', 'wp-images/links/')
497 WHERE option_name LIKE 'links_rating_image%'
498 AND option_value LIKE 'wp-links/links-images/%'");
500 $done_ids = $wpdb->get_results("SELECT DISTINCT post_id FROM $wpdb->post2cat");
502 foreach ($done_ids as $done_id) :
503 $done_posts[] = $done_id->post_id;
505 $catwhere = ' AND ID NOT IN (' . implode(',', $done_posts) . ')';
510 $allposts = $wpdb->get_results("SELECT ID, post_category FROM $wpdb->posts WHERE post_category != '0' $catwhere");
512 foreach ($allposts as $post) {
513 // Check to see if it's already been imported
514 $cat = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->post2cat WHERE post_id = %d AND category_id = %d", $post->ID, $post->post_category) );
515 if (!$cat && 0 != $post->post_category) { // If there's no result
516 $wpdb->insert( $wpdb->post2cat, array('post_id' => $post->ID, 'category_id' => $post->post_category) );
523 * Execute changes made in WordPress 1.0.1.
527 function upgrade_101() {
530 // Clean up indices, add a few
531 add_clean_index($wpdb->posts, 'post_name');
532 add_clean_index($wpdb->posts, 'post_status');
533 add_clean_index($wpdb->categories, 'category_nicename');
534 add_clean_index($wpdb->comments, 'comment_approved');
535 add_clean_index($wpdb->comments, 'comment_post_ID');
536 add_clean_index($wpdb->links , 'link_category');
537 add_clean_index($wpdb->links , 'link_visible');
541 * Execute changes made in WordPress 1.2.
545 function upgrade_110() {
548 // Set user_nicename.
549 $users = $wpdb->get_results("SELECT ID, user_nickname, user_nicename FROM $wpdb->users");
550 foreach ($users as $user) {
551 if ('' == $user->user_nicename) {
552 $newname = sanitize_title($user->user_nickname);
553 $wpdb->update( $wpdb->users, array('user_nicename' => $newname), array('ID' => $user->ID) );
557 $users = $wpdb->get_results("SELECT ID, user_pass from $wpdb->users");
558 foreach ($users as $row) {
559 if (!preg_match('/^[A-Fa-f0-9]{32}$/', $row->user_pass)) {
560 $wpdb->update( $wpdb->users, array('user_pass' => md5($row->user_pass)), array('ID' => $row->ID) );
564 // Get the GMT offset, we'll use that later on
565 $all_options = get_alloptions_110();
567 $time_difference = $all_options->time_difference;
569 $server_time = time()+date('Z');
570 $weblogger_time = $server_time + $time_difference*3600;
573 $diff_gmt_server = ($gmt_time - $server_time) / 3600;
574 $diff_weblogger_server = ($weblogger_time - $server_time) / 3600;
575 $diff_gmt_weblogger = $diff_gmt_server - $diff_weblogger_server;
576 $gmt_offset = -$diff_gmt_weblogger;
578 // Add a gmt_offset option, with value $gmt_offset
579 add_option('gmt_offset', $gmt_offset);
581 // Check if we already set the GMT fields (if we did, then
582 // MAX(post_date_gmt) can't be '0000-00-00 00:00:00'
583 // <michel_v> I just slapped myself silly for not thinking about it earlier
584 $got_gmt_fields = ! ($wpdb->get_var("SELECT MAX(post_date_gmt) FROM $wpdb->posts") == '0000-00-00 00:00:00');
586 if (!$got_gmt_fields) {
588 // Add or subtract time to all dates, to get GMT dates
589 $add_hours = intval($diff_gmt_weblogger);
590 $add_minutes = intval(60 * ($diff_gmt_weblogger - $add_hours));
591 $wpdb->query("UPDATE $wpdb->posts SET post_date_gmt = DATE_ADD(post_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
592 $wpdb->query("UPDATE $wpdb->posts SET post_modified = post_date");
593 $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'");
594 $wpdb->query("UPDATE $wpdb->comments SET comment_date_gmt = DATE_ADD(comment_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
595 $wpdb->query("UPDATE $wpdb->users SET user_registered = DATE_ADD(user_registered, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
601 * Execute changes made in WordPress 1.5.
605 function upgrade_130() {
608 // Remove extraneous backslashes.
609 $posts = $wpdb->get_results("SELECT ID, post_title, post_content, post_excerpt, guid, post_date, post_name, post_status, post_author FROM $wpdb->posts");
611 foreach($posts as $post) {
612 $post_content = addslashes(deslash($post->post_content));
613 $post_title = addslashes(deslash($post->post_title));
614 $post_excerpt = addslashes(deslash($post->post_excerpt));
615 if ( empty($post->guid) )
616 $guid = get_permalink($post->ID);
620 $wpdb->update( $wpdb->posts, compact('post_title', 'post_content', 'post_excerpt', 'guid'), array('ID' => $post->ID) );
625 // Remove extraneous backslashes.
626 $comments = $wpdb->get_results("SELECT comment_ID, comment_author, comment_content FROM $wpdb->comments");
628 foreach($comments as $comment) {
629 $comment_content = deslash($comment->comment_content);
630 $comment_author = deslash($comment->comment_author);
632 $wpdb->update($wpdb->comments, compact('comment_content', 'comment_author'), array('comment_ID' => $comment->comment_ID) );
636 // Remove extraneous backslashes.
637 $links = $wpdb->get_results("SELECT link_id, link_name, link_description FROM $wpdb->links");
639 foreach($links as $link) {
640 $link_name = deslash($link->link_name);
641 $link_description = deslash($link->link_description);
643 $wpdb->update( $wpdb->links, compact('link_name', 'link_description'), array('link_id' => $link->link_id) );
647 $active_plugins = __get_option('active_plugins');
649 // If plugins are not stored in an array, they're stored in the old
650 // newline separated format. Convert to new format.
651 if ( !is_array( $active_plugins ) ) {
652 $active_plugins = explode("\n", trim($active_plugins));
653 update_option('active_plugins', $active_plugins);
657 $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optionvalues');
658 $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiontypes');
659 $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiongroups');
660 $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiongroup_options');
662 // Update comments table to use comment_type
663 $wpdb->query("UPDATE $wpdb->comments SET comment_type='trackback', comment_content = REPLACE(comment_content, '<trackback />', '') WHERE comment_content LIKE '<trackback />%'");
664 $wpdb->query("UPDATE $wpdb->comments SET comment_type='pingback', comment_content = REPLACE(comment_content, '<pingback />', '') WHERE comment_content LIKE '<pingback />%'");
666 // Some versions have multiple duplicate option_name rows with the same values
667 $options = $wpdb->get_results("SELECT option_name, COUNT(option_name) AS dupes FROM `$wpdb->options` GROUP BY option_name");
668 foreach ( $options as $option ) {
669 if ( 1 != $option->dupes ) { // Could this be done in the query?
670 $limit = $option->dupes - 1;
671 $dupe_ids = $wpdb->get_col( $wpdb->prepare("SELECT option_id FROM $wpdb->options WHERE option_name = %s LIMIT %d", $option->option_name, $limit) );
673 $dupe_ids = join($dupe_ids, ',');
674 $wpdb->query("DELETE FROM $wpdb->options WHERE option_id IN ($dupe_ids)");
683 * Execute changes made in WordPress 2.0.
687 function upgrade_160() {
688 global $wpdb, $wp_current_db_version;
690 populate_roles_160();
692 $users = $wpdb->get_results("SELECT * FROM $wpdb->users");
693 foreach ( $users as $user ) :
694 if ( !empty( $user->user_firstname ) )
695 update_user_meta( $user->ID, 'first_name', $wpdb->escape($user->user_firstname) );
696 if ( !empty( $user->user_lastname ) )
697 update_user_meta( $user->ID, 'last_name', $wpdb->escape($user->user_lastname) );
698 if ( !empty( $user->user_nickname ) )
699 update_user_meta( $user->ID, 'nickname', $wpdb->escape($user->user_nickname) );
700 if ( !empty( $user->user_level ) )
701 update_user_meta( $user->ID, $wpdb->prefix . 'user_level', $user->user_level );
702 if ( !empty( $user->user_icq ) )
703 update_user_meta( $user->ID, 'icq', $wpdb->escape($user->user_icq) );
704 if ( !empty( $user->user_aim ) )
705 update_user_meta( $user->ID, 'aim', $wpdb->escape($user->user_aim) );
706 if ( !empty( $user->user_msn ) )
707 update_user_meta( $user->ID, 'msn', $wpdb->escape($user->user_msn) );
708 if ( !empty( $user->user_yim ) )
709 update_user_meta( $user->ID, 'yim', $wpdb->escape($user->user_icq) );
710 if ( !empty( $user->user_description ) )
711 update_user_meta( $user->ID, 'description', $wpdb->escape($user->user_description) );
713 if ( isset( $user->user_idmode ) ):
714 $idmode = $user->user_idmode;
715 if ($idmode == 'nickname') $id = $user->user_nickname;
716 if ($idmode == 'login') $id = $user->user_login;
717 if ($idmode == 'firstname') $id = $user->user_firstname;
718 if ($idmode == 'lastname') $id = $user->user_lastname;
719 if ($idmode == 'namefl') $id = $user->user_firstname.' '.$user->user_lastname;
720 if ($idmode == 'namelf') $id = $user->user_lastname.' '.$user->user_firstname;
721 if (!$idmode) $id = $user->user_nickname;
722 $wpdb->update( $wpdb->users, array('display_name' => $id), array('ID' => $user->ID) );
725 // FIXME: RESET_CAPS is temporary code to reset roles and caps if flag is set.
726 $caps = get_user_meta( $user->ID, $wpdb->prefix . 'capabilities');
727 if ( empty($caps) || defined('RESET_CAPS') ) {
728 $level = get_user_meta($user->ID, $wpdb->prefix . 'user_level', true);
729 $role = translate_level_to_role($level);
730 update_user_meta( $user->ID, $wpdb->prefix . 'capabilities', array($role => true) );
734 $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' );
735 $wpdb->hide_errors();
736 foreach ( $old_user_fields as $old )
737 $wpdb->query("ALTER TABLE $wpdb->users DROP $old");
738 $wpdb->show_errors();
740 // populate comment_count field of posts table
741 $comments = $wpdb->get_results( "SELECT comment_post_ID, COUNT(*) as c FROM $wpdb->comments WHERE comment_approved = '1' GROUP BY comment_post_ID" );
742 if ( is_array( $comments ) )
743 foreach ($comments as $comment)
744 $wpdb->update( $wpdb->posts, array('comment_count' => $comment->c), array('ID' => $comment->comment_post_ID) );
746 // Some alpha versions used a post status of object instead of attachment and put
747 // the mime type in post_type instead of post_mime_type.
748 if ( $wp_current_db_version > 2541 && $wp_current_db_version <= 3091 ) {
749 $objects = $wpdb->get_results("SELECT ID, post_type FROM $wpdb->posts WHERE post_status = 'object'");
750 foreach ($objects as $object) {
751 $wpdb->update( $wpdb->posts, array( 'post_status' => 'attachment',
752 'post_mime_type' => $object->post_type,
754 array( 'ID' => $object->ID ) );
756 $meta = get_post_meta($object->ID, 'imagedata', true);
757 if ( ! empty($meta['file']) )
758 update_attached_file( $object->ID, $meta['file'] );
764 * Execute changes made in WordPress 2.1.
768 function upgrade_210() {
769 global $wpdb, $wp_current_db_version;
771 if ( $wp_current_db_version < 3506 ) {
772 // Update status and type.
773 $posts = $wpdb->get_results("SELECT ID, post_status FROM $wpdb->posts");
775 if ( ! empty($posts) ) foreach ($posts as $post) {
776 $status = $post->post_status;
779 if ( 'static' == $status ) {
782 } else if ( 'attachment' == $status ) {
784 $type = 'attachment';
787 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_status = %s, post_type = %s WHERE ID = %d", $status, $type, $post->ID) );
791 if ( $wp_current_db_version < 3845 ) {
792 populate_roles_210();
795 if ( $wp_current_db_version < 3531 ) {
796 // Give future posts a post_status of future.
797 $now = gmdate('Y-m-d H:i:59');
798 $wpdb->query ("UPDATE $wpdb->posts SET post_status = 'future' WHERE post_status = 'publish' AND post_date_gmt > '$now'");
800 $posts = $wpdb->get_results("SELECT ID, post_date FROM $wpdb->posts WHERE post_status ='future'");
801 if ( !empty($posts) )
802 foreach ( $posts as $post )
803 wp_schedule_single_event(mysql2date('U', $post->post_date, false), 'publish_future_post', array($post->ID));
808 * Execute changes made in WordPress 2.3.
812 function upgrade_230() {
813 global $wp_current_db_version, $wpdb;
815 if ( $wp_current_db_version < 5200 ) {
816 populate_roles_230();
819 // Convert categories to terms.
822 $categories = $wpdb->get_results("SELECT * FROM $wpdb->categories ORDER BY cat_ID");
823 foreach ($categories as $category) {
824 $term_id = (int) $category->cat_ID;
825 $name = $category->cat_name;
826 $description = $category->category_description;
827 $slug = $category->category_nicename;
828 $parent = $category->category_parent;
831 // Associate terms with the same slug in a term group and make slugs unique.
832 if ( $exists = $wpdb->get_results( $wpdb->prepare("SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $slug) ) ) {
833 $term_group = $exists[0]->term_group;
834 $id = $exists[0]->term_id;
837 $alt_slug = $slug . "-$num";
839 $slug_check = $wpdb->get_var( $wpdb->prepare("SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug) );
840 } while ( $slug_check );
844 if ( empty( $term_group ) ) {
845 $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms GROUP BY term_group") + 1;
846 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->terms SET term_group = %d WHERE term_id = %d", $term_group, $id) );
850 $wpdb->query( $wpdb->prepare("INSERT INTO $wpdb->terms (term_id, name, slug, term_group) VALUES
851 (%d, %s, %s, %d)", $term_id, $name, $slug, $term_group) );
854 if ( !empty($category->category_count) ) {
855 $count = (int) $category->category_count;
856 $taxonomy = 'category';
857 $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) );
858 $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
861 if ( !empty($category->link_count) ) {
862 $count = (int) $category->link_count;
863 $taxonomy = 'link_category';
864 $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) );
865 $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
868 if ( !empty($category->tag_count) ) {
870 $count = (int) $category->tag_count;
871 $taxonomy = 'post_tag';
872 $wpdb->insert( $wpdb->term_taxonomy, compact('term_id', 'taxonomy', 'description', 'parent', 'count') );
873 $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
876 if ( empty($count) ) {
878 $taxonomy = 'category';
879 $wpdb->insert( $wpdb->term_taxonomy, compact('term_id', 'taxonomy', 'description', 'parent', 'count') );
880 $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
884 $select = 'post_id, category_id';
886 $select .= ', rel_type';
888 $posts = $wpdb->get_results("SELECT $select FROM $wpdb->post2cat GROUP BY post_id, category_id");
889 foreach ( $posts as $post ) {
890 $post_id = (int) $post->post_id;
891 $term_id = (int) $post->category_id;
892 $taxonomy = 'category';
893 if ( !empty($post->rel_type) && 'tag' == $post->rel_type)
895 $tt_id = $tt_ids[$term_id][$taxonomy];
899 $wpdb->insert( $wpdb->term_relationships, array('object_id' => $post_id, 'term_taxonomy_id' => $tt_id) );
902 // < 3570 we used linkcategories. >= 3570 we used categories and link2cat.
903 if ( $wp_current_db_version < 3570 ) {
904 // Create link_category terms for link categories. Create a map of link cat IDs
905 // to link_category terms.
906 $link_cat_id_map = array();
907 $default_link_cat = 0;
909 $link_cats = $wpdb->get_results("SELECT cat_id, cat_name FROM " . $wpdb->prefix . 'linkcategories');
910 foreach ( $link_cats as $category) {
911 $cat_id = (int) $category->cat_id;
913 $name = $wpdb->escape($category->cat_name);
914 $slug = sanitize_title($name);
917 // Associate terms with the same slug in a term group and make slugs unique.
918 if ( $exists = $wpdb->get_results( $wpdb->prepare("SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $slug) ) ) {
919 $term_group = $exists[0]->term_group;
920 $term_id = $exists[0]->term_id;
923 if ( empty($term_id) ) {
924 $wpdb->insert( $wpdb->terms, compact('name', 'slug', 'term_group') );
925 $term_id = (int) $wpdb->insert_id;
928 $link_cat_id_map[$cat_id] = $term_id;
929 $default_link_cat = $term_id;
931 $wpdb->insert( $wpdb->term_taxonomy, array('term_id' => $term_id, 'taxonomy' => 'link_category', 'description' => '', 'parent' => 0, 'count' => 0) );
932 $tt_ids[$term_id] = (int) $wpdb->insert_id;
935 // Associate links to cats.
936 $links = $wpdb->get_results("SELECT link_id, link_category FROM $wpdb->links");
937 if ( !empty($links) ) foreach ( $links as $link ) {
938 if ( 0 == $link->link_category )
940 if ( ! isset($link_cat_id_map[$link->link_category]) )
942 $term_id = $link_cat_id_map[$link->link_category];
943 $tt_id = $tt_ids[$term_id];
947 $wpdb->insert( $wpdb->term_relationships, array('object_id' => $link->link_id, 'term_taxonomy_id' => $tt_id) );
950 // Set default to the last category we grabbed during the upgrade loop.
951 update_option('default_link_category', $default_link_cat);
953 $links = $wpdb->get_results("SELECT link_id, category_id FROM $wpdb->link2cat GROUP BY link_id, category_id");
954 foreach ( $links as $link ) {
955 $link_id = (int) $link->link_id;
956 $term_id = (int) $link->category_id;
957 $taxonomy = 'link_category';
958 $tt_id = $tt_ids[$term_id][$taxonomy];
961 $wpdb->insert( $wpdb->term_relationships, array('object_id' => $link_id, 'term_taxonomy_id' => $tt_id) );
965 if ( $wp_current_db_version < 4772 ) {
966 // Obsolete linkcategories table
967 $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'linkcategories');
970 // Recalculate all counts
971 $terms = $wpdb->get_results("SELECT term_taxonomy_id, taxonomy FROM $wpdb->term_taxonomy");
972 foreach ( (array) $terms as $term ) {
973 if ( ('post_tag' == $term->taxonomy) || ('category' == $term->taxonomy) )
974 $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) );
976 $count = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term->term_taxonomy_id) );
977 $wpdb->update( $wpdb->term_taxonomy, array('count' => $count), array('term_taxonomy_id' => $term->term_taxonomy_id) );
982 * Remove old options from the database.
986 function upgrade_230_options_table() {
988 $old_options_fields = array( 'option_can_override', 'option_type', 'option_width', 'option_height', 'option_description', 'option_admin_level' );
989 $wpdb->hide_errors();
990 foreach ( $old_options_fields as $old )
991 $wpdb->query("ALTER TABLE $wpdb->options DROP $old");
992 $wpdb->show_errors();
996 * Remove old categories, link2cat, and post2cat database tables.
1000 function upgrade_230_old_tables() {
1002 $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'categories');
1003 $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'link2cat');
1004 $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'post2cat');
1008 * Upgrade old slugs made in version 2.2.
1012 function upgrade_old_slugs() {
1013 // upgrade people who were using the Redirect Old Slugs plugin
1015 $wpdb->query("UPDATE $wpdb->postmeta SET meta_key = '_wp_old_slug' WHERE meta_key = 'old_slug'");
1019 * Execute changes made in WordPress 2.5.0.
1023 function upgrade_250() {
1024 global $wp_current_db_version;
1026 if ( $wp_current_db_version < 6689 ) {
1027 populate_roles_250();
1033 * Execute changes made in WordPress 2.5.2.
1037 function upgrade_252() {
1040 $wpdb->query("UPDATE $wpdb->users SET user_activation_key = ''");
1044 * Execute changes made in WordPress 2.6.
1048 function upgrade_260() {
1049 global $wp_current_db_version;
1051 if ( $wp_current_db_version < 8000 )
1052 populate_roles_260();
1054 if ( $wp_current_db_version < 8201 ) {
1055 update_option('enable_app', 1);
1056 update_option('enable_xmlrpc', 1);
1061 * Execute changes made in WordPress 2.7.
1065 function upgrade_270() {
1066 global $wpdb, $wp_current_db_version;
1068 if ( $wp_current_db_version < 8980 )
1069 populate_roles_270();
1071 // Update post_date for unpublished posts with empty timestamp
1072 if ( $wp_current_db_version < 8921 )
1073 $wpdb->query( "UPDATE $wpdb->posts SET post_date = post_modified WHERE post_date = '0000-00-00 00:00:00'" );
1077 * Execute changes made in WordPress 2.8.
1081 function upgrade_280() {
1082 global $wp_current_db_version, $wpdb;
1084 if ( $wp_current_db_version < 10360 )
1085 populate_roles_280();
1086 if ( is_multisite() ) {
1088 while( $rows = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options ORDER BY option_id LIMIT $start, 20" ) ) {
1089 foreach( $rows as $row ) {
1090 $value = $row->option_value;
1091 if ( !@unserialize( $value ) )
1092 $value = stripslashes( $value );
1093 if ( $value !== $row->option_value ) {
1094 update_option( $row->option_name, $value );
1099 refresh_blog_details( $wpdb->blogid );
1104 * Execute changes made in WordPress 2.9.
1108 function upgrade_290() {
1109 global $wp_current_db_version;
1111 if ( $wp_current_db_version < 11958 ) {
1112 // Previously, setting depth to 1 would redundantly disable threading, but now 2 is the minimum depth to avoid confusion
1113 if ( get_option( 'thread_comments_depth' ) == '1' ) {
1114 update_option( 'thread_comments_depth', 2 );
1115 update_option( 'thread_comments', 0 );
1121 * Execute changes made in WordPress 3.0.
1125 function upgrade_300() {
1126 global $wp_current_db_version, $wpdb;
1128 if ( $wp_current_db_version < 15093 )
1129 populate_roles_300();
1131 if ( $wp_current_db_version < 14139 && is_multisite() && is_main_site() && ! defined( 'MULTISITE' ) && get_site_option( 'siteurl' ) === false )
1132 add_site_option( 'siteurl', '' );
1134 // 3.0 screen options key name changes.
1135 if ( is_main_site() && !defined('DO_NOT_UPGRADE_GLOBAL_TABLES') ) {
1136 $prefix = like_escape($wpdb->base_prefix);
1137 $wpdb->query( "DELETE FROM $wpdb->usermeta WHERE meta_key LIKE '{$prefix}%meta-box-hidden%' OR meta_key LIKE '{$prefix}%closedpostboxes%' OR meta_key LIKE '{$prefix}%manage-%-columns-hidden%' OR meta_key LIKE '{$prefix}%meta-box-order%' OR meta_key LIKE '{$prefix}%metaboxorder%' OR meta_key LIKE '{$prefix}%screen_layout%'
1138 OR meta_key = 'manageedittagscolumnshidden' OR meta_key='managecategoriescolumnshidden' OR meta_key = 'manageedit-tagscolumnshidden' OR meta_key = 'manageeditcolumnshidden' OR meta_key = 'categories_per_page' OR meta_key = 'edit_tags_per_page'" );
1144 * Execute changes made in WordPress 3.3.
1148 function upgrade_330() {
1149 global $wp_current_db_version, $wpdb, $wp_registered_widgets, $sidebars_widgets;
1151 if ( $wp_current_db_version < 19061 && is_main_site() && ! defined( 'DO_NOT_UPGRADE_GLOBAL_TABLES' ) ) {
1152 $wpdb->query( "DELETE FROM $wpdb->usermeta WHERE meta_key IN ('show_admin_bar_admin', 'plugins_last_view')" );
1155 if ( $wp_current_db_version >= 11548 )
1158 $sidebars_widgets = get_option( 'sidebars_widgets', array() );
1159 $_sidebars_widgets = array();
1161 if ( isset($sidebars_widgets['wp_inactive_widgets']) || empty($sidebars_widgets) )
1162 $sidebars_widgets['array_version'] = 3;
1163 elseif ( !isset($sidebars_widgets['array_version']) )
1164 $sidebars_widgets['array_version'] = 1;
1166 switch ( $sidebars_widgets['array_version'] ) {
1168 foreach ( (array) $sidebars_widgets as $index => $sidebar )
1169 if ( is_array($sidebar) )
1170 foreach ( (array) $sidebar as $i => $name ) {
1171 $id = strtolower($name);
1172 if ( isset($wp_registered_widgets[$id]) ) {
1173 $_sidebars_widgets[$index][$i] = $id;
1176 $id = sanitize_title($name);
1177 if ( isset($wp_registered_widgets[$id]) ) {
1178 $_sidebars_widgets[$index][$i] = $id;
1184 foreach ( $wp_registered_widgets as $widget_id => $widget ) {
1185 if ( strtolower($widget['name']) == strtolower($name) ) {
1186 $_sidebars_widgets[$index][$i] = $widget['id'];
1189 } elseif ( sanitize_title($widget['name']) == sanitize_title($name) ) {
1190 $_sidebars_widgets[$index][$i] = $widget['id'];
1199 unset($_sidebars_widgets[$index][$i]);
1201 $_sidebars_widgets['array_version'] = 2;
1202 $sidebars_widgets = $_sidebars_widgets;
1203 unset($_sidebars_widgets);
1206 $sidebars_widgets = retrieve_widgets();
1207 $sidebars_widgets['array_version'] = 3;
1208 update_option( 'sidebars_widgets', $sidebars_widgets );
1213 * Execute changes made in WordPress 3.4.
1217 function upgrade_340() {
1218 global $wp_current_db_version, $wpdb;
1220 if ( $wp_current_db_version < 19798 ) {
1221 $wpdb->hide_errors();
1222 $wpdb->query( "ALTER TABLE $wpdb->options DROP COLUMN blog_id" );
1223 $wpdb->show_errors();
1226 if ( $wp_current_db_version < 19799 ) {
1227 $wpdb->hide_errors();
1228 $wpdb->query("ALTER TABLE $wpdb->comments DROP INDEX comment_approved");
1229 $wpdb->show_errors();
1232 if ( $wp_current_db_version < 20022 && is_main_site() && ! defined( 'DO_NOT_UPGRADE_GLOBAL_TABLES' ) ) {
1233 $wpdb->query( "DELETE FROM $wpdb->usermeta WHERE meta_key = 'themes_last_view'" );
1236 if ( $wp_current_db_version < 20080 ) {
1237 if ( 'yes' == $wpdb->get_var( "SELECT autoload FROM $wpdb->options WHERE option_name = 'uninstall_plugins'" ) ) {
1238 $uninstall_plugins = get_option( 'uninstall_plugins' );
1239 delete_option( 'uninstall_plugins' );
1240 add_option( 'uninstall_plugins', $uninstall_plugins, null, 'no' );
1246 * Execute network level changes
1250 function upgrade_network() {
1251 global $wp_current_db_version, $wpdb;
1253 if ( $wp_current_db_version < 11549 ) {
1254 $wpmu_sitewide_plugins = get_site_option( 'wpmu_sitewide_plugins' );
1255 $active_sitewide_plugins = get_site_option( 'active_sitewide_plugins' );
1256 if ( $wpmu_sitewide_plugins ) {
1257 if ( !$active_sitewide_plugins )
1258 $sitewide_plugins = (array) $wpmu_sitewide_plugins;
1260 $sitewide_plugins = array_merge( (array) $active_sitewide_plugins, (array) $wpmu_sitewide_plugins );
1262 update_site_option( 'active_sitewide_plugins', $sitewide_plugins );
1264 delete_site_option( 'wpmu_sitewide_plugins' );
1265 delete_site_option( 'deactivated_sitewide_plugins' );
1268 while( $rows = $wpdb->get_results( "SELECT meta_key, meta_value FROM {$wpdb->sitemeta} ORDER BY meta_id LIMIT $start, 20" ) ) {
1269 foreach( $rows as $row ) {
1270 $value = $row->meta_value;
1271 if ( !@unserialize( $value ) )
1272 $value = stripslashes( $value );
1273 if ( $value !== $row->meta_value ) {
1274 update_site_option( $row->meta_key, $value );
1282 if ( $wp_current_db_version < 13576 )
1283 update_site_option( 'global_terms_enabled', '1' );
1286 if ( $wp_current_db_version < 19390 )
1287 update_site_option( 'initial_db_version', $wp_current_db_version );
1289 if ( $wp_current_db_version < 19470 ) {
1290 if ( false === get_site_option( 'active_sitewide_plugins' ) )
1291 update_site_option( 'active_sitewide_plugins', array() );
1295 if ( $wp_current_db_version < 20148 ) {
1296 // 'allowedthemes' keys things by stylesheet. 'allowed_themes' keyed things by name.
1297 $allowedthemes = get_site_option( 'allowedthemes' );
1298 $allowed_themes = get_site_option( 'allowed_themes' );
1299 if ( false === $allowedthemes && is_array( $allowed_themes ) && $allowed_themes ) {
1300 $converted = array();
1301 $themes = wp_get_themes();
1302 foreach ( $themes as $stylesheet => $theme_data ) {
1303 if ( isset( $allowed_themes[ $theme_data->get('Name') ] ) )
1304 $converted[ $stylesheet ] = true;
1306 update_site_option( 'allowedthemes', $converted );
1307 delete_site_option( 'allowed_themes' );
1312 // The functions we use to actually do stuff
1317 * {@internal Missing Short Description}}
1319 * {@internal Missing Long Description}}
1323 * @param string $table_name Database table name to create.
1324 * @param string $create_ddl SQL statement to create table.
1325 * @return bool If table already exists or was created by function.
1327 function maybe_create_table($table_name, $create_ddl) {
1329 if ( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") == $table_name )
1331 //didn't find it try to create it.
1332 $q = $wpdb->query($create_ddl);
1333 // we cannot directly tell that whether this succeeded!
1334 if ( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") == $table_name )
1340 * {@internal Missing Short Description}}
1342 * {@internal Missing Long Description}}
1346 * @param string $table Database table name.
1347 * @param string $index Index name to drop.
1348 * @return bool True, when finished.
1350 function drop_index($table, $index) {
1352 $wpdb->hide_errors();
1353 $wpdb->query("ALTER TABLE `$table` DROP INDEX `$index`");
1354 // Now we need to take out all the extra ones we may have created
1355 for ($i = 0; $i < 25; $i++) {
1356 $wpdb->query("ALTER TABLE `$table` DROP INDEX `{$index}_$i`");
1358 $wpdb->show_errors();
1363 * {@internal Missing Short Description}}
1365 * {@internal Missing Long Description}}
1369 * @param string $table Database table name.
1370 * @param string $index Database table index column.
1371 * @return bool True, when done with execution.
1373 function add_clean_index($table, $index) {
1375 drop_index($table, $index);
1376 $wpdb->query("ALTER TABLE `$table` ADD INDEX ( `$index` )");
1381 ** maybe_add_column()
1382 ** Add column to db table if it doesn't exist.
1383 ** Returns: true if already exists or on successful completion
1386 function maybe_add_column($table_name, $column_name, $create_ddl) {
1388 foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) {
1389 if ($column == $column_name) {
1393 //didn't find it try to create it.
1394 $q = $wpdb->query($create_ddl);
1395 // we cannot directly tell that whether this succeeded!
1396 foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) {
1397 if ($column == $column_name) {
1405 * Retrieve all options as it was for 1.2.
1409 * @return array List of options.
1411 function get_alloptions_110() {
1413 $all_options = new stdClass;
1414 if ( $options = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options" ) ) {
1415 foreach ( $options as $option ) {
1416 if ( 'siteurl' == $option->option_name || 'home' == $option->option_name || 'category_base' == $option->option_name )
1417 $option->option_value = untrailingslashit( $option->option_value );
1418 $all_options->{$option->option_name} = stripslashes( $option->option_value );
1421 return $all_options;
1425 * Version of get_option that is private to install/upgrade.
1430 * @param string $setting Option name.
1433 function __get_option($setting) {
1436 if ( $setting == 'home' && defined( 'WP_HOME' ) )
1437 return untrailingslashit( WP_HOME );
1439 if ( $setting == 'siteurl' && defined( 'WP_SITEURL' ) )
1440 return untrailingslashit( WP_SITEURL );
1442 $option = $wpdb->get_var( $wpdb->prepare("SELECT option_value FROM $wpdb->options WHERE option_name = %s", $setting ) );
1444 if ( 'home' == $setting && '' == $option )
1445 return __get_option( 'siteurl' );
1447 if ( 'siteurl' == $setting || 'home' == $setting || 'category_base' == $setting || 'tag_base' == $setting )
1448 $option = untrailingslashit( $option );
1450 @ $kellogs = unserialize( $option );
1451 if ( $kellogs !== false )
1458 * {@internal Missing Short Description}}
1460 * {@internal Missing Long Description}}
1464 * @param string $content
1467 function deslash($content) {
1468 // Note: \\\ inside a regex denotes a single backslash.
1470 // Replace one or more backslashes followed by a single quote with
1472 $content = preg_replace("/\\\+'/", "'", $content);
1474 // Replace one or more backslashes followed by a double quote with
1476 $content = preg_replace('/\\\+"/', '"', $content);
1478 // Replace one or more backslashes with one backslash.
1479 $content = preg_replace("/\\\+/", "\\", $content);
1485 * {@internal Missing Short Description}}
1487 * {@internal Missing Long Description}}
1491 * @param unknown_type $queries
1492 * @param unknown_type $execute
1495 function dbDelta( $queries = '', $execute = true ) {
1498 if ( in_array( $queries, array( '', 'all', 'blog', 'global', 'ms_global' ), true ) )
1499 $queries = wp_get_db_schema( $queries );
1501 // Separate individual queries into an array
1502 if ( !is_array($queries) ) {
1503 $queries = explode( ';', $queries );
1504 $queries = array_filter( $queries );
1506 $queries = apply_filters( 'dbdelta_queries', $queries );
1508 $cqueries = array(); // Creation Queries
1509 $iqueries = array(); // Insertion Queries
1510 $for_update = array();
1512 // Create a tablename index for an array ($cqueries) of queries
1513 foreach($queries as $qry) {
1514 if (preg_match("|CREATE TABLE ([^ ]*)|", $qry, $matches)) {
1515 $cqueries[ trim( $matches[1], '`' ) ] = $qry;
1516 $for_update[$matches[1]] = 'Created table '.$matches[1];
1517 } else if (preg_match("|CREATE DATABASE ([^ ]*)|", $qry, $matches)) {
1518 array_unshift($cqueries, $qry);
1519 } else if (preg_match("|INSERT INTO ([^ ]*)|", $qry, $matches)) {
1521 } else if (preg_match("|UPDATE ([^ ]*)|", $qry, $matches)) {
1524 // Unrecognized query type
1527 $cqueries = apply_filters( 'dbdelta_create_queries', $cqueries );
1528 $iqueries = apply_filters( 'dbdelta_insert_queries', $iqueries );
1530 $global_tables = $wpdb->tables( 'global' );
1531 foreach ( $cqueries as $table => $qry ) {
1532 // Upgrade global tables only for the main site. Don't upgrade at all if DO_NOT_UPGRADE_GLOBAL_TABLES is defined.
1533 if ( in_array( $table, $global_tables ) && ( !is_main_site() || defined( 'DO_NOT_UPGRADE_GLOBAL_TABLES' ) ) )
1536 // Fetch the table column structure from the database
1537 $wpdb->suppress_errors();
1538 $tablefields = $wpdb->get_results("DESCRIBE {$table};");
1539 $wpdb->suppress_errors( false );
1541 if ( ! $tablefields )
1544 // Clear the field and index arrays
1545 $cfields = $indices = array();
1546 // Get all of the field names in the query from between the parens
1547 preg_match("|\((.*)\)|ms", $qry, $match2);
1548 $qryline = trim($match2[1]);
1550 // Separate field lines into an array
1551 $flds = explode("\n", $qryline);
1553 //echo "<hr/><pre>\n".print_r(strtolower($table), true).":\n".print_r($cqueries, true)."</pre><hr/>";
1555 // For every field line specified in the query
1556 foreach ($flds as $fld) {
1557 // Extract the field name
1558 preg_match("|^([^ ]*)|", trim($fld), $fvals);
1559 $fieldname = trim( $fvals[1], '`' );
1561 // Verify the found field name
1563 switch (strtolower($fieldname)) {
1570 $validfield = false;
1571 $indices[] = trim(trim($fld), ", \n");
1576 // If it's a valid field, add it to the field array
1578 $cfields[strtolower($fieldname)] = trim($fld, ", \n");
1582 // For every field in the table
1583 foreach ($tablefields as $tablefield) {
1584 // If the table field exists in the field array...
1585 if (array_key_exists(strtolower($tablefield->Field), $cfields)) {
1586 // Get the field type from the query
1587 preg_match("|".$tablefield->Field." ([^ ]*( unsigned)?)|i", $cfields[strtolower($tablefield->Field)], $matches);
1588 $fieldtype = $matches[1];
1590 // Is actual field type different from the field type in query?
1591 if ($tablefield->Type != $fieldtype) {
1592 // Add a query to change the column type
1593 $cqueries[] = "ALTER TABLE {$table} CHANGE COLUMN {$tablefield->Field} " . $cfields[strtolower($tablefield->Field)];
1594 $for_update[$table.'.'.$tablefield->Field] = "Changed type of {$table}.{$tablefield->Field} from {$tablefield->Type} to {$fieldtype}";
1597 // Get the default value from the array
1598 //echo "{$cfields[strtolower($tablefield->Field)]}<br>";
1599 if (preg_match("| DEFAULT '(.*)'|i", $cfields[strtolower($tablefield->Field)], $matches)) {
1600 $default_value = $matches[1];
1601 if ($tablefield->Default != $default_value) {
1602 // Add a query to change the column's default value
1603 $cqueries[] = "ALTER TABLE {$table} ALTER COLUMN {$tablefield->Field} SET DEFAULT '{$default_value}'";
1604 $for_update[$table.'.'.$tablefield->Field] = "Changed default value of {$table}.{$tablefield->Field} from {$tablefield->Default} to {$default_value}";
1608 // Remove the field from the array (so it's not added)
1609 unset($cfields[strtolower($tablefield->Field)]);
1611 // This field exists in the table, but not in the creation queries?
1615 // For every remaining field specified for the table
1616 foreach ($cfields as $fieldname => $fielddef) {
1617 // Push a query line into $cqueries that adds the field to that table
1618 $cqueries[] = "ALTER TABLE {$table} ADD COLUMN $fielddef";
1619 $for_update[$table.'.'.$fieldname] = 'Added column '.$table.'.'.$fieldname;
1622 // Index stuff goes here
1623 // Fetch the table index structure from the database
1624 $tableindices = $wpdb->get_results("SHOW INDEX FROM {$table};");
1626 if ($tableindices) {
1627 // Clear the index array
1630 // For every index in the table
1631 foreach ($tableindices as $tableindex) {
1632 // Add the index to the index data array
1633 $keyname = $tableindex->Key_name;
1634 $index_ary[$keyname]['columns'][] = array('fieldname' => $tableindex->Column_name, 'subpart' => $tableindex->Sub_part);
1635 $index_ary[$keyname]['unique'] = ($tableindex->Non_unique == 0)?true:false;
1638 // For each actual index in the index array
1639 foreach ($index_ary as $index_name => $index_data) {
1640 // Build a create string to compare to the query
1642 if ($index_name == 'PRIMARY') {
1643 $index_string .= 'PRIMARY ';
1644 } else if($index_data['unique']) {
1645 $index_string .= 'UNIQUE ';
1647 $index_string .= 'KEY ';
1648 if ($index_name != 'PRIMARY') {
1649 $index_string .= $index_name;
1651 $index_columns = '';
1652 // For each column in the index
1653 foreach ($index_data['columns'] as $column_data) {
1654 if ($index_columns != '') $index_columns .= ',';
1655 // Add the field to the column list string
1656 $index_columns .= $column_data['fieldname'];
1657 if ($column_data['subpart'] != '') {
1658 $index_columns .= '('.$column_data['subpart'].')';
1661 // Add the column list to the index create string
1662 $index_string .= ' ('.$index_columns.')';
1663 if (!(($aindex = array_search($index_string, $indices)) === false)) {
1664 unset($indices[$aindex]);
1665 //echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">{$table}:<br />Found index:".$index_string."</pre>\n";
1667 //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";
1671 // For every remaining index specified for the table
1672 foreach ( (array) $indices as $index ) {
1673 // Push a query line into $cqueries that adds the index to that table
1674 $cqueries[] = "ALTER TABLE {$table} ADD $index";
1675 $for_update[$table.'.'.$fieldname] = 'Added index '.$table.' '.$index;
1678 // Remove the original table creation query from processing
1679 unset( $cqueries[ $table ], $for_update[ $table ] );
1682 $allqueries = array_merge($cqueries, $iqueries);
1684 foreach ($allqueries as $query) {
1685 //echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">".print_r($query, true)."</pre>\n";
1686 $wpdb->query($query);
1694 * {@internal Missing Short Description}}
1696 * {@internal Missing Long Description}}
1700 function make_db_current( $tables = 'all' ) {
1701 $alterations = dbDelta( $tables );
1703 foreach($alterations as $alteration) echo "<li>$alteration</li>\n";
1708 * {@internal Missing Short Description}}
1710 * {@internal Missing Long Description}}
1714 function make_db_current_silent( $tables = 'all' ) {
1715 $alterations = dbDelta( $tables );
1719 * {@internal Missing Short Description}}
1721 * {@internal Missing Long Description}}
1725 * @param unknown_type $theme_name
1726 * @param unknown_type $template
1729 function make_site_theme_from_oldschool($theme_name, $template) {
1730 $home_path = get_home_path();
1731 $site_dir = WP_CONTENT_DIR . "/themes/$template";
1733 if (! file_exists("$home_path/index.php"))
1736 // Copy files from the old locations to the site theme.
1737 // TODO: This does not copy arbitrary include dependencies. Only the
1738 // standard WP files are copied.
1739 $files = array('index.php' => 'index.php', 'wp-layout.css' => 'style.css', 'wp-comments.php' => 'comments.php', 'wp-comments-popup.php' => 'comments-popup.php');
1741 foreach ($files as $oldfile => $newfile) {
1742 if ($oldfile == 'index.php')
1743 $oldpath = $home_path;
1747 if ($oldfile == 'index.php') { // Check to make sure it's not a new index
1748 $index = implode('', file("$oldpath/$oldfile"));
1749 if (strpos($index, 'WP_USE_THEMES') !== false) {
1750 if (! @copy(WP_CONTENT_DIR . '/themes/' . WP_DEFAULT_THEME . '/index.php', "$site_dir/$newfile"))
1752 continue; // Don't copy anything
1756 if (! @copy("$oldpath/$oldfile", "$site_dir/$newfile"))
1759 chmod("$site_dir/$newfile", 0777);
1761 // Update the blog header include in each file.
1762 $lines = explode("\n", implode('', file("$site_dir/$newfile")));
1764 $f = fopen("$site_dir/$newfile", 'w');
1766 foreach ($lines as $line) {
1767 if (preg_match('/require.*wp-blog-header/', $line))
1768 $line = '//' . $line;
1770 // Update stylesheet references.
1771 $line = str_replace("<?php echo __get_option('siteurl'); ?>/wp-layout.css", "<?php bloginfo('stylesheet_url'); ?>", $line);
1773 // Update comments template inclusion.
1774 $line = str_replace("<?php include(ABSPATH . 'wp-comments.php'); ?>", "<?php comments_template(); ?>", $line);
1776 fwrite($f, "{$line}\n");
1782 // Add a theme header.
1783 $header = "/*\nTheme Name: $theme_name\nTheme URI: " . __get_option('siteurl') . "\nDescription: A theme automatically created by the update.\nVersion: 1.0\nAuthor: Moi\n*/\n";
1785 $stylelines = file_get_contents("$site_dir/style.css");
1787 $f = fopen("$site_dir/style.css", 'w');
1789 fwrite($f, $header);
1790 fwrite($f, $stylelines);
1798 * {@internal Missing Short Description}}
1800 * {@internal Missing Long Description}}
1804 * @param unknown_type $theme_name
1805 * @param unknown_type $template
1808 function make_site_theme_from_default($theme_name, $template) {
1809 $site_dir = WP_CONTENT_DIR . "/themes/$template";
1810 $default_dir = WP_CONTENT_DIR . '/themes/' . WP_DEFAULT_THEME;
1812 // Copy files from the default theme to the site theme.
1813 //$files = array('index.php', 'comments.php', 'comments-popup.php', 'footer.php', 'header.php', 'sidebar.php', 'style.css');
1815 $theme_dir = @ opendir($default_dir);
1817 while(($theme_file = readdir( $theme_dir )) !== false) {
1818 if (is_dir("$default_dir/$theme_file"))
1820 if (! @copy("$default_dir/$theme_file", "$site_dir/$theme_file"))
1822 chmod("$site_dir/$theme_file", 0777);
1825 @closedir($theme_dir);
1827 // Rewrite the theme header.
1828 $stylelines = explode("\n", implode('', file("$site_dir/style.css")));
1830 $f = fopen("$site_dir/style.css", 'w');
1832 foreach ($stylelines as $line) {
1833 if (strpos($line, 'Theme Name:') !== false) $line = 'Theme Name: ' . $theme_name;
1834 elseif (strpos($line, 'Theme URI:') !== false) $line = 'Theme URI: ' . __get_option('url');
1835 elseif (strpos($line, 'Description:') !== false) $line = 'Description: Your theme.';
1836 elseif (strpos($line, 'Version:') !== false) $line = 'Version: 1';
1837 elseif (strpos($line, 'Author:') !== false) $line = 'Author: You';
1838 fwrite($f, $line . "\n");
1845 if (! mkdir("$site_dir/images", 0777)) {
1849 $images_dir = @ opendir("$default_dir/images");
1851 while(($image = readdir($images_dir)) !== false) {
1852 if (is_dir("$default_dir/images/$image"))
1854 if (! @copy("$default_dir/images/$image", "$site_dir/images/$image"))
1856 chmod("$site_dir/images/$image", 0777);
1859 @closedir($images_dir);
1862 // Create a site theme from the default theme.
1864 * {@internal Missing Short Description}}
1866 * {@internal Missing Long Description}}
1872 function make_site_theme() {
1873 // Name the theme after the blog.
1874 $theme_name = __get_option('blogname');
1875 $template = sanitize_title($theme_name);
1876 $site_dir = WP_CONTENT_DIR . "/themes/$template";
1878 // If the theme already exists, nothing to do.
1879 if ( is_dir($site_dir)) {
1883 // We must be able to write to the themes dir.
1884 if (! is_writable(WP_CONTENT_DIR . "/themes")) {
1889 if (! mkdir($site_dir, 0777)) {
1893 if (file_exists(ABSPATH . 'wp-layout.css')) {
1894 if (! make_site_theme_from_oldschool($theme_name, $template)) {
1895 // TODO: rm -rf the site theme directory.
1899 if (! make_site_theme_from_default($theme_name, $template))
1900 // TODO: rm -rf the site theme directory.
1904 // Make the new site theme active.
1905 $current_template = __get_option('template');
1906 if ($current_template == WP_DEFAULT_THEME) {
1907 update_option('template', $template);
1908 update_option('stylesheet', $template);
1914 * Translate user level to user role name.
1918 * @param int $level User level.
1919 * @return string User role name.
1921 function translate_level_to_role($level) {
1926 return 'administrator';
1936 return 'contributor';
1938 return 'subscriber';
1943 * {@internal Missing Short Description}}
1945 * {@internal Missing Long Description}}
1949 function wp_check_mysql_version() {
1951 $result = $wpdb->check_database_version();
1952 if ( is_wp_error( $result ) )
1953 die( $result->get_error_message() );
1957 * {@internal Missing Short Description}}
1959 * {@internal Missing Long Description}}
1963 function maybe_disable_automattic_widgets() {
1964 $plugins = __get_option( 'active_plugins' );
1966 foreach ( (array) $plugins as $plugin ) {
1967 if ( basename( $plugin ) == 'widgets.php' ) {
1968 array_splice( $plugins, array_search( $plugin, $plugins ), 1 );
1969 update_option( 'active_plugins', $plugins );
1976 * Runs before the schema is upgraded.
1980 function pre_schema_upgrade() {
1981 global $wp_current_db_version, $wp_db_version, $wpdb;
1983 // Upgrade versions prior to 2.9
1984 if ( $wp_current_db_version < 11557 ) {
1985 // Delete duplicate options. Keep the option with the highest option_id.
1986 $wpdb->query("DELETE o1 FROM $wpdb->options AS o1 JOIN $wpdb->options AS o2 USING (`option_name`) WHERE o2.option_id > o1.option_id");
1988 // Drop the old primary key and add the new.
1989 $wpdb->query("ALTER TABLE $wpdb->options DROP PRIMARY KEY, ADD PRIMARY KEY(option_id)");
1991 // Drop the old option_name index. dbDelta() doesn't do the drop.
1992 $wpdb->query("ALTER TABLE $wpdb->options DROP INDEX option_name");
1998 * Install global terms.
2003 if ( !function_exists( 'install_global_terms' ) ) :
2004 function install_global_terms() {
2005 global $wpdb, $charset_collate;
2007 CREATE TABLE $wpdb->sitecategories (
2008 cat_ID bigint(20) NOT NULL auto_increment,
2009 cat_name varchar(55) NOT NULL default '',
2010 category_nicename varchar(200) NOT NULL default '',
2011 last_updated timestamp NOT NULL,
2012 PRIMARY KEY (cat_ID),
2013 KEY category_nicename (category_nicename),
2014 KEY last_updated (last_updated)
2017 // now create tables
2018 dbDelta( $ms_queries );