[ Index ]

PHP Cross Reference of Wordpress 2.9.1

title

Body

[close]

/wp-admin/includes/ -> upgrade.php (source)

   1  <?php
   2  /**
   3   * WordPress Upgrade API
   4   *
   5   * Most of the functions are pluggable and can be overwritten
   6   *
   7   * @package WordPress
   8   * @subpackage Administration
   9   */
  10  
  11  /** Include user install customize script. */
  12  if ( file_exists(WP_CONTENT_DIR . '/install.php') )
  13      require (WP_CONTENT_DIR . '/install.php');
  14  
  15  /** WordPress Administration API */
  16  require_once (ABSPATH . 'wp-admin/includes/admin.php');
  17  
  18  /** WordPress Schema API */
  19  require_once (ABSPATH . 'wp-admin/includes/schema.php');
  20  
  21  if ( !function_exists('wp_install') ) :
  22  /**
  23   * Installs the blog
  24   *
  25   * {@internal Missing Long Description}}
  26   *
  27   * @since unknown
  28   *
  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   * @return array Array keys 'url', 'user_id', 'password', 'password_message'.
  35   */
  36  function wp_install($blog_title, $user_name, $user_email, $public, $deprecated='') {
  37      global $wp_rewrite;
  38  
  39      wp_check_mysql_version();
  40      wp_cache_flush();
  41      make_db_current_silent();
  42      populate_options();
  43      populate_roles();
  44  
  45      update_option('blogname', $blog_title);
  46      update_option('admin_email', $user_email);
  47      update_option('blog_public', $public);
  48  
  49      $guessurl = wp_guess_url();
  50  
  51      update_option('siteurl', $guessurl);
  52  
  53      // If not a public blog, don't ping.
  54      if ( ! $public )
  55          update_option('default_pingback_flag', 0);
  56  
  57      // Create default user.  If the user already exists, the user tables are
  58      // being shared among blogs.  Just set the role in that case.
  59      $user_id = username_exists($user_name);
  60      if ( !$user_id ) {
  61          $random_password = wp_generate_password();
  62          $message = __('<strong><em>Note that password</em></strong> carefully! It is a <em>random</em> password that was generated just for you.');
  63          $user_id = wp_create_user($user_name, $random_password, $user_email);
  64          update_usermeta($user_id, 'default_password_nag', true);
  65      } else {
  66          $random_password = '';
  67          $message =  __('User already exists.  Password inherited.');
  68      }
  69  
  70      $user = new WP_User($user_id);
  71      $user->set_role('administrator');
  72  
  73      wp_install_defaults($user_id);
  74  
  75      $wp_rewrite->flush_rules();
  76  
  77      wp_new_blog_notification($blog_title, $guessurl, $user_id, $random_password);
  78  
  79      wp_cache_flush();
  80  
  81      return array('url' => $guessurl, 'user_id' => $user_id, 'password' => $random_password, 'password_message' => $message);
  82  }
  83  endif;
  84  
  85  if ( !function_exists('wp_install_defaults') ) :
  86  /**
  87   * {@internal Missing Short Description}}
  88   *
  89   * {@internal Missing Long Description}}
  90   *
  91   * @since unknown
  92   *
  93   * @param int $user_id User ID.
  94   */
  95  function wp_install_defaults($user_id) {
  96      global $wpdb;
  97  
  98      // Default category
  99      $cat_name = __('Uncategorized');
 100      /* translators: Default category slug */
 101      $cat_slug = sanitize_title(_x('Uncategorized', 'Default category slug'));
 102  
 103      $wpdb->insert( $wpdb->terms, array('name' => $cat_name, 'slug' => $cat_slug, 'term_group' => 0) );
 104      $wpdb->insert( $wpdb->term_taxonomy, array('term_id' => '1', 'taxonomy' => 'category', 'description' => '', 'parent' => 0, 'count' => 1));
 105  
 106      // Default link category
 107      $cat_name = __('Blogroll');
 108      /* translators: Default link category slug */
 109      $cat_slug = sanitize_title(_x('Blogroll', 'Default link category slug'));
 110  
 111      $wpdb->insert( $wpdb->terms, array('name' => $cat_name, 'slug' => $cat_slug, 'term_group' => 0) );
 112      $wpdb->insert( $wpdb->term_taxonomy, array('term_id' => '2', 'taxonomy' => 'link_category', 'description' => '', 'parent' => 0, 'count' => 7));
 113  
 114      // Now drop in some default links
 115      $default_links = array();
 116      $default_links[] = array(    'link_url' => 'http://codex.wordpress.org/',
 117                                  'link_name' => 'Documentation',
 118                                  'link_rss' => '',
 119                                  'link_notes' => '');
 120  
 121      $default_links[] = array(    'link_url' => 'http://wordpress.org/development/',
 122                                  'link_name' => 'Development Blog',
 123                                  'link_rss' => 'http://wordpress.org/development/feed/',
 124                                  'link_notes' => '');
 125  
 126      $default_links[] = array(    'link_url' => 'http://wordpress.org/extend/ideas/',
 127                                  'link_name' => 'Suggest Ideas',
 128                                  'link_rss' => '',
 129                                  'link_notes' =>'');
 130  
 131      $default_links[] = array(    'link_url' => 'http://wordpress.org/support/',
 132                                  'link_name' => 'Support Forum',
 133                                  'link_rss' => '',
 134                                  'link_notes' =>'');
 135  
 136      $default_links[] = array(    'link_url' => 'http://wordpress.org/extend/plugins/',
 137                                  'link_name' => 'Plugins',
 138                                  'link_rss' => '',
 139                                  'link_notes' =>'');
 140  
 141      $default_links[] = array(    'link_url' => 'http://wordpress.org/extend/themes/',
 142                                  'link_name' => 'Themes',
 143                                  'link_rss' => '',
 144                                  'link_notes' =>'');
 145  
 146      $default_links[] = array(    'link_url' => 'http://planet.wordpress.org/',
 147                                  'link_name' => 'WordPress Planet',
 148                                  'link_rss' => '',
 149                                  'link_notes' =>'');
 150  
 151      foreach ( $default_links as $link ) {
 152          $wpdb->insert( $wpdb->links, $link);
 153          $wpdb->insert( $wpdb->term_relationships, array('term_taxonomy_id' => 2, 'object_id' => $wpdb->insert_id) );
 154      }
 155  
 156      // First post
 157      $now = date('Y-m-d H:i:s');
 158      $now_gmt = gmdate('Y-m-d H:i:s');
 159      $first_post_guid = get_option('home') . '/?p=1';
 160  
 161      $wpdb->insert( $wpdb->posts, array(
 162                                  'post_author' => $user_id,
 163                                  'post_date' => $now,
 164                                  'post_date_gmt' => $now_gmt,
 165                                  'post_content' => __('Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!'),
 166                                  'post_excerpt' => '',
 167                                  'post_title' => __('Hello world!'),
 168                                  /* translators: Default post slug */
 169                                  'post_name' => _x('hello-world', 'Default post slug'),
 170                                  'post_modified' => $now,
 171                                  'post_modified_gmt' => $now_gmt,
 172                                  'guid' => $first_post_guid,
 173                                  'comment_count' => 1,
 174                                  'to_ping' => '',
 175                                  'pinged' => '',
 176                                  'post_content_filtered' => ''
 177                                  ));
 178      $wpdb->insert( $wpdb->term_relationships, array('term_taxonomy_id' => 1, 'object_id' => 1) );
 179  
 180      // Default comment
 181      $wpdb->insert( $wpdb->comments, array(
 182                                  'comment_post_ID' => 1,
 183                                  'comment_author' => __('Mr WordPress'),
 184                                  'comment_author_email' => '',
 185                                  'comment_author_url' => 'http://wordpress.org/',
 186                                  'comment_date' => $now,
 187                                  'comment_date_gmt' => $now_gmt,
 188                                  'comment_content' => __('Hi, this is a comment.<br />To delete a comment, just log in and view the post&#039;s comments. There you will have the option to edit or delete them.')
 189                                  ));
 190      // First Page
 191      $first_post_guid = get_option('home') . '/?page_id=2';
 192      $wpdb->insert( $wpdb->posts, array(
 193                                  'post_author' => $user_id,
 194                                  'post_date' => $now,
 195                                  'post_date_gmt' => $now_gmt,
 196                                  'post_content' => __('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.'),
 197                                  'post_excerpt' => '',
 198                                  'post_title' => __('About'),
 199                                  /* translators: Default page slug */
 200                                  'post_name' => _x('about', 'Default page slug'),
 201                                  'post_modified' => $now,
 202                                  'post_modified_gmt' => $now_gmt,
 203                                  'guid' => $first_post_guid,
 204                                  'post_type' => 'page',
 205                                  'to_ping' => '',
 206                                  'pinged' => '',
 207                                  'post_content_filtered' => ''
 208                                  ));
 209  }
 210  endif;
 211  
 212  if ( !function_exists('wp_new_blog_notification') ) :
 213  /**
 214   * {@internal Missing Short Description}}
 215   *
 216   * {@internal Missing Long Description}}
 217   *
 218   * @since unknown
 219   *
 220   * @param string $blog_title Blog title.
 221   * @param string $blog_url Blog url.
 222   * @param int $user_id User ID.
 223   * @param string $password User's Password.
 224   */
 225  function wp_new_blog_notification($blog_title, $blog_url, $user_id, $password) {
 226      $user = new WP_User($user_id);
 227      $email = $user->user_email;
 228      $name = $user->user_login;
 229      $message = sprintf(__("Your new WordPress blog has been successfully set up at:
 230  
 231  %1\$s
 232  
 233  You can log in to the administrator account with the following information:
 234  
 235  Username: %2\$s
 236  Password: %3\$s
 237  
 238  We hope you enjoy your new blog. Thanks!
 239  
 240  --The WordPress Team
 241  http://wordpress.org/
 242  "), $blog_url, $name, $password);
 243  
 244      @wp_mail($email, __('New WordPress Blog'), $message);
 245  }
 246  endif;
 247  
 248  if ( !function_exists('wp_upgrade') ) :
 249  /**
 250   * Run WordPress Upgrade functions.
 251   *
 252   * {@internal Missing Long Description}}
 253   *
 254   * @since unknown
 255   *
 256   * @return null
 257   */
 258  function wp_upgrade() {
 259      global $wp_current_db_version, $wp_db_version;
 260  
 261      $wp_current_db_version = __get_option('db_version');
 262  
 263      // We are up-to-date.  Nothing to do.
 264      if ( $wp_db_version == $wp_current_db_version )
 265          return;
 266  
 267      if( ! is_blog_installed() )
 268          return;
 269  
 270      wp_check_mysql_version();
 271      wp_cache_flush();
 272      pre_schema_upgrade();
 273      make_db_current_silent();
 274      upgrade_all();
 275      wp_cache_flush();
 276  }
 277  endif;
 278  
 279  /**
 280   * Functions to be called in install and upgrade scripts.
 281   *
 282   * {@internal Missing Long Description}}
 283   *
 284   * @since unknown
 285   */
 286  function upgrade_all() {
 287      global $wp_current_db_version, $wp_db_version, $wp_rewrite;
 288      $wp_current_db_version = __get_option('db_version');
 289  
 290      // We are up-to-date.  Nothing to do.
 291      if ( $wp_db_version == $wp_current_db_version )
 292          return;
 293  
 294      // If the version is not set in the DB, try to guess the version.
 295      if ( empty($wp_current_db_version) ) {
 296          $wp_current_db_version = 0;
 297  
 298          // If the template option exists, we have 1.5.
 299          $template = __get_option('template');
 300          if ( !empty($template) )
 301              $wp_current_db_version = 2541;
 302      }
 303  
 304      if ( $wp_current_db_version < 6039 )
 305          upgrade_230_options_table();
 306  
 307      populate_options();
 308  
 309      if ( $wp_current_db_version < 2541 ) {
 310          upgrade_100();
 311          upgrade_101();
 312          upgrade_110();
 313          upgrade_130();
 314      }
 315  
 316      if ( $wp_current_db_version < 3308 )
 317          upgrade_160();
 318  
 319      if ( $wp_current_db_version < 4772 )
 320          upgrade_210();
 321  
 322      if ( $wp_current_db_version < 4351 )
 323          upgrade_old_slugs();
 324  
 325      if ( $wp_current_db_version < 5539 )
 326          upgrade_230();
 327  
 328      if ( $wp_current_db_version < 6124 )
 329          upgrade_230_old_tables();
 330  
 331      if ( $wp_current_db_version < 7499 )
 332          upgrade_250();
 333  
 334      if ( $wp_current_db_version < 7796 )
 335          upgrade_251();
 336  
 337      if ( $wp_current_db_version < 7935 )
 338          upgrade_252();
 339  
 340      if ( $wp_current_db_version < 8201 )
 341          upgrade_260();
 342  
 343      if ( $wp_current_db_version < 8989 )
 344          upgrade_270();
 345  
 346      if ( $wp_current_db_version < 10360 )
 347          upgrade_280();
 348  
 349      if ( $wp_current_db_version < 11958 )
 350          upgrade_290();
 351  
 352      maybe_disable_automattic_widgets();
 353  
 354      update_option( 'db_version', $wp_db_version );
 355      update_option( 'db_upgraded', true );
 356  }
 357  
 358  /**
 359   * Execute changes made in WordPress 1.0.
 360   *
 361   * @since 1.0.0
 362   */
 363  function upgrade_100() {
 364      global $wpdb;
 365  
 366      // Get the title and ID of every post, post_name to check if it already has a value
 367      $posts = $wpdb->get_results("SELECT ID, post_title, post_name FROM $wpdb->posts WHERE post_name = ''");
 368      if ($posts) {
 369          foreach($posts as $post) {
 370              if ('' == $post->post_name) {
 371                  $newtitle = sanitize_title($post->post_title);
 372                  $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_name = %s WHERE ID = %d", $newtitle, $post->ID) );
 373              }
 374          }
 375      }
 376  
 377      $categories = $wpdb->get_results("SELECT cat_ID, cat_name, category_nicename FROM $wpdb->categories");
 378      foreach ($categories as $category) {
 379          if ('' == $category->category_nicename) {
 380              $newtitle = sanitize_title($category->cat_name);
 381              $wpdb>update( $wpdb->categories, array('category_nicename' => $newtitle), array('cat_ID' => $category->cat_ID) );
 382          }
 383      }
 384  
 385      $wpdb->query("UPDATE $wpdb->options SET option_value = REPLACE(option_value, 'wp-links/links-images/', 'wp-images/links/')
 386      WHERE option_name LIKE 'links_rating_image%'
 387      AND option_value LIKE 'wp-links/links-images/%'");
 388  
 389      $done_ids = $wpdb->get_results("SELECT DISTINCT post_id FROM $wpdb->post2cat");
 390      if ($done_ids) :
 391          foreach ($done_ids as $done_id) :
 392              $done_posts[] = $done_id->post_id;
 393          endforeach;
 394          $catwhere = ' AND ID NOT IN (' . implode(',', $done_posts) . ')';
 395      else:
 396          $catwhere = '';
 397      endif;
 398  
 399      $allposts = $wpdb->get_results("SELECT ID, post_category FROM $wpdb->posts WHERE post_category != '0' $catwhere");
 400      if ($allposts) :
 401          foreach ($allposts as $post) {
 402              // Check to see if it's already been imported
 403              $cat = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->post2cat WHERE post_id = %d AND category_id = %d", $post->ID, $post->post_category) );
 404              if (!$cat && 0 != $post->post_category) { // If there's no result
 405                  $wpdb->insert( $wpdb->post2cat, array('post_id' => $post->ID, 'category_id' => $post->post_category) );
 406              }
 407          }
 408      endif;
 409  }
 410  
 411  /**
 412   * Execute changes made in WordPress 1.0.1.
 413   *
 414   * @since 1.0.1
 415   */
 416  function upgrade_101() {
 417      global $wpdb;
 418  
 419      // Clean up indices, add a few
 420      add_clean_index($wpdb->posts, 'post_name');
 421      add_clean_index($wpdb->posts, 'post_status');
 422      add_clean_index($wpdb->categories, 'category_nicename');
 423      add_clean_index($wpdb->comments, 'comment_approved');
 424      add_clean_index($wpdb->comments, 'comment_post_ID');
 425      add_clean_index($wpdb->links , 'link_category');
 426      add_clean_index($wpdb->links , 'link_visible');
 427  }
 428  
 429  /**
 430   * Execute changes made in WordPress 1.2.
 431   *
 432   * @since 1.2.0
 433   */
 434  function upgrade_110() {
 435      global $wpdb;
 436  
 437      // Set user_nicename.
 438      $users = $wpdb->get_results("SELECT ID, user_nickname, user_nicename FROM $wpdb->users");
 439      foreach ($users as $user) {
 440          if ('' == $user->user_nicename) {
 441              $newname = sanitize_title($user->user_nickname);
 442              $wpdb->update( $wpdb->users, array('user_nicename' => $newname), array('ID' => $user->ID) );
 443          }
 444      }
 445  
 446      $users = $wpdb->get_results("SELECT ID, user_pass from $wpdb->users");
 447      foreach ($users as $row) {
 448          if (!preg_match('/^[A-Fa-f0-9]{32}$/', $row->user_pass)) {
 449              $wpdb->update( $wpdb->users, array('user_pass' => md5($row->user_pass)), array('ID' => $row->ID) );
 450          }
 451      }
 452  
 453      // Get the GMT offset, we'll use that later on
 454      $all_options = get_alloptions_110();
 455  
 456      $time_difference = $all_options->time_difference;
 457  
 458      $server_time = time()+date('Z');
 459      $weblogger_time = $server_time + $time_difference*3600;
 460      $gmt_time = time();
 461  
 462      $diff_gmt_server = ($gmt_time - $server_time) / 3600;
 463      $diff_weblogger_server = ($weblogger_time - $server_time) / 3600;
 464      $diff_gmt_weblogger = $diff_gmt_server - $diff_weblogger_server;
 465      $gmt_offset = -$diff_gmt_weblogger;
 466  
 467      // Add a gmt_offset option, with value $gmt_offset
 468      add_option('gmt_offset', $gmt_offset);
 469  
 470      // Check if we already set the GMT fields (if we did, then
 471      // MAX(post_date_gmt) can't be '0000-00-00 00:00:00'
 472      // <michel_v> I just slapped myself silly for not thinking about it earlier
 473      $got_gmt_fields = ($wpdb->get_var("SELECT MAX(post_date_gmt) FROM $wpdb->posts") == '0000-00-00 00:00:00') ? false : true;
 474  
 475      if (!$got_gmt_fields) {
 476  
 477          // Add or substract time to all dates, to get GMT dates
 478          $add_hours = intval($diff_gmt_weblogger);
 479          $add_minutes = intval(60 * ($diff_gmt_weblogger - $add_hours));
 480          $wpdb->query("UPDATE $wpdb->posts SET post_date_gmt = DATE_ADD(post_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
 481          $wpdb->query("UPDATE $wpdb->posts SET post_modified = post_date");
 482          $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'");
 483          $wpdb->query("UPDATE $wpdb->comments SET comment_date_gmt = DATE_ADD(comment_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
 484          $wpdb->query("UPDATE $wpdb->users SET user_registered = DATE_ADD(user_registered, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
 485      }
 486  
 487  }
 488  
 489  /**
 490   * Execute changes made in WordPress 1.5.
 491   *
 492   * @since 1.5.0
 493   */
 494  function upgrade_130() {
 495      global $wpdb;
 496  
 497      // Remove extraneous backslashes.
 498      $posts = $wpdb->get_results("SELECT ID, post_title, post_content, post_excerpt, guid, post_date, post_name, post_status, post_author FROM $wpdb->posts");
 499      if ($posts) {
 500          foreach($posts as $post) {
 501              $post_content = addslashes(deslash($post->post_content));
 502              $post_title = addslashes(deslash($post->post_title));
 503              $post_excerpt = addslashes(deslash($post->post_excerpt));
 504              if ( empty($post->guid) )
 505                  $guid = get_permalink($post->ID);
 506              else
 507                  $guid = $post->guid;
 508  
 509              $wpdb->update( $wpdb->posts, compact('post_title', 'post_content', 'post_excerpt', 'guid'), array('ID' => $post->ID) );
 510  
 511          }
 512      }
 513  
 514      // Remove extraneous backslashes.
 515      $comments = $wpdb->get_results("SELECT comment_ID, comment_author, comment_content FROM $wpdb->comments");
 516      if ($comments) {
 517          foreach($comments as $comment) {
 518              $comment_content = deslash($comment->comment_content);
 519              $comment_author = deslash($comment->comment_author);
 520  
 521              $wpdb->update($wpdb->comments, compact('comment_content', 'comment_author'), array('comment_ID' => $comment->comment_ID) );
 522          }
 523      }
 524  
 525      // Remove extraneous backslashes.
 526      $links = $wpdb->get_results("SELECT link_id, link_name, link_description FROM $wpdb->links");
 527      if ($links) {
 528          foreach($links as $link) {
 529              $link_name = deslash($link->link_name);
 530              $link_description = deslash($link->link_description);
 531  
 532              $wpdb->update( $wpdb->links, compact('link_name', 'link_description'), array('link_id' => $link->link_id) );
 533          }
 534      }
 535  
 536      $active_plugins = __get_option('active_plugins');
 537  
 538      // If plugins are not stored in an array, they're stored in the old
 539      // newline separated format.  Convert to new format.
 540      if ( !is_array( $active_plugins ) ) {
 541          $active_plugins = explode("\n", trim($active_plugins));
 542          update_option('active_plugins', $active_plugins);
 543      }
 544  
 545      // Obsolete tables
 546      $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optionvalues');
 547      $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiontypes');
 548      $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiongroups');
 549      $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiongroup_options');
 550  
 551      // Update comments table to use comment_type
 552      $wpdb->query("UPDATE $wpdb->comments SET comment_type='trackback', comment_content = REPLACE(comment_content, '<trackback />', '') WHERE comment_content LIKE '<trackback />%'");
 553      $wpdb->query("UPDATE $wpdb->comments SET comment_type='pingback', comment_content = REPLACE(comment_content, '<pingback />', '') WHERE comment_content LIKE '<pingback />%'");
 554  
 555      // Some versions have multiple duplicate option_name rows with the same values
 556      $options = $wpdb->get_results("SELECT option_name, COUNT(option_name) AS dupes FROM `$wpdb->options` GROUP BY option_name");
 557      foreach ( $options as $option ) {
 558          if ( 1 != $option->dupes ) { // Could this be done in the query?
 559              $limit = $option->dupes - 1;
 560              $dupe_ids = $wpdb->get_col( $wpdb->prepare("SELECT option_id FROM $wpdb->options WHERE option_name = %s LIMIT %d", $option->option_name, $limit) );
 561              if ( $dupe_ids ) {
 562                  $dupe_ids = join($dupe_ids, ',');
 563                  $wpdb->query("DELETE FROM $wpdb->options WHERE option_id IN ($dupe_ids)");
 564              }
 565          }
 566      }
 567  
 568      make_site_theme();
 569  }
 570  
 571  /**
 572   * Execute changes made in WordPress 2.0.
 573   *
 574   * @since 2.0.0
 575   */
 576  function upgrade_160() {
 577      global $wpdb, $wp_current_db_version;
 578  
 579      populate_roles_160();
 580  
 581      $users = $wpdb->get_results("SELECT * FROM $wpdb->users");
 582      foreach ( $users as $user ) :
 583          if ( !empty( $user->user_firstname ) )
 584              update_usermeta( $user->ID, 'first_name', $wpdb->escape($user->user_firstname) );
 585          if ( !empty( $user->user_lastname ) )
 586              update_usermeta( $user->ID, 'last_name', $wpdb->escape($user->user_lastname) );
 587          if ( !empty( $user->user_nickname ) )
 588              update_usermeta( $user->ID, 'nickname', $wpdb->escape($user->user_nickname) );
 589          if ( !empty( $user->user_level ) )
 590              update_usermeta( $user->ID, $wpdb->prefix . 'user_level', $user->user_level );
 591          if ( !empty( $user->user_icq ) )
 592              update_usermeta( $user->ID, 'icq', $wpdb->escape($user->user_icq) );
 593          if ( !empty( $user->user_aim ) )
 594              update_usermeta( $user->ID, 'aim', $wpdb->escape($user->user_aim) );
 595          if ( !empty( $user->user_msn ) )
 596              update_usermeta( $user->ID, 'msn', $wpdb->escape($user->user_msn) );
 597          if ( !empty( $user->user_yim ) )
 598              update_usermeta( $user->ID, 'yim', $wpdb->escape($user->user_icq) );
 599          if ( !empty( $user->user_description ) )
 600              update_usermeta( $user->ID, 'description', $wpdb->escape($user->user_description) );
 601  
 602          if ( isset( $user->user_idmode ) ):
 603              $idmode = $user->user_idmode;
 604              if ($idmode == 'nickname') $id = $user->user_nickname;
 605              if ($idmode == 'login') $id = $user->user_login;
 606              if ($idmode == 'firstname') $id = $user->user_firstname;
 607              if ($idmode == 'lastname') $id = $user->user_lastname;
 608              if ($idmode == 'namefl') $id = $user->user_firstname.' '.$user->user_lastname;
 609              if ($idmode == 'namelf') $id = $user->user_lastname.' '.$user->user_firstname;
 610              if (!$idmode) $id = $user->user_nickname;
 611              $wpdb->update( $wpdb->users, array('display_name' => $id), array('ID' => $user->ID) );
 612          endif;
 613  
 614          // FIXME: RESET_CAPS is temporary code to reset roles and caps if flag is set.
 615          $caps = get_usermeta( $user->ID, $wpdb->prefix . 'capabilities');
 616          if ( empty($caps) || defined('RESET_CAPS') ) {
 617              $level = get_usermeta($user->ID, $wpdb->prefix . 'user_level');
 618              $role = translate_level_to_role($level);
 619              update_usermeta( $user->ID, $wpdb->prefix . 'capabilities', array($role => true) );
 620          }
 621  
 622      endforeach;
 623      $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' );
 624      $wpdb->hide_errors();
 625      foreach ( $old_user_fields as $old )
 626          $wpdb->query("ALTER TABLE $wpdb->users DROP $old");
 627      $wpdb->show_errors();
 628  
 629      // populate comment_count field of posts table
 630      $comments = $wpdb->get_results( "SELECT comment_post_ID, COUNT(*) as c FROM $wpdb->comments WHERE comment_approved = '1' GROUP BY comment_post_ID" );
 631      if( is_array( $comments ) )
 632          foreach ($comments as $comment)
 633              $wpdb->update( $wpdb->posts, array('comment_count' => $comment->c), array('ID' => $comment->comment_post_ID) );
 634  
 635      // Some alpha versions used a post status of object instead of attachment and put
 636      // the mime type in post_type instead of post_mime_type.
 637      if ( $wp_current_db_version > 2541 && $wp_current_db_version <= 3091 ) {
 638          $objects = $wpdb->get_results("SELECT ID, post_type FROM $wpdb->posts WHERE post_status = 'object'");
 639          foreach ($objects as $object) {
 640              $wpdb->update( $wpdb->posts, array(    'post_status' => 'attachment',
 641                                                  'post_mime_type' => $object->post_type,
 642                                                  'post_type' => ''),
 643                                           array( 'ID' => $object->ID ) );
 644  
 645              $meta = get_post_meta($object->ID, 'imagedata', true);
 646              if ( ! empty($meta['file']) )
 647                  update_attached_file( $object->ID, $meta['file'] );
 648          }
 649      }
 650  }
 651  
 652  /**
 653   * Execute changes made in WordPress 2.1.
 654   *
 655   * @since 2.1.0
 656   */
 657  function upgrade_210() {
 658      global $wpdb, $wp_current_db_version;
 659  
 660      if ( $wp_current_db_version < 3506 ) {
 661          // Update status and type.
 662          $posts = $wpdb->get_results("SELECT ID, post_status FROM $wpdb->posts");
 663  
 664          if ( ! empty($posts) ) foreach ($posts as $post) {
 665              $status = $post->post_status;
 666              $type = 'post';
 667  
 668              if ( 'static' == $status ) {
 669                  $status = 'publish';
 670                  $type = 'page';
 671              } else if ( 'attachment' == $status ) {
 672                  $status = 'inherit';
 673                  $type = 'attachment';
 674              }
 675  
 676              $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_status = %s, post_type = %s WHERE ID = %d", $status, $type, $post->ID) );
 677          }
 678      }
 679  
 680      if ( $wp_current_db_version < 3845 ) {
 681          populate_roles_210();
 682      }
 683  
 684      if ( $wp_current_db_version < 3531 ) {
 685          // Give future posts a post_status of future.
 686          $now = gmdate('Y-m-d H:i:59');
 687          $wpdb->query ("UPDATE $wpdb->posts SET post_status = 'future' WHERE post_status = 'publish' AND post_date_gmt > '$now'");
 688  
 689          $posts = $wpdb->get_results("SELECT ID, post_date FROM $wpdb->posts WHERE post_status ='future'");
 690          if ( !empty($posts) )
 691              foreach ( $posts as $post )
 692                  wp_schedule_single_event(mysql2date('U', $post->post_date, false), 'publish_future_post', array($post->ID));
 693      }
 694  }
 695  
 696  /**
 697   * Execute changes made in WordPress 2.3.
 698   *
 699   * @since 2.3.0
 700   */
 701  function upgrade_230() {
 702      global $wp_current_db_version, $wpdb;
 703  
 704      if ( $wp_current_db_version < 5200 ) {
 705          populate_roles_230();
 706      }
 707  
 708      // Convert categories to terms.
 709      $tt_ids = array();
 710      $have_tags = false;
 711      $categories = $wpdb->get_results("SELECT * FROM $wpdb->categories ORDER BY cat_ID");
 712      foreach ($categories as $category) {
 713          $term_id = (int) $category->cat_ID;
 714          $name = $category->cat_name;
 715          $description = $category->category_description;
 716          $slug = $category->category_nicename;
 717          $parent = $category->category_parent;
 718          $term_group = 0;
 719  
 720          // Associate terms with the same slug in a term group and make slugs unique.
 721          if ( $exists = $wpdb->get_results( $wpdb->prepare("SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $slug) ) ) {
 722              $term_group = $exists[0]->term_group;
 723              $id = $exists[0]->term_id;
 724              $num = 2;
 725              do {
 726                  $alt_slug = $slug . "-$num";
 727                  $num++;
 728                  $slug_check = $wpdb->get_var( $wpdb->prepare("SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug) );
 729              } while ( $slug_check );
 730  
 731              $slug = $alt_slug;
 732  
 733              if ( empty( $term_group ) ) {
 734                  $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms GROUP BY term_group") + 1;
 735                  $wpdb->query( $wpdb->prepare("UPDATE $wpdb->terms SET term_group = %d WHERE term_id = %d", $term_group, $id) );
 736              }
 737          }
 738  
 739          $wpdb->query( $wpdb->prepare("INSERT INTO $wpdb->terms (term_id, name, slug, term_group) VALUES
 740          (%d, %s, %s, %d)", $term_id, $name, $slug, $term_group) );
 741  
 742          $count = 0;
 743          if ( !empty($category->category_count) ) {
 744              $count = (int) $category->category_count;
 745              $taxonomy = 'category';
 746              $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) );
 747              $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
 748          }
 749  
 750          if ( !empty($category->link_count) ) {
 751              $count = (int) $category->link_count;
 752              $taxonomy = 'link_category';
 753              $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) );
 754              $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
 755          }
 756  
 757          if ( !empty($category->tag_count) ) {
 758              $have_tags = true;
 759              $count = (int) $category->tag_count;
 760              $taxonomy = 'post_tag';
 761              $wpdb->insert( $wpdb->term_taxonomy, compact('term_id', 'taxonomy', 'description', 'parent', 'count') );
 762              $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
 763          }
 764  
 765          if ( empty($count) ) {
 766              $count = 0;
 767              $taxonomy = 'category';
 768              $wpdb->insert( $wpdb->term_taxonomy, compact('term_id', 'taxonomy', 'description', 'parent', 'count') );
 769              $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
 770          }
 771      }
 772  
 773      $select = 'post_id, category_id';
 774      if ( $have_tags )
 775          $select .= ', rel_type';
 776  
 777      $posts = $wpdb->get_results("SELECT $select FROM $wpdb->post2cat GROUP BY post_id, category_id");
 778      foreach ( $posts as $post ) {
 779          $post_id = (int) $post->post_id;
 780          $term_id = (int) $post->category_id;
 781          $taxonomy = 'category';
 782          if ( !empty($post->rel_type) && 'tag' == $post->rel_type)
 783              $taxonomy = 'tag';
 784          $tt_id = $tt_ids[$term_id][$taxonomy];
 785          if ( empty($tt_id) )
 786              continue;
 787  
 788          $wpdb->insert( $wpdb->term_relationships, array('object_id' => $post_id, 'term_taxonomy_id' => $tt_id) );
 789      }
 790  
 791      // < 3570 we used linkcategories.  >= 3570 we used categories and link2cat.
 792      if ( $wp_current_db_version < 3570 ) {
 793          // Create link_category terms for link categories.  Create a map of link cat IDs
 794          // to link_category terms.
 795          $link_cat_id_map = array();
 796          $default_link_cat = 0;
 797          $tt_ids = array();
 798          $link_cats = $wpdb->get_results("SELECT cat_id, cat_name FROM " . $wpdb->prefix . 'linkcategories');
 799          foreach ( $link_cats as $category) {
 800              $cat_id = (int) $category->cat_id;
 801              $term_id = 0;
 802              $name = $wpdb->escape($category->cat_name);
 803              $slug = sanitize_title($name);
 804              $term_group = 0;
 805  
 806              // Associate terms with the same slug in a term group and make slugs unique.
 807              if ( $exists = $wpdb->get_results( $wpdb->prepare("SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $slug) ) ) {
 808                  $term_group = $exists[0]->term_group;
 809                  $term_id = $exists[0]->term_id;
 810              }
 811  
 812              if ( empty($term_id) ) {
 813                  $wpdb->insert( $wpdb->terms, compact('name', 'slug', 'term_group') );
 814                  $term_id = (int) $wpdb->insert_id;
 815              }
 816  
 817              $link_cat_id_map[$cat_id] = $term_id;
 818              $default_link_cat = $term_id;
 819  
 820              $wpdb->insert( $wpdb->term_taxonomy, array('term_id' => $term_id, 'taxonomy' => 'link_category', 'description' => '', 'parent' => 0, 'count' => 0) );
 821              $tt_ids[$term_id] = (int) $wpdb->insert_id;
 822          }
 823  
 824          // Associate links to cats.
 825          $links = $wpdb->get_results("SELECT link_id, link_category FROM $wpdb->links");
 826          if ( !empty($links) ) foreach ( $links as $link ) {
 827              if ( 0 == $link->link_category )
 828                  continue;
 829              if ( ! isset($link_cat_id_map[$link->link_category]) )
 830                  continue;
 831              $term_id = $link_cat_id_map[$link->link_category];
 832              $tt_id = $tt_ids[$term_id];
 833              if ( empty($tt_id) )
 834                  continue;
 835  
 836              $wpdb->insert( $wpdb->term_relationships, array('object_id' => $link->link_id, 'term_taxonomy_id' => $tt_id) );
 837          }
 838  
 839          // Set default to the last category we grabbed during the upgrade loop.
 840          update_option('default_link_category', $default_link_cat);
 841      } else {
 842          $links = $wpdb->get_results("SELECT link_id, category_id FROM $wpdb->link2cat GROUP BY link_id, category_id");
 843          foreach ( $links as $link ) {
 844              $link_id = (int) $link->link_id;
 845              $term_id = (int) $link->category_id;
 846              $taxonomy = 'link_category';
 847              $tt_id = $tt_ids[$term_id][$taxonomy];
 848              if ( empty($tt_id) )
 849                  continue;
 850              $wpdb->insert( $wpdb->term_relationships, array('object_id' => $link_id, 'term_taxonomy_id' => $tt_id) );
 851          }
 852      }
 853  
 854      if ( $wp_current_db_version < 4772 ) {
 855          // Obsolete linkcategories table
 856          $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'linkcategories');
 857      }
 858  
 859      // Recalculate all counts
 860      $terms = $wpdb->get_results("SELECT term_taxonomy_id, taxonomy FROM $wpdb->term_taxonomy");
 861      foreach ( (array) $terms as $term ) {
 862          if ( ('post_tag' == $term->taxonomy) || ('category' == $term->taxonomy) )
 863              $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) );
 864          else
 865              $count = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term->term_taxonomy_id) );
 866          $wpdb->update( $wpdb->term_taxonomy, array('count' => $count), array('term_taxonomy_id' => $term->term_taxonomy_id) );
 867      }
 868  }
 869  
 870  /**
 871   * Remove old options from the database.
 872   *
 873   * @since 2.3.0
 874   */
 875  function upgrade_230_options_table() {
 876      global $wpdb;
 877      $old_options_fields = array( 'option_can_override', 'option_type', 'option_width', 'option_height', 'option_description', 'option_admin_level' );
 878      $wpdb->hide_errors();
 879      foreach ( $old_options_fields as $old )
 880          $wpdb->query("ALTER TABLE $wpdb->options DROP $old");
 881      $wpdb->show_errors();
 882  }
 883  
 884  /**
 885   * Remove old categories, link2cat, and post2cat database tables.
 886   *
 887   * @since 2.3.0
 888   */
 889  function upgrade_230_old_tables() {
 890      global $wpdb;
 891      $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'categories');
 892      $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'link2cat');
 893      $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'post2cat');
 894  }
 895  
 896  /**
 897   * Upgrade old slugs made in version 2.2.
 898   *
 899   * @since 2.2.0
 900   */
 901  function upgrade_old_slugs() {
 902      // upgrade people who were using the Redirect Old Slugs plugin
 903      global $wpdb;
 904      $wpdb->query("UPDATE $wpdb->postmeta SET meta_key = '_wp_old_slug' WHERE meta_key = 'old_slug'");
 905  }
 906  
 907  /**
 908   * Execute changes made in WordPress 2.5.0.
 909   *
 910   * @since 2.5.0
 911   */
 912  function upgrade_250() {
 913      global $wp_current_db_version;
 914  
 915      if ( $wp_current_db_version < 6689 ) {
 916          populate_roles_250();
 917      }
 918  
 919  }
 920  
 921  /**
 922   * Execute changes made in WordPress 2.5.1.
 923   *
 924   * @since 2.5.1
 925   */
 926  function upgrade_251() {
 927      global $wp_current_db_version;
 928  
 929      // Make the secret longer
 930      update_option('secret', wp_generate_password(64));
 931  }
 932  
 933  /**
 934   * Execute changes made in WordPress 2.5.2.
 935   *
 936   * @since 2.5.2
 937   */
 938  function upgrade_252() {
 939      global $wpdb;
 940  
 941      $wpdb->query("UPDATE $wpdb->users SET user_activation_key = ''");
 942  }
 943  
 944  /**
 945   * Execute changes made in WordPress 2.6.
 946   *
 947   * @since 2.6.0
 948   */
 949  function upgrade_260() {
 950      global $wp_current_db_version;
 951  
 952      if ( $wp_current_db_version < 8000 )
 953          populate_roles_260();
 954  
 955      if ( $wp_current_db_version < 8201 ) {
 956          update_option('enable_app', 1);
 957          update_option('enable_xmlrpc', 1);
 958      }
 959  }
 960  
 961  /**
 962   * Execute changes made in WordPress 2.7.
 963   *
 964   * @since 2.7.0
 965   */
 966  function upgrade_270() {
 967      global $wpdb, $wp_current_db_version;
 968  
 969      if ( $wp_current_db_version < 8980 )
 970          populate_roles_270();
 971  
 972      // Update post_date for unpublished posts with empty timestamp
 973      if ( $wp_current_db_version < 8921 )
 974          $wpdb->query( "UPDATE $wpdb->posts SET post_date = post_modified WHERE post_date = '0000-00-00 00:00:00'" );
 975  }
 976  
 977  /**
 978   * Execute changes made in WordPress 2.8.
 979   *
 980   * @since 2.8.0
 981   */
 982  function upgrade_280() {
 983      global $wp_current_db_version;
 984  
 985      if ( $wp_current_db_version < 10360 )
 986          populate_roles_280();
 987  }
 988  
 989  /**
 990   * Execute changes made in WordPress 2.9.
 991   *
 992   * @since 2.9.0
 993   */
 994  function upgrade_290() {
 995      global $wp_current_db_version;
 996  
 997      if ( $wp_current_db_version < 11958 ) {
 998          // Previously, setting depth to 1 would redundantly disable threading, but now 2 is the minimum depth to avoid confusion
 999          if ( get_option( 'thread_comments_depth' ) == '1' ) {
1000              update_option( 'thread_comments_depth', 2 );
1001              update_option( 'thread_comments', 0 );
1002          }
1003      }
1004  }
1005  
1006  
1007  // The functions we use to actually do stuff
1008  
1009  // General
1010  
1011  /**
1012   * {@internal Missing Short Description}}
1013   *
1014   * {@internal Missing Long Description}}
1015   *
1016   * @since unknown
1017   *
1018   * @param string $table_name Database table name to create.
1019   * @param string $create_ddl SQL statement to create table.
1020   * @return bool If table already exists or was created by function.
1021   */
1022  function maybe_create_table($table_name, $create_ddl) {
1023      global $wpdb;
1024      if ( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") == $table_name )
1025          return true;
1026      //didn't find it try to create it.
1027      $q = $wpdb->query($create_ddl);
1028      // we cannot directly tell that whether this succeeded!
1029      if ( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") == $table_name )
1030          return true;
1031      return false;
1032  }
1033  
1034  /**
1035   * {@internal Missing Short Description}}
1036   *
1037   * {@internal Missing Long Description}}
1038   *
1039   * @since unknown
1040   *
1041   * @param string $table Database table name.
1042   * @param string $index Index name to drop.
1043   * @return bool True, when finished.
1044   */
1045  function drop_index($table, $index) {
1046      global $wpdb;
1047      $wpdb->hide_errors();
1048      $wpdb->query("ALTER TABLE `$table` DROP INDEX `$index`");
1049      // Now we need to take out all the extra ones we may have created
1050      for ($i = 0; $i < 25; $i++) {
1051          $wpdb->query("ALTER TABLE `$table` DROP INDEX `{$index}_$i`");
1052      }
1053      $wpdb->show_errors();
1054      return true;
1055  }
1056  
1057  /**
1058   * {@internal Missing Short Description}}
1059   *
1060   * {@internal Missing Long Description}}
1061   *
1062   * @since unknown
1063   *
1064   * @param string $table Database table name.
1065   * @param string $index Database table index column.
1066   * @return bool True, when done with execution.
1067   */
1068  function add_clean_index($table, $index) {
1069      global $wpdb;
1070      drop_index($table, $index);
1071      $wpdb->query("ALTER TABLE `$table` ADD INDEX ( `$index` )");
1072      return true;
1073  }
1074  
1075  /**
1076   ** maybe_add_column()
1077   ** Add column to db table if it doesn't exist.
1078   ** Returns:  true if already exists or on successful completion
1079   **           false on error
1080   */
1081  function maybe_add_column($table_name, $column_name, $create_ddl) {
1082      global $wpdb, $debug;
1083      foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) {
1084          if ($debug) echo("checking $column == $column_name<br />");
1085          if ($column == $column_name) {
1086              return true;
1087          }
1088      }
1089      //didn't find it try to create it.
1090      $q = $wpdb->query($create_ddl);
1091      // we cannot directly tell that whether this succeeded!
1092      foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) {
1093          if ($column == $column_name) {
1094              return true;
1095          }
1096      }
1097      return false;
1098  }
1099  
1100  /**
1101   * Retrieve all options as it was for 1.2.
1102   *
1103   * @since 1.2.0
1104   *
1105   * @return array List of options.
1106   */
1107  function get_alloptions_110() {
1108      global $wpdb;
1109      if ($options = $wpdb->get_results("SELECT option_name, option_value FROM $wpdb->options")) {
1110          foreach ($options as $option) {
1111              // "When trying to design a foolproof system,
1112              //  never underestimate the ingenuity of the fools :)" -- Dougal
1113              if ('siteurl' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value);
1114              if ('home' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value);
1115              if ('category_base' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value);
1116              $all_options->{$option->option_name} = stripslashes($option->option_value);
1117          }
1118      }
1119      return $all_options;
1120  }
1121  
1122  /**
1123   * Version of get_option that is private to install/upgrade.
1124   *
1125   * @since unknown
1126   * @access private
1127   *
1128   * @param string $setting Option name.
1129   * @return mixed
1130   */
1131  function __get_option($setting) {
1132      global $wpdb;
1133  
1134      if ( $setting == 'home' && defined( 'WP_HOME' ) ) {
1135          return preg_replace( '|/+$|', '', constant( 'WP_HOME' ) );
1136      }
1137  
1138      if ( $setting == 'siteurl' && defined( 'WP_SITEURL' ) ) {
1139          return preg_replace( '|/+$|', '', constant( 'WP_SITEURL' ) );
1140      }
1141  
1142      $option = $wpdb->get_var( $wpdb->prepare("SELECT option_value FROM $wpdb->options WHERE option_name = %s", $setting) );
1143  
1144      if ( 'home' == $setting && '' == $option )
1145          return __get_option('siteurl');
1146  
1147      if ( 'siteurl' == $setting || 'home' == $setting || 'category_base' == $setting )
1148          $option = preg_replace('|/+$|', '', $option);
1149  
1150      @ $kellogs = unserialize($option);
1151      if ($kellogs !== FALSE)
1152          return $kellogs;
1153      else
1154          return $option;
1155  }
1156  
1157  /**
1158   * {@internal Missing Short Description}}
1159   *
1160   * {@internal Missing Long Description}}
1161   *
1162   * @since unknown
1163   *
1164   * @param string $content
1165   * @return string
1166   */
1167  function deslash($content) {
1168      // Note: \\\ inside a regex denotes a single backslash.
1169  
1170      // Replace one or more backslashes followed by a single quote with
1171      // a single quote.
1172      $content = preg_replace("/\\\+'/", "'", $content);
1173  
1174      // Replace one or more backslashes followed by a double quote with
1175      // a double quote.
1176      $content = preg_replace('/\\\+"/', '"', $content);
1177  
1178      // Replace one or more backslashes with one backslash.
1179      $content = preg_replace("/\\\+/", "\\", $content);
1180  
1181      return $content;
1182  }
1183  
1184  /**
1185   * {@internal Missing Short Description}}
1186   *
1187   * {@internal Missing Long Description}}
1188   *
1189   * @since unknown
1190   *
1191   * @param unknown_type $queries
1192   * @param unknown_type $execute
1193   * @return unknown
1194   */
1195  function dbDelta($queries, $execute = true) {
1196      global $wpdb;
1197  
1198      // Separate individual queries into an array
1199      if( !is_array($queries) ) {
1200          $queries = explode( ';', $queries );
1201          if('' == $queries[count($queries) - 1]) array_pop($queries);
1202      }
1203  
1204      $cqueries = array(); // Creation Queries
1205      $iqueries = array(); // Insertion Queries
1206      $for_update = array();
1207  
1208      // Create a tablename index for an array ($cqueries) of queries
1209      foreach($queries as $qry) {
1210          if(preg_match("|CREATE TABLE ([^ ]*)|", $qry, $matches)) {
1211              $cqueries[trim( strtolower($matches[1]), '`' )] = $qry;
1212              $for_update[$matches[1]] = 'Created table '.$matches[1];
1213          }
1214          else if(preg_match("|CREATE DATABASE ([^ ]*)|", $qry, $matches)) {
1215              array_unshift($cqueries, $qry);
1216          }
1217          else if(preg_match("|INSERT INTO ([^ ]*)|", $qry, $matches)) {
1218              $iqueries[] = $qry;
1219          }
1220          else if(preg_match("|UPDATE ([^ ]*)|", $qry, $matches)) {
1221              $iqueries[] = $qry;
1222          }
1223          else {
1224              // Unrecognized query type
1225          }
1226      }
1227  
1228      // Check to see which tables and fields exist
1229      if($tables = $wpdb->get_col('SHOW TABLES;')) {
1230          // For every table in the database
1231          foreach($tables as $table) {
1232              // If a table query exists for the database table...
1233              if( array_key_exists(strtolower($table), $cqueries) ) {
1234                  // Clear the field and index arrays
1235                  unset($cfields);
1236                  unset($indices);
1237                  // Get all of the field names in the query from between the parens
1238                  preg_match("|\((.*)\)|ms", $cqueries[strtolower($table)], $match2);
1239                  $qryline = trim($match2[1]);
1240  
1241                  // Separate field lines into an array
1242                  $flds = explode("\n", $qryline);
1243  
1244                  //echo "<hr/><pre>\n".print_r(strtolower($table), true).":\n".print_r($cqueries, true)."</pre><hr/>";
1245  
1246                  // For every field line specified in the query
1247                  foreach($flds as $fld) {
1248                      // Extract the field name
1249                      preg_match("|^([^ ]*)|", trim($fld), $fvals);
1250                      $fieldname = trim( $fvals[1], '`' );
1251  
1252                      // Verify the found field name
1253                      $validfield = true;
1254                      switch(strtolower($fieldname))
1255                      {
1256                      case '':
1257                      case 'primary':
1258                      case 'index':
1259                      case 'fulltext':
1260                      case 'unique':
1261                      case 'key':
1262                          $validfield = false;
1263                          $indices[] = trim(trim($fld), ", \n");
1264                          break;
1265                      }
1266                      $fld = trim($fld);
1267  
1268                      // If it's a valid field, add it to the field array
1269                      if($validfield) {
1270                          $cfields[strtolower($fieldname)] = trim($fld, ", \n");
1271                      }
1272                  }
1273  
1274                  // Fetch the table column structure from the database
1275                  $tablefields = $wpdb->get_results("DESCRIBE {$table};");
1276  
1277                  // For every field in the table
1278                  foreach($tablefields as $tablefield) {
1279                      // If the table field exists in the field array...
1280                      if(array_key_exists(strtolower($tablefield->Field), $cfields)) {
1281                          // Get the field type from the query
1282                          preg_match("|".$tablefield->Field." ([^ ]*( unsigned)?)|i", $cfields[strtolower($tablefield->Field)], $matches);
1283                          $fieldtype = $matches[1];
1284  
1285                          // Is actual field type different from the field type in query?
1286                          if($tablefield->Type != $fieldtype) {
1287                              // Add a query to change the column type
1288                              $cqueries[] = "ALTER TABLE {$table} CHANGE COLUMN {$tablefield->Field} " . $cfields[strtolower($tablefield->Field)];
1289                              $for_update[$table.'.'.$tablefield->Field] = "Changed type of {$table}.{$tablefield->Field} from {$tablefield->Type} to {$fieldtype}";
1290                          }
1291  
1292                          // Get the default value from the array
1293                              //echo "{$cfields[strtolower($tablefield->Field)]}<br>";
1294                          if(preg_match("| DEFAULT '(.*)'|i", $cfields[strtolower($tablefield->Field)], $matches)) {
1295                              $default_value = $matches[1];
1296                              if($tablefield->Default != $default_value)
1297                              {
1298                                  // Add a query to change the column's default value
1299                                  $cqueries[] = "ALTER TABLE {$table} ALTER COLUMN {$tablefield->Field} SET DEFAULT '{$default_value}'";
1300                                  $for_update[$table.'.'.$tablefield->Field] = "Changed default value of {$table}.{$tablefield->Field} from {$tablefield->Default} to {$default_value}";
1301                              }
1302                          }
1303  
1304                          // Remove the field from the array (so it's not added)
1305                          unset($cfields[strtolower($tablefield->Field)]);
1306                      }
1307                      else {
1308                          // This field exists in the table, but not in the creation queries?
1309                      }
1310                  }
1311  
1312                  // For every remaining field specified for the table
1313                  foreach($cfields as $fieldname => $fielddef) {
1314                      // Push a query line into $cqueries that adds the field to that table
1315                      $cqueries[] = "ALTER TABLE {$table} ADD COLUMN $fielddef";
1316                      $for_update[$table.'.'.$fieldname] = 'Added column '.$table.'.'.$fieldname;
1317                  }
1318  
1319                  // Index stuff goes here
1320                  // Fetch the table index structure from the database
1321                  $tableindices = $wpdb->get_results("SHOW INDEX FROM {$table};");
1322  
1323                  if($tableindices) {
1324                      // Clear the index array
1325                      unset($index_ary);
1326  
1327                      // For every index in the table
1328                      foreach($tableindices as $tableindex) {
1329                          // Add the index to the index data array
1330                          $keyname = $tableindex->Key_name;
1331                          $index_ary[$keyname]['columns'][] = array('fieldname' => $tableindex->Column_name, 'subpart' => $tableindex->Sub_part);
1332                          $index_ary[$keyname]['unique'] = ($tableindex->Non_unique == 0)?true:false;
1333                      }
1334  
1335                      // For each actual index in the index array
1336                      foreach($index_ary as $index_name => $index_data) {
1337                          // Build a create string to compare to the query
1338                          $index_string = '';
1339                          if($index_name == 'PRIMARY') {
1340                              $index_string .= 'PRIMARY ';
1341                          }
1342                          else if($index_data['unique']) {
1343                              $index_string .= 'UNIQUE ';
1344                          }
1345                          $index_string .= 'KEY ';
1346                          if($index_name != 'PRIMARY') {
1347                              $index_string .= $index_name;
1348                          }
1349                          $index_columns = '';
1350                          // For each column in the index
1351                          foreach($index_data['columns'] as $column_data) {
1352                              if($index_columns != '') $index_columns .= ',';
1353                              // Add the field to the column list string
1354                              $index_columns .= $column_data['fieldname'];
1355                              if($column_data['subpart'] != '') {
1356                                  $index_columns .= '('.$column_data['subpart'].')';
1357                              }
1358                          }
1359                          // Add the column list to the index create string
1360                          $index_string .= ' ('.$index_columns.')';
1361                          if(!(($aindex = array_search($index_string, $indices)) === false)) {
1362                              unset($indices[$aindex]);
1363                              //echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">{$table}:<br />Found index:".$index_string."</pre>\n";
1364                          }
1365                          //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";
1366                      }
1367                  }
1368  
1369                  // For every remaining index specified for the table
1370                  foreach ( (array) $indices as $index ) {
1371                      // Push a query line into $cqueries that adds the index to that table
1372                      $cqueries[] = "ALTER TABLE {$table} ADD $index";
1373                      $for_update[$table.'.'.$fieldname] = 'Added index '.$table.' '.$index;
1374                  }
1375  
1376                  // Remove the original table creation query from processing
1377                  unset($cqueries[strtolower($table)]);
1378                  unset($for_update[strtolower($table)]);
1379              } else {
1380                  // This table exists in the database, but not in the creation queries?
1381              }
1382          }
1383      }
1384  
1385      $allqueries = array_merge($cqueries, $iqueries);
1386      if($execute) {
1387          foreach($allqueries as $query) {
1388              //echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">".print_r($query, true)."</pre>\n";
1389              $wpdb->query($query);
1390          }
1391      }
1392  
1393      return $for_update;
1394  }
1395  
1396  /**
1397   * {@internal Missing Short Description}}
1398   *
1399   * {@internal Missing Long Description}}
1400   *
1401   * @since unknown
1402   */
1403  function make_db_current() {
1404      global $wp_queries;
1405  
1406      $alterations = dbDelta($wp_queries);
1407      echo "<ol>\n";
1408      foreach($alterations as $alteration) echo "<li>$alteration</li>\n";
1409      echo "</ol>\n";
1410  }
1411  
1412  /**
1413   * {@internal Missing Short Description}}
1414   *
1415   * {@internal Missing Long Description}}
1416   *
1417   * @since unknown
1418   */
1419  function make_db_current_silent() {
1420      global $wp_queries;
1421  
1422      $alterations = dbDelta($wp_queries);
1423  }
1424  
1425  /**
1426   * {@internal Missing Short Description}}
1427   *
1428   * {@internal Missing Long Description}}
1429   *
1430   * @since unknown
1431   *
1432   * @param unknown_type $theme_name
1433   * @param unknown_type $template
1434   * @return unknown
1435   */
1436  function make_site_theme_from_oldschool($theme_name, $template) {
1437      $home_path = get_home_path();
1438      $site_dir = WP_CONTENT_DIR . "/themes/$template";
1439  
1440      if (! file_exists("$home_path/index.php"))
1441          return false;
1442  
1443      // Copy files from the old locations to the site theme.
1444      // TODO: This does not copy arbitarary include dependencies.  Only the
1445      // standard WP files are copied.
1446      $files = array('index.php' => 'index.php', 'wp-layout.css' => 'style.css', 'wp-comments.php' => 'comments.php', 'wp-comments-popup.php' => 'comments-popup.php');
1447  
1448      foreach ($files as $oldfile => $newfile) {
1449          if ($oldfile == 'index.php')
1450              $oldpath = $home_path;
1451          else
1452              $oldpath = ABSPATH;
1453  
1454          if ($oldfile == 'index.php') { // Check to make sure it's not a new index
1455              $index = implode('', file("$oldpath/$oldfile"));
1456              if (strpos($index, 'WP_USE_THEMES') !== false) {
1457                  if (! @copy(WP_CONTENT_DIR . '/themes/default/index.php', "$site_dir/$newfile"))
1458                      return false;
1459                  continue; // Don't copy anything
1460                  }
1461          }
1462  
1463          if (! @copy("$oldpath/$oldfile", "$site_dir/$newfile"))
1464              return false;
1465  
1466          chmod("$site_dir/$newfile", 0777);
1467  
1468          // Update the blog header include in each file.
1469          $lines = explode("\n", implode('', file("$site_dir/$newfile")));
1470          if ($lines) {
1471              $f = fopen("$site_dir/$newfile", 'w');
1472  
1473              foreach ($lines as $line) {
1474                  if (preg_match('/require.*wp-blog-header/', $line))
1475                      $line = '//' . $line;
1476  
1477                  // Update stylesheet references.
1478                  $line = str_replace("<?php echo __get_option('siteurl'); ?>/wp-layout.css", "<?php bloginfo('stylesheet_url'); ?>", $line);
1479  
1480                  // Update comments template inclusion.
1481                  $line = str_replace("<?php include(ABSPATH . 'wp-comments.php'); ?>", "<?php comments_template(); ?>", $line);
1482  
1483                  fwrite($f, "{$line}\n");
1484              }
1485              fclose($f);
1486          }
1487      }
1488  
1489      // Add a theme header.
1490      $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";
1491  
1492      $stylelines = file_get_contents("$site_dir/style.css");
1493      if ($stylelines) {
1494          $f = fopen("$site_dir/style.css", 'w');
1495  
1496          fwrite($f, $header);
1497          fwrite($f, $stylelines);
1498          fclose($f);
1499      }
1500  
1501      return true;
1502  }
1503  
1504  /**
1505   * {@internal Missing Short Description}}
1506   *
1507   * {@internal Missing Long Description}}
1508   *
1509   * @since unknown
1510   *
1511   * @param unknown_type $theme_name
1512   * @param unknown_type $template
1513   * @return unknown
1514   */
1515  function make_site_theme_from_default($theme_name, $template) {
1516      $site_dir = WP_CONTENT_DIR . "/themes/$template";
1517      $default_dir = WP_CONTENT_DIR . '/themes/default';
1518  
1519      // Copy files from the default theme to the site theme.
1520      //$files = array('index.php', 'comments.php', 'comments-popup.php', 'footer.php', 'header.php', 'sidebar.php', 'style.css');
1521  
1522      $theme_dir = @ opendir("$default_dir");
1523      if ($theme_dir) {
1524          while(($theme_file = readdir( $theme_dir )) !== false) {
1525              if (is_dir("$default_dir/$theme_file"))
1526                  continue;
1527              if (! @copy("$default_dir/$theme_file", "$site_dir/$theme_file"))
1528                  return;
1529              chmod("$site_dir/$theme_file", 0777);
1530          }
1531      }
1532      @closedir($theme_dir);
1533  
1534      // Rewrite the theme header.
1535      $stylelines = explode("\n", implode('', file("$site_dir/style.css")));
1536      if ($stylelines) {
1537          $f = fopen("$site_dir/style.css", 'w');
1538  
1539          foreach ($stylelines as $line) {
1540              if (strpos($line, 'Theme Name:') !== false) $line = 'Theme Name: ' . $theme_name;
1541              elseif (strpos($line, 'Theme URI:') !== false) $line = 'Theme URI: ' . __get_option('url');
1542              elseif (strpos($line, 'Description:') !== false) $line = 'Description: Your theme.';
1543              elseif (strpos($line, 'Version:') !== false) $line = 'Version: 1';
1544              elseif (strpos($line, 'Author:') !== false) $line = 'Author: You';
1545              fwrite($f, $line . "\n");
1546          }
1547          fclose($f);
1548      }
1549  
1550      // Copy the images.
1551      umask(0);
1552      if (! mkdir("$site_dir/images", 0777)) {
1553          return false;
1554      }
1555  
1556      $images_dir = @ opendir("$default_dir/images");
1557      if ($images_dir) {
1558          while(($image = readdir($images_dir)) !== false) {
1559              if (is_dir("$default_dir/images/$image"))
1560                  continue;
1561              if (! @copy("$default_dir/images/$image", "$site_dir/images/$image"))
1562                  return;
1563              chmod("$site_dir/images/$image", 0777);
1564          }
1565      }
1566      @closedir($images_dir);
1567  }
1568  
1569  // Create a site theme from the default theme.
1570  /**
1571   * {@internal Missing Short Description}}
1572   *
1573   * {@internal Missing Long Description}}
1574   *
1575   * @since unknown
1576   *
1577   * @return unknown
1578   */
1579  function make_site_theme() {
1580      // Name the theme after the blog.
1581      $theme_name = __get_option('blogname');
1582      $template = sanitize_title($theme_name);
1583      $site_dir = WP_CONTENT_DIR . "/themes/$template";
1584  
1585      // If the theme already exists, nothing to do.
1586      if ( is_dir($site_dir)) {
1587          return false;
1588      }
1589  
1590      // We must be able to write to the themes dir.
1591      if (! is_writable(WP_CONTENT_DIR . "/themes")) {
1592          return false;
1593      }
1594  
1595      umask(0);
1596      if (! mkdir($site_dir, 0777)) {
1597          return false;
1598      }
1599  
1600      if (file_exists(ABSPATH . 'wp-layout.css')) {
1601          if (! make_site_theme_from_oldschool($theme_name, $template)) {
1602              // TODO:  rm -rf the site theme directory.
1603              return false;
1604          }
1605      } else {
1606          if (! make_site_theme_from_default($theme_name, $template))
1607              // TODO:  rm -rf the site theme directory.
1608              return false;
1609      }
1610  
1611      // Make the new site theme active.
1612      $current_template = __get_option('template');
1613      if ($current_template == 'default') {
1614          update_option('template', $template);
1615          update_option('stylesheet', $template);
1616      }
1617      return $template;
1618  }
1619  
1620  /**
1621   * Translate user level to user role name.
1622   *
1623   * @since unknown
1624   *
1625   * @param int $level User level.
1626   * @return string User role name.
1627   */
1628  function translate_level_to_role($level) {
1629      switch ($level) {
1630      case 10:
1631      case 9:
1632      case 8:
1633          return 'administrator';
1634      case 7:
1635      case 6:
1636      case 5:
1637          return 'editor';
1638      case 4:
1639      case 3:
1640      case 2:
1641          return 'author';
1642      case 1:
1643          return 'contributor';
1644      case 0:
1645          return 'subscriber';
1646      }
1647  }
1648  
1649  /**
1650   * {@internal Missing Short Description}}
1651   *
1652   * {@internal Missing Long Description}}
1653   *
1654   * @since unknown
1655   */
1656  function wp_check_mysql_version() {
1657      global $wpdb;
1658      $result = $wpdb->check_database_version();
1659      if ( is_wp_error( $result ) )
1660          die( $result->get_error_message() );
1661  }
1662  
1663  /**
1664   * {@internal Missing Short Description}}
1665   *
1666   * {@internal Missing Long Description}}
1667   *
1668   * @since unknown
1669   */
1670  function maybe_disable_automattic_widgets() {
1671      $plugins = __get_option( 'active_plugins' );
1672  
1673      foreach ( (array) $plugins as $plugin ) {
1674          if ( basename( $plugin ) == 'widgets.php' ) {
1675              array_splice( $plugins, array_search( $plugin, $plugins ), 1 );
1676              update_option( 'active_plugins', $plugins );
1677              break;
1678          }
1679      }
1680  }
1681  
1682  /**
1683   * Runs before the schema is upgraded.
1684   */
1685  function pre_schema_upgrade() {
1686      global $wp_current_db_version, $wp_db_version, $wpdb;
1687  
1688      // Upgrade versions prior to 2.9
1689      if ( $wp_current_db_version < 11557 ) {
1690          // Delete duplicate options.  Keep the option with the highest option_id.
1691          $wpdb->query("DELETE o1 FROM $wpdb->options AS o1 JOIN $wpdb->options AS o2 USING (`option_name`) WHERE o2.option_id > o1.option_id");
1692  
1693          // Drop the old primary key and add the new.
1694          $wpdb->query("ALTER TABLE $wpdb->options DROP PRIMARY KEY, ADD PRIMARY KEY(option_id)");
1695  
1696          // Drop the old option_name index. dbDelta() doesn't do the drop.
1697          $wpdb->query("ALTER TABLE $wpdb->options DROP INDEX option_name");
1698      }
1699  
1700  }
1701  
1702  ?>


Generated: Fri Jan 8 00:19:48 2010 Cross-referenced by PHPXref 0.7