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 = '' ) {
40 if ( !empty( $deprecated ) )
41 _deprecated_argument( __FUNCTION__, '2.6' );
43 wp_check_mysql_version();
45 make_db_current_silent();
49 update_option('blogname', $blog_title);
50 update_option('admin_email', $user_email);
51 update_option('blog_public', $public);
53 $guessurl = wp_guess_url();
55 update_option('siteurl', $guessurl);
57 // If not a public blog, don't ping.
59 update_option('default_pingback_flag', 0);
61 // Create default user. If the user already exists, the user tables are
62 // being shared among blogs. Just set the role in that case.
63 $user_id = username_exists($user_name);
64 $user_password = trim($user_password);
65 $email_password = false;
66 if ( !$user_id && empty($user_password) ) {
67 $user_password = wp_generate_password( 12, false );
68 $message = __('<strong><em>Note that password</em></strong> carefully! It is a <em>random</em> password that was generated just for you.');
69 $user_id = wp_create_user($user_name, $user_password, $user_email);
70 update_user_option($user_id, 'default_password_nag', true, true);
71 $email_password = true;
72 } else if ( !$user_id ) {
73 // Password has been provided
74 $message = '<em>'.__('Your chosen password.').'</em>';
75 $user_id = wp_create_user($user_name, $user_password, $user_email);
77 $message = __('User already exists. Password inherited.');
80 $user = new WP_User($user_id);
81 $user->set_role('administrator');
83 wp_install_defaults($user_id);
85 $wp_rewrite->flush_rules();
87 wp_new_blog_notification($blog_title, $guessurl, $user_id, ($email_password ? $user_password : __('The password you chose during the install.') ) );
91 return array('url' => $guessurl, 'user_id' => $user_id, 'password' => $user_password, 'password_message' => $message);
95 if ( !function_exists('wp_install_defaults') ) :
97 * {@internal Missing Short Description}}
99 * {@internal Missing Long Description}}
103 * @param int $user_id User ID.
105 function wp_install_defaults($user_id) {
106 global $wpdb, $wp_rewrite, $current_site, $table_prefix;
109 $cat_name = __('Uncategorized');
110 /* translators: Default category slug */
111 $cat_slug = sanitize_title(_x('Uncategorized', 'Default category slug'));
113 if ( global_terms_enabled() ) {
114 $cat_id = $wpdb->get_var( $wpdb->prepare( "SELECT cat_ID FROM {$wpdb->sitecategories} WHERE category_nicename = %s", $cat_slug ) );
115 if ( $cat_id == null ) {
116 $wpdb->insert( $wpdb->sitecategories, array('cat_ID' => 0, 'cat_name' => $cat_name, 'category_nicename' => $cat_slug, 'last_updated' => current_time('mysql', true)) );
117 $cat_id = $wpdb->insert_id;
119 update_option('default_category', $cat_id);
124 $wpdb->insert( $wpdb->terms, array('term_id' => $cat_id, 'name' => $cat_name, 'slug' => $cat_slug, 'term_group' => 0) );
125 $wpdb->insert( $wpdb->term_taxonomy, array('term_id' => $cat_id, 'taxonomy' => 'category', 'description' => '', 'parent' => 0, 'count' => 1));
126 $cat_tt_id = $wpdb->insert_id;
128 // Default link category
129 $cat_name = __('Blogroll');
130 /* translators: Default link category slug */
131 $cat_slug = sanitize_title(_x('Blogroll', 'Default link category slug'));
133 if ( global_terms_enabled() ) {
134 $blogroll_id = $wpdb->get_var( $wpdb->prepare( "SELECT cat_ID FROM {$wpdb->sitecategories} WHERE category_nicename = %s", $cat_slug ) );
135 if ( $blogroll_id == null ) {
136 $wpdb->insert( $wpdb->sitecategories, array('cat_ID' => 0, 'cat_name' => $cat_name, 'category_nicename' => $cat_slug, 'last_updated' => current_time('mysql', true)) );
137 $blogroll_id = $wpdb->insert_id;
139 update_option('default_link_category', $blogroll_id);
144 $wpdb->insert( $wpdb->terms, array('term_id' => $blogroll_id, 'name' => $cat_name, 'slug' => $cat_slug, 'term_group' => 0) );
145 $wpdb->insert( $wpdb->term_taxonomy, array('term_id' => $blogroll_id, 'taxonomy' => 'link_category', 'description' => '', 'parent' => 0, 'count' => 7));
146 $blogroll_tt_id = $wpdb->insert_id;
148 // Now drop in some default links
149 $default_links = array();
150 $default_links[] = array( 'link_url' => 'http://codex.wordpress.org/',
151 'link_name' => 'Documentation',
155 $default_links[] = array( 'link_url' => 'http://wordpress.org/news/',
156 'link_name' => 'WordPress Blog',
157 'link_rss' => 'http://wordpress.org/news/feed/',
160 $default_links[] = array( 'link_url' => 'http://wordpress.org/extend/ideas/',
161 'link_name' => 'Suggest Ideas',
165 $default_links[] = array( 'link_url' => 'http://wordpress.org/support/',
166 'link_name' => 'Support Forum',
170 $default_links[] = array( 'link_url' => 'http://wordpress.org/extend/plugins/',
171 'link_name' => 'Plugins',
175 $default_links[] = array( 'link_url' => 'http://wordpress.org/extend/themes/',
176 'link_name' => 'Themes',
180 $default_links[] = array( 'link_url' => 'http://planet.wordpress.org/',
181 'link_name' => 'WordPress Planet',
185 foreach ( $default_links as $link ) {
186 $wpdb->insert( $wpdb->links, $link);
187 $wpdb->insert( $wpdb->term_relationships, array('term_taxonomy_id' => $blogroll_tt_id, 'object_id' => $wpdb->insert_id) );
191 $now = date('Y-m-d H:i:s');
192 $now_gmt = gmdate('Y-m-d H:i:s');
193 $first_post_guid = get_option('home') . '/?p=1';
195 if ( is_multisite() ) {
196 $first_post = get_site_option( 'first_post' );
198 if ( empty($first_post) )
199 $first_post = stripslashes( __( 'Welcome to <a href="SITE_URL">SITE_NAME</a>. This is your first post. Edit or delete it, then start blogging!' ) );
201 $first_post = str_replace( "SITE_URL", esc_url( network_home_url() ), $first_post );
202 $first_post = str_replace( "SITE_NAME", $current_site->site_name, $first_post );
204 $first_post = __('Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!');
207 $wpdb->insert( $wpdb->posts, array(
208 'post_author' => $user_id,
210 'post_date_gmt' => $now_gmt,
211 'post_content' => $first_post,
212 'post_excerpt' => '',
213 'post_title' => __('Hello world!'),
214 /* translators: Default post slug */
215 'post_name' => sanitize_title( _x('hello-world', 'Default post slug') ),
216 'post_modified' => $now,
217 'post_modified_gmt' => $now_gmt,
218 'guid' => $first_post_guid,
219 'comment_count' => 1,
222 'post_content_filtered' => ''
224 $wpdb->insert( $wpdb->term_relationships, array('term_taxonomy_id' => $cat_tt_id, 'object_id' => 1) );
227 $first_comment_author = __('Mr WordPress');
228 $first_comment_url = 'http://wordpress.org/';
229 $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.');
230 if ( is_multisite() ) {
231 $first_comment_author = get_site_option( 'first_comment_author', $first_comment_author );
232 $first_comment_url = get_site_option( 'first_comment_url', network_home_url() );
233 $first_comment = get_site_option( 'first_comment', $first_comment );
235 $wpdb->insert( $wpdb->comments, array(
236 'comment_post_ID' => 1,
237 'comment_author' => $first_comment_author,
238 'comment_author_email' => '',
239 'comment_author_url' => $first_comment_url,
240 'comment_date' => $now,
241 'comment_date_gmt' => $now_gmt,
242 'comment_content' => $first_comment
246 $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:
248 <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>
250 ...or something like this:
252 <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>
254 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() );
255 if ( is_multisite() )
256 $first_page = get_site_option( 'first_page', $first_page );
257 $first_post_guid = get_option('home') . '/?page_id=2';
258 $wpdb->insert( $wpdb->posts, array(
259 'post_author' => $user_id,
261 'post_date_gmt' => $now_gmt,
262 'post_content' => $first_page,
263 'post_excerpt' => '',
264 'post_title' => __( 'Sample Page' ),
265 /* translators: Default page slug */
266 'post_name' => __( 'sample-page' ),
267 'post_modified' => $now,
268 'post_modified_gmt' => $now_gmt,
269 'guid' => $first_post_guid,
270 'post_type' => 'page',
273 'post_content_filtered' => ''
275 $wpdb->insert( $wpdb->postmeta, array( 'post_id' => 2, 'meta_key' => '_wp_page_template', 'meta_value' => 'default' ) );
277 // Set up default widgets for default theme.
278 update_option( 'widget_search', array ( 2 => array ( 'title' => '' ), '_multiwidget' => 1 ) );
279 update_option( 'widget_recent-posts', array ( 2 => array ( 'title' => '', 'number' => 5 ), '_multiwidget' => 1 ) );
280 update_option( 'widget_recent-comments', array ( 2 => array ( 'title' => '', 'number' => 5 ), '_multiwidget' => 1 ) );
281 update_option( 'widget_archives', array ( 2 => array ( 'title' => '', 'count' => 0, 'dropdown' => 0 ), '_multiwidget' => 1 ) );
282 update_option( 'widget_categories', array ( 2 => array ( 'title' => '', 'count' => 0, 'hierarchical' => 0, 'dropdown' => 0 ), '_multiwidget' => 1 ) );
283 update_option( 'widget_meta', array ( 2 => array ( 'title' => '' ), '_multiwidget' => 1 ) );
284 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 ) );
286 if ( ! is_multisite() )
287 update_user_meta( $user_id, 'show_welcome_panel', 1 );
288 elseif ( ! is_super_admin( $user_id ) && ! metadata_exists( 'user', $user_id, 'show_welcome_panel' ) )
289 update_user_meta( $user_id, 'show_welcome_panel', 2 );
291 if ( is_multisite() ) {
292 // Flush rules to pick up the new page.
294 $wp_rewrite->flush_rules();
296 $user = new WP_User($user_id);
297 $wpdb->update( $wpdb->options, array('option_value' => $user->user_email), array('option_name' => 'admin_email') );
299 // Remove all perms except for the login user.
300 $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id != %d AND meta_key = %s", $user_id, $table_prefix.'user_level') );
301 $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id != %d AND meta_key = %s", $user_id, $table_prefix.'capabilities') );
303 // Delete any caps that snuck into the previously active blog. (Hardcoded to blog 1 for now.) TODO: Get previous_blog_id.
304 if ( !is_super_admin( $user_id ) && $user_id != 1 )
305 $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id = %d AND meta_key = %s", $user_id, $wpdb->base_prefix.'1_capabilities') );
310 if ( !function_exists('wp_new_blog_notification') ) :
312 * {@internal Missing Short Description}}
314 * {@internal Missing Long Description}}
318 * @param string $blog_title Blog title.
319 * @param string $blog_url Blog url.
320 * @param int $user_id User ID.
321 * @param string $password User's Password.
323 function wp_new_blog_notification($blog_title, $blog_url, $user_id, $password) {
324 $user = new WP_User($user_id);
325 $email = $user->user_email;
326 $name = $user->user_login;
327 $message = sprintf(__("Your new WordPress site has been successfully set up at:
331 You can log in to the administrator account with the following information:
336 We hope you enjoy your new site. Thanks!
339 http://wordpress.org/
340 "), $blog_url, $name, $password);
342 @wp_mail($email, __('New WordPress Site'), $message);
346 if ( !function_exists('wp_upgrade') ) :
348 * Run WordPress Upgrade functions.
350 * {@internal Missing Long Description}}
356 function wp_upgrade() {
357 global $wp_current_db_version, $wp_db_version, $wpdb;
359 $wp_current_db_version = __get_option('db_version');
361 // We are up-to-date. Nothing to do.
362 if ( $wp_db_version == $wp_current_db_version )
365 if ( ! is_blog_installed() )
368 wp_check_mysql_version();
370 pre_schema_upgrade();
371 make_db_current_silent();
373 if ( is_multisite() && is_main_site() )
377 if ( is_multisite() ) {
378 if ( $wpdb->get_row( "SELECT blog_id FROM {$wpdb->blog_versions} WHERE blog_id = '{$wpdb->blogid}'" ) )
379 $wpdb->query( "UPDATE {$wpdb->blog_versions} SET db_version = '{$wp_db_version}' WHERE blog_id = '{$wpdb->blogid}'" );
381 $wpdb->query( "INSERT INTO {$wpdb->blog_versions} ( `blog_id` , `db_version` , `last_updated` ) VALUES ( '{$wpdb->blogid}', '{$wp_db_version}', NOW());" );
387 * Functions to be called in install and upgrade scripts.
389 * {@internal Missing Long Description}}
393 function upgrade_all() {
394 global $wp_current_db_version, $wp_db_version, $wp_rewrite;
395 $wp_current_db_version = __get_option('db_version');
397 // We are up-to-date. Nothing to do.
398 if ( $wp_db_version == $wp_current_db_version )
401 // If the version is not set in the DB, try to guess the version.
402 if ( empty($wp_current_db_version) ) {
403 $wp_current_db_version = 0;
405 // If the template option exists, we have 1.5.
406 $template = __get_option('template');
407 if ( !empty($template) )
408 $wp_current_db_version = 2541;
411 if ( $wp_current_db_version < 6039 )
412 upgrade_230_options_table();
416 if ( $wp_current_db_version < 2541 ) {
423 if ( $wp_current_db_version < 3308 )
426 if ( $wp_current_db_version < 4772 )
429 if ( $wp_current_db_version < 4351 )
432 if ( $wp_current_db_version < 5539 )
435 if ( $wp_current_db_version < 6124 )
436 upgrade_230_old_tables();
438 if ( $wp_current_db_version < 7499 )
441 if ( $wp_current_db_version < 7935 )
444 if ( $wp_current_db_version < 8201 )
447 if ( $wp_current_db_version < 8989 )
450 if ( $wp_current_db_version < 10360 )
453 if ( $wp_current_db_version < 11958 )
456 if ( $wp_current_db_version < 15260 )
459 if ( $wp_current_db_version < 19389 )
462 maybe_disable_automattic_widgets();
464 update_option( 'db_version', $wp_db_version );
465 update_option( 'db_upgraded', true );
469 * Execute changes made in WordPress 1.0.
473 function upgrade_100() {
476 // Get the title and ID of every post, post_name to check if it already has a value
477 $posts = $wpdb->get_results("SELECT ID, post_title, post_name FROM $wpdb->posts WHERE post_name = ''");
479 foreach($posts as $post) {
480 if ('' == $post->post_name) {
481 $newtitle = sanitize_title($post->post_title);
482 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_name = %s WHERE ID = %d", $newtitle, $post->ID) );
487 $categories = $wpdb->get_results("SELECT cat_ID, cat_name, category_nicename FROM $wpdb->categories");
488 foreach ($categories as $category) {
489 if ('' == $category->category_nicename) {
490 $newtitle = sanitize_title($category->cat_name);
491 $wpdb>update( $wpdb->categories, array('category_nicename' => $newtitle), array('cat_ID' => $category->cat_ID) );
495 $wpdb->query("UPDATE $wpdb->options SET option_value = REPLACE(option_value, 'wp-links/links-images/', 'wp-images/links/')
496 WHERE option_name LIKE 'links_rating_image%'
497 AND option_value LIKE 'wp-links/links-images/%'");
499 $done_ids = $wpdb->get_results("SELECT DISTINCT post_id FROM $wpdb->post2cat");
501 foreach ($done_ids as $done_id) :
502 $done_posts[] = $done_id->post_id;
504 $catwhere = ' AND ID NOT IN (' . implode(',', $done_posts) . ')';
509 $allposts = $wpdb->get_results("SELECT ID, post_category FROM $wpdb->posts WHERE post_category != '0' $catwhere");
511 foreach ($allposts as $post) {
512 // Check to see if it's already been imported
513 $cat = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->post2cat WHERE post_id = %d AND category_id = %d", $post->ID, $post->post_category) );
514 if (!$cat && 0 != $post->post_category) { // If there's no result
515 $wpdb->insert( $wpdb->post2cat, array('post_id' => $post->ID, 'category_id' => $post->post_category) );
522 * Execute changes made in WordPress 1.0.1.
526 function upgrade_101() {
529 // Clean up indices, add a few
530 add_clean_index($wpdb->posts, 'post_name');
531 add_clean_index($wpdb->posts, 'post_status');
532 add_clean_index($wpdb->categories, 'category_nicename');
533 add_clean_index($wpdb->comments, 'comment_approved');
534 add_clean_index($wpdb->comments, 'comment_post_ID');
535 add_clean_index($wpdb->links , 'link_category');
536 add_clean_index($wpdb->links , 'link_visible');
540 * Execute changes made in WordPress 1.2.
544 function upgrade_110() {
547 // Set user_nicename.
548 $users = $wpdb->get_results("SELECT ID, user_nickname, user_nicename FROM $wpdb->users");
549 foreach ($users as $user) {
550 if ('' == $user->user_nicename) {
551 $newname = sanitize_title($user->user_nickname);
552 $wpdb->update( $wpdb->users, array('user_nicename' => $newname), array('ID' => $user->ID) );
556 $users = $wpdb->get_results("SELECT ID, user_pass from $wpdb->users");
557 foreach ($users as $row) {
558 if (!preg_match('/^[A-Fa-f0-9]{32}$/', $row->user_pass)) {
559 $wpdb->update( $wpdb->users, array('user_pass' => md5($row->user_pass)), array('ID' => $row->ID) );
563 // Get the GMT offset, we'll use that later on
564 $all_options = get_alloptions_110();
566 $time_difference = $all_options->time_difference;
568 $server_time = time()+date('Z');
569 $weblogger_time = $server_time + $time_difference*3600;
572 $diff_gmt_server = ($gmt_time - $server_time) / 3600;
573 $diff_weblogger_server = ($weblogger_time - $server_time) / 3600;
574 $diff_gmt_weblogger = $diff_gmt_server - $diff_weblogger_server;
575 $gmt_offset = -$diff_gmt_weblogger;
577 // Add a gmt_offset option, with value $gmt_offset
578 add_option('gmt_offset', $gmt_offset);
580 // Check if we already set the GMT fields (if we did, then
581 // MAX(post_date_gmt) can't be '0000-00-00 00:00:00'
582 // <michel_v> I just slapped myself silly for not thinking about it earlier
583 $got_gmt_fields = ! ($wpdb->get_var("SELECT MAX(post_date_gmt) FROM $wpdb->posts") == '0000-00-00 00:00:00');
585 if (!$got_gmt_fields) {
587 // Add or subtract time to all dates, to get GMT dates
588 $add_hours = intval($diff_gmt_weblogger);
589 $add_minutes = intval(60 * ($diff_gmt_weblogger - $add_hours));
590 $wpdb->query("UPDATE $wpdb->posts SET post_date_gmt = DATE_ADD(post_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
591 $wpdb->query("UPDATE $wpdb->posts SET post_modified = post_date");
592 $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'");
593 $wpdb->query("UPDATE $wpdb->comments SET comment_date_gmt = DATE_ADD(comment_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
594 $wpdb->query("UPDATE $wpdb->users SET user_registered = DATE_ADD(user_registered, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
600 * Execute changes made in WordPress 1.5.
604 function upgrade_130() {
607 // Remove extraneous backslashes.
608 $posts = $wpdb->get_results("SELECT ID, post_title, post_content, post_excerpt, guid, post_date, post_name, post_status, post_author FROM $wpdb->posts");
610 foreach($posts as $post) {
611 $post_content = addslashes(deslash($post->post_content));
612 $post_title = addslashes(deslash($post->post_title));
613 $post_excerpt = addslashes(deslash($post->post_excerpt));
614 if ( empty($post->guid) )
615 $guid = get_permalink($post->ID);
619 $wpdb->update( $wpdb->posts, compact('post_title', 'post_content', 'post_excerpt', 'guid'), array('ID' => $post->ID) );
624 // Remove extraneous backslashes.
625 $comments = $wpdb->get_results("SELECT comment_ID, comment_author, comment_content FROM $wpdb->comments");
627 foreach($comments as $comment) {
628 $comment_content = deslash($comment->comment_content);
629 $comment_author = deslash($comment->comment_author);
631 $wpdb->update($wpdb->comments, compact('comment_content', 'comment_author'), array('comment_ID' => $comment->comment_ID) );
635 // Remove extraneous backslashes.
636 $links = $wpdb->get_results("SELECT link_id, link_name, link_description FROM $wpdb->links");
638 foreach($links as $link) {
639 $link_name = deslash($link->link_name);
640 $link_description = deslash($link->link_description);
642 $wpdb->update( $wpdb->links, compact('link_name', 'link_description'), array('link_id' => $link->link_id) );
646 $active_plugins = __get_option('active_plugins');
648 // If plugins are not stored in an array, they're stored in the old
649 // newline separated format. Convert to new format.
650 if ( !is_array( $active_plugins ) ) {
651 $active_plugins = explode("\n", trim($active_plugins));
652 update_option('active_plugins', $active_plugins);
656 $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optionvalues');
657 $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiontypes');
658 $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiongroups');
659 $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiongroup_options');
661 // Update comments table to use comment_type
662 $wpdb->query("UPDATE $wpdb->comments SET comment_type='trackback', comment_content = REPLACE(comment_content, '<trackback />', '') WHERE comment_content LIKE '<trackback />%'");
663 $wpdb->query("UPDATE $wpdb->comments SET comment_type='pingback', comment_content = REPLACE(comment_content, '<pingback />', '') WHERE comment_content LIKE '<pingback />%'");
665 // Some versions have multiple duplicate option_name rows with the same values
666 $options = $wpdb->get_results("SELECT option_name, COUNT(option_name) AS dupes FROM `$wpdb->options` GROUP BY option_name");
667 foreach ( $options as $option ) {
668 if ( 1 != $option->dupes ) { // Could this be done in the query?
669 $limit = $option->dupes - 1;
670 $dupe_ids = $wpdb->get_col( $wpdb->prepare("SELECT option_id FROM $wpdb->options WHERE option_name = %s LIMIT %d", $option->option_name, $limit) );
672 $dupe_ids = join($dupe_ids, ',');
673 $wpdb->query("DELETE FROM $wpdb->options WHERE option_id IN ($dupe_ids)");
682 * Execute changes made in WordPress 2.0.
686 function upgrade_160() {
687 global $wpdb, $wp_current_db_version;
689 populate_roles_160();
691 $users = $wpdb->get_results("SELECT * FROM $wpdb->users");
692 foreach ( $users as $user ) :
693 if ( !empty( $user->user_firstname ) )
694 update_user_meta( $user->ID, 'first_name', $wpdb->escape($user->user_firstname) );
695 if ( !empty( $user->user_lastname ) )
696 update_user_meta( $user->ID, 'last_name', $wpdb->escape($user->user_lastname) );
697 if ( !empty( $user->user_nickname ) )
698 update_user_meta( $user->ID, 'nickname', $wpdb->escape($user->user_nickname) );
699 if ( !empty( $user->user_level ) )
700 update_user_meta( $user->ID, $wpdb->prefix . 'user_level', $user->user_level );
701 if ( !empty( $user->user_icq ) )
702 update_user_meta( $user->ID, 'icq', $wpdb->escape($user->user_icq) );
703 if ( !empty( $user->user_aim ) )
704 update_user_meta( $user->ID, 'aim', $wpdb->escape($user->user_aim) );
705 if ( !empty( $user->user_msn ) )
706 update_user_meta( $user->ID, 'msn', $wpdb->escape($user->user_msn) );
707 if ( !empty( $user->user_yim ) )
708 update_user_meta( $user->ID, 'yim', $wpdb->escape($user->user_icq) );
709 if ( !empty( $user->user_description ) )
710 update_user_meta( $user->ID, 'description', $wpdb->escape($user->user_description) );
712 if ( isset( $user->user_idmode ) ):
713 $idmode = $user->user_idmode;
714 if ($idmode == 'nickname') $id = $user->user_nickname;
715 if ($idmode == 'login') $id = $user->user_login;
716 if ($idmode == 'firstname') $id = $user->user_firstname;
717 if ($idmode == 'lastname') $id = $user->user_lastname;
718 if ($idmode == 'namefl') $id = $user->user_firstname.' '.$user->user_lastname;
719 if ($idmode == 'namelf') $id = $user->user_lastname.' '.$user->user_firstname;
720 if (!$idmode) $id = $user->user_nickname;
721 $wpdb->update( $wpdb->users, array('display_name' => $id), array('ID' => $user->ID) );
724 // FIXME: RESET_CAPS is temporary code to reset roles and caps if flag is set.
725 $caps = get_user_meta( $user->ID, $wpdb->prefix . 'capabilities');
726 if ( empty($caps) || defined('RESET_CAPS') ) {
727 $level = get_user_meta($user->ID, $wpdb->prefix . 'user_level', true);
728 $role = translate_level_to_role($level);
729 update_user_meta( $user->ID, $wpdb->prefix . 'capabilities', array($role => true) );
733 $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' );
734 $wpdb->hide_errors();
735 foreach ( $old_user_fields as $old )
736 $wpdb->query("ALTER TABLE $wpdb->users DROP $old");
737 $wpdb->show_errors();
739 // populate comment_count field of posts table
740 $comments = $wpdb->get_results( "SELECT comment_post_ID, COUNT(*) as c FROM $wpdb->comments WHERE comment_approved = '1' GROUP BY comment_post_ID" );
741 if ( is_array( $comments ) )
742 foreach ($comments as $comment)
743 $wpdb->update( $wpdb->posts, array('comment_count' => $comment->c), array('ID' => $comment->comment_post_ID) );
745 // Some alpha versions used a post status of object instead of attachment and put
746 // the mime type in post_type instead of post_mime_type.
747 if ( $wp_current_db_version > 2541 && $wp_current_db_version <= 3091 ) {
748 $objects = $wpdb->get_results("SELECT ID, post_type FROM $wpdb->posts WHERE post_status = 'object'");
749 foreach ($objects as $object) {
750 $wpdb->update( $wpdb->posts, array( 'post_status' => 'attachment',
751 'post_mime_type' => $object->post_type,
753 array( 'ID' => $object->ID ) );
755 $meta = get_post_meta($object->ID, 'imagedata', true);
756 if ( ! empty($meta['file']) )
757 update_attached_file( $object->ID, $meta['file'] );
763 * Execute changes made in WordPress 2.1.
767 function upgrade_210() {
768 global $wpdb, $wp_current_db_version;
770 if ( $wp_current_db_version < 3506 ) {
771 // Update status and type.
772 $posts = $wpdb->get_results("SELECT ID, post_status FROM $wpdb->posts");
774 if ( ! empty($posts) ) foreach ($posts as $post) {
775 $status = $post->post_status;
778 if ( 'static' == $status ) {
781 } else if ( 'attachment' == $status ) {
783 $type = 'attachment';
786 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_status = %s, post_type = %s WHERE ID = %d", $status, $type, $post->ID) );
790 if ( $wp_current_db_version < 3845 ) {
791 populate_roles_210();
794 if ( $wp_current_db_version < 3531 ) {
795 // Give future posts a post_status of future.
796 $now = gmdate('Y-m-d H:i:59');
797 $wpdb->query ("UPDATE $wpdb->posts SET post_status = 'future' WHERE post_status = 'publish' AND post_date_gmt > '$now'");
799 $posts = $wpdb->get_results("SELECT ID, post_date FROM $wpdb->posts WHERE post_status ='future'");
800 if ( !empty($posts) )
801 foreach ( $posts as $post )
802 wp_schedule_single_event(mysql2date('U', $post->post_date, false), 'publish_future_post', array($post->ID));
807 * Execute changes made in WordPress 2.3.
811 function upgrade_230() {
812 global $wp_current_db_version, $wpdb;
814 if ( $wp_current_db_version < 5200 ) {
815 populate_roles_230();
818 // Convert categories to terms.
821 $categories = $wpdb->get_results("SELECT * FROM $wpdb->categories ORDER BY cat_ID");
822 foreach ($categories as $category) {
823 $term_id = (int) $category->cat_ID;
824 $name = $category->cat_name;
825 $description = $category->category_description;
826 $slug = $category->category_nicename;
827 $parent = $category->category_parent;
830 // Associate terms with the same slug in a term group and make slugs unique.
831 if ( $exists = $wpdb->get_results( $wpdb->prepare("SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $slug) ) ) {
832 $term_group = $exists[0]->term_group;
833 $id = $exists[0]->term_id;
836 $alt_slug = $slug . "-$num";
838 $slug_check = $wpdb->get_var( $wpdb->prepare("SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug) );
839 } while ( $slug_check );
843 if ( empty( $term_group ) ) {
844 $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms GROUP BY term_group") + 1;
845 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->terms SET term_group = %d WHERE term_id = %d", $term_group, $id) );
849 $wpdb->query( $wpdb->prepare("INSERT INTO $wpdb->terms (term_id, name, slug, term_group) VALUES
850 (%d, %s, %s, %d)", $term_id, $name, $slug, $term_group) );
853 if ( !empty($category->category_count) ) {
854 $count = (int) $category->category_count;
855 $taxonomy = 'category';
856 $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) );
857 $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
860 if ( !empty($category->link_count) ) {
861 $count = (int) $category->link_count;
862 $taxonomy = 'link_category';
863 $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) );
864 $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
867 if ( !empty($category->tag_count) ) {
869 $count = (int) $category->tag_count;
870 $taxonomy = 'post_tag';
871 $wpdb->insert( $wpdb->term_taxonomy, compact('term_id', 'taxonomy', 'description', 'parent', 'count') );
872 $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
875 if ( empty($count) ) {
877 $taxonomy = 'category';
878 $wpdb->insert( $wpdb->term_taxonomy, compact('term_id', 'taxonomy', 'description', 'parent', 'count') );
879 $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
883 $select = 'post_id, category_id';
885 $select .= ', rel_type';
887 $posts = $wpdb->get_results("SELECT $select FROM $wpdb->post2cat GROUP BY post_id, category_id");
888 foreach ( $posts as $post ) {
889 $post_id = (int) $post->post_id;
890 $term_id = (int) $post->category_id;
891 $taxonomy = 'category';
892 if ( !empty($post->rel_type) && 'tag' == $post->rel_type)
894 $tt_id = $tt_ids[$term_id][$taxonomy];
898 $wpdb->insert( $wpdb->term_relationships, array('object_id' => $post_id, 'term_taxonomy_id' => $tt_id) );
901 // < 3570 we used linkcategories. >= 3570 we used categories and link2cat.
902 if ( $wp_current_db_version < 3570 ) {
903 // Create link_category terms for link categories. Create a map of link cat IDs
904 // to link_category terms.
905 $link_cat_id_map = array();
906 $default_link_cat = 0;
908 $link_cats = $wpdb->get_results("SELECT cat_id, cat_name FROM " . $wpdb->prefix . 'linkcategories');
909 foreach ( $link_cats as $category) {
910 $cat_id = (int) $category->cat_id;
912 $name = $wpdb->escape($category->cat_name);
913 $slug = sanitize_title($name);
916 // Associate terms with the same slug in a term group and make slugs unique.
917 if ( $exists = $wpdb->get_results( $wpdb->prepare("SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $slug) ) ) {
918 $term_group = $exists[0]->term_group;
919 $term_id = $exists[0]->term_id;
922 if ( empty($term_id) ) {
923 $wpdb->insert( $wpdb->terms, compact('name', 'slug', 'term_group') );
924 $term_id = (int) $wpdb->insert_id;
927 $link_cat_id_map[$cat_id] = $term_id;
928 $default_link_cat = $term_id;
930 $wpdb->insert( $wpdb->term_taxonomy, array('term_id' => $term_id, 'taxonomy' => 'link_category', 'description' => '', 'parent' => 0, 'count' => 0) );
931 $tt_ids[$term_id] = (int) $wpdb->insert_id;
934 // Associate links to cats.
935 $links = $wpdb->get_results("SELECT link_id, link_category FROM $wpdb->links");
936 if ( !empty($links) ) foreach ( $links as $link ) {
937 if ( 0 == $link->link_category )
939 if ( ! isset($link_cat_id_map[$link->link_category]) )
941 $term_id = $link_cat_id_map[$link->link_category];
942 $tt_id = $tt_ids[$term_id];
946 $wpdb->insert( $wpdb->term_relationships, array('object_id' => $link->link_id, 'term_taxonomy_id' => $tt_id) );
949 // Set default to the last category we grabbed during the upgrade loop.
950 update_option('default_link_category', $default_link_cat);
952 $links = $wpdb->get_results("SELECT link_id, category_id FROM $wpdb->link2cat GROUP BY link_id, category_id");
953 foreach ( $links as $link ) {
954 $link_id = (int) $link->link_id;
955 $term_id = (int) $link->category_id;
956 $taxonomy = 'link_category';
957 $tt_id = $tt_ids[$term_id][$taxonomy];
960 $wpdb->insert( $wpdb->term_relationships, array('object_id' => $link_id, 'term_taxonomy_id' => $tt_id) );
964 if ( $wp_current_db_version < 4772 ) {
965 // Obsolete linkcategories table
966 $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'linkcategories');
969 // Recalculate all counts
970 $terms = $wpdb->get_results("SELECT term_taxonomy_id, taxonomy FROM $wpdb->term_taxonomy");
971 foreach ( (array) $terms as $term ) {
972 if ( ('post_tag' == $term->taxonomy) || ('category' == $term->taxonomy) )
973 $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) );
975 $count = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term->term_taxonomy_id) );
976 $wpdb->update( $wpdb->term_taxonomy, array('count' => $count), array('term_taxonomy_id' => $term->term_taxonomy_id) );
981 * Remove old options from the database.
985 function upgrade_230_options_table() {
987 $old_options_fields = array( 'option_can_override', 'option_type', 'option_width', 'option_height', 'option_description', 'option_admin_level' );
988 $wpdb->hide_errors();
989 foreach ( $old_options_fields as $old )
990 $wpdb->query("ALTER TABLE $wpdb->options DROP $old");
991 $wpdb->show_errors();
995 * Remove old categories, link2cat, and post2cat database tables.
999 function upgrade_230_old_tables() {
1001 $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'categories');
1002 $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'link2cat');
1003 $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'post2cat');
1007 * Upgrade old slugs made in version 2.2.
1011 function upgrade_old_slugs() {
1012 // upgrade people who were using the Redirect Old Slugs plugin
1014 $wpdb->query("UPDATE $wpdb->postmeta SET meta_key = '_wp_old_slug' WHERE meta_key = 'old_slug'");
1018 * Execute changes made in WordPress 2.5.0.
1022 function upgrade_250() {
1023 global $wp_current_db_version;
1025 if ( $wp_current_db_version < 6689 ) {
1026 populate_roles_250();
1032 * Execute changes made in WordPress 2.5.2.
1036 function upgrade_252() {
1039 $wpdb->query("UPDATE $wpdb->users SET user_activation_key = ''");
1043 * Execute changes made in WordPress 2.6.
1047 function upgrade_260() {
1048 global $wp_current_db_version;
1050 if ( $wp_current_db_version < 8000 )
1051 populate_roles_260();
1053 if ( $wp_current_db_version < 8201 ) {
1054 update_option('enable_app', 1);
1055 update_option('enable_xmlrpc', 1);
1060 * Execute changes made in WordPress 2.7.
1064 function upgrade_270() {
1065 global $wpdb, $wp_current_db_version;
1067 if ( $wp_current_db_version < 8980 )
1068 populate_roles_270();
1070 // Update post_date for unpublished posts with empty timestamp
1071 if ( $wp_current_db_version < 8921 )
1072 $wpdb->query( "UPDATE $wpdb->posts SET post_date = post_modified WHERE post_date = '0000-00-00 00:00:00'" );
1076 * Execute changes made in WordPress 2.8.
1080 function upgrade_280() {
1081 global $wp_current_db_version, $wpdb;
1083 if ( $wp_current_db_version < 10360 )
1084 populate_roles_280();
1085 if ( is_multisite() ) {
1087 while( $rows = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options ORDER BY option_id LIMIT $start, 20" ) ) {
1088 foreach( $rows as $row ) {
1089 $value = $row->option_value;
1090 if ( !@unserialize( $value ) )
1091 $value = stripslashes( $value );
1092 if ( $value !== $row->option_value ) {
1093 update_option( $row->option_name, $value );
1098 refresh_blog_details( $wpdb->blogid );
1103 * Execute changes made in WordPress 2.9.
1107 function upgrade_290() {
1108 global $wp_current_db_version;
1110 if ( $wp_current_db_version < 11958 ) {
1111 // Previously, setting depth to 1 would redundantly disable threading, but now 2 is the minimum depth to avoid confusion
1112 if ( get_option( 'thread_comments_depth' ) == '1' ) {
1113 update_option( 'thread_comments_depth', 2 );
1114 update_option( 'thread_comments', 0 );
1120 * Execute changes made in WordPress 3.0.
1124 function upgrade_300() {
1125 global $wp_current_db_version, $wpdb;
1127 if ( $wp_current_db_version < 15093 )
1128 populate_roles_300();
1130 if ( $wp_current_db_version < 14139 && is_multisite() && is_main_site() && ! defined( 'MULTISITE' ) && get_site_option( 'siteurl' ) === false )
1131 add_site_option( 'siteurl', '' );
1133 // 3.0 screen options key name changes.
1134 if ( is_main_site() && !defined('DO_NOT_UPGRADE_GLOBAL_TABLES') ) {
1135 $prefix = like_escape($wpdb->base_prefix);
1136 $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%'
1137 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'" );
1143 * Execute changes made in WordPress 3.3.
1147 function upgrade_330() {
1148 global $wp_current_db_version, $wpdb, $wp_registered_widgets, $sidebars_widgets;
1150 if ( $wp_current_db_version < 19061 && is_main_site() && ! defined( 'DO_NOT_UPGRADE_GLOBAL_TABLES' ) ) {
1151 $wpdb->query( "DELETE FROM $wpdb->usermeta WHERE meta_key IN ('show_admin_bar_admin', 'plugins_last_view')" );
1154 // 3.3-beta. Can remove before release.
1155 if ( $wp_current_db_version > 18715 && $wp_current_db_version < 19389
1156 && is_main_site() && ! defined( 'DO_NOT_UPGRADE_GLOBAL_TABLES' ) )
1157 delete_metadata( 'user', 0, 'dismissed_wp_pointers', '', true );
1159 if ( $wp_current_db_version >= 11548 )
1162 $sidebars_widgets = get_option( 'sidebars_widgets', array() );
1163 $_sidebars_widgets = array();
1165 if ( isset($sidebars_widgets['wp_inactive_widgets']) || empty($sidebars_widgets) )
1166 $sidebars_widgets['array_version'] = 3;
1167 elseif ( !isset($sidebars_widgets['array_version']) )
1168 $sidebars_widgets['array_version'] = 1;
1170 switch ( $sidebars_widgets['array_version'] ) {
1172 foreach ( (array) $sidebars_widgets as $index => $sidebar )
1173 if ( is_array($sidebar) )
1174 foreach ( (array) $sidebar as $i => $name ) {
1175 $id = strtolower($name);
1176 if ( isset($wp_registered_widgets[$id]) ) {
1177 $_sidebars_widgets[$index][$i] = $id;
1180 $id = sanitize_title($name);
1181 if ( isset($wp_registered_widgets[$id]) ) {
1182 $_sidebars_widgets[$index][$i] = $id;
1188 foreach ( $wp_registered_widgets as $widget_id => $widget ) {
1189 if ( strtolower($widget['name']) == strtolower($name) ) {
1190 $_sidebars_widgets[$index][$i] = $widget['id'];
1193 } elseif ( sanitize_title($widget['name']) == sanitize_title($name) ) {
1194 $_sidebars_widgets[$index][$i] = $widget['id'];
1203 unset($_sidebars_widgets[$index][$i]);
1205 $_sidebars_widgets['array_version'] = 2;
1206 $sidebars_widgets = $_sidebars_widgets;
1207 unset($_sidebars_widgets);
1210 $sidebars_widgets = retrieve_widgets();
1211 $sidebars_widgets['array_version'] = 3;
1212 update_option( 'sidebars_widgets', $sidebars_widgets );
1217 * Execute network level changes
1221 function upgrade_network() {
1222 global $wp_current_db_version, $wpdb;
1224 if ( $wp_current_db_version < 11549 ) {
1225 $wpmu_sitewide_plugins = get_site_option( 'wpmu_sitewide_plugins' );
1226 $active_sitewide_plugins = get_site_option( 'active_sitewide_plugins' );
1227 if ( $wpmu_sitewide_plugins ) {
1228 if ( !$active_sitewide_plugins )
1229 $sitewide_plugins = (array) $wpmu_sitewide_plugins;
1231 $sitewide_plugins = array_merge( (array) $active_sitewide_plugins, (array) $wpmu_sitewide_plugins );
1233 update_site_option( 'active_sitewide_plugins', $sitewide_plugins );
1235 delete_site_option( 'wpmu_sitewide_plugins' );
1236 delete_site_option( 'deactivated_sitewide_plugins' );
1239 while( $rows = $wpdb->get_results( "SELECT meta_key, meta_value FROM {$wpdb->sitemeta} ORDER BY meta_id LIMIT $start, 20" ) ) {
1240 foreach( $rows as $row ) {
1241 $value = $row->meta_value;
1242 if ( !@unserialize( $value ) )
1243 $value = stripslashes( $value );
1244 if ( $value !== $row->meta_value ) {
1245 update_site_option( $row->meta_key, $value );
1252 if ( $wp_current_db_version < 13576 )
1253 update_site_option( 'global_terms_enabled', '1' );
1255 if ( $wp_current_db_version < 19390 )
1256 update_site_option( 'initial_db_version', $wp_current_db_version );
1257 if ( $wp_current_db_version < 19470 ) {
1258 if ( false === get_site_option( 'active_sitewide_plugins' ) )
1259 update_site_option( 'active_sitewide_plugins', array() );
1263 // The functions we use to actually do stuff
1268 * {@internal Missing Short Description}}
1270 * {@internal Missing Long Description}}
1274 * @param string $table_name Database table name to create.
1275 * @param string $create_ddl SQL statement to create table.
1276 * @return bool If table already exists or was created by function.
1278 function maybe_create_table($table_name, $create_ddl) {
1280 if ( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") == $table_name )
1282 //didn't find it try to create it.
1283 $q = $wpdb->query($create_ddl);
1284 // we cannot directly tell that whether this succeeded!
1285 if ( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") == $table_name )
1291 * {@internal Missing Short Description}}
1293 * {@internal Missing Long Description}}
1297 * @param string $table Database table name.
1298 * @param string $index Index name to drop.
1299 * @return bool True, when finished.
1301 function drop_index($table, $index) {
1303 $wpdb->hide_errors();
1304 $wpdb->query("ALTER TABLE `$table` DROP INDEX `$index`");
1305 // Now we need to take out all the extra ones we may have created
1306 for ($i = 0; $i < 25; $i++) {
1307 $wpdb->query("ALTER TABLE `$table` DROP INDEX `{$index}_$i`");
1309 $wpdb->show_errors();
1314 * {@internal Missing Short Description}}
1316 * {@internal Missing Long Description}}
1320 * @param string $table Database table name.
1321 * @param string $index Database table index column.
1322 * @return bool True, when done with execution.
1324 function add_clean_index($table, $index) {
1326 drop_index($table, $index);
1327 $wpdb->query("ALTER TABLE `$table` ADD INDEX ( `$index` )");
1332 ** maybe_add_column()
1333 ** Add column to db table if it doesn't exist.
1334 ** Returns: true if already exists or on successful completion
1337 function maybe_add_column($table_name, $column_name, $create_ddl) {
1338 global $wpdb, $debug;
1339 foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) {
1340 if ($debug) echo("checking $column == $column_name<br />");
1341 if ($column == $column_name) {
1345 //didn't find it try to create it.
1346 $q = $wpdb->query($create_ddl);
1347 // we cannot directly tell that whether this succeeded!
1348 foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) {
1349 if ($column == $column_name) {
1357 * Retrieve all options as it was for 1.2.
1361 * @return array List of options.
1363 function get_alloptions_110() {
1365 if ($options = $wpdb->get_results("SELECT option_name, option_value FROM $wpdb->options")) {
1366 foreach ($options as $option) {
1367 // "When trying to design a foolproof system,
1368 // never underestimate the ingenuity of the fools :)" -- Dougal
1369 if ('siteurl' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value);
1370 if ('home' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value);
1371 if ('category_base' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value);
1372 $all_options->{$option->option_name} = stripslashes($option->option_value);
1375 return $all_options;
1379 * Version of get_option that is private to install/upgrade.
1384 * @param string $setting Option name.
1387 function __get_option($setting) {
1390 if ( $setting == 'home' && defined( 'WP_HOME' ) ) {
1391 return preg_replace( '|/+$|', '', WP_HOME );
1394 if ( $setting == 'siteurl' && defined( 'WP_SITEURL' ) ) {
1395 return preg_replace( '|/+$|', '', WP_SITEURL );
1398 $option = $wpdb->get_var( $wpdb->prepare("SELECT option_value FROM $wpdb->options WHERE option_name = %s", $setting) );
1400 if ( 'home' == $setting && '' == $option )
1401 return __get_option('siteurl');
1403 if ( 'siteurl' == $setting || 'home' == $setting || 'category_base' == $setting )
1404 $option = preg_replace('|/+$|', '', $option);
1406 @ $kellogs = unserialize($option);
1407 if ($kellogs !== FALSE)
1414 * {@internal Missing Short Description}}
1416 * {@internal Missing Long Description}}
1420 * @param string $content
1423 function deslash($content) {
1424 // Note: \\\ inside a regex denotes a single backslash.
1426 // Replace one or more backslashes followed by a single quote with
1428 $content = preg_replace("/\\\+'/", "'", $content);
1430 // Replace one or more backslashes followed by a double quote with
1432 $content = preg_replace('/\\\+"/', '"', $content);
1434 // Replace one or more backslashes with one backslash.
1435 $content = preg_replace("/\\\+/", "\\", $content);
1441 * {@internal Missing Short Description}}
1443 * {@internal Missing Long Description}}
1447 * @param unknown_type $queries
1448 * @param unknown_type $execute
1451 function dbDelta( $queries = '', $execute = true ) {
1454 if ( in_array( $queries, array( '', 'all', 'blog', 'global', 'ms_global' ), true ) )
1455 $queries = wp_get_db_schema( $queries );
1457 // Separate individual queries into an array
1458 if ( !is_array($queries) ) {
1459 $queries = explode( ';', $queries );
1460 if ('' == $queries[count($queries) - 1]) array_pop($queries);
1462 $queries = apply_filters( 'dbdelta_queries', $queries );
1464 $cqueries = array(); // Creation Queries
1465 $iqueries = array(); // Insertion Queries
1466 $for_update = array();
1468 // Create a tablename index for an array ($cqueries) of queries
1469 foreach($queries as $qry) {
1470 if (preg_match("|CREATE TABLE ([^ ]*)|", $qry, $matches)) {
1471 $cqueries[trim( strtolower($matches[1]), '`' )] = $qry;
1472 $for_update[$matches[1]] = 'Created table '.$matches[1];
1473 } else if (preg_match("|CREATE DATABASE ([^ ]*)|", $qry, $matches)) {
1474 array_unshift($cqueries, $qry);
1475 } else if (preg_match("|INSERT INTO ([^ ]*)|", $qry, $matches)) {
1477 } else if (preg_match("|UPDATE ([^ ]*)|", $qry, $matches)) {
1480 // Unrecognized query type
1483 $cqueries = apply_filters( 'dbdelta_create_queries', $cqueries );
1484 $iqueries = apply_filters( 'dbdelta_insert_queries', $iqueries );
1486 $global_tables = $wpdb->tables( 'global' );
1487 foreach ( $cqueries as $table => $qry ) {
1488 // Upgrade global tables only for the main site. Don't upgrade at all if DO_NOT_UPGRADE_GLOBAL_TABLES is defined.
1489 if ( in_array( $table, $global_tables ) && ( !is_main_site() || defined( 'DO_NOT_UPGRADE_GLOBAL_TABLES' ) ) )
1492 // Fetch the table column structure from the database
1493 $wpdb->suppress_errors();
1494 $tablefields = $wpdb->get_results("DESCRIBE {$table};");
1495 $wpdb->suppress_errors( false );
1497 if ( ! $tablefields )
1500 // Clear the field and index arrays
1501 $cfields = $indices = array();
1502 // Get all of the field names in the query from between the parens
1503 preg_match("|\((.*)\)|ms", $qry, $match2);
1504 $qryline = trim($match2[1]);
1506 // Separate field lines into an array
1507 $flds = explode("\n", $qryline);
1509 //echo "<hr/><pre>\n".print_r(strtolower($table), true).":\n".print_r($cqueries, true)."</pre><hr/>";
1511 // For every field line specified in the query
1512 foreach ($flds as $fld) {
1513 // Extract the field name
1514 preg_match("|^([^ ]*)|", trim($fld), $fvals);
1515 $fieldname = trim( $fvals[1], '`' );
1517 // Verify the found field name
1519 switch (strtolower($fieldname)) {
1526 $validfield = false;
1527 $indices[] = trim(trim($fld), ", \n");
1532 // If it's a valid field, add it to the field array
1534 $cfields[strtolower($fieldname)] = trim($fld, ", \n");
1538 // For every field in the table
1539 foreach ($tablefields as $tablefield) {
1540 // If the table field exists in the field array...
1541 if (array_key_exists(strtolower($tablefield->Field), $cfields)) {
1542 // Get the field type from the query
1543 preg_match("|".$tablefield->Field." ([^ ]*( unsigned)?)|i", $cfields[strtolower($tablefield->Field)], $matches);
1544 $fieldtype = $matches[1];
1546 // Is actual field type different from the field type in query?
1547 if ($tablefield->Type != $fieldtype) {
1548 // Add a query to change the column type
1549 $cqueries[] = "ALTER TABLE {$table} CHANGE COLUMN {$tablefield->Field} " . $cfields[strtolower($tablefield->Field)];
1550 $for_update[$table.'.'.$tablefield->Field] = "Changed type of {$table}.{$tablefield->Field} from {$tablefield->Type} to {$fieldtype}";
1553 // Get the default value from the array
1554 //echo "{$cfields[strtolower($tablefield->Field)]}<br>";
1555 if (preg_match("| DEFAULT '(.*)'|i", $cfields[strtolower($tablefield->Field)], $matches)) {
1556 $default_value = $matches[1];
1557 if ($tablefield->Default != $default_value) {
1558 // Add a query to change the column's default value
1559 $cqueries[] = "ALTER TABLE {$table} ALTER COLUMN {$tablefield->Field} SET DEFAULT '{$default_value}'";
1560 $for_update[$table.'.'.$tablefield->Field] = "Changed default value of {$table}.{$tablefield->Field} from {$tablefield->Default} to {$default_value}";
1564 // Remove the field from the array (so it's not added)
1565 unset($cfields[strtolower($tablefield->Field)]);
1567 // This field exists in the table, but not in the creation queries?
1571 // For every remaining field specified for the table
1572 foreach ($cfields as $fieldname => $fielddef) {
1573 // Push a query line into $cqueries that adds the field to that table
1574 $cqueries[] = "ALTER TABLE {$table} ADD COLUMN $fielddef";
1575 $for_update[$table.'.'.$fieldname] = 'Added column '.$table.'.'.$fieldname;
1578 // Index stuff goes here
1579 // Fetch the table index structure from the database
1580 $tableindices = $wpdb->get_results("SHOW INDEX FROM {$table};");
1582 if ($tableindices) {
1583 // Clear the index array
1586 // For every index in the table
1587 foreach ($tableindices as $tableindex) {
1588 // Add the index to the index data array
1589 $keyname = $tableindex->Key_name;
1590 $index_ary[$keyname]['columns'][] = array('fieldname' => $tableindex->Column_name, 'subpart' => $tableindex->Sub_part);
1591 $index_ary[$keyname]['unique'] = ($tableindex->Non_unique == 0)?true:false;
1594 // For each actual index in the index array
1595 foreach ($index_ary as $index_name => $index_data) {
1596 // Build a create string to compare to the query
1598 if ($index_name == 'PRIMARY') {
1599 $index_string .= 'PRIMARY ';
1600 } else if($index_data['unique']) {
1601 $index_string .= 'UNIQUE ';
1603 $index_string .= 'KEY ';
1604 if ($index_name != 'PRIMARY') {
1605 $index_string .= $index_name;
1607 $index_columns = '';
1608 // For each column in the index
1609 foreach ($index_data['columns'] as $column_data) {
1610 if ($index_columns != '') $index_columns .= ',';
1611 // Add the field to the column list string
1612 $index_columns .= $column_data['fieldname'];
1613 if ($column_data['subpart'] != '') {
1614 $index_columns .= '('.$column_data['subpart'].')';
1617 // Add the column list to the index create string
1618 $index_string .= ' ('.$index_columns.')';
1619 if (!(($aindex = array_search($index_string, $indices)) === false)) {
1620 unset($indices[$aindex]);
1621 //echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">{$table}:<br />Found index:".$index_string."</pre>\n";
1623 //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";
1627 // For every remaining index specified for the table
1628 foreach ( (array) $indices as $index ) {
1629 // Push a query line into $cqueries that adds the index to that table
1630 $cqueries[] = "ALTER TABLE {$table} ADD $index";
1631 $for_update[$table.'.'.$fieldname] = 'Added index '.$table.' '.$index;
1634 // Remove the original table creation query from processing
1635 unset( $cqueries[ $table ], $for_update[ $table ] );
1638 $allqueries = array_merge($cqueries, $iqueries);
1640 foreach ($allqueries as $query) {
1641 //echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">".print_r($query, true)."</pre>\n";
1642 $wpdb->query($query);
1650 * {@internal Missing Short Description}}
1652 * {@internal Missing Long Description}}
1656 function make_db_current( $tables = 'all' ) {
1657 $alterations = dbDelta( $tables );
1659 foreach($alterations as $alteration) echo "<li>$alteration</li>\n";
1664 * {@internal Missing Short Description}}
1666 * {@internal Missing Long Description}}
1670 function make_db_current_silent( $tables = 'all' ) {
1671 $alterations = dbDelta( $tables );
1675 * {@internal Missing Short Description}}
1677 * {@internal Missing Long Description}}
1681 * @param unknown_type $theme_name
1682 * @param unknown_type $template
1685 function make_site_theme_from_oldschool($theme_name, $template) {
1686 $home_path = get_home_path();
1687 $site_dir = WP_CONTENT_DIR . "/themes/$template";
1689 if (! file_exists("$home_path/index.php"))
1692 // Copy files from the old locations to the site theme.
1693 // TODO: This does not copy arbitrary include dependencies. Only the
1694 // standard WP files are copied.
1695 $files = array('index.php' => 'index.php', 'wp-layout.css' => 'style.css', 'wp-comments.php' => 'comments.php', 'wp-comments-popup.php' => 'comments-popup.php');
1697 foreach ($files as $oldfile => $newfile) {
1698 if ($oldfile == 'index.php')
1699 $oldpath = $home_path;
1703 if ($oldfile == 'index.php') { // Check to make sure it's not a new index
1704 $index = implode('', file("$oldpath/$oldfile"));
1705 if (strpos($index, 'WP_USE_THEMES') !== false) {
1706 if (! @copy(WP_CONTENT_DIR . '/themes/' . WP_DEFAULT_THEME . '/index.php', "$site_dir/$newfile"))
1708 continue; // Don't copy anything
1712 if (! @copy("$oldpath/$oldfile", "$site_dir/$newfile"))
1715 chmod("$site_dir/$newfile", 0777);
1717 // Update the blog header include in each file.
1718 $lines = explode("\n", implode('', file("$site_dir/$newfile")));
1720 $f = fopen("$site_dir/$newfile", 'w');
1722 foreach ($lines as $line) {
1723 if (preg_match('/require.*wp-blog-header/', $line))
1724 $line = '//' . $line;
1726 // Update stylesheet references.
1727 $line = str_replace("<?php echo __get_option('siteurl'); ?>/wp-layout.css", "<?php bloginfo('stylesheet_url'); ?>", $line);
1729 // Update comments template inclusion.
1730 $line = str_replace("<?php include(ABSPATH . 'wp-comments.php'); ?>", "<?php comments_template(); ?>", $line);
1732 fwrite($f, "{$line}\n");
1738 // Add a theme header.
1739 $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";
1741 $stylelines = file_get_contents("$site_dir/style.css");
1743 $f = fopen("$site_dir/style.css", 'w');
1745 fwrite($f, $header);
1746 fwrite($f, $stylelines);
1754 * {@internal Missing Short Description}}
1756 * {@internal Missing Long Description}}
1760 * @param unknown_type $theme_name
1761 * @param unknown_type $template
1764 function make_site_theme_from_default($theme_name, $template) {
1765 $site_dir = WP_CONTENT_DIR . "/themes/$template";
1766 $default_dir = WP_CONTENT_DIR . '/themes/' . WP_DEFAULT_THEME;
1768 // Copy files from the default theme to the site theme.
1769 //$files = array('index.php', 'comments.php', 'comments-popup.php', 'footer.php', 'header.php', 'sidebar.php', 'style.css');
1771 $theme_dir = @ opendir($default_dir);
1773 while(($theme_file = readdir( $theme_dir )) !== false) {
1774 if (is_dir("$default_dir/$theme_file"))
1776 if (! @copy("$default_dir/$theme_file", "$site_dir/$theme_file"))
1778 chmod("$site_dir/$theme_file", 0777);
1781 @closedir($theme_dir);
1783 // Rewrite the theme header.
1784 $stylelines = explode("\n", implode('', file("$site_dir/style.css")));
1786 $f = fopen("$site_dir/style.css", 'w');
1788 foreach ($stylelines as $line) {
1789 if (strpos($line, 'Theme Name:') !== false) $line = 'Theme Name: ' . $theme_name;
1790 elseif (strpos($line, 'Theme URI:') !== false) $line = 'Theme URI: ' . __get_option('url');
1791 elseif (strpos($line, 'Description:') !== false) $line = 'Description: Your theme.';
1792 elseif (strpos($line, 'Version:') !== false) $line = 'Version: 1';
1793 elseif (strpos($line, 'Author:') !== false) $line = 'Author: You';
1794 fwrite($f, $line . "\n");
1801 if (! mkdir("$site_dir/images", 0777)) {
1805 $images_dir = @ opendir("$default_dir/images");
1807 while(($image = readdir($images_dir)) !== false) {
1808 if (is_dir("$default_dir/images/$image"))
1810 if (! @copy("$default_dir/images/$image", "$site_dir/images/$image"))
1812 chmod("$site_dir/images/$image", 0777);
1815 @closedir($images_dir);
1818 // Create a site theme from the default theme.
1820 * {@internal Missing Short Description}}
1822 * {@internal Missing Long Description}}
1828 function make_site_theme() {
1829 // Name the theme after the blog.
1830 $theme_name = __get_option('blogname');
1831 $template = sanitize_title($theme_name);
1832 $site_dir = WP_CONTENT_DIR . "/themes/$template";
1834 // If the theme already exists, nothing to do.
1835 if ( is_dir($site_dir)) {
1839 // We must be able to write to the themes dir.
1840 if (! is_writable(WP_CONTENT_DIR . "/themes")) {
1845 if (! mkdir($site_dir, 0777)) {
1849 if (file_exists(ABSPATH . 'wp-layout.css')) {
1850 if (! make_site_theme_from_oldschool($theme_name, $template)) {
1851 // TODO: rm -rf the site theme directory.
1855 if (! make_site_theme_from_default($theme_name, $template))
1856 // TODO: rm -rf the site theme directory.
1860 // Make the new site theme active.
1861 $current_template = __get_option('template');
1862 if ($current_template == WP_DEFAULT_THEME) {
1863 update_option('template', $template);
1864 update_option('stylesheet', $template);
1870 * Translate user level to user role name.
1874 * @param int $level User level.
1875 * @return string User role name.
1877 function translate_level_to_role($level) {
1882 return 'administrator';
1892 return 'contributor';
1894 return 'subscriber';
1899 * {@internal Missing Short Description}}
1901 * {@internal Missing Long Description}}
1905 function wp_check_mysql_version() {
1907 $result = $wpdb->check_database_version();
1908 if ( is_wp_error( $result ) )
1909 die( $result->get_error_message() );
1913 * {@internal Missing Short Description}}
1915 * {@internal Missing Long Description}}
1919 function maybe_disable_automattic_widgets() {
1920 $plugins = __get_option( 'active_plugins' );
1922 foreach ( (array) $plugins as $plugin ) {
1923 if ( basename( $plugin ) == 'widgets.php' ) {
1924 array_splice( $plugins, array_search( $plugin, $plugins ), 1 );
1925 update_option( 'active_plugins', $plugins );
1932 * Runs before the schema is upgraded.
1936 function pre_schema_upgrade() {
1937 global $wp_current_db_version, $wp_db_version, $wpdb;
1939 // Upgrade versions prior to 2.9
1940 if ( $wp_current_db_version < 11557 ) {
1941 // Delete duplicate options. Keep the option with the highest option_id.
1942 $wpdb->query("DELETE o1 FROM $wpdb->options AS o1 JOIN $wpdb->options AS o2 USING (`option_name`) WHERE o2.option_id > o1.option_id");
1944 // Drop the old primary key and add the new.
1945 $wpdb->query("ALTER TABLE $wpdb->options DROP PRIMARY KEY, ADD PRIMARY KEY(option_id)");
1947 // Drop the old option_name index. dbDelta() doesn't do the drop.
1948 $wpdb->query("ALTER TABLE $wpdb->options DROP INDEX option_name");
1954 * Install global terms.
1959 if ( !function_exists( 'install_global_terms' ) ) :
1960 function install_global_terms() {
1961 global $wpdb, $charset_collate;
1963 CREATE TABLE $wpdb->sitecategories (
1964 cat_ID bigint(20) NOT NULL auto_increment,
1965 cat_name varchar(55) NOT NULL default '',
1966 category_nicename varchar(200) NOT NULL default '',
1967 last_updated timestamp NOT NULL,
1968 PRIMARY KEY (cat_ID),
1969 KEY category_nicename (category_nicename),
1970 KEY last_updated (last_updated)
1973 // now create tables
1974 dbDelta( $ms_queries );