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 ( ), 'primary-widget-area' => array ( 0 => 'search-2', 1 => 'recent-posts-2', 2 => 'recent-comments-2', 3 => 'archives-2', 4 => 'categories-2', 5 => 'meta-2', ), 'secondary-widget-area' => array ( ), 'first-footer-widget-area' => array ( ), 'second-footer-widget-area' => array ( ), 'third-footer-widget-area' => array ( ), 'fourth-footer-widget-area' => array ( ), 'array_version' => 3 ) );
286 if ( is_multisite() ) {
287 // Flush rules to pick up the new page.
289 $wp_rewrite->flush_rules();
291 $user = new WP_User($user_id);
292 $wpdb->update( $wpdb->options, array('option_value' => $user->user_email), array('option_name' => 'admin_email') );
294 // Remove all perms except for the login user.
295 $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id != %d AND meta_key = %s", $user_id, $table_prefix.'user_level') );
296 $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id != %d AND meta_key = %s", $user_id, $table_prefix.'capabilities') );
298 // Delete any caps that snuck into the previously active blog. (Hardcoded to blog 1 for now.) TODO: Get previous_blog_id.
299 if ( !is_super_admin( $user_id ) && $user_id != 1 )
300 $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id = %d AND meta_key = %s", $user_id, $wpdb->base_prefix.'1_capabilities') );
305 if ( !function_exists('wp_new_blog_notification') ) :
307 * {@internal Missing Short Description}}
309 * {@internal Missing Long Description}}
313 * @param string $blog_title Blog title.
314 * @param string $blog_url Blog url.
315 * @param int $user_id User ID.
316 * @param string $password User's Password.
318 function wp_new_blog_notification($blog_title, $blog_url, $user_id, $password) {
319 $user = new WP_User($user_id);
320 $email = $user->user_email;
321 $name = $user->user_login;
322 $message = sprintf(__("Your new WordPress site has been successfully set up at:
326 You can log in to the administrator account with the following information:
331 We hope you enjoy your new site. Thanks!
334 http://wordpress.org/
335 "), $blog_url, $name, $password);
337 @wp_mail($email, __('New WordPress Site'), $message);
341 if ( !function_exists('wp_upgrade') ) :
343 * Run WordPress Upgrade functions.
345 * {@internal Missing Long Description}}
351 function wp_upgrade() {
352 global $wp_current_db_version, $wp_db_version, $wpdb;
354 $wp_current_db_version = __get_option('db_version');
356 // We are up-to-date. Nothing to do.
357 if ( $wp_db_version == $wp_current_db_version )
360 if ( ! is_blog_installed() )
363 wp_check_mysql_version();
365 pre_schema_upgrade();
366 make_db_current_silent();
368 if ( is_multisite() && is_main_site() )
372 if ( is_multisite() ) {
373 if ( $wpdb->get_row( "SELECT blog_id FROM {$wpdb->blog_versions} WHERE blog_id = '{$wpdb->blogid}'" ) )
374 $wpdb->query( "UPDATE {$wpdb->blog_versions} SET db_version = '{$wp_db_version}' WHERE blog_id = '{$wpdb->blogid}'" );
376 $wpdb->query( "INSERT INTO {$wpdb->blog_versions} ( `blog_id` , `db_version` , `last_updated` ) VALUES ( '{$wpdb->blogid}', '{$wp_db_version}', NOW());" );
382 * Functions to be called in install and upgrade scripts.
384 * {@internal Missing Long Description}}
388 function upgrade_all() {
389 global $wp_current_db_version, $wp_db_version, $wp_rewrite;
390 $wp_current_db_version = __get_option('db_version');
392 // We are up-to-date. Nothing to do.
393 if ( $wp_db_version == $wp_current_db_version )
396 // If the version is not set in the DB, try to guess the version.
397 if ( empty($wp_current_db_version) ) {
398 $wp_current_db_version = 0;
400 // If the template option exists, we have 1.5.
401 $template = __get_option('template');
402 if ( !empty($template) )
403 $wp_current_db_version = 2541;
406 if ( $wp_current_db_version < 6039 )
407 upgrade_230_options_table();
411 if ( $wp_current_db_version < 2541 ) {
418 if ( $wp_current_db_version < 3308 )
421 if ( $wp_current_db_version < 4772 )
424 if ( $wp_current_db_version < 4351 )
427 if ( $wp_current_db_version < 5539 )
430 if ( $wp_current_db_version < 6124 )
431 upgrade_230_old_tables();
433 if ( $wp_current_db_version < 7499 )
436 if ( $wp_current_db_version < 7935 )
439 if ( $wp_current_db_version < 8201 )
442 if ( $wp_current_db_version < 8989 )
445 if ( $wp_current_db_version < 10360 )
448 if ( $wp_current_db_version < 11958 )
451 if ( $wp_current_db_version < 15260 )
454 maybe_disable_automattic_widgets();
456 update_option( 'db_version', $wp_db_version );
457 update_option( 'db_upgraded', true );
461 * Execute changes made in WordPress 1.0.
465 function upgrade_100() {
468 // Get the title and ID of every post, post_name to check if it already has a value
469 $posts = $wpdb->get_results("SELECT ID, post_title, post_name FROM $wpdb->posts WHERE post_name = ''");
471 foreach($posts as $post) {
472 if ('' == $post->post_name) {
473 $newtitle = sanitize_title($post->post_title);
474 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_name = %s WHERE ID = %d", $newtitle, $post->ID) );
479 $categories = $wpdb->get_results("SELECT cat_ID, cat_name, category_nicename FROM $wpdb->categories");
480 foreach ($categories as $category) {
481 if ('' == $category->category_nicename) {
482 $newtitle = sanitize_title($category->cat_name);
483 $wpdb>update( $wpdb->categories, array('category_nicename' => $newtitle), array('cat_ID' => $category->cat_ID) );
487 $wpdb->query("UPDATE $wpdb->options SET option_value = REPLACE(option_value, 'wp-links/links-images/', 'wp-images/links/')
488 WHERE option_name LIKE 'links_rating_image%'
489 AND option_value LIKE 'wp-links/links-images/%'");
491 $done_ids = $wpdb->get_results("SELECT DISTINCT post_id FROM $wpdb->post2cat");
493 foreach ($done_ids as $done_id) :
494 $done_posts[] = $done_id->post_id;
496 $catwhere = ' AND ID NOT IN (' . implode(',', $done_posts) . ')';
501 $allposts = $wpdb->get_results("SELECT ID, post_category FROM $wpdb->posts WHERE post_category != '0' $catwhere");
503 foreach ($allposts as $post) {
504 // Check to see if it's already been imported
505 $cat = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->post2cat WHERE post_id = %d AND category_id = %d", $post->ID, $post->post_category) );
506 if (!$cat && 0 != $post->post_category) { // If there's no result
507 $wpdb->insert( $wpdb->post2cat, array('post_id' => $post->ID, 'category_id' => $post->post_category) );
514 * Execute changes made in WordPress 1.0.1.
518 function upgrade_101() {
521 // Clean up indices, add a few
522 add_clean_index($wpdb->posts, 'post_name');
523 add_clean_index($wpdb->posts, 'post_status');
524 add_clean_index($wpdb->categories, 'category_nicename');
525 add_clean_index($wpdb->comments, 'comment_approved');
526 add_clean_index($wpdb->comments, 'comment_post_ID');
527 add_clean_index($wpdb->links , 'link_category');
528 add_clean_index($wpdb->links , 'link_visible');
532 * Execute changes made in WordPress 1.2.
536 function upgrade_110() {
539 // Set user_nicename.
540 $users = $wpdb->get_results("SELECT ID, user_nickname, user_nicename FROM $wpdb->users");
541 foreach ($users as $user) {
542 if ('' == $user->user_nicename) {
543 $newname = sanitize_title($user->user_nickname);
544 $wpdb->update( $wpdb->users, array('user_nicename' => $newname), array('ID' => $user->ID) );
548 $users = $wpdb->get_results("SELECT ID, user_pass from $wpdb->users");
549 foreach ($users as $row) {
550 if (!preg_match('/^[A-Fa-f0-9]{32}$/', $row->user_pass)) {
551 $wpdb->update( $wpdb->users, array('user_pass' => md5($row->user_pass)), array('ID' => $row->ID) );
555 // Get the GMT offset, we'll use that later on
556 $all_options = get_alloptions_110();
558 $time_difference = $all_options->time_difference;
560 $server_time = time()+date('Z');
561 $weblogger_time = $server_time + $time_difference*3600;
564 $diff_gmt_server = ($gmt_time - $server_time) / 3600;
565 $diff_weblogger_server = ($weblogger_time - $server_time) / 3600;
566 $diff_gmt_weblogger = $diff_gmt_server - $diff_weblogger_server;
567 $gmt_offset = -$diff_gmt_weblogger;
569 // Add a gmt_offset option, with value $gmt_offset
570 add_option('gmt_offset', $gmt_offset);
572 // Check if we already set the GMT fields (if we did, then
573 // MAX(post_date_gmt) can't be '0000-00-00 00:00:00'
574 // <michel_v> I just slapped myself silly for not thinking about it earlier
575 $got_gmt_fields = ! ($wpdb->get_var("SELECT MAX(post_date_gmt) FROM $wpdb->posts") == '0000-00-00 00:00:00');
577 if (!$got_gmt_fields) {
579 // Add or substract time to all dates, to get GMT dates
580 $add_hours = intval($diff_gmt_weblogger);
581 $add_minutes = intval(60 * ($diff_gmt_weblogger - $add_hours));
582 $wpdb->query("UPDATE $wpdb->posts SET post_date_gmt = DATE_ADD(post_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
583 $wpdb->query("UPDATE $wpdb->posts SET post_modified = post_date");
584 $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'");
585 $wpdb->query("UPDATE $wpdb->comments SET comment_date_gmt = DATE_ADD(comment_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
586 $wpdb->query("UPDATE $wpdb->users SET user_registered = DATE_ADD(user_registered, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
592 * Execute changes made in WordPress 1.5.
596 function upgrade_130() {
599 // Remove extraneous backslashes.
600 $posts = $wpdb->get_results("SELECT ID, post_title, post_content, post_excerpt, guid, post_date, post_name, post_status, post_author FROM $wpdb->posts");
602 foreach($posts as $post) {
603 $post_content = addslashes(deslash($post->post_content));
604 $post_title = addslashes(deslash($post->post_title));
605 $post_excerpt = addslashes(deslash($post->post_excerpt));
606 if ( empty($post->guid) )
607 $guid = get_permalink($post->ID);
611 $wpdb->update( $wpdb->posts, compact('post_title', 'post_content', 'post_excerpt', 'guid'), array('ID' => $post->ID) );
616 // Remove extraneous backslashes.
617 $comments = $wpdb->get_results("SELECT comment_ID, comment_author, comment_content FROM $wpdb->comments");
619 foreach($comments as $comment) {
620 $comment_content = deslash($comment->comment_content);
621 $comment_author = deslash($comment->comment_author);
623 $wpdb->update($wpdb->comments, compact('comment_content', 'comment_author'), array('comment_ID' => $comment->comment_ID) );
627 // Remove extraneous backslashes.
628 $links = $wpdb->get_results("SELECT link_id, link_name, link_description FROM $wpdb->links");
630 foreach($links as $link) {
631 $link_name = deslash($link->link_name);
632 $link_description = deslash($link->link_description);
634 $wpdb->update( $wpdb->links, compact('link_name', 'link_description'), array('link_id' => $link->link_id) );
638 $active_plugins = __get_option('active_plugins');
640 // If plugins are not stored in an array, they're stored in the old
641 // newline separated format. Convert to new format.
642 if ( !is_array( $active_plugins ) ) {
643 $active_plugins = explode("\n", trim($active_plugins));
644 update_option('active_plugins', $active_plugins);
648 $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optionvalues');
649 $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiontypes');
650 $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiongroups');
651 $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiongroup_options');
653 // Update comments table to use comment_type
654 $wpdb->query("UPDATE $wpdb->comments SET comment_type='trackback', comment_content = REPLACE(comment_content, '<trackback />', '') WHERE comment_content LIKE '<trackback />%'");
655 $wpdb->query("UPDATE $wpdb->comments SET comment_type='pingback', comment_content = REPLACE(comment_content, '<pingback />', '') WHERE comment_content LIKE '<pingback />%'");
657 // Some versions have multiple duplicate option_name rows with the same values
658 $options = $wpdb->get_results("SELECT option_name, COUNT(option_name) AS dupes FROM `$wpdb->options` GROUP BY option_name");
659 foreach ( $options as $option ) {
660 if ( 1 != $option->dupes ) { // Could this be done in the query?
661 $limit = $option->dupes - 1;
662 $dupe_ids = $wpdb->get_col( $wpdb->prepare("SELECT option_id FROM $wpdb->options WHERE option_name = %s LIMIT %d", $option->option_name, $limit) );
664 $dupe_ids = join($dupe_ids, ',');
665 $wpdb->query("DELETE FROM $wpdb->options WHERE option_id IN ($dupe_ids)");
674 * Execute changes made in WordPress 2.0.
678 function upgrade_160() {
679 global $wpdb, $wp_current_db_version;
681 populate_roles_160();
683 $users = $wpdb->get_results("SELECT * FROM $wpdb->users");
684 foreach ( $users as $user ) :
685 if ( !empty( $user->user_firstname ) )
686 update_user_meta( $user->ID, 'first_name', $wpdb->escape($user->user_firstname) );
687 if ( !empty( $user->user_lastname ) )
688 update_user_meta( $user->ID, 'last_name', $wpdb->escape($user->user_lastname) );
689 if ( !empty( $user->user_nickname ) )
690 update_user_meta( $user->ID, 'nickname', $wpdb->escape($user->user_nickname) );
691 if ( !empty( $user->user_level ) )
692 update_user_meta( $user->ID, $wpdb->prefix . 'user_level', $user->user_level );
693 if ( !empty( $user->user_icq ) )
694 update_user_meta( $user->ID, 'icq', $wpdb->escape($user->user_icq) );
695 if ( !empty( $user->user_aim ) )
696 update_user_meta( $user->ID, 'aim', $wpdb->escape($user->user_aim) );
697 if ( !empty( $user->user_msn ) )
698 update_user_meta( $user->ID, 'msn', $wpdb->escape($user->user_msn) );
699 if ( !empty( $user->user_yim ) )
700 update_user_meta( $user->ID, 'yim', $wpdb->escape($user->user_icq) );
701 if ( !empty( $user->user_description ) )
702 update_user_meta( $user->ID, 'description', $wpdb->escape($user->user_description) );
704 if ( isset( $user->user_idmode ) ):
705 $idmode = $user->user_idmode;
706 if ($idmode == 'nickname') $id = $user->user_nickname;
707 if ($idmode == 'login') $id = $user->user_login;
708 if ($idmode == 'firstname') $id = $user->user_firstname;
709 if ($idmode == 'lastname') $id = $user->user_lastname;
710 if ($idmode == 'namefl') $id = $user->user_firstname.' '.$user->user_lastname;
711 if ($idmode == 'namelf') $id = $user->user_lastname.' '.$user->user_firstname;
712 if (!$idmode) $id = $user->user_nickname;
713 $wpdb->update( $wpdb->users, array('display_name' => $id), array('ID' => $user->ID) );
716 // FIXME: RESET_CAPS is temporary code to reset roles and caps if flag is set.
717 $caps = get_user_meta( $user->ID, $wpdb->prefix . 'capabilities');
718 if ( empty($caps) || defined('RESET_CAPS') ) {
719 $level = get_user_meta($user->ID, $wpdb->prefix . 'user_level', true);
720 $role = translate_level_to_role($level);
721 update_user_meta( $user->ID, $wpdb->prefix . 'capabilities', array($role => true) );
725 $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' );
726 $wpdb->hide_errors();
727 foreach ( $old_user_fields as $old )
728 $wpdb->query("ALTER TABLE $wpdb->users DROP $old");
729 $wpdb->show_errors();
731 // populate comment_count field of posts table
732 $comments = $wpdb->get_results( "SELECT comment_post_ID, COUNT(*) as c FROM $wpdb->comments WHERE comment_approved = '1' GROUP BY comment_post_ID" );
733 if ( is_array( $comments ) )
734 foreach ($comments as $comment)
735 $wpdb->update( $wpdb->posts, array('comment_count' => $comment->c), array('ID' => $comment->comment_post_ID) );
737 // Some alpha versions used a post status of object instead of attachment and put
738 // the mime type in post_type instead of post_mime_type.
739 if ( $wp_current_db_version > 2541 && $wp_current_db_version <= 3091 ) {
740 $objects = $wpdb->get_results("SELECT ID, post_type FROM $wpdb->posts WHERE post_status = 'object'");
741 foreach ($objects as $object) {
742 $wpdb->update( $wpdb->posts, array( 'post_status' => 'attachment',
743 'post_mime_type' => $object->post_type,
745 array( 'ID' => $object->ID ) );
747 $meta = get_post_meta($object->ID, 'imagedata', true);
748 if ( ! empty($meta['file']) )
749 update_attached_file( $object->ID, $meta['file'] );
755 * Execute changes made in WordPress 2.1.
759 function upgrade_210() {
760 global $wpdb, $wp_current_db_version;
762 if ( $wp_current_db_version < 3506 ) {
763 // Update status and type.
764 $posts = $wpdb->get_results("SELECT ID, post_status FROM $wpdb->posts");
766 if ( ! empty($posts) ) foreach ($posts as $post) {
767 $status = $post->post_status;
770 if ( 'static' == $status ) {
773 } else if ( 'attachment' == $status ) {
775 $type = 'attachment';
778 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_status = %s, post_type = %s WHERE ID = %d", $status, $type, $post->ID) );
782 if ( $wp_current_db_version < 3845 ) {
783 populate_roles_210();
786 if ( $wp_current_db_version < 3531 ) {
787 // Give future posts a post_status of future.
788 $now = gmdate('Y-m-d H:i:59');
789 $wpdb->query ("UPDATE $wpdb->posts SET post_status = 'future' WHERE post_status = 'publish' AND post_date_gmt > '$now'");
791 $posts = $wpdb->get_results("SELECT ID, post_date FROM $wpdb->posts WHERE post_status ='future'");
792 if ( !empty($posts) )
793 foreach ( $posts as $post )
794 wp_schedule_single_event(mysql2date('U', $post->post_date, false), 'publish_future_post', array($post->ID));
799 * Execute changes made in WordPress 2.3.
803 function upgrade_230() {
804 global $wp_current_db_version, $wpdb;
806 if ( $wp_current_db_version < 5200 ) {
807 populate_roles_230();
810 // Convert categories to terms.
813 $categories = $wpdb->get_results("SELECT * FROM $wpdb->categories ORDER BY cat_ID");
814 foreach ($categories as $category) {
815 $term_id = (int) $category->cat_ID;
816 $name = $category->cat_name;
817 $description = $category->category_description;
818 $slug = $category->category_nicename;
819 $parent = $category->category_parent;
822 // Associate terms with the same slug in a term group and make slugs unique.
823 if ( $exists = $wpdb->get_results( $wpdb->prepare("SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $slug) ) ) {
824 $term_group = $exists[0]->term_group;
825 $id = $exists[0]->term_id;
828 $alt_slug = $slug . "-$num";
830 $slug_check = $wpdb->get_var( $wpdb->prepare("SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug) );
831 } while ( $slug_check );
835 if ( empty( $term_group ) ) {
836 $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms GROUP BY term_group") + 1;
837 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->terms SET term_group = %d WHERE term_id = %d", $term_group, $id) );
841 $wpdb->query( $wpdb->prepare("INSERT INTO $wpdb->terms (term_id, name, slug, term_group) VALUES
842 (%d, %s, %s, %d)", $term_id, $name, $slug, $term_group) );
845 if ( !empty($category->category_count) ) {
846 $count = (int) $category->category_count;
847 $taxonomy = 'category';
848 $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) );
849 $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
852 if ( !empty($category->link_count) ) {
853 $count = (int) $category->link_count;
854 $taxonomy = 'link_category';
855 $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) );
856 $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
859 if ( !empty($category->tag_count) ) {
861 $count = (int) $category->tag_count;
862 $taxonomy = 'post_tag';
863 $wpdb->insert( $wpdb->term_taxonomy, compact('term_id', 'taxonomy', 'description', 'parent', 'count') );
864 $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
867 if ( empty($count) ) {
869 $taxonomy = 'category';
870 $wpdb->insert( $wpdb->term_taxonomy, compact('term_id', 'taxonomy', 'description', 'parent', 'count') );
871 $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
875 $select = 'post_id, category_id';
877 $select .= ', rel_type';
879 $posts = $wpdb->get_results("SELECT $select FROM $wpdb->post2cat GROUP BY post_id, category_id");
880 foreach ( $posts as $post ) {
881 $post_id = (int) $post->post_id;
882 $term_id = (int) $post->category_id;
883 $taxonomy = 'category';
884 if ( !empty($post->rel_type) && 'tag' == $post->rel_type)
886 $tt_id = $tt_ids[$term_id][$taxonomy];
890 $wpdb->insert( $wpdb->term_relationships, array('object_id' => $post_id, 'term_taxonomy_id' => $tt_id) );
893 // < 3570 we used linkcategories. >= 3570 we used categories and link2cat.
894 if ( $wp_current_db_version < 3570 ) {
895 // Create link_category terms for link categories. Create a map of link cat IDs
896 // to link_category terms.
897 $link_cat_id_map = array();
898 $default_link_cat = 0;
900 $link_cats = $wpdb->get_results("SELECT cat_id, cat_name FROM " . $wpdb->prefix . 'linkcategories');
901 foreach ( $link_cats as $category) {
902 $cat_id = (int) $category->cat_id;
904 $name = $wpdb->escape($category->cat_name);
905 $slug = sanitize_title($name);
908 // Associate terms with the same slug in a term group and make slugs unique.
909 if ( $exists = $wpdb->get_results( $wpdb->prepare("SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $slug) ) ) {
910 $term_group = $exists[0]->term_group;
911 $term_id = $exists[0]->term_id;
914 if ( empty($term_id) ) {
915 $wpdb->insert( $wpdb->terms, compact('name', 'slug', 'term_group') );
916 $term_id = (int) $wpdb->insert_id;
919 $link_cat_id_map[$cat_id] = $term_id;
920 $default_link_cat = $term_id;
922 $wpdb->insert( $wpdb->term_taxonomy, array('term_id' => $term_id, 'taxonomy' => 'link_category', 'description' => '', 'parent' => 0, 'count' => 0) );
923 $tt_ids[$term_id] = (int) $wpdb->insert_id;
926 // Associate links to cats.
927 $links = $wpdb->get_results("SELECT link_id, link_category FROM $wpdb->links");
928 if ( !empty($links) ) foreach ( $links as $link ) {
929 if ( 0 == $link->link_category )
931 if ( ! isset($link_cat_id_map[$link->link_category]) )
933 $term_id = $link_cat_id_map[$link->link_category];
934 $tt_id = $tt_ids[$term_id];
938 $wpdb->insert( $wpdb->term_relationships, array('object_id' => $link->link_id, 'term_taxonomy_id' => $tt_id) );
941 // Set default to the last category we grabbed during the upgrade loop.
942 update_option('default_link_category', $default_link_cat);
944 $links = $wpdb->get_results("SELECT link_id, category_id FROM $wpdb->link2cat GROUP BY link_id, category_id");
945 foreach ( $links as $link ) {
946 $link_id = (int) $link->link_id;
947 $term_id = (int) $link->category_id;
948 $taxonomy = 'link_category';
949 $tt_id = $tt_ids[$term_id][$taxonomy];
952 $wpdb->insert( $wpdb->term_relationships, array('object_id' => $link_id, 'term_taxonomy_id' => $tt_id) );
956 if ( $wp_current_db_version < 4772 ) {
957 // Obsolete linkcategories table
958 $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'linkcategories');
961 // Recalculate all counts
962 $terms = $wpdb->get_results("SELECT term_taxonomy_id, taxonomy FROM $wpdb->term_taxonomy");
963 foreach ( (array) $terms as $term ) {
964 if ( ('post_tag' == $term->taxonomy) || ('category' == $term->taxonomy) )
965 $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) );
967 $count = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term->term_taxonomy_id) );
968 $wpdb->update( $wpdb->term_taxonomy, array('count' => $count), array('term_taxonomy_id' => $term->term_taxonomy_id) );
973 * Remove old options from the database.
977 function upgrade_230_options_table() {
979 $old_options_fields = array( 'option_can_override', 'option_type', 'option_width', 'option_height', 'option_description', 'option_admin_level' );
980 $wpdb->hide_errors();
981 foreach ( $old_options_fields as $old )
982 $wpdb->query("ALTER TABLE $wpdb->options DROP $old");
983 $wpdb->show_errors();
987 * Remove old categories, link2cat, and post2cat database tables.
991 function upgrade_230_old_tables() {
993 $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'categories');
994 $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'link2cat');
995 $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'post2cat');
999 * Upgrade old slugs made in version 2.2.
1003 function upgrade_old_slugs() {
1004 // upgrade people who were using the Redirect Old Slugs plugin
1006 $wpdb->query("UPDATE $wpdb->postmeta SET meta_key = '_wp_old_slug' WHERE meta_key = 'old_slug'");
1010 * Execute changes made in WordPress 2.5.0.
1014 function upgrade_250() {
1015 global $wp_current_db_version;
1017 if ( $wp_current_db_version < 6689 ) {
1018 populate_roles_250();
1024 * Execute changes made in WordPress 2.5.2.
1028 function upgrade_252() {
1031 $wpdb->query("UPDATE $wpdb->users SET user_activation_key = ''");
1035 * Execute changes made in WordPress 2.6.
1039 function upgrade_260() {
1040 global $wp_current_db_version;
1042 if ( $wp_current_db_version < 8000 )
1043 populate_roles_260();
1045 if ( $wp_current_db_version < 8201 ) {
1046 update_option('enable_app', 1);
1047 update_option('enable_xmlrpc', 1);
1052 * Execute changes made in WordPress 2.7.
1056 function upgrade_270() {
1057 global $wpdb, $wp_current_db_version;
1059 if ( $wp_current_db_version < 8980 )
1060 populate_roles_270();
1062 // Update post_date for unpublished posts with empty timestamp
1063 if ( $wp_current_db_version < 8921 )
1064 $wpdb->query( "UPDATE $wpdb->posts SET post_date = post_modified WHERE post_date = '0000-00-00 00:00:00'" );
1068 * Execute changes made in WordPress 2.8.
1072 function upgrade_280() {
1073 global $wp_current_db_version, $wpdb;
1075 if ( $wp_current_db_version < 10360 )
1076 populate_roles_280();
1077 if ( is_multisite() ) {
1079 while( $rows = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options ORDER BY option_id LIMIT $start, 20" ) ) {
1080 foreach( $rows as $row ) {
1081 $value = $row->option_value;
1082 if ( !@unserialize( $value ) )
1083 $value = stripslashes( $value );
1084 if ( $value !== $row->option_value ) {
1085 update_option( $row->option_name, $value );
1090 refresh_blog_details( $wpdb->blogid );
1095 * Execute changes made in WordPress 2.9.
1099 function upgrade_290() {
1100 global $wp_current_db_version;
1102 if ( $wp_current_db_version < 11958 ) {
1103 // Previously, setting depth to 1 would redundantly disable threading, but now 2 is the minimum depth to avoid confusion
1104 if ( get_option( 'thread_comments_depth' ) == '1' ) {
1105 update_option( 'thread_comments_depth', 2 );
1106 update_option( 'thread_comments', 0 );
1112 * Execute changes made in WordPress 3.0.
1116 function upgrade_300() {
1117 global $wp_current_db_version, $wpdb;
1119 if ( $wp_current_db_version < 15093 )
1120 populate_roles_300();
1122 if ( $wp_current_db_version < 14139 && is_multisite() && is_main_site() && ! defined( 'MULTISITE' ) && get_site_option( 'siteurl' ) === false )
1123 add_site_option( 'siteurl', '' );
1125 // 3.0-alpha nav menu postmeta changes. can be removed before release. // r13802
1126 if ( $wp_current_db_version >= 13226 && $wp_current_db_version < 13974 )
1127 $wpdb->query( "DELETE FROM $wpdb->postmeta WHERE meta_key IN( 'menu_type', 'object_id', 'menu_new_window', 'menu_link', '_menu_item_append', 'menu_item_append', 'menu_item_type', 'menu_item_object_id', 'menu_item_target', 'menu_item_classes', 'menu_item_xfn', 'menu_item_url' )" );
1129 // 3.0-beta1 remove_user primitive->meta cap. can be removed before release. r13956
1130 if ( $wp_current_db_version >= 12751 && $wp_current_db_version < 13974 ) {
1131 $role =& get_role( 'administrator' );
1132 if ( ! empty( $role ) )
1133 $role->remove_cap( 'remove_user' );
1136 // 3.0-beta1 nav menu postmeta changes. can be removed before release. r13974
1137 if ( $wp_current_db_version >= 13802 && $wp_current_db_version < 13974 )
1138 $wpdb->update( $wpdb->postmeta, array( 'meta_value' => '' ), array( 'meta_key' => '_menu_item_target', 'meta_value' => '_self' ) );
1140 // 3.0 screen options key name changes.
1141 if ( is_main_site() && !defined('DO_NOT_UPGRADE_GLOBAL_TABLES') ) {
1142 $prefix = like_escape($wpdb->base_prefix);
1143 $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%'
1144 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'" );
1150 * Execute network level changes
1154 function upgrade_network() {
1155 global $wp_current_db_version, $wpdb;
1157 if ( $wp_current_db_version < 11549 ) {
1158 $wpmu_sitewide_plugins = get_site_option( 'wpmu_sitewide_plugins' );
1159 $active_sitewide_plugins = get_site_option( 'active_sitewide_plugins' );
1160 if ( $wpmu_sitewide_plugins ) {
1161 if ( !$active_sitewide_plugins )
1162 $sitewide_plugins = (array) $wpmu_sitewide_plugins;
1164 $sitewide_plugins = array_merge( (array) $active_sitewide_plugins, (array) $wpmu_sitewide_plugins );
1166 update_site_option( 'active_sitewide_plugins', $sitewide_plugins );
1168 delete_site_option( 'wpmu_sitewide_plugins' );
1169 delete_site_option( 'deactivated_sitewide_plugins' );
1172 while( $rows = $wpdb->get_results( "SELECT meta_key, meta_value FROM {$wpdb->sitemeta} ORDER BY meta_id LIMIT $start, 20" ) ) {
1173 foreach( $rows as $row ) {
1174 $value = $row->meta_value;
1175 if ( !@unserialize( $value ) )
1176 $value = stripslashes( $value );
1177 if ( $value !== $row->meta_value ) {
1178 update_site_option( $row->meta_key, $value );
1185 if ( $wp_current_db_version < 13576 )
1186 update_site_option( 'global_terms_enabled', '1' );
1189 // The functions we use to actually do stuff
1194 * {@internal Missing Short Description}}
1196 * {@internal Missing Long Description}}
1200 * @param string $table_name Database table name to create.
1201 * @param string $create_ddl SQL statement to create table.
1202 * @return bool If table already exists or was created by function.
1204 function maybe_create_table($table_name, $create_ddl) {
1206 if ( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") == $table_name )
1208 //didn't find it try to create it.
1209 $q = $wpdb->query($create_ddl);
1210 // we cannot directly tell that whether this succeeded!
1211 if ( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") == $table_name )
1217 * {@internal Missing Short Description}}
1219 * {@internal Missing Long Description}}
1223 * @param string $table Database table name.
1224 * @param string $index Index name to drop.
1225 * @return bool True, when finished.
1227 function drop_index($table, $index) {
1229 $wpdb->hide_errors();
1230 $wpdb->query("ALTER TABLE `$table` DROP INDEX `$index`");
1231 // Now we need to take out all the extra ones we may have created
1232 for ($i = 0; $i < 25; $i++) {
1233 $wpdb->query("ALTER TABLE `$table` DROP INDEX `{$index}_$i`");
1235 $wpdb->show_errors();
1240 * {@internal Missing Short Description}}
1242 * {@internal Missing Long Description}}
1246 * @param string $table Database table name.
1247 * @param string $index Database table index column.
1248 * @return bool True, when done with execution.
1250 function add_clean_index($table, $index) {
1252 drop_index($table, $index);
1253 $wpdb->query("ALTER TABLE `$table` ADD INDEX ( `$index` )");
1258 ** maybe_add_column()
1259 ** Add column to db table if it doesn't exist.
1260 ** Returns: true if already exists or on successful completion
1263 function maybe_add_column($table_name, $column_name, $create_ddl) {
1264 global $wpdb, $debug;
1265 foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) {
1266 if ($debug) echo("checking $column == $column_name<br />");
1267 if ($column == $column_name) {
1271 //didn't find it try to create it.
1272 $q = $wpdb->query($create_ddl);
1273 // we cannot directly tell that whether this succeeded!
1274 foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) {
1275 if ($column == $column_name) {
1283 * Retrieve all options as it was for 1.2.
1287 * @return array List of options.
1289 function get_alloptions_110() {
1291 if ($options = $wpdb->get_results("SELECT option_name, option_value FROM $wpdb->options")) {
1292 foreach ($options as $option) {
1293 // "When trying to design a foolproof system,
1294 // never underestimate the ingenuity of the fools :)" -- Dougal
1295 if ('siteurl' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value);
1296 if ('home' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value);
1297 if ('category_base' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value);
1298 $all_options->{$option->option_name} = stripslashes($option->option_value);
1301 return $all_options;
1305 * Version of get_option that is private to install/upgrade.
1310 * @param string $setting Option name.
1313 function __get_option($setting) {
1316 if ( $setting == 'home' && defined( 'WP_HOME' ) ) {
1317 return preg_replace( '|/+$|', '', WP_HOME );
1320 if ( $setting == 'siteurl' && defined( 'WP_SITEURL' ) ) {
1321 return preg_replace( '|/+$|', '', WP_SITEURL );
1324 $option = $wpdb->get_var( $wpdb->prepare("SELECT option_value FROM $wpdb->options WHERE option_name = %s", $setting) );
1326 if ( 'home' == $setting && '' == $option )
1327 return __get_option('siteurl');
1329 if ( 'siteurl' == $setting || 'home' == $setting || 'category_base' == $setting )
1330 $option = preg_replace('|/+$|', '', $option);
1332 @ $kellogs = unserialize($option);
1333 if ($kellogs !== FALSE)
1340 * {@internal Missing Short Description}}
1342 * {@internal Missing Long Description}}
1346 * @param string $content
1349 function deslash($content) {
1350 // Note: \\\ inside a regex denotes a single backslash.
1352 // Replace one or more backslashes followed by a single quote with
1354 $content = preg_replace("/\\\+'/", "'", $content);
1356 // Replace one or more backslashes followed by a double quote with
1358 $content = preg_replace('/\\\+"/', '"', $content);
1360 // Replace one or more backslashes with one backslash.
1361 $content = preg_replace("/\\\+/", "\\", $content);
1367 * {@internal Missing Short Description}}
1369 * {@internal Missing Long Description}}
1373 * @param unknown_type $queries
1374 * @param unknown_type $execute
1377 function dbDelta($queries, $execute = true) {
1380 // Separate individual queries into an array
1381 if ( !is_array($queries) ) {
1382 $queries = explode( ';', $queries );
1383 if ('' == $queries[count($queries) - 1]) array_pop($queries);
1386 $cqueries = array(); // Creation Queries
1387 $iqueries = array(); // Insertion Queries
1388 $for_update = array();
1390 // Create a tablename index for an array ($cqueries) of queries
1391 foreach($queries as $qry) {
1392 if (preg_match("|CREATE TABLE ([^ ]*)|", $qry, $matches)) {
1393 $cqueries[trim( strtolower($matches[1]), '`' )] = $qry;
1394 $for_update[$matches[1]] = 'Created table '.$matches[1];
1395 } else if (preg_match("|CREATE DATABASE ([^ ]*)|", $qry, $matches)) {
1396 array_unshift($cqueries, $qry);
1397 } else if (preg_match("|INSERT INTO ([^ ]*)|", $qry, $matches)) {
1399 } else if (preg_match("|UPDATE ([^ ]*)|", $qry, $matches)) {
1402 // Unrecognized query type
1406 // Check to see which tables and fields exist
1407 if ($tables = $wpdb->get_col('SHOW TABLES;')) {
1408 // For every table in the database
1409 foreach ($tables as $table) {
1410 // Upgrade global tables only for the main site. Don't upgrade at all if DO_NOT_UPGRADE_GLOBAL_TABLES is defined.
1411 if ( in_array($table, $wpdb->tables('global')) && ( !is_main_site() || defined('DO_NOT_UPGRADE_GLOBAL_TABLES') ) )
1414 // If a table query exists for the database table...
1415 if ( array_key_exists(strtolower($table), $cqueries) ) {
1416 // Clear the field and index arrays
1417 $cfields = $indices = array();
1418 // Get all of the field names in the query from between the parens
1419 preg_match("|\((.*)\)|ms", $cqueries[strtolower($table)], $match2);
1420 $qryline = trim($match2[1]);
1422 // Separate field lines into an array
1423 $flds = explode("\n", $qryline);
1425 //echo "<hr/><pre>\n".print_r(strtolower($table), true).":\n".print_r($cqueries, true)."</pre><hr/>";
1427 // For every field line specified in the query
1428 foreach ($flds as $fld) {
1429 // Extract the field name
1430 preg_match("|^([^ ]*)|", trim($fld), $fvals);
1431 $fieldname = trim( $fvals[1], '`' );
1433 // Verify the found field name
1435 switch (strtolower($fieldname)) {
1442 $validfield = false;
1443 $indices[] = trim(trim($fld), ", \n");
1448 // If it's a valid field, add it to the field array
1450 $cfields[strtolower($fieldname)] = trim($fld, ", \n");
1454 // Fetch the table column structure from the database
1455 $tablefields = $wpdb->get_results("DESCRIBE {$table};");
1457 // For every field in the table
1458 foreach ($tablefields as $tablefield) {
1459 // If the table field exists in the field array...
1460 if (array_key_exists(strtolower($tablefield->Field), $cfields)) {
1461 // Get the field type from the query
1462 preg_match("|".$tablefield->Field." ([^ ]*( unsigned)?)|i", $cfields[strtolower($tablefield->Field)], $matches);
1463 $fieldtype = $matches[1];
1465 // Is actual field type different from the field type in query?
1466 if ($tablefield->Type != $fieldtype) {
1467 // Add a query to change the column type
1468 $cqueries[] = "ALTER TABLE {$table} CHANGE COLUMN {$tablefield->Field} " . $cfields[strtolower($tablefield->Field)];
1469 $for_update[$table.'.'.$tablefield->Field] = "Changed type of {$table}.{$tablefield->Field} from {$tablefield->Type} to {$fieldtype}";
1472 // Get the default value from the array
1473 //echo "{$cfields[strtolower($tablefield->Field)]}<br>";
1474 if (preg_match("| DEFAULT '(.*)'|i", $cfields[strtolower($tablefield->Field)], $matches)) {
1475 $default_value = $matches[1];
1476 if ($tablefield->Default != $default_value) {
1477 // Add a query to change the column's default value
1478 $cqueries[] = "ALTER TABLE {$table} ALTER COLUMN {$tablefield->Field} SET DEFAULT '{$default_value}'";
1479 $for_update[$table.'.'.$tablefield->Field] = "Changed default value of {$table}.{$tablefield->Field} from {$tablefield->Default} to {$default_value}";
1483 // Remove the field from the array (so it's not added)
1484 unset($cfields[strtolower($tablefield->Field)]);
1486 // This field exists in the table, but not in the creation queries?
1490 // For every remaining field specified for the table
1491 foreach ($cfields as $fieldname => $fielddef) {
1492 // Push a query line into $cqueries that adds the field to that table
1493 $cqueries[] = "ALTER TABLE {$table} ADD COLUMN $fielddef";
1494 $for_update[$table.'.'.$fieldname] = 'Added column '.$table.'.'.$fieldname;
1497 // Index stuff goes here
1498 // Fetch the table index structure from the database
1499 $tableindices = $wpdb->get_results("SHOW INDEX FROM {$table};");
1501 if ($tableindices) {
1502 // Clear the index array
1505 // For every index in the table
1506 foreach ($tableindices as $tableindex) {
1507 // Add the index to the index data array
1508 $keyname = $tableindex->Key_name;
1509 $index_ary[$keyname]['columns'][] = array('fieldname' => $tableindex->Column_name, 'subpart' => $tableindex->Sub_part);
1510 $index_ary[$keyname]['unique'] = ($tableindex->Non_unique == 0)?true:false;
1513 // For each actual index in the index array
1514 foreach ($index_ary as $index_name => $index_data) {
1515 // Build a create string to compare to the query
1517 if ($index_name == 'PRIMARY') {
1518 $index_string .= 'PRIMARY ';
1519 } else if($index_data['unique']) {
1520 $index_string .= 'UNIQUE ';
1522 $index_string .= 'KEY ';
1523 if ($index_name != 'PRIMARY') {
1524 $index_string .= $index_name;
1526 $index_columns = '';
1527 // For each column in the index
1528 foreach ($index_data['columns'] as $column_data) {
1529 if ($index_columns != '') $index_columns .= ',';
1530 // Add the field to the column list string
1531 $index_columns .= $column_data['fieldname'];
1532 if ($column_data['subpart'] != '') {
1533 $index_columns .= '('.$column_data['subpart'].')';
1536 // Add the column list to the index create string
1537 $index_string .= ' ('.$index_columns.')';
1538 if (!(($aindex = array_search($index_string, $indices)) === false)) {
1539 unset($indices[$aindex]);
1540 //echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">{$table}:<br />Found index:".$index_string."</pre>\n";
1542 //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";
1546 // For every remaining index specified for the table
1547 foreach ( (array) $indices as $index ) {
1548 // Push a query line into $cqueries that adds the index to that table
1549 $cqueries[] = "ALTER TABLE {$table} ADD $index";
1550 $for_update[$table.'.'.$fieldname] = 'Added index '.$table.' '.$index;
1553 // Remove the original table creation query from processing
1554 unset($cqueries[strtolower($table)]);
1555 unset($for_update[strtolower($table)]);
1557 // This table exists in the database, but not in the creation queries?
1562 $allqueries = array_merge($cqueries, $iqueries);
1564 foreach ($allqueries as $query) {
1565 //echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">".print_r($query, true)."</pre>\n";
1566 $wpdb->query($query);
1574 * {@internal Missing Short Description}}
1576 * {@internal Missing Long Description}}
1580 function make_db_current() {
1583 $alterations = dbDelta($wp_queries);
1585 foreach($alterations as $alteration) echo "<li>$alteration</li>\n";
1590 * {@internal Missing Short Description}}
1592 * {@internal Missing Long Description}}
1596 function make_db_current_silent() {
1599 $alterations = dbDelta($wp_queries);
1603 * {@internal Missing Short Description}}
1605 * {@internal Missing Long Description}}
1609 * @param unknown_type $theme_name
1610 * @param unknown_type $template
1613 function make_site_theme_from_oldschool($theme_name, $template) {
1614 $home_path = get_home_path();
1615 $site_dir = WP_CONTENT_DIR . "/themes/$template";
1617 if (! file_exists("$home_path/index.php"))
1620 // Copy files from the old locations to the site theme.
1621 // TODO: This does not copy arbitarary include dependencies. Only the
1622 // standard WP files are copied.
1623 $files = array('index.php' => 'index.php', 'wp-layout.css' => 'style.css', 'wp-comments.php' => 'comments.php', 'wp-comments-popup.php' => 'comments-popup.php');
1625 foreach ($files as $oldfile => $newfile) {
1626 if ($oldfile == 'index.php')
1627 $oldpath = $home_path;
1631 if ($oldfile == 'index.php') { // Check to make sure it's not a new index
1632 $index = implode('', file("$oldpath/$oldfile"));
1633 if (strpos($index, 'WP_USE_THEMES') !== false) {
1634 if (! @copy(WP_CONTENT_DIR . '/themes/' . WP_DEFAULT_THEME . '/index.php', "$site_dir/$newfile"))
1636 continue; // Don't copy anything
1640 if (! @copy("$oldpath/$oldfile", "$site_dir/$newfile"))
1643 chmod("$site_dir/$newfile", 0777);
1645 // Update the blog header include in each file.
1646 $lines = explode("\n", implode('', file("$site_dir/$newfile")));
1648 $f = fopen("$site_dir/$newfile", 'w');
1650 foreach ($lines as $line) {
1651 if (preg_match('/require.*wp-blog-header/', $line))
1652 $line = '//' . $line;
1654 // Update stylesheet references.
1655 $line = str_replace("<?php echo __get_option('siteurl'); ?>/wp-layout.css", "<?php bloginfo('stylesheet_url'); ?>", $line);
1657 // Update comments template inclusion.
1658 $line = str_replace("<?php include(ABSPATH . 'wp-comments.php'); ?>", "<?php comments_template(); ?>", $line);
1660 fwrite($f, "{$line}\n");
1666 // Add a theme header.
1667 $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";
1669 $stylelines = file_get_contents("$site_dir/style.css");
1671 $f = fopen("$site_dir/style.css", 'w');
1673 fwrite($f, $header);
1674 fwrite($f, $stylelines);
1682 * {@internal Missing Short Description}}
1684 * {@internal Missing Long Description}}
1688 * @param unknown_type $theme_name
1689 * @param unknown_type $template
1692 function make_site_theme_from_default($theme_name, $template) {
1693 $site_dir = WP_CONTENT_DIR . "/themes/$template";
1694 $default_dir = WP_CONTENT_DIR . '/themes/' . WP_DEFAULT_THEME;
1696 // Copy files from the default theme to the site theme.
1697 //$files = array('index.php', 'comments.php', 'comments-popup.php', 'footer.php', 'header.php', 'sidebar.php', 'style.css');
1699 $theme_dir = @ opendir($default_dir);
1701 while(($theme_file = readdir( $theme_dir )) !== false) {
1702 if (is_dir("$default_dir/$theme_file"))
1704 if (! @copy("$default_dir/$theme_file", "$site_dir/$theme_file"))
1706 chmod("$site_dir/$theme_file", 0777);
1709 @closedir($theme_dir);
1711 // Rewrite the theme header.
1712 $stylelines = explode("\n", implode('', file("$site_dir/style.css")));
1714 $f = fopen("$site_dir/style.css", 'w');
1716 foreach ($stylelines as $line) {
1717 if (strpos($line, 'Theme Name:') !== false) $line = 'Theme Name: ' . $theme_name;
1718 elseif (strpos($line, 'Theme URI:') !== false) $line = 'Theme URI: ' . __get_option('url');
1719 elseif (strpos($line, 'Description:') !== false) $line = 'Description: Your theme.';
1720 elseif (strpos($line, 'Version:') !== false) $line = 'Version: 1';
1721 elseif (strpos($line, 'Author:') !== false) $line = 'Author: You';
1722 fwrite($f, $line . "\n");
1729 if (! mkdir("$site_dir/images", 0777)) {
1733 $images_dir = @ opendir("$default_dir/images");
1735 while(($image = readdir($images_dir)) !== false) {
1736 if (is_dir("$default_dir/images/$image"))
1738 if (! @copy("$default_dir/images/$image", "$site_dir/images/$image"))
1740 chmod("$site_dir/images/$image", 0777);
1743 @closedir($images_dir);
1746 // Create a site theme from the default theme.
1748 * {@internal Missing Short Description}}
1750 * {@internal Missing Long Description}}
1756 function make_site_theme() {
1757 // Name the theme after the blog.
1758 $theme_name = __get_option('blogname');
1759 $template = sanitize_title($theme_name);
1760 $site_dir = WP_CONTENT_DIR . "/themes/$template";
1762 // If the theme already exists, nothing to do.
1763 if ( is_dir($site_dir)) {
1767 // We must be able to write to the themes dir.
1768 if (! is_writable(WP_CONTENT_DIR . "/themes")) {
1773 if (! mkdir($site_dir, 0777)) {
1777 if (file_exists(ABSPATH . 'wp-layout.css')) {
1778 if (! make_site_theme_from_oldschool($theme_name, $template)) {
1779 // TODO: rm -rf the site theme directory.
1783 if (! make_site_theme_from_default($theme_name, $template))
1784 // TODO: rm -rf the site theme directory.
1788 // Make the new site theme active.
1789 $current_template = __get_option('template');
1790 if ($current_template == WP_DEFAULT_THEME) {
1791 update_option('template', $template);
1792 update_option('stylesheet', $template);
1798 * Translate user level to user role name.
1802 * @param int $level User level.
1803 * @return string User role name.
1805 function translate_level_to_role($level) {
1810 return 'administrator';
1820 return 'contributor';
1822 return 'subscriber';
1827 * {@internal Missing Short Description}}
1829 * {@internal Missing Long Description}}
1833 function wp_check_mysql_version() {
1835 $result = $wpdb->check_database_version();
1836 if ( is_wp_error( $result ) )
1837 die( $result->get_error_message() );
1841 * {@internal Missing Short Description}}
1843 * {@internal Missing Long Description}}
1847 function maybe_disable_automattic_widgets() {
1848 $plugins = __get_option( 'active_plugins' );
1850 foreach ( (array) $plugins as $plugin ) {
1851 if ( basename( $plugin ) == 'widgets.php' ) {
1852 array_splice( $plugins, array_search( $plugin, $plugins ), 1 );
1853 update_option( 'active_plugins', $plugins );
1860 * Runs before the schema is upgraded.
1864 function pre_schema_upgrade() {
1865 global $wp_current_db_version, $wp_db_version, $wpdb;
1867 // Upgrade versions prior to 2.9
1868 if ( $wp_current_db_version < 11557 ) {
1869 // Delete duplicate options. Keep the option with the highest option_id.
1870 $wpdb->query("DELETE o1 FROM $wpdb->options AS o1 JOIN $wpdb->options AS o2 USING (`option_name`) WHERE o2.option_id > o1.option_id");
1872 // Drop the old primary key and add the new.
1873 $wpdb->query("ALTER TABLE $wpdb->options DROP PRIMARY KEY, ADD PRIMARY KEY(option_id)");
1875 // Drop the old option_name index. dbDelta() doesn't do the drop.
1876 $wpdb->query("ALTER TABLE $wpdb->options DROP INDEX option_name");
1887 if ( !function_exists( 'install_network' ) ) :
1888 function install_network() {
1889 global $wpdb, $charset_collate;
1891 CREATE TABLE $wpdb->users (
1892 ID bigint(20) unsigned NOT NULL auto_increment,
1893 user_login varchar(60) NOT NULL default '',
1894 user_pass varchar(64) NOT NULL default '',
1895 user_nicename varchar(50) NOT NULL default '',
1896 user_email varchar(100) NOT NULL default '',
1897 user_url varchar(100) NOT NULL default '',
1898 user_registered datetime NOT NULL default '0000-00-00 00:00:00',
1899 user_activation_key varchar(60) NOT NULL default '',
1900 user_status int(11) NOT NULL default '0',
1901 display_name varchar(250) NOT NULL default '',
1902 spam tinyint(2) NOT NULL default '0',
1903 deleted tinyint(2) NOT NULL default '0',
1905 KEY user_login_key (user_login),
1906 KEY user_nicename (user_nicename)
1908 CREATE TABLE $wpdb->blogs (
1909 blog_id bigint(20) NOT NULL auto_increment,
1910 site_id bigint(20) NOT NULL default '0',
1911 domain varchar(200) NOT NULL default '',
1912 path varchar(100) NOT NULL default '',
1913 registered datetime NOT NULL default '0000-00-00 00:00:00',
1914 last_updated datetime NOT NULL default '0000-00-00 00:00:00',
1915 public tinyint(2) NOT NULL default '1',
1916 archived enum('0','1') NOT NULL default '0',
1917 mature tinyint(2) NOT NULL default '0',
1918 spam tinyint(2) NOT NULL default '0',
1919 deleted tinyint(2) NOT NULL default '0',
1920 lang_id int(11) NOT NULL default '0',
1921 PRIMARY KEY (blog_id),
1922 KEY domain (domain(50),path(5)),
1923 KEY lang_id (lang_id)
1925 CREATE TABLE $wpdb->blog_versions (
1926 blog_id bigint(20) NOT NULL default '0',
1927 db_version varchar(20) NOT NULL default '',
1928 last_updated datetime NOT NULL default '0000-00-00 00:00:00',
1929 PRIMARY KEY (blog_id),
1930 KEY db_version (db_version)
1932 CREATE TABLE $wpdb->registration_log (
1933 ID bigint(20) NOT NULL auto_increment,
1934 email varchar(255) NOT NULL default '',
1935 IP varchar(30) NOT NULL default '',
1936 blog_id bigint(20) NOT NULL default '0',
1937 date_registered datetime NOT NULL default '0000-00-00 00:00:00',
1941 CREATE TABLE $wpdb->site (
1942 id bigint(20) NOT NULL auto_increment,
1943 domain varchar(200) NOT NULL default '',
1944 path varchar(100) NOT NULL default '',
1946 KEY domain (domain,path)
1948 CREATE TABLE $wpdb->sitemeta (
1949 meta_id bigint(20) NOT NULL auto_increment,
1950 site_id bigint(20) NOT NULL default '0',
1951 meta_key varchar(255) default NULL,
1952 meta_value longtext,
1953 PRIMARY KEY (meta_id),
1954 KEY meta_key (meta_key),
1955 KEY site_id (site_id)
1957 CREATE TABLE $wpdb->signups (
1958 domain varchar(200) NOT NULL default '',
1959 path varchar(100) NOT NULL default '',
1960 title longtext NOT NULL,
1961 user_login varchar(60) NOT NULL default '',
1962 user_email varchar(100) NOT NULL default '',
1963 registered datetime NOT NULL default '0000-00-00 00:00:00',
1964 activated datetime NOT NULL default '0000-00-00 00:00:00',
1965 active tinyint(1) NOT NULL default '0',
1966 activation_key varchar(50) NOT NULL default '',
1968 KEY activation_key (activation_key),
1972 // now create tables
1973 dbDelta( $ms_queries );
1978 * Install global terms.
1983 if ( !function_exists( 'install_global_terms' ) ) :
1984 function install_global_terms() {
1985 global $wpdb, $charset_collate;
1987 CREATE TABLE $wpdb->sitecategories (
1988 cat_ID bigint(20) NOT NULL auto_increment,
1989 cat_name varchar(55) NOT NULL default '',
1990 category_nicename varchar(200) NOT NULL default '',
1991 last_updated timestamp NOT NULL,
1992 PRIMARY KEY (cat_ID),
1993 KEY category_nicename (category_nicename),
1994 KEY last_updated (last_updated)
1997 // now create tables
1998 dbDelta( $ms_queries );