[ Index ]

PHP Cross Reference of WordPress

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


Generated: Fri May 25 03:56:23 2012 Hosted by follow the white rabbit.