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();
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 = __('This is an example of a WordPress page, you could edit this to put information about yourself or your site so readers know where you are coming from. You can create as many pages like this one or sub-pages as you like and manage all of your content inside of WordPress.');
247 if ( is_multisite() )
248 $first_page = get_site_option( 'first_page', $first_page );
249 $first_post_guid = get_option('home') . '/?page_id=2';
250 $wpdb->insert( $wpdb->posts, array(
251 'post_author' => $user_id,
253 'post_date_gmt' => $now_gmt,
254 'post_content' => $first_page,
255 'post_excerpt' => '',
256 'post_title' => __('About'),
257 /* translators: Default page slug */
258 'post_name' => _x('about', 'Default page slug'),
259 'post_modified' => $now,
260 'post_modified_gmt' => $now_gmt,
261 'guid' => $first_post_guid,
262 'post_type' => 'page',
265 'post_content_filtered' => ''
267 $wpdb->insert( $wpdb->postmeta, array( 'post_id' => 2, 'meta_key' => '_wp_page_template', 'meta_value' => 'default' ) );
269 // Setup default widgets for default theme.
270 update_option( 'widget_search', array ( 2 => array ( 'title' => '' ), '_multiwidget' => 1 ) );
271 update_option( 'widget_recent-posts', array ( 2 => array ( 'title' => '', 'number' => 5 ), '_multiwidget' => 1 ) );
272 update_option( 'widget_recent-comments', array ( 2 => array ( 'title' => '', 'number' => 5 ), '_multiwidget' => 1 ) );
273 update_option( 'widget_archives', array ( 2 => array ( 'title' => '', 'count' => 0, 'dropdown' => 0 ), '_multiwidget' => 1 ) );
274 update_option( 'widget_categories', array ( 2 => array ( 'title' => '', 'count' => 0, 'hierarchical' => 0, 'dropdown' => 0 ), '_multiwidget' => 1 ) );
275 update_option( 'widget_meta', array ( 2 => array ( 'title' => '' ), '_multiwidget' => 1 ) );
276 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 ) );
278 if ( is_multisite() ) {
279 // Flush rules to pick up the new page.
281 $wp_rewrite->flush_rules();
283 $user = new WP_User($user_id);
284 $wpdb->update( $wpdb->options, array('option_value' => $user->user_email), array('option_name' => 'admin_email') );
286 // Remove all perms except for the login user.
287 $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id != %d AND meta_key = %s", $user_id, $table_prefix.'user_level') );
288 $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id != %d AND meta_key = %s", $user_id, $table_prefix.'capabilities') );
290 // Delete any caps that snuck into the previously active blog. (Hardcoded to blog 1 for now.) TODO: Get previous_blog_id.
291 if ( !is_super_admin( $user_id ) && $user_id != 1 )
292 $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id = %d AND meta_key = %s", $user_id, $wpdb->base_prefix.'1_capabilities') );
297 if ( !function_exists('wp_new_blog_notification') ) :
299 * {@internal Missing Short Description}}
301 * {@internal Missing Long Description}}
305 * @param string $blog_title Blog title.
306 * @param string $blog_url Blog url.
307 * @param int $user_id User ID.
308 * @param string $password User's Password.
310 function wp_new_blog_notification($blog_title, $blog_url, $user_id, $password) {
311 $user = new WP_User($user_id);
312 $email = $user->user_email;
313 $name = $user->user_login;
314 $message = sprintf(__("Your new WordPress site has been successfully set up at:
318 You can log in to the administrator account with the following information:
323 We hope you enjoy your new site. Thanks!
326 http://wordpress.org/
327 "), $blog_url, $name, $password);
329 @wp_mail($email, __('New WordPress Site'), $message);
333 if ( !function_exists('wp_upgrade') ) :
335 * Run WordPress Upgrade functions.
337 * {@internal Missing Long Description}}
343 function wp_upgrade() {
344 global $wp_current_db_version, $wp_db_version, $wpdb;
346 $wp_current_db_version = __get_option('db_version');
348 // We are up-to-date. Nothing to do.
349 if ( $wp_db_version == $wp_current_db_version )
352 if ( ! is_blog_installed() )
355 wp_check_mysql_version();
357 pre_schema_upgrade();
358 make_db_current_silent();
360 if ( is_multisite() && is_main_site() )
364 if ( is_multisite() ) {
365 if ( $wpdb->get_row( "SELECT blog_id FROM {$wpdb->blog_versions} WHERE blog_id = '{$wpdb->blogid}'" ) )
366 $wpdb->query( "UPDATE {$wpdb->blog_versions} SET db_version = '{$wp_db_version}' WHERE blog_id = '{$wpdb->blogid}'" );
368 $wpdb->query( "INSERT INTO {$wpdb->blog_versions} ( `blog_id` , `db_version` , `last_updated` ) VALUES ( '{$wpdb->blogid}', '{$wp_db_version}', NOW());" );
374 * Functions to be called in install and upgrade scripts.
376 * {@internal Missing Long Description}}
380 function upgrade_all() {
381 global $wp_current_db_version, $wp_db_version, $wp_rewrite;
382 $wp_current_db_version = __get_option('db_version');
384 // We are up-to-date. Nothing to do.
385 if ( $wp_db_version == $wp_current_db_version )
388 // If the version is not set in the DB, try to guess the version.
389 if ( empty($wp_current_db_version) ) {
390 $wp_current_db_version = 0;
392 // If the template option exists, we have 1.5.
393 $template = __get_option('template');
394 if ( !empty($template) )
395 $wp_current_db_version = 2541;
398 if ( $wp_current_db_version < 6039 )
399 upgrade_230_options_table();
403 if ( $wp_current_db_version < 2541 ) {
410 if ( $wp_current_db_version < 3308 )
413 if ( $wp_current_db_version < 4772 )
416 if ( $wp_current_db_version < 4351 )
419 if ( $wp_current_db_version < 5539 )
422 if ( $wp_current_db_version < 6124 )
423 upgrade_230_old_tables();
425 if ( $wp_current_db_version < 7499 )
428 if ( $wp_current_db_version < 7935 )
431 if ( $wp_current_db_version < 8201 )
434 if ( $wp_current_db_version < 8989 )
437 if ( $wp_current_db_version < 10360 )
440 if ( $wp_current_db_version < 11958 )
443 if ( $wp_current_db_version < 15260 )
446 maybe_disable_automattic_widgets();
448 update_option( 'db_version', $wp_db_version );
449 update_option( 'db_upgraded', true );
453 * Execute changes made in WordPress 1.0.
457 function upgrade_100() {
460 // Get the title and ID of every post, post_name to check if it already has a value
461 $posts = $wpdb->get_results("SELECT ID, post_title, post_name FROM $wpdb->posts WHERE post_name = ''");
463 foreach($posts as $post) {
464 if ('' == $post->post_name) {
465 $newtitle = sanitize_title($post->post_title);
466 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_name = %s WHERE ID = %d", $newtitle, $post->ID) );
471 $categories = $wpdb->get_results("SELECT cat_ID, cat_name, category_nicename FROM $wpdb->categories");
472 foreach ($categories as $category) {
473 if ('' == $category->category_nicename) {
474 $newtitle = sanitize_title($category->cat_name);
475 $wpdb>update( $wpdb->categories, array('category_nicename' => $newtitle), array('cat_ID' => $category->cat_ID) );
479 $wpdb->query("UPDATE $wpdb->options SET option_value = REPLACE(option_value, 'wp-links/links-images/', 'wp-images/links/')
480 WHERE option_name LIKE 'links_rating_image%'
481 AND option_value LIKE 'wp-links/links-images/%'");
483 $done_ids = $wpdb->get_results("SELECT DISTINCT post_id FROM $wpdb->post2cat");
485 foreach ($done_ids as $done_id) :
486 $done_posts[] = $done_id->post_id;
488 $catwhere = ' AND ID NOT IN (' . implode(',', $done_posts) . ')';
493 $allposts = $wpdb->get_results("SELECT ID, post_category FROM $wpdb->posts WHERE post_category != '0' $catwhere");
495 foreach ($allposts as $post) {
496 // Check to see if it's already been imported
497 $cat = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->post2cat WHERE post_id = %d AND category_id = %d", $post->ID, $post->post_category) );
498 if (!$cat && 0 != $post->post_category) { // If there's no result
499 $wpdb->insert( $wpdb->post2cat, array('post_id' => $post->ID, 'category_id' => $post->post_category) );
506 * Execute changes made in WordPress 1.0.1.
510 function upgrade_101() {
513 // Clean up indices, add a few
514 add_clean_index($wpdb->posts, 'post_name');
515 add_clean_index($wpdb->posts, 'post_status');
516 add_clean_index($wpdb->categories, 'category_nicename');
517 add_clean_index($wpdb->comments, 'comment_approved');
518 add_clean_index($wpdb->comments, 'comment_post_ID');
519 add_clean_index($wpdb->links , 'link_category');
520 add_clean_index($wpdb->links , 'link_visible');
524 * Execute changes made in WordPress 1.2.
528 function upgrade_110() {
531 // Set user_nicename.
532 $users = $wpdb->get_results("SELECT ID, user_nickname, user_nicename FROM $wpdb->users");
533 foreach ($users as $user) {
534 if ('' == $user->user_nicename) {
535 $newname = sanitize_title($user->user_nickname);
536 $wpdb->update( $wpdb->users, array('user_nicename' => $newname), array('ID' => $user->ID) );
540 $users = $wpdb->get_results("SELECT ID, user_pass from $wpdb->users");
541 foreach ($users as $row) {
542 if (!preg_match('/^[A-Fa-f0-9]{32}$/', $row->user_pass)) {
543 $wpdb->update( $wpdb->users, array('user_pass' => md5($row->user_pass)), array('ID' => $row->ID) );
547 // Get the GMT offset, we'll use that later on
548 $all_options = get_alloptions_110();
550 $time_difference = $all_options->time_difference;
552 $server_time = time()+date('Z');
553 $weblogger_time = $server_time + $time_difference*3600;
556 $diff_gmt_server = ($gmt_time - $server_time) / 3600;
557 $diff_weblogger_server = ($weblogger_time - $server_time) / 3600;
558 $diff_gmt_weblogger = $diff_gmt_server - $diff_weblogger_server;
559 $gmt_offset = -$diff_gmt_weblogger;
561 // Add a gmt_offset option, with value $gmt_offset
562 add_option('gmt_offset', $gmt_offset);
564 // Check if we already set the GMT fields (if we did, then
565 // MAX(post_date_gmt) can't be '0000-00-00 00:00:00'
566 // <michel_v> I just slapped myself silly for not thinking about it earlier
567 $got_gmt_fields = ! ($wpdb->get_var("SELECT MAX(post_date_gmt) FROM $wpdb->posts") == '0000-00-00 00:00:00');
569 if (!$got_gmt_fields) {
571 // Add or substract time to all dates, to get GMT dates
572 $add_hours = intval($diff_gmt_weblogger);
573 $add_minutes = intval(60 * ($diff_gmt_weblogger - $add_hours));
574 $wpdb->query("UPDATE $wpdb->posts SET post_date_gmt = DATE_ADD(post_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
575 $wpdb->query("UPDATE $wpdb->posts SET post_modified = post_date");
576 $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'");
577 $wpdb->query("UPDATE $wpdb->comments SET comment_date_gmt = DATE_ADD(comment_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
578 $wpdb->query("UPDATE $wpdb->users SET user_registered = DATE_ADD(user_registered, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
584 * Execute changes made in WordPress 1.5.
588 function upgrade_130() {
591 // Remove extraneous backslashes.
592 $posts = $wpdb->get_results("SELECT ID, post_title, post_content, post_excerpt, guid, post_date, post_name, post_status, post_author FROM $wpdb->posts");
594 foreach($posts as $post) {
595 $post_content = addslashes(deslash($post->post_content));
596 $post_title = addslashes(deslash($post->post_title));
597 $post_excerpt = addslashes(deslash($post->post_excerpt));
598 if ( empty($post->guid) )
599 $guid = get_permalink($post->ID);
603 $wpdb->update( $wpdb->posts, compact('post_title', 'post_content', 'post_excerpt', 'guid'), array('ID' => $post->ID) );
608 // Remove extraneous backslashes.
609 $comments = $wpdb->get_results("SELECT comment_ID, comment_author, comment_content FROM $wpdb->comments");
611 foreach($comments as $comment) {
612 $comment_content = deslash($comment->comment_content);
613 $comment_author = deslash($comment->comment_author);
615 $wpdb->update($wpdb->comments, compact('comment_content', 'comment_author'), array('comment_ID' => $comment->comment_ID) );
619 // Remove extraneous backslashes.
620 $links = $wpdb->get_results("SELECT link_id, link_name, link_description FROM $wpdb->links");
622 foreach($links as $link) {
623 $link_name = deslash($link->link_name);
624 $link_description = deslash($link->link_description);
626 $wpdb->update( $wpdb->links, compact('link_name', 'link_description'), array('link_id' => $link->link_id) );
630 $active_plugins = __get_option('active_plugins');
632 // If plugins are not stored in an array, they're stored in the old
633 // newline separated format. Convert to new format.
634 if ( !is_array( $active_plugins ) ) {
635 $active_plugins = explode("\n", trim($active_plugins));
636 update_option('active_plugins', $active_plugins);
640 $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optionvalues');
641 $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiontypes');
642 $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiongroups');
643 $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiongroup_options');
645 // Update comments table to use comment_type
646 $wpdb->query("UPDATE $wpdb->comments SET comment_type='trackback', comment_content = REPLACE(comment_content, '<trackback />', '') WHERE comment_content LIKE '<trackback />%'");
647 $wpdb->query("UPDATE $wpdb->comments SET comment_type='pingback', comment_content = REPLACE(comment_content, '<pingback />', '') WHERE comment_content LIKE '<pingback />%'");
649 // Some versions have multiple duplicate option_name rows with the same values
650 $options = $wpdb->get_results("SELECT option_name, COUNT(option_name) AS dupes FROM `$wpdb->options` GROUP BY option_name");
651 foreach ( $options as $option ) {
652 if ( 1 != $option->dupes ) { // Could this be done in the query?
653 $limit = $option->dupes - 1;
654 $dupe_ids = $wpdb->get_col( $wpdb->prepare("SELECT option_id FROM $wpdb->options WHERE option_name = %s LIMIT %d", $option->option_name, $limit) );
656 $dupe_ids = join($dupe_ids, ',');
657 $wpdb->query("DELETE FROM $wpdb->options WHERE option_id IN ($dupe_ids)");
666 * Execute changes made in WordPress 2.0.
670 function upgrade_160() {
671 global $wpdb, $wp_current_db_version;
673 populate_roles_160();
675 $users = $wpdb->get_results("SELECT * FROM $wpdb->users");
676 foreach ( $users as $user ) :
677 if ( !empty( $user->user_firstname ) )
678 update_user_meta( $user->ID, 'first_name', $wpdb->escape($user->user_firstname) );
679 if ( !empty( $user->user_lastname ) )
680 update_user_meta( $user->ID, 'last_name', $wpdb->escape($user->user_lastname) );
681 if ( !empty( $user->user_nickname ) )
682 update_user_meta( $user->ID, 'nickname', $wpdb->escape($user->user_nickname) );
683 if ( !empty( $user->user_level ) )
684 update_user_meta( $user->ID, $wpdb->prefix . 'user_level', $user->user_level );
685 if ( !empty( $user->user_icq ) )
686 update_user_meta( $user->ID, 'icq', $wpdb->escape($user->user_icq) );
687 if ( !empty( $user->user_aim ) )
688 update_user_meta( $user->ID, 'aim', $wpdb->escape($user->user_aim) );
689 if ( !empty( $user->user_msn ) )
690 update_user_meta( $user->ID, 'msn', $wpdb->escape($user->user_msn) );
691 if ( !empty( $user->user_yim ) )
692 update_user_meta( $user->ID, 'yim', $wpdb->escape($user->user_icq) );
693 if ( !empty( $user->user_description ) )
694 update_user_meta( $user->ID, 'description', $wpdb->escape($user->user_description) );
696 if ( isset( $user->user_idmode ) ):
697 $idmode = $user->user_idmode;
698 if ($idmode == 'nickname') $id = $user->user_nickname;
699 if ($idmode == 'login') $id = $user->user_login;
700 if ($idmode == 'firstname') $id = $user->user_firstname;
701 if ($idmode == 'lastname') $id = $user->user_lastname;
702 if ($idmode == 'namefl') $id = $user->user_firstname.' '.$user->user_lastname;
703 if ($idmode == 'namelf') $id = $user->user_lastname.' '.$user->user_firstname;
704 if (!$idmode) $id = $user->user_nickname;
705 $wpdb->update( $wpdb->users, array('display_name' => $id), array('ID' => $user->ID) );
708 // FIXME: RESET_CAPS is temporary code to reset roles and caps if flag is set.
709 $caps = get_user_meta( $user->ID, $wpdb->prefix . 'capabilities');
710 if ( empty($caps) || defined('RESET_CAPS') ) {
711 $level = get_user_meta($user->ID, $wpdb->prefix . 'user_level', true);
712 $role = translate_level_to_role($level);
713 update_user_meta( $user->ID, $wpdb->prefix . 'capabilities', array($role => true) );
717 $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' );
718 $wpdb->hide_errors();
719 foreach ( $old_user_fields as $old )
720 $wpdb->query("ALTER TABLE $wpdb->users DROP $old");
721 $wpdb->show_errors();
723 // populate comment_count field of posts table
724 $comments = $wpdb->get_results( "SELECT comment_post_ID, COUNT(*) as c FROM $wpdb->comments WHERE comment_approved = '1' GROUP BY comment_post_ID" );
725 if ( is_array( $comments ) )
726 foreach ($comments as $comment)
727 $wpdb->update( $wpdb->posts, array('comment_count' => $comment->c), array('ID' => $comment->comment_post_ID) );
729 // Some alpha versions used a post status of object instead of attachment and put
730 // the mime type in post_type instead of post_mime_type.
731 if ( $wp_current_db_version > 2541 && $wp_current_db_version <= 3091 ) {
732 $objects = $wpdb->get_results("SELECT ID, post_type FROM $wpdb->posts WHERE post_status = 'object'");
733 foreach ($objects as $object) {
734 $wpdb->update( $wpdb->posts, array( 'post_status' => 'attachment',
735 'post_mime_type' => $object->post_type,
737 array( 'ID' => $object->ID ) );
739 $meta = get_post_meta($object->ID, 'imagedata', true);
740 if ( ! empty($meta['file']) )
741 update_attached_file( $object->ID, $meta['file'] );
747 * Execute changes made in WordPress 2.1.
751 function upgrade_210() {
752 global $wpdb, $wp_current_db_version;
754 if ( $wp_current_db_version < 3506 ) {
755 // Update status and type.
756 $posts = $wpdb->get_results("SELECT ID, post_status FROM $wpdb->posts");
758 if ( ! empty($posts) ) foreach ($posts as $post) {
759 $status = $post->post_status;
762 if ( 'static' == $status ) {
765 } else if ( 'attachment' == $status ) {
767 $type = 'attachment';
770 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_status = %s, post_type = %s WHERE ID = %d", $status, $type, $post->ID) );
774 if ( $wp_current_db_version < 3845 ) {
775 populate_roles_210();
778 if ( $wp_current_db_version < 3531 ) {
779 // Give future posts a post_status of future.
780 $now = gmdate('Y-m-d H:i:59');
781 $wpdb->query ("UPDATE $wpdb->posts SET post_status = 'future' WHERE post_status = 'publish' AND post_date_gmt > '$now'");
783 $posts = $wpdb->get_results("SELECT ID, post_date FROM $wpdb->posts WHERE post_status ='future'");
784 if ( !empty($posts) )
785 foreach ( $posts as $post )
786 wp_schedule_single_event(mysql2date('U', $post->post_date, false), 'publish_future_post', array($post->ID));
791 * Execute changes made in WordPress 2.3.
795 function upgrade_230() {
796 global $wp_current_db_version, $wpdb;
798 if ( $wp_current_db_version < 5200 ) {
799 populate_roles_230();
802 // Convert categories to terms.
805 $categories = $wpdb->get_results("SELECT * FROM $wpdb->categories ORDER BY cat_ID");
806 foreach ($categories as $category) {
807 $term_id = (int) $category->cat_ID;
808 $name = $category->cat_name;
809 $description = $category->category_description;
810 $slug = $category->category_nicename;
811 $parent = $category->category_parent;
814 // Associate terms with the same slug in a term group and make slugs unique.
815 if ( $exists = $wpdb->get_results( $wpdb->prepare("SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $slug) ) ) {
816 $term_group = $exists[0]->term_group;
817 $id = $exists[0]->term_id;
820 $alt_slug = $slug . "-$num";
822 $slug_check = $wpdb->get_var( $wpdb->prepare("SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug) );
823 } while ( $slug_check );
827 if ( empty( $term_group ) ) {
828 $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms GROUP BY term_group") + 1;
829 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->terms SET term_group = %d WHERE term_id = %d", $term_group, $id) );
833 $wpdb->query( $wpdb->prepare("INSERT INTO $wpdb->terms (term_id, name, slug, term_group) VALUES
834 (%d, %s, %s, %d)", $term_id, $name, $slug, $term_group) );
837 if ( !empty($category->category_count) ) {
838 $count = (int) $category->category_count;
839 $taxonomy = 'category';
840 $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) );
841 $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
844 if ( !empty($category->link_count) ) {
845 $count = (int) $category->link_count;
846 $taxonomy = 'link_category';
847 $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) );
848 $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
851 if ( !empty($category->tag_count) ) {
853 $count = (int) $category->tag_count;
854 $taxonomy = 'post_tag';
855 $wpdb->insert( $wpdb->term_taxonomy, compact('term_id', 'taxonomy', 'description', 'parent', 'count') );
856 $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
859 if ( empty($count) ) {
861 $taxonomy = 'category';
862 $wpdb->insert( $wpdb->term_taxonomy, compact('term_id', 'taxonomy', 'description', 'parent', 'count') );
863 $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
867 $select = 'post_id, category_id';
869 $select .= ', rel_type';
871 $posts = $wpdb->get_results("SELECT $select FROM $wpdb->post2cat GROUP BY post_id, category_id");
872 foreach ( $posts as $post ) {
873 $post_id = (int) $post->post_id;
874 $term_id = (int) $post->category_id;
875 $taxonomy = 'category';
876 if ( !empty($post->rel_type) && 'tag' == $post->rel_type)
878 $tt_id = $tt_ids[$term_id][$taxonomy];
882 $wpdb->insert( $wpdb->term_relationships, array('object_id' => $post_id, 'term_taxonomy_id' => $tt_id) );
885 // < 3570 we used linkcategories. >= 3570 we used categories and link2cat.
886 if ( $wp_current_db_version < 3570 ) {
887 // Create link_category terms for link categories. Create a map of link cat IDs
888 // to link_category terms.
889 $link_cat_id_map = array();
890 $default_link_cat = 0;
892 $link_cats = $wpdb->get_results("SELECT cat_id, cat_name FROM " . $wpdb->prefix . 'linkcategories');
893 foreach ( $link_cats as $category) {
894 $cat_id = (int) $category->cat_id;
896 $name = $wpdb->escape($category->cat_name);
897 $slug = sanitize_title($name);
900 // Associate terms with the same slug in a term group and make slugs unique.
901 if ( $exists = $wpdb->get_results( $wpdb->prepare("SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $slug) ) ) {
902 $term_group = $exists[0]->term_group;
903 $term_id = $exists[0]->term_id;
906 if ( empty($term_id) ) {
907 $wpdb->insert( $wpdb->terms, compact('name', 'slug', 'term_group') );
908 $term_id = (int) $wpdb->insert_id;
911 $link_cat_id_map[$cat_id] = $term_id;
912 $default_link_cat = $term_id;
914 $wpdb->insert( $wpdb->term_taxonomy, array('term_id' => $term_id, 'taxonomy' => 'link_category', 'description' => '', 'parent' => 0, 'count' => 0) );
915 $tt_ids[$term_id] = (int) $wpdb->insert_id;
918 // Associate links to cats.
919 $links = $wpdb->get_results("SELECT link_id, link_category FROM $wpdb->links");
920 if ( !empty($links) ) foreach ( $links as $link ) {
921 if ( 0 == $link->link_category )
923 if ( ! isset($link_cat_id_map[$link->link_category]) )
925 $term_id = $link_cat_id_map[$link->link_category];
926 $tt_id = $tt_ids[$term_id];
930 $wpdb->insert( $wpdb->term_relationships, array('object_id' => $link->link_id, 'term_taxonomy_id' => $tt_id) );
933 // Set default to the last category we grabbed during the upgrade loop.
934 update_option('default_link_category', $default_link_cat);
936 $links = $wpdb->get_results("SELECT link_id, category_id FROM $wpdb->link2cat GROUP BY link_id, category_id");
937 foreach ( $links as $link ) {
938 $link_id = (int) $link->link_id;
939 $term_id = (int) $link->category_id;
940 $taxonomy = 'link_category';
941 $tt_id = $tt_ids[$term_id][$taxonomy];
944 $wpdb->insert( $wpdb->term_relationships, array('object_id' => $link_id, 'term_taxonomy_id' => $tt_id) );
948 if ( $wp_current_db_version < 4772 ) {
949 // Obsolete linkcategories table
950 $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'linkcategories');
953 // Recalculate all counts
954 $terms = $wpdb->get_results("SELECT term_taxonomy_id, taxonomy FROM $wpdb->term_taxonomy");
955 foreach ( (array) $terms as $term ) {
956 if ( ('post_tag' == $term->taxonomy) || ('category' == $term->taxonomy) )
957 $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) );
959 $count = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term->term_taxonomy_id) );
960 $wpdb->update( $wpdb->term_taxonomy, array('count' => $count), array('term_taxonomy_id' => $term->term_taxonomy_id) );
965 * Remove old options from the database.
969 function upgrade_230_options_table() {
971 $old_options_fields = array( 'option_can_override', 'option_type', 'option_width', 'option_height', 'option_description', 'option_admin_level' );
972 $wpdb->hide_errors();
973 foreach ( $old_options_fields as $old )
974 $wpdb->query("ALTER TABLE $wpdb->options DROP $old");
975 $wpdb->show_errors();
979 * Remove old categories, link2cat, and post2cat database tables.
983 function upgrade_230_old_tables() {
985 $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'categories');
986 $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'link2cat');
987 $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'post2cat');
991 * Upgrade old slugs made in version 2.2.
995 function upgrade_old_slugs() {
996 // upgrade people who were using the Redirect Old Slugs plugin
998 $wpdb->query("UPDATE $wpdb->postmeta SET meta_key = '_wp_old_slug' WHERE meta_key = 'old_slug'");
1002 * Execute changes made in WordPress 2.5.0.
1006 function upgrade_250() {
1007 global $wp_current_db_version;
1009 if ( $wp_current_db_version < 6689 ) {
1010 populate_roles_250();
1016 * Execute changes made in WordPress 2.5.2.
1020 function upgrade_252() {
1023 $wpdb->query("UPDATE $wpdb->users SET user_activation_key = ''");
1027 * Execute changes made in WordPress 2.6.
1031 function upgrade_260() {
1032 global $wp_current_db_version;
1034 if ( $wp_current_db_version < 8000 )
1035 populate_roles_260();
1037 if ( $wp_current_db_version < 8201 ) {
1038 update_option('enable_app', 1);
1039 update_option('enable_xmlrpc', 1);
1044 * Execute changes made in WordPress 2.7.
1048 function upgrade_270() {
1049 global $wpdb, $wp_current_db_version;
1051 if ( $wp_current_db_version < 8980 )
1052 populate_roles_270();
1054 // Update post_date for unpublished posts with empty timestamp
1055 if ( $wp_current_db_version < 8921 )
1056 $wpdb->query( "UPDATE $wpdb->posts SET post_date = post_modified WHERE post_date = '0000-00-00 00:00:00'" );
1060 * Execute changes made in WordPress 2.8.
1064 function upgrade_280() {
1065 global $wp_current_db_version, $wpdb;
1067 if ( $wp_current_db_version < 10360 )
1068 populate_roles_280();
1069 if ( is_multisite() ) {
1071 while( $rows = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options ORDER BY option_id LIMIT $start, 20" ) ) {
1072 foreach( $rows as $row ) {
1073 $value = $row->option_value;
1074 if ( !@unserialize( $value ) )
1075 $value = stripslashes( $value );
1076 if ( $value !== $row->option_value ) {
1077 update_option( $row->option_name, $value );
1082 refresh_blog_details( $wpdb->blogid );
1087 * Execute changes made in WordPress 2.9.
1091 function upgrade_290() {
1092 global $wp_current_db_version;
1094 if ( $wp_current_db_version < 11958 ) {
1095 // Previously, setting depth to 1 would redundantly disable threading, but now 2 is the minimum depth to avoid confusion
1096 if ( get_option( 'thread_comments_depth' ) == '1' ) {
1097 update_option( 'thread_comments_depth', 2 );
1098 update_option( 'thread_comments', 0 );
1104 * Execute changes made in WordPress 3.0.
1108 function upgrade_300() {
1109 global $wp_current_db_version, $wpdb;
1111 if ( $wp_current_db_version < 15093 )
1112 populate_roles_300();
1114 if ( $wp_current_db_version < 14139 && is_multisite() && is_main_site() && ! defined( 'MULTISITE' ) && get_site_option( 'siteurl' ) === false )
1115 add_site_option( 'siteurl', '' );
1117 // 3.0-alpha nav menu postmeta changes. can be removed before release. // r13802
1118 if ( $wp_current_db_version >= 13226 && $wp_current_db_version < 13974 )
1119 $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' )" );
1121 // 3.0-beta1 remove_user primitive->meta cap. can be removed before release. r13956
1122 if ( $wp_current_db_version >= 12751 && $wp_current_db_version < 13974 ) {
1123 $role =& get_role( 'administrator' );
1124 if ( ! empty( $role ) )
1125 $role->remove_cap( 'remove_user' );
1128 // 3.0-beta1 nav menu postmeta changes. can be removed before release. r13974
1129 if ( $wp_current_db_version >= 13802 && $wp_current_db_version < 13974 )
1130 $wpdb->update( $wpdb->postmeta, array( 'meta_value' => '' ), array( 'meta_key' => '_menu_item_target', 'meta_value' => '_self' ) );
1132 // 3.0 screen options key name changes.
1133 if ( is_main_site() && !defined('DO_NOT_UPGRADE_GLOBAL_TABLES') ) {
1134 $prefix = like_escape($wpdb->base_prefix);
1135 $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%'
1136 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'" );
1142 * Execute network level changes
1146 function upgrade_network() {
1147 global $wp_current_db_version, $wpdb;
1149 if ( $wp_current_db_version < 11549 ) {
1150 $wpmu_sitewide_plugins = get_site_option( 'wpmu_sitewide_plugins' );
1151 $active_sitewide_plugins = get_site_option( 'active_sitewide_plugins' );
1152 if ( $wpmu_sitewide_plugins ) {
1153 if ( !$active_sitewide_plugins )
1154 $sitewide_plugins = (array) $wpmu_sitewide_plugins;
1156 $sitewide_plugins = array_merge( (array) $active_sitewide_plugins, (array) $wpmu_sitewide_plugins );
1158 update_site_option( 'active_sitewide_plugins', $sitewide_plugins );
1160 delete_site_option( 'wpmu_sitewide_plugins' );
1161 delete_site_option( 'deactivated_sitewide_plugins' );
1164 while( $rows = $wpdb->get_results( "SELECT meta_key, meta_value FROM {$wpdb->sitemeta} ORDER BY meta_id LIMIT $start, 20" ) ) {
1165 foreach( $rows as $row ) {
1166 $value = $row->meta_value;
1167 if ( !@unserialize( $value ) )
1168 $value = stripslashes( $value );
1169 if ( $value !== $row->meta_value ) {
1170 update_site_option( $row->meta_key, $value );
1177 if ( $wp_current_db_version < 13576 )
1178 update_site_option( 'global_terms_enabled', '1' );
1181 // The functions we use to actually do stuff
1186 * {@internal Missing Short Description}}
1188 * {@internal Missing Long Description}}
1192 * @param string $table_name Database table name to create.
1193 * @param string $create_ddl SQL statement to create table.
1194 * @return bool If table already exists or was created by function.
1196 function maybe_create_table($table_name, $create_ddl) {
1198 if ( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") == $table_name )
1200 //didn't find it try to create it.
1201 $q = $wpdb->query($create_ddl);
1202 // we cannot directly tell that whether this succeeded!
1203 if ( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") == $table_name )
1209 * {@internal Missing Short Description}}
1211 * {@internal Missing Long Description}}
1215 * @param string $table Database table name.
1216 * @param string $index Index name to drop.
1217 * @return bool True, when finished.
1219 function drop_index($table, $index) {
1221 $wpdb->hide_errors();
1222 $wpdb->query("ALTER TABLE `$table` DROP INDEX `$index`");
1223 // Now we need to take out all the extra ones we may have created
1224 for ($i = 0; $i < 25; $i++) {
1225 $wpdb->query("ALTER TABLE `$table` DROP INDEX `{$index}_$i`");
1227 $wpdb->show_errors();
1232 * {@internal Missing Short Description}}
1234 * {@internal Missing Long Description}}
1238 * @param string $table Database table name.
1239 * @param string $index Database table index column.
1240 * @return bool True, when done with execution.
1242 function add_clean_index($table, $index) {
1244 drop_index($table, $index);
1245 $wpdb->query("ALTER TABLE `$table` ADD INDEX ( `$index` )");
1250 ** maybe_add_column()
1251 ** Add column to db table if it doesn't exist.
1252 ** Returns: true if already exists or on successful completion
1255 function maybe_add_column($table_name, $column_name, $create_ddl) {
1256 global $wpdb, $debug;
1257 foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) {
1258 if ($debug) echo("checking $column == $column_name<br />");
1259 if ($column == $column_name) {
1263 //didn't find it try to create it.
1264 $q = $wpdb->query($create_ddl);
1265 // we cannot directly tell that whether this succeeded!
1266 foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) {
1267 if ($column == $column_name) {
1275 * Retrieve all options as it was for 1.2.
1279 * @return array List of options.
1281 function get_alloptions_110() {
1283 if ($options = $wpdb->get_results("SELECT option_name, option_value FROM $wpdb->options")) {
1284 foreach ($options as $option) {
1285 // "When trying to design a foolproof system,
1286 // never underestimate the ingenuity of the fools :)" -- Dougal
1287 if ('siteurl' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value);
1288 if ('home' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value);
1289 if ('category_base' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value);
1290 $all_options->{$option->option_name} = stripslashes($option->option_value);
1293 return $all_options;
1297 * Version of get_option that is private to install/upgrade.
1302 * @param string $setting Option name.
1305 function __get_option($setting) {
1308 if ( $setting == 'home' && defined( 'WP_HOME' ) ) {
1309 return preg_replace( '|/+$|', '', WP_HOME );
1312 if ( $setting == 'siteurl' && defined( 'WP_SITEURL' ) ) {
1313 return preg_replace( '|/+$|', '', WP_SITEURL );
1316 $option = $wpdb->get_var( $wpdb->prepare("SELECT option_value FROM $wpdb->options WHERE option_name = %s", $setting) );
1318 if ( 'home' == $setting && '' == $option )
1319 return __get_option('siteurl');
1321 if ( 'siteurl' == $setting || 'home' == $setting || 'category_base' == $setting )
1322 $option = preg_replace('|/+$|', '', $option);
1324 @ $kellogs = unserialize($option);
1325 if ($kellogs !== FALSE)
1332 * {@internal Missing Short Description}}
1334 * {@internal Missing Long Description}}
1338 * @param string $content
1341 function deslash($content) {
1342 // Note: \\\ inside a regex denotes a single backslash.
1344 // Replace one or more backslashes followed by a single quote with
1346 $content = preg_replace("/\\\+'/", "'", $content);
1348 // Replace one or more backslashes followed by a double quote with
1350 $content = preg_replace('/\\\+"/', '"', $content);
1352 // Replace one or more backslashes with one backslash.
1353 $content = preg_replace("/\\\+/", "\\", $content);
1359 * {@internal Missing Short Description}}
1361 * {@internal Missing Long Description}}
1365 * @param unknown_type $queries
1366 * @param unknown_type $execute
1369 function dbDelta($queries, $execute = true) {
1372 // Separate individual queries into an array
1373 if ( !is_array($queries) ) {
1374 $queries = explode( ';', $queries );
1375 if ('' == $queries[count($queries) - 1]) array_pop($queries);
1378 $cqueries = array(); // Creation Queries
1379 $iqueries = array(); // Insertion Queries
1380 $for_update = array();
1382 // Create a tablename index for an array ($cqueries) of queries
1383 foreach($queries as $qry) {
1384 if (preg_match("|CREATE TABLE ([^ ]*)|", $qry, $matches)) {
1385 $cqueries[trim( strtolower($matches[1]), '`' )] = $qry;
1386 $for_update[$matches[1]] = 'Created table '.$matches[1];
1387 } else if (preg_match("|CREATE DATABASE ([^ ]*)|", $qry, $matches)) {
1388 array_unshift($cqueries, $qry);
1389 } else if (preg_match("|INSERT INTO ([^ ]*)|", $qry, $matches)) {
1391 } else if (preg_match("|UPDATE ([^ ]*)|", $qry, $matches)) {
1394 // Unrecognized query type
1398 // Check to see which tables and fields exist
1399 if ($tables = $wpdb->get_col('SHOW TABLES;')) {
1400 // For every table in the database
1401 foreach ($tables as $table) {
1402 // Upgrade global tables only for the main site. Don't upgrade at all if DO_NOT_UPGRADE_GLOBAL_TABLES is defined.
1403 if ( in_array($table, $wpdb->tables('global')) && ( !is_main_site() || defined('DO_NOT_UPGRADE_GLOBAL_TABLES') ) )
1406 // If a table query exists for the database table...
1407 if ( array_key_exists(strtolower($table), $cqueries) ) {
1408 // Clear the field and index arrays
1409 $cfields = $indices = array();
1410 // Get all of the field names in the query from between the parens
1411 preg_match("|\((.*)\)|ms", $cqueries[strtolower($table)], $match2);
1412 $qryline = trim($match2[1]);
1414 // Separate field lines into an array
1415 $flds = explode("\n", $qryline);
1417 //echo "<hr/><pre>\n".print_r(strtolower($table), true).":\n".print_r($cqueries, true)."</pre><hr/>";
1419 // For every field line specified in the query
1420 foreach ($flds as $fld) {
1421 // Extract the field name
1422 preg_match("|^([^ ]*)|", trim($fld), $fvals);
1423 $fieldname = trim( $fvals[1], '`' );
1425 // Verify the found field name
1427 switch (strtolower($fieldname)) {
1434 $validfield = false;
1435 $indices[] = trim(trim($fld), ", \n");
1440 // If it's a valid field, add it to the field array
1442 $cfields[strtolower($fieldname)] = trim($fld, ", \n");
1446 // Fetch the table column structure from the database
1447 $tablefields = $wpdb->get_results("DESCRIBE {$table};");
1449 // For every field in the table
1450 foreach ($tablefields as $tablefield) {
1451 // If the table field exists in the field array...
1452 if (array_key_exists(strtolower($tablefield->Field), $cfields)) {
1453 // Get the field type from the query
1454 preg_match("|".$tablefield->Field." ([^ ]*( unsigned)?)|i", $cfields[strtolower($tablefield->Field)], $matches);
1455 $fieldtype = $matches[1];
1457 // Is actual field type different from the field type in query?
1458 if ($tablefield->Type != $fieldtype) {
1459 // Add a query to change the column type
1460 $cqueries[] = "ALTER TABLE {$table} CHANGE COLUMN {$tablefield->Field} " . $cfields[strtolower($tablefield->Field)];
1461 $for_update[$table.'.'.$tablefield->Field] = "Changed type of {$table}.{$tablefield->Field} from {$tablefield->Type} to {$fieldtype}";
1464 // Get the default value from the array
1465 //echo "{$cfields[strtolower($tablefield->Field)]}<br>";
1466 if (preg_match("| DEFAULT '(.*)'|i", $cfields[strtolower($tablefield->Field)], $matches)) {
1467 $default_value = $matches[1];
1468 if ($tablefield->Default != $default_value) {
1469 // Add a query to change the column's default value
1470 $cqueries[] = "ALTER TABLE {$table} ALTER COLUMN {$tablefield->Field} SET DEFAULT '{$default_value}'";
1471 $for_update[$table.'.'.$tablefield->Field] = "Changed default value of {$table}.{$tablefield->Field} from {$tablefield->Default} to {$default_value}";
1475 // Remove the field from the array (so it's not added)
1476 unset($cfields[strtolower($tablefield->Field)]);
1478 // This field exists in the table, but not in the creation queries?
1482 // For every remaining field specified for the table
1483 foreach ($cfields as $fieldname => $fielddef) {
1484 // Push a query line into $cqueries that adds the field to that table
1485 $cqueries[] = "ALTER TABLE {$table} ADD COLUMN $fielddef";
1486 $for_update[$table.'.'.$fieldname] = 'Added column '.$table.'.'.$fieldname;
1489 // Index stuff goes here
1490 // Fetch the table index structure from the database
1491 $tableindices = $wpdb->get_results("SHOW INDEX FROM {$table};");
1493 if ($tableindices) {
1494 // Clear the index array
1497 // For every index in the table
1498 foreach ($tableindices as $tableindex) {
1499 // Add the index to the index data array
1500 $keyname = $tableindex->Key_name;
1501 $index_ary[$keyname]['columns'][] = array('fieldname' => $tableindex->Column_name, 'subpart' => $tableindex->Sub_part);
1502 $index_ary[$keyname]['unique'] = ($tableindex->Non_unique == 0)?true:false;
1505 // For each actual index in the index array
1506 foreach ($index_ary as $index_name => $index_data) {
1507 // Build a create string to compare to the query
1509 if ($index_name == 'PRIMARY') {
1510 $index_string .= 'PRIMARY ';
1511 } else if($index_data['unique']) {
1512 $index_string .= 'UNIQUE ';
1514 $index_string .= 'KEY ';
1515 if ($index_name != 'PRIMARY') {
1516 $index_string .= $index_name;
1518 $index_columns = '';
1519 // For each column in the index
1520 foreach ($index_data['columns'] as $column_data) {
1521 if ($index_columns != '') $index_columns .= ',';
1522 // Add the field to the column list string
1523 $index_columns .= $column_data['fieldname'];
1524 if ($column_data['subpart'] != '') {
1525 $index_columns .= '('.$column_data['subpart'].')';
1528 // Add the column list to the index create string
1529 $index_string .= ' ('.$index_columns.')';
1530 if (!(($aindex = array_search($index_string, $indices)) === false)) {
1531 unset($indices[$aindex]);
1532 //echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">{$table}:<br />Found index:".$index_string."</pre>\n";
1534 //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";
1538 // For every remaining index specified for the table
1539 foreach ( (array) $indices as $index ) {
1540 // Push a query line into $cqueries that adds the index to that table
1541 $cqueries[] = "ALTER TABLE {$table} ADD $index";
1542 $for_update[$table.'.'.$fieldname] = 'Added index '.$table.' '.$index;
1545 // Remove the original table creation query from processing
1546 unset($cqueries[strtolower($table)]);
1547 unset($for_update[strtolower($table)]);
1549 // This table exists in the database, but not in the creation queries?
1554 $allqueries = array_merge($cqueries, $iqueries);
1556 foreach ($allqueries as $query) {
1557 //echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">".print_r($query, true)."</pre>\n";
1558 $wpdb->query($query);
1566 * {@internal Missing Short Description}}
1568 * {@internal Missing Long Description}}
1572 function make_db_current() {
1575 $alterations = dbDelta($wp_queries);
1577 foreach($alterations as $alteration) echo "<li>$alteration</li>\n";
1582 * {@internal Missing Short Description}}
1584 * {@internal Missing Long Description}}
1588 function make_db_current_silent() {
1591 $alterations = dbDelta($wp_queries);
1595 * {@internal Missing Short Description}}
1597 * {@internal Missing Long Description}}
1601 * @param unknown_type $theme_name
1602 * @param unknown_type $template
1605 function make_site_theme_from_oldschool($theme_name, $template) {
1606 $home_path = get_home_path();
1607 $site_dir = WP_CONTENT_DIR . "/themes/$template";
1609 if (! file_exists("$home_path/index.php"))
1612 // Copy files from the old locations to the site theme.
1613 // TODO: This does not copy arbitarary include dependencies. Only the
1614 // standard WP files are copied.
1615 $files = array('index.php' => 'index.php', 'wp-layout.css' => 'style.css', 'wp-comments.php' => 'comments.php', 'wp-comments-popup.php' => 'comments-popup.php');
1617 foreach ($files as $oldfile => $newfile) {
1618 if ($oldfile == 'index.php')
1619 $oldpath = $home_path;
1623 if ($oldfile == 'index.php') { // Check to make sure it's not a new index
1624 $index = implode('', file("$oldpath/$oldfile"));
1625 if (strpos($index, 'WP_USE_THEMES') !== false) {
1626 if (! @copy(WP_CONTENT_DIR . '/themes/' . WP_DEFAULT_THEME . '/index.php', "$site_dir/$newfile"))
1628 continue; // Don't copy anything
1632 if (! @copy("$oldpath/$oldfile", "$site_dir/$newfile"))
1635 chmod("$site_dir/$newfile", 0777);
1637 // Update the blog header include in each file.
1638 $lines = explode("\n", implode('', file("$site_dir/$newfile")));
1640 $f = fopen("$site_dir/$newfile", 'w');
1642 foreach ($lines as $line) {
1643 if (preg_match('/require.*wp-blog-header/', $line))
1644 $line = '//' . $line;
1646 // Update stylesheet references.
1647 $line = str_replace("<?php echo __get_option('siteurl'); ?>/wp-layout.css", "<?php bloginfo('stylesheet_url'); ?>", $line);
1649 // Update comments template inclusion.
1650 $line = str_replace("<?php include(ABSPATH . 'wp-comments.php'); ?>", "<?php comments_template(); ?>", $line);
1652 fwrite($f, "{$line}\n");
1658 // Add a theme header.
1659 $header = "/*\nTheme Name: $theme_name\nTheme URI: " . __get_option('siteurl') . "\nDescription: A theme automatically created by the upgrade.\nVersion: 1.0\nAuthor: Moi\n*/\n";
1661 $stylelines = file_get_contents("$site_dir/style.css");
1663 $f = fopen("$site_dir/style.css", 'w');
1665 fwrite($f, $header);
1666 fwrite($f, $stylelines);
1674 * {@internal Missing Short Description}}
1676 * {@internal Missing Long Description}}
1680 * @param unknown_type $theme_name
1681 * @param unknown_type $template
1684 function make_site_theme_from_default($theme_name, $template) {
1685 $site_dir = WP_CONTENT_DIR . "/themes/$template";
1686 $default_dir = WP_CONTENT_DIR . '/themes/' . WP_DEFAULT_THEME;
1688 // Copy files from the default theme to the site theme.
1689 //$files = array('index.php', 'comments.php', 'comments-popup.php', 'footer.php', 'header.php', 'sidebar.php', 'style.css');
1691 $theme_dir = @ opendir($default_dir);
1693 while(($theme_file = readdir( $theme_dir )) !== false) {
1694 if (is_dir("$default_dir/$theme_file"))
1696 if (! @copy("$default_dir/$theme_file", "$site_dir/$theme_file"))
1698 chmod("$site_dir/$theme_file", 0777);
1701 @closedir($theme_dir);
1703 // Rewrite the theme header.
1704 $stylelines = explode("\n", implode('', file("$site_dir/style.css")));
1706 $f = fopen("$site_dir/style.css", 'w');
1708 foreach ($stylelines as $line) {
1709 if (strpos($line, 'Theme Name:') !== false) $line = 'Theme Name: ' . $theme_name;
1710 elseif (strpos($line, 'Theme URI:') !== false) $line = 'Theme URI: ' . __get_option('url');
1711 elseif (strpos($line, 'Description:') !== false) $line = 'Description: Your theme.';
1712 elseif (strpos($line, 'Version:') !== false) $line = 'Version: 1';
1713 elseif (strpos($line, 'Author:') !== false) $line = 'Author: You';
1714 fwrite($f, $line . "\n");
1721 if (! mkdir("$site_dir/images", 0777)) {
1725 $images_dir = @ opendir("$default_dir/images");
1727 while(($image = readdir($images_dir)) !== false) {
1728 if (is_dir("$default_dir/images/$image"))
1730 if (! @copy("$default_dir/images/$image", "$site_dir/images/$image"))
1732 chmod("$site_dir/images/$image", 0777);
1735 @closedir($images_dir);
1738 // Create a site theme from the default theme.
1740 * {@internal Missing Short Description}}
1742 * {@internal Missing Long Description}}
1748 function make_site_theme() {
1749 // Name the theme after the blog.
1750 $theme_name = __get_option('blogname');
1751 $template = sanitize_title($theme_name);
1752 $site_dir = WP_CONTENT_DIR . "/themes/$template";
1754 // If the theme already exists, nothing to do.
1755 if ( is_dir($site_dir)) {
1759 // We must be able to write to the themes dir.
1760 if (! is_writable(WP_CONTENT_DIR . "/themes")) {
1765 if (! mkdir($site_dir, 0777)) {
1769 if (file_exists(ABSPATH . 'wp-layout.css')) {
1770 if (! make_site_theme_from_oldschool($theme_name, $template)) {
1771 // TODO: rm -rf the site theme directory.
1775 if (! make_site_theme_from_default($theme_name, $template))
1776 // TODO: rm -rf the site theme directory.
1780 // Make the new site theme active.
1781 $current_template = __get_option('template');
1782 if ($current_template == WP_DEFAULT_THEME) {
1783 update_option('template', $template);
1784 update_option('stylesheet', $template);
1790 * Translate user level to user role name.
1794 * @param int $level User level.
1795 * @return string User role name.
1797 function translate_level_to_role($level) {
1802 return 'administrator';
1812 return 'contributor';
1814 return 'subscriber';
1819 * {@internal Missing Short Description}}
1821 * {@internal Missing Long Description}}
1825 function wp_check_mysql_version() {
1827 $result = $wpdb->check_database_version();
1828 if ( is_wp_error( $result ) )
1829 die( $result->get_error_message() );
1833 * {@internal Missing Short Description}}
1835 * {@internal Missing Long Description}}
1839 function maybe_disable_automattic_widgets() {
1840 $plugins = __get_option( 'active_plugins' );
1842 foreach ( (array) $plugins as $plugin ) {
1843 if ( basename( $plugin ) == 'widgets.php' ) {
1844 array_splice( $plugins, array_search( $plugin, $plugins ), 1 );
1845 update_option( 'active_plugins', $plugins );
1852 * Runs before the schema is upgraded.
1854 function pre_schema_upgrade() {
1855 global $wp_current_db_version, $wp_db_version, $wpdb;
1857 // Upgrade versions prior to 2.9
1858 if ( $wp_current_db_version < 11557 ) {
1859 // Delete duplicate options. Keep the option with the highest option_id.
1860 $wpdb->query("DELETE o1 FROM $wpdb->options AS o1 JOIN $wpdb->options AS o2 USING (`option_name`) WHERE o2.option_id > o1.option_id");
1862 // Drop the old primary key and add the new.
1863 $wpdb->query("ALTER TABLE $wpdb->options DROP PRIMARY KEY, ADD PRIMARY KEY(option_id)");
1865 // Drop the old option_name index. dbDelta() doesn't do the drop.
1866 $wpdb->query("ALTER TABLE $wpdb->options DROP INDEX option_name");
1877 if ( !function_exists( 'install_network' ) ) :
1878 function install_network() {
1879 global $wpdb, $charset_collate;
1881 CREATE TABLE $wpdb->users (
1882 ID bigint(20) unsigned NOT NULL auto_increment,
1883 user_login varchar(60) NOT NULL default '',
1884 user_pass varchar(64) NOT NULL default '',
1885 user_nicename varchar(50) NOT NULL default '',
1886 user_email varchar(100) NOT NULL default '',
1887 user_url varchar(100) NOT NULL default '',
1888 user_registered datetime NOT NULL default '0000-00-00 00:00:00',
1889 user_activation_key varchar(60) NOT NULL default '',
1890 user_status int(11) NOT NULL default '0',
1891 display_name varchar(250) NOT NULL default '',
1892 spam tinyint(2) NOT NULL default '0',
1893 deleted tinyint(2) NOT NULL default '0',
1895 KEY user_login_key (user_login),
1896 KEY user_nicename (user_nicename)
1898 CREATE TABLE $wpdb->blogs (
1899 blog_id bigint(20) NOT NULL auto_increment,
1900 site_id bigint(20) NOT NULL default '0',
1901 domain varchar(200) NOT NULL default '',
1902 path varchar(100) NOT NULL default '',
1903 registered datetime NOT NULL default '0000-00-00 00:00:00',
1904 last_updated datetime NOT NULL default '0000-00-00 00:00:00',
1905 public tinyint(2) NOT NULL default '1',
1906 archived enum('0','1') NOT NULL default '0',
1907 mature tinyint(2) NOT NULL default '0',
1908 spam tinyint(2) NOT NULL default '0',
1909 deleted tinyint(2) NOT NULL default '0',
1910 lang_id int(11) NOT NULL default '0',
1911 PRIMARY KEY (blog_id),
1912 KEY domain (domain(50),path(5)),
1913 KEY lang_id (lang_id)
1915 CREATE TABLE $wpdb->blog_versions (
1916 blog_id bigint(20) NOT NULL default '0',
1917 db_version varchar(20) NOT NULL default '',
1918 last_updated datetime NOT NULL default '0000-00-00 00:00:00',
1919 PRIMARY KEY (blog_id),
1920 KEY db_version (db_version)
1922 CREATE TABLE $wpdb->registration_log (
1923 ID bigint(20) NOT NULL auto_increment,
1924 email varchar(255) NOT NULL default '',
1925 IP varchar(30) NOT NULL default '',
1926 blog_id bigint(20) NOT NULL default '0',
1927 date_registered datetime NOT NULL default '0000-00-00 00:00:00',
1931 CREATE TABLE $wpdb->site (
1932 id bigint(20) NOT NULL auto_increment,
1933 domain varchar(200) NOT NULL default '',
1934 path varchar(100) NOT NULL default '',
1936 KEY domain (domain,path)
1938 CREATE TABLE $wpdb->sitemeta (
1939 meta_id bigint(20) NOT NULL auto_increment,
1940 site_id bigint(20) NOT NULL default '0',
1941 meta_key varchar(255) default NULL,
1942 meta_value longtext,
1943 PRIMARY KEY (meta_id),
1944 KEY meta_key (meta_key),
1945 KEY site_id (site_id)
1947 CREATE TABLE $wpdb->signups (
1948 domain varchar(200) NOT NULL default '',
1949 path varchar(100) NOT NULL default '',
1950 title longtext NOT NULL,
1951 user_login varchar(60) NOT NULL default '',
1952 user_email varchar(100) NOT NULL default '',
1953 registered datetime NOT NULL default '0000-00-00 00:00:00',
1954 activated datetime NOT NULL default '0000-00-00 00:00:00',
1955 active tinyint(1) NOT NULL default '0',
1956 activation_key varchar(50) NOT NULL default '',
1958 KEY activation_key (activation_key),
1962 // now create tables
1963 dbDelta( $ms_queries );
1968 * Install global terms.
1973 if ( !function_exists( 'install_global_terms' ) ) :
1974 function install_global_terms() {
1975 global $wpdb, $charset_collate;
1977 CREATE TABLE $wpdb->sitecategories (
1978 cat_ID bigint(20) NOT NULL auto_increment,
1979 cat_name varchar(55) NOT NULL default '',
1980 category_nicename varchar(200) NOT NULL default '',
1981 last_updated timestamp NOT NULL,
1982 PRIMARY KEY (cat_ID),
1983 KEY category_nicename (category_nicename),
1984 KEY last_updated (last_updated)
1987 // now create tables
1988 dbDelta( $ms_queries );