[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

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 installation customization script. */
  12  if ( file_exists( WP_CONTENT_DIR . '/install.php' ) ) {
  13      require( WP_CONTENT_DIR . '/install.php' );
  14  }
  15  
  16  /** WordPress Administration API */
  17  require_once ( ABSPATH . 'wp-admin/includes/admin.php' );
  18  
  19  /** WordPress Schema API */
  20  require_once ( ABSPATH . 'wp-admin/includes/schema.php' );
  21  
  22  if ( ! function_exists( 'wp_install' ) ) :
  23      /**
  24       * Installs the site.
  25       *
  26       * Runs the required functions to set up and populate the database,
  27       * including primary admin user and initial options.
  28       *
  29       * @since 2.1.0
  30       *
  31       * @param string $blog_title    Site title.
  32       * @param string $user_name     User's username.
  33       * @param string $user_email    User's email.
  34       * @param bool   $public        Whether site is public.
  35       * @param string $deprecated    Optional. Not used.
  36       * @param string $user_password Optional. User's chosen password. Default empty (random password).
  37       * @param string $language      Optional. Language chosen. Default empty.
  38       * @return array Array keys 'url', 'user_id', 'password', and 'password_message'.
  39       */
  40  	function wp_install( $blog_title, $user_name, $user_email, $public, $deprecated = '', $user_password = '', $language = '' ) {
  41          if ( ! empty( $deprecated ) ) {
  42              _deprecated_argument( __FUNCTION__, '2.6.0' );
  43          }
  44  
  45          wp_check_mysql_version();
  46          wp_cache_flush();
  47          make_db_current_silent();
  48          populate_options();
  49          populate_roles();
  50  
  51          update_option( 'blogname', $blog_title );
  52          update_option( 'admin_email', $user_email );
  53          update_option( 'blog_public', $public );
  54  
  55          // Freshness of site - in the future, this could get more specific about actions taken, perhaps.
  56          update_option( 'fresh_site', 1 );
  57  
  58          if ( $language ) {
  59              update_option( 'WPLANG', $language );
  60          }
  61  
  62          $guessurl = wp_guess_url();
  63  
  64          update_option( 'siteurl', $guessurl );
  65  
  66          // If not a public site, don't ping.
  67          if ( ! $public ) {
  68              update_option( 'default_pingback_flag', 0 );
  69          }
  70  
  71          /*
  72           * Create default user. If the user already exists, the user tables are
  73           * being shared among sites. Just set the role in that case.
  74           */
  75          $user_id        = username_exists( $user_name );
  76          $user_password  = trim( $user_password );
  77          $email_password = false;
  78          if ( ! $user_id && empty( $user_password ) ) {
  79              $user_password = wp_generate_password( 12, false );
  80              $message       = __( '<strong><em>Note that password</em></strong> carefully! It is a <em>random</em> password that was generated just for you.' );
  81              $user_id       = wp_create_user( $user_name, $user_password, $user_email );
  82              update_user_option( $user_id, 'default_password_nag', true, true );
  83              $email_password = true;
  84          } elseif ( ! $user_id ) {
  85              // Password has been provided
  86              $message = '<em>' . __( 'Your chosen password.' ) . '</em>';
  87              $user_id = wp_create_user( $user_name, $user_password, $user_email );
  88          } else {
  89              $message = __( 'User already exists. Password inherited.' );
  90          }
  91  
  92          $user = new WP_User( $user_id );
  93          $user->set_role( 'administrator' );
  94  
  95          wp_install_defaults( $user_id );
  96  
  97          wp_install_maybe_enable_pretty_permalinks();
  98  
  99          flush_rewrite_rules();
 100  
 101          wp_new_blog_notification( $blog_title, $guessurl, $user_id, ( $email_password ? $user_password : __( 'The password you chose during installation.' ) ) );
 102  
 103          wp_cache_flush();
 104  
 105          /**
 106           * Fires after a site is fully installed.
 107           *
 108           * @since 3.9.0
 109           *
 110           * @param WP_User $user The site owner.
 111           */
 112          do_action( 'wp_install', $user );
 113  
 114          return array(
 115              'url'              => $guessurl,
 116              'user_id'          => $user_id,
 117              'password'         => $user_password,
 118              'password_message' => $message,
 119          );
 120      }
 121  endif;
 122  
 123  if ( ! function_exists( 'wp_install_defaults' ) ) :
 124      /**
 125       * Creates the initial content for a newly-installed site.
 126       *
 127       * Adds the default "Uncategorized" category, the first post (with comment),
 128       * first page, and default widgets for default theme for the current version.
 129       *
 130       * @since 2.1.0
 131       *
 132       * @global wpdb       $wpdb
 133       * @global WP_Rewrite $wp_rewrite
 134       * @global string     $table_prefix
 135       *
 136       * @param int $user_id User ID.
 137       */
 138  	function wp_install_defaults( $user_id ) {
 139          global $wpdb, $wp_rewrite, $table_prefix;
 140  
 141          // Default category
 142          $cat_name = __( 'Uncategorized' );
 143          /* translators: Default category slug */
 144          $cat_slug = sanitize_title( _x( 'Uncategorized', 'Default category slug' ) );
 145  
 146          if ( global_terms_enabled() ) {
 147              $cat_id = $wpdb->get_var( $wpdb->prepare( "SELECT cat_ID FROM {$wpdb->sitecategories} WHERE category_nicename = %s", $cat_slug ) );
 148              if ( $cat_id == null ) {
 149                  $wpdb->insert(
 150                      $wpdb->sitecategories,
 151                      array(
 152                          'cat_ID'            => 0,
 153                          'cat_name'          => $cat_name,
 154                          'category_nicename' => $cat_slug,
 155                          'last_updated'      => current_time( 'mysql', true ),
 156                      )
 157                  );
 158                  $cat_id = $wpdb->insert_id;
 159              }
 160              update_option( 'default_category', $cat_id );
 161          } else {
 162              $cat_id = 1;
 163          }
 164  
 165          $wpdb->insert(
 166              $wpdb->terms,
 167              array(
 168                  'term_id'    => $cat_id,
 169                  'name'       => $cat_name,
 170                  'slug'       => $cat_slug,
 171                  'term_group' => 0,
 172              )
 173          );
 174          $wpdb->insert(
 175              $wpdb->term_taxonomy,
 176              array(
 177                  'term_id'     => $cat_id,
 178                  'taxonomy'    => 'category',
 179                  'description' => '',
 180                  'parent'      => 0,
 181                  'count'       => 1,
 182              )
 183          );
 184          $cat_tt_id = $wpdb->insert_id;
 185  
 186          // First post
 187          $now             = current_time( 'mysql' );
 188          $now_gmt         = current_time( 'mysql', 1 );
 189          $first_post_guid = get_option( 'home' ) . '/?p=1';
 190  
 191          if ( is_multisite() ) {
 192              $first_post = get_site_option( 'first_post' );
 193  
 194              if ( ! $first_post ) {
 195                  $first_post = "<!-- wp:paragraph -->\n<p>" .
 196                  /* translators: first post content, %s: site link */
 197                  __( 'Welcome to %s. This is your first post. Edit or delete it, then start writing!' ) .
 198                  "</p>\n<!-- /wp:paragraph -->";
 199              }
 200  
 201              $first_post = sprintf(
 202                  $first_post,
 203                  sprintf( '<a href="%s">%s</a>', esc_url( network_home_url() ), get_network()->site_name )
 204              );
 205  
 206              // Back-compat for pre-4.4
 207              $first_post = str_replace( 'SITE_URL', esc_url( network_home_url() ), $first_post );
 208              $first_post = str_replace( 'SITE_NAME', get_network()->site_name, $first_post );
 209          } else {
 210              $first_post = "<!-- wp:paragraph -->\n<p>" .
 211              /* translators: first post content, %s: site link */
 212              __( 'Welcome to WordPress. This is your first post. Edit or delete it, then start writing!' ) .
 213              "</p>\n<!-- /wp:paragraph -->";
 214          }
 215  
 216          $wpdb->insert(
 217              $wpdb->posts,
 218              array(
 219                  'post_author'           => $user_id,
 220                  'post_date'             => $now,
 221                  'post_date_gmt'         => $now_gmt,
 222                  'post_content'          => $first_post,
 223                  'post_excerpt'          => '',
 224                  'post_title'            => __( 'Hello world!' ),
 225                  /* translators: Default post slug */
 226                  'post_name'             => sanitize_title( _x( 'hello-world', 'Default post slug' ) ),
 227                  'post_modified'         => $now,
 228                  'post_modified_gmt'     => $now_gmt,
 229                  'guid'                  => $first_post_guid,
 230                  'comment_count'         => 1,
 231                  'to_ping'               => '',
 232                  'pinged'                => '',
 233                  'post_content_filtered' => '',
 234              )
 235          );
 236          $wpdb->insert(
 237              $wpdb->term_relationships,
 238              array(
 239                  'term_taxonomy_id' => $cat_tt_id,
 240                  'object_id'        => 1,
 241              )
 242          );
 243  
 244          // Default comment
 245          if ( is_multisite() ) {
 246              $first_comment_author = get_site_option( 'first_comment_author' );
 247              $first_comment_email  = get_site_option( 'first_comment_email' );
 248              $first_comment_url    = get_site_option( 'first_comment_url', network_home_url() );
 249              $first_comment        = get_site_option( 'first_comment' );
 250          }
 251  
 252          $first_comment_author = ! empty( $first_comment_author ) ? $first_comment_author : __( 'A WordPress Commenter' );
 253          $first_comment_email  = ! empty( $first_comment_email ) ? $first_comment_email : 'wapuu@wordpress.example';
 254          $first_comment_url    = ! empty( $first_comment_url ) ? $first_comment_url : 'https://wordpress.org/';
 255          $first_comment        = ! empty( $first_comment ) ? $first_comment : __(
 256              'Hi, this is a comment.
 257  To get started with moderating, editing, and deleting comments, please visit the Comments screen in the dashboard.
 258  Commenter avatars come from <a href="https://gravatar.com">Gravatar</a>.'
 259          );
 260          $wpdb->insert(
 261              $wpdb->comments,
 262              array(
 263                  'comment_post_ID'      => 1,
 264                  'comment_author'       => $first_comment_author,
 265                  'comment_author_email' => $first_comment_email,
 266                  'comment_author_url'   => $first_comment_url,
 267                  'comment_date'         => $now,
 268                  'comment_date_gmt'     => $now_gmt,
 269                  'comment_content'      => $first_comment,
 270              )
 271          );
 272  
 273          // First Page
 274          if ( is_multisite() ) {
 275              $first_page = get_site_option( 'first_page' );
 276          }
 277  
 278          if ( empty( $first_page ) ) {
 279              $first_page = "<!-- wp:paragraph -->\n<p>";
 280              /* translators: first page content */
 281              $first_page .= __( "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:" );
 282              $first_page .= "</p>\n<!-- /wp:paragraph -->\n\n";
 283  
 284              $first_page .= "<!-- wp:quote -->\n<blockquote class=\"wp-block-quote\"><p>";
 285              /* translators: first page content */
 286              $first_page .= __( "Hi there! I'm a bike messenger by day, aspiring actor by night, and this is my website. I live in Los Angeles, have a great dog named Jack, and I like pi&#241;a coladas. (And gettin' caught in the rain.)" );
 287              $first_page .= "</p></blockquote>\n<!-- /wp:quote -->\n\n";
 288  
 289              $first_page .= "<!-- wp:paragraph -->\n<p>";
 290              /* translators: first page content */
 291              $first_page .= __( '...or something like this:' );
 292              $first_page .= "</p>\n<!-- /wp:paragraph -->\n\n";
 293  
 294              $first_page .= "<!-- wp:quote -->\n<blockquote class=\"wp-block-quote\"><p>";
 295              /* translators: first page content */
 296              $first_page .= __( 'The XYZ Doohickey Company was founded in 1971, and has been providing quality doohickeys 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.' );
 297              $first_page .= "</p></blockquote>\n<!-- /wp:quote -->\n\n";
 298  
 299              $first_page .= "<!-- wp:paragraph -->\n<p>";
 300              $first_page .= sprintf(
 301                  /* translators: first page content, %s: site admin URL */
 302                  __( '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!' ),
 303                  admin_url()
 304              );
 305              $first_page .= "</p>\n<!-- /wp:paragraph -->";
 306          }
 307  
 308          $first_post_guid = get_option( 'home' ) . '/?page_id=2';
 309          $wpdb->insert(
 310              $wpdb->posts,
 311              array(
 312                  'post_author'           => $user_id,
 313                  'post_date'             => $now,
 314                  'post_date_gmt'         => $now_gmt,
 315                  'post_content'          => $first_page,
 316                  'post_excerpt'          => '',
 317                  'comment_status'        => 'closed',
 318                  'post_title'            => __( 'Sample Page' ),
 319                  /* translators: Default page slug */
 320                  'post_name'             => __( 'sample-page' ),
 321                  'post_modified'         => $now,
 322                  'post_modified_gmt'     => $now_gmt,
 323                  'guid'                  => $first_post_guid,
 324                  'post_type'             => 'page',
 325                  'to_ping'               => '',
 326                  'pinged'                => '',
 327                  'post_content_filtered' => '',
 328              )
 329          );
 330          $wpdb->insert(
 331              $wpdb->postmeta,
 332              array(
 333                  'post_id'    => 2,
 334                  'meta_key'   => '_wp_page_template',
 335                  'meta_value' => 'default',
 336              )
 337          );
 338  
 339          // Privacy Policy page
 340          if ( is_multisite() ) {
 341              // Disable by default unless the suggested content is provided.
 342              $privacy_policy_content = get_site_option( 'default_privacy_policy_content' );
 343          } else {
 344              if ( ! class_exists( 'WP_Privacy_Policy_Content' ) ) {
 345                  include_once ( ABSPATH . 'wp-admin/includes/class-wp-privacy-policy-content.php' );
 346              }
 347  
 348              $privacy_policy_content = WP_Privacy_Policy_Content::get_default_content();
 349          }
 350  
 351          if ( ! empty( $privacy_policy_content ) ) {
 352              $privacy_policy_guid = get_option( 'home' ) . '/?page_id=3';
 353  
 354              $wpdb->insert(
 355                  $wpdb->posts,
 356                  array(
 357                      'post_author'           => $user_id,
 358                      'post_date'             => $now,
 359                      'post_date_gmt'         => $now_gmt,
 360                      'post_content'          => $privacy_policy_content,
 361                      'post_excerpt'          => '',
 362                      'comment_status'        => 'closed',
 363                      'post_title'            => __( 'Privacy Policy' ),
 364                      /* translators: Privacy Policy page slug */
 365                      'post_name'             => __( 'privacy-policy' ),
 366                      'post_modified'         => $now,
 367                      'post_modified_gmt'     => $now_gmt,
 368                      'guid'                  => $privacy_policy_guid,
 369                      'post_type'             => 'page',
 370                      'post_status'           => 'draft',
 371                      'to_ping'               => '',
 372                      'pinged'                => '',
 373                      'post_content_filtered' => '',
 374                  )
 375              );
 376              $wpdb->insert(
 377                  $wpdb->postmeta,
 378                  array(
 379                      'post_id'    => 3,
 380                      'meta_key'   => '_wp_page_template',
 381                      'meta_value' => 'default',
 382                  )
 383              );
 384              update_option( 'wp_page_for_privacy_policy', 3 );
 385          }
 386  
 387          // Set up default widgets for default theme.
 388          update_option(
 389              'widget_search',
 390              array(
 391                  2              => array( 'title' => '' ),
 392                  '_multiwidget' => 1,
 393              )
 394          );
 395          update_option(
 396              'widget_recent-posts',
 397              array(
 398                  2              => array(
 399                      'title'  => '',
 400                      'number' => 5,
 401                  ),
 402                  '_multiwidget' => 1,
 403              )
 404          );
 405          update_option(
 406              'widget_recent-comments',
 407              array(
 408                  2              => array(
 409                      'title'  => '',
 410                      'number' => 5,
 411                  ),
 412                  '_multiwidget' => 1,
 413              )
 414          );
 415          update_option(
 416              'widget_archives',
 417              array(
 418                  2              => array(
 419                      'title'    => '',
 420                      'count'    => 0,
 421                      'dropdown' => 0,
 422                  ),
 423                  '_multiwidget' => 1,
 424              )
 425          );
 426          update_option(
 427              'widget_categories',
 428              array(
 429                  2              => array(
 430                      'title'        => '',
 431                      'count'        => 0,
 432                      'hierarchical' => 0,
 433                      'dropdown'     => 0,
 434                  ),
 435                  '_multiwidget' => 1,
 436              )
 437          );
 438          update_option(
 439              'widget_meta',
 440              array(
 441                  2              => array( 'title' => '' ),
 442                  '_multiwidget' => 1,
 443              )
 444          );
 445          update_option(
 446              'sidebars_widgets',
 447              array(
 448                  'wp_inactive_widgets' => array(),
 449                  'sidebar-1'           => array(
 450                      0 => 'search-2',
 451                      1 => 'recent-posts-2',
 452                      2 => 'recent-comments-2',
 453                      3 => 'archives-2',
 454                      4 => 'categories-2',
 455                      5 => 'meta-2',
 456                  ),
 457                  'array_version'       => 3,
 458              )
 459          );
 460          if ( ! is_multisite() ) {
 461              update_user_meta( $user_id, 'show_welcome_panel', 1 );
 462          } elseif ( ! is_super_admin( $user_id ) && ! metadata_exists( 'user', $user_id, 'show_welcome_panel' ) ) {
 463              update_user_meta( $user_id, 'show_welcome_panel', 2 );
 464          }
 465  
 466          if ( is_multisite() ) {
 467              // Flush rules to pick up the new page.
 468              $wp_rewrite->init();
 469              $wp_rewrite->flush_rules();
 470  
 471              $user = new WP_User( $user_id );
 472              $wpdb->update( $wpdb->options, array( 'option_value' => $user->user_email ), array( 'option_name' => 'admin_email' ) );
 473  
 474              // Remove all perms except for the login user.
 475              $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->usermeta WHERE user_id != %d AND meta_key = %s", $user_id, $table_prefix . 'user_level' ) );
 476              $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->usermeta WHERE user_id != %d AND meta_key = %s", $user_id, $table_prefix . 'capabilities' ) );
 477  
 478              // Delete any caps that snuck into the previously active blog. (Hardcoded to blog 1 for now.) TODO: Get previous_blog_id.
 479              if ( ! is_super_admin( $user_id ) && $user_id != 1 ) {
 480                  $wpdb->delete(
 481                      $wpdb->usermeta,
 482                      array(
 483                          'user_id'  => $user_id,
 484                          'meta_key' => $wpdb->base_prefix . '1_capabilities',
 485                      )
 486                  );
 487              }
 488          }
 489      }
 490  endif;
 491  
 492  /**
 493   * Maybe enable pretty permalinks on installation.
 494   *
 495   * If after enabling pretty permalinks don't work, fallback to query-string permalinks.
 496   *
 497   * @since 4.2.0
 498   *
 499   * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
 500   *
 501   * @return bool Whether pretty permalinks are enabled. False otherwise.
 502   */
 503  function wp_install_maybe_enable_pretty_permalinks() {
 504      global $wp_rewrite;
 505  
 506      // Bail if a permalink structure is already enabled.
 507      if ( get_option( 'permalink_structure' ) ) {
 508          return true;
 509      }
 510  
 511      /*
 512       * The Permalink structures to attempt.
 513       *
 514       * The first is designed for mod_rewrite or nginx rewriting.
 515       *
 516       * The second is PATHINFO-based permalinks for web server configurations
 517       * without a true rewrite module enabled.
 518       */
 519      $permalink_structures = array(
 520          '/%year%/%monthnum%/%day%/%postname%/',
 521          '/index.php/%year%/%monthnum%/%day%/%postname%/',
 522      );
 523  
 524      foreach ( (array) $permalink_structures as $permalink_structure ) {
 525          $wp_rewrite->set_permalink_structure( $permalink_structure );
 526  
 527          /*
 528            * Flush rules with the hard option to force refresh of the web-server's
 529            * rewrite config file (e.g. .htaccess or web.config).
 530            */
 531          $wp_rewrite->flush_rules( true );
 532  
 533          $test_url = '';
 534  
 535          // Test against a real WordPress Post
 536          $first_post = get_page_by_path( sanitize_title( _x( 'hello-world', 'Default post slug' ) ), OBJECT, 'post' );
 537          if ( $first_post ) {
 538              $test_url = get_permalink( $first_post->ID );
 539          }
 540  
 541          /*
 542            * Send a request to the site, and check whether
 543            * the 'x-pingback' header is returned as expected.
 544            *
 545            * Uses wp_remote_get() instead of wp_remote_head() because web servers
 546            * can block head requests.
 547            */
 548          $response          = wp_remote_get( $test_url, array( 'timeout' => 5 ) );
 549          $x_pingback_header = wp_remote_retrieve_header( $response, 'x-pingback' );
 550          $pretty_permalinks = $x_pingback_header && $x_pingback_header === get_bloginfo( 'pingback_url' );
 551  
 552          if ( $pretty_permalinks ) {
 553              return true;
 554          }
 555      }
 556  
 557      /*
 558       * If it makes it this far, pretty permalinks failed.
 559       * Fallback to query-string permalinks.
 560       */
 561      $wp_rewrite->set_permalink_structure( '' );
 562      $wp_rewrite->flush_rules( true );
 563  
 564      return false;
 565  }
 566  
 567  if ( ! function_exists( 'wp_new_blog_notification' ) ) :
 568      /**
 569       * Notifies the site admin that the setup is complete.
 570       *
 571       * Sends an email with wp_mail to the new administrator that the site setup is complete,
 572       * and provides them with a record of their login credentials.
 573       *
 574       * @since 2.1.0
 575       *
 576       * @param string $blog_title Site title.
 577       * @param string $blog_url   Site url.
 578       * @param int    $user_id    User ID.
 579       * @param string $password   User's Password.
 580       */
 581  	function wp_new_blog_notification( $blog_title, $blog_url, $user_id, $password ) {
 582          $user      = new WP_User( $user_id );
 583          $email     = $user->user_email;
 584          $name      = $user->user_login;
 585          $login_url = wp_login_url();
 586          /* translators: New site notification email. 1: New site URL, 2: User login, 3: User password or password reset link, 4: Login URL */
 587          $message = sprintf(
 588              __(
 589                  'Your new WordPress site has been successfully set up at:
 590  
 591  %1$s
 592  
 593  You can log in to the administrator account with the following information:
 594  
 595  Username: %2$s
 596  Password: %3$s
 597  Log in here: %4$s
 598  
 599  We hope you enjoy your new site. Thanks!
 600  
 601  --The WordPress Team
 602  https://wordpress.org/
 603  '
 604              ),
 605              $blog_url,
 606              $name,
 607              $password,
 608              $login_url
 609          );
 610  
 611          @wp_mail( $email, __( 'New WordPress Site' ), $message );
 612      }
 613  endif;
 614  
 615  if ( ! function_exists( 'wp_upgrade' ) ) :
 616      /**
 617       * Runs WordPress Upgrade functions.
 618       *
 619       * Upgrades the database if needed during a site update.
 620       *
 621       * @since 2.1.0
 622       *
 623       * @global int  $wp_current_db_version
 624       * @global int  $wp_db_version
 625       * @global wpdb $wpdb WordPress database abstraction object.
 626       */
 627  	function wp_upgrade() {
 628          global $wp_current_db_version, $wp_db_version, $wpdb;
 629  
 630          $wp_current_db_version = __get_option( 'db_version' );
 631  
 632          // We are up-to-date. Nothing to do.
 633          if ( $wp_db_version == $wp_current_db_version ) {
 634              return;
 635          }
 636  
 637          if ( ! is_blog_installed() ) {
 638              return;
 639          }
 640  
 641          wp_check_mysql_version();
 642          wp_cache_flush();
 643          pre_schema_upgrade();
 644          make_db_current_silent();
 645          upgrade_all();
 646          if ( is_multisite() && is_main_site() ) {
 647              upgrade_network();
 648          }
 649          wp_cache_flush();
 650  
 651          if ( is_multisite() ) {
 652              $site_id = get_current_blog_id();
 653  
 654              if ( $wpdb->get_row( $wpdb->prepare( "SELECT blog_id FROM {$wpdb->blog_versions} WHERE blog_id = %d", $site_id ) ) ) {
 655                  $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->blog_versions} SET db_version = %d WHERE blog_id = %d", $wp_db_version, $site_id ) );
 656              } else {
 657                  $wpdb->query( $wpdb->prepare( "INSERT INTO {$wpdb->blog_versions} ( `blog_id` , `db_version` , `last_updated` ) VALUES ( %d, %d, NOW() );", $site_id, $wp_db_version ) );
 658              }
 659          }
 660  
 661          /**
 662           * Fires after a site is fully upgraded.
 663           *
 664           * @since 3.9.0
 665           *
 666           * @param int $wp_db_version         The new $wp_db_version.
 667           * @param int $wp_current_db_version The old (current) $wp_db_version.
 668           */
 669          do_action( 'wp_upgrade', $wp_db_version, $wp_current_db_version );
 670      }
 671  endif;
 672  
 673  /**
 674   * Functions to be called in installation and upgrade scripts.
 675   *
 676   * Contains conditional checks to determine which upgrade scripts to run,
 677   * based on database version and WP version being updated-to.
 678   *
 679   * @ignore
 680   * @since 1.0.1
 681   *
 682   * @global int $wp_current_db_version
 683   * @global int $wp_db_version
 684   */
 685  function upgrade_all() {
 686      global $wp_current_db_version, $wp_db_version;
 687      $wp_current_db_version = __get_option( 'db_version' );
 688  
 689      // We are up-to-date. Nothing to do.
 690      if ( $wp_db_version == $wp_current_db_version ) {
 691          return;
 692      }
 693  
 694      // If the version is not set in the DB, try to guess the version.
 695      if ( empty( $wp_current_db_version ) ) {
 696          $wp_current_db_version = 0;
 697  
 698          // If the template option exists, we have 1.5.
 699          $template = __get_option( 'template' );
 700          if ( ! empty( $template ) ) {
 701              $wp_current_db_version = 2541;
 702          }
 703      }
 704  
 705      if ( $wp_current_db_version < 6039 ) {
 706          upgrade_230_options_table();
 707      }
 708  
 709      populate_options();
 710  
 711      if ( $wp_current_db_version < 2541 ) {
 712          upgrade_100();
 713          upgrade_101();
 714          upgrade_110();
 715          upgrade_130();
 716      }
 717  
 718      if ( $wp_current_db_version < 3308 ) {
 719          upgrade_160();
 720      }
 721  
 722      if ( $wp_current_db_version < 4772 ) {
 723          upgrade_210();
 724      }
 725  
 726      if ( $wp_current_db_version < 4351 ) {
 727          upgrade_old_slugs();
 728      }
 729  
 730      if ( $wp_current_db_version < 5539 ) {
 731          upgrade_230();
 732      }
 733  
 734      if ( $wp_current_db_version < 6124 ) {
 735          upgrade_230_old_tables();
 736      }
 737  
 738      if ( $wp_current_db_version < 7499 ) {
 739          upgrade_250();
 740      }
 741  
 742      if ( $wp_current_db_version < 7935 ) {
 743          upgrade_252();
 744      }
 745  
 746      if ( $wp_current_db_version < 8201 ) {
 747          upgrade_260();
 748      }
 749  
 750      if ( $wp_current_db_version < 8989 ) {
 751          upgrade_270();
 752      }
 753  
 754      if ( $wp_current_db_version < 10360 ) {
 755          upgrade_280();
 756      }
 757  
 758      if ( $wp_current_db_version < 11958 ) {
 759          upgrade_290();
 760      }
 761  
 762      if ( $wp_current_db_version < 15260 ) {
 763          upgrade_300();
 764      }
 765  
 766      if ( $wp_current_db_version < 19389 ) {
 767          upgrade_330();
 768      }
 769  
 770      if ( $wp_current_db_version < 20080 ) {
 771          upgrade_340();
 772      }
 773  
 774      if ( $wp_current_db_version < 22422 ) {
 775          upgrade_350();
 776      }
 777  
 778      if ( $wp_current_db_version < 25824 ) {
 779          upgrade_370();
 780      }
 781  
 782      if ( $wp_current_db_version < 26148 ) {
 783          upgrade_372();
 784      }
 785  
 786      if ( $wp_current_db_version < 26691 ) {
 787          upgrade_380();
 788      }
 789  
 790      if ( $wp_current_db_version < 29630 ) {
 791          upgrade_400();
 792      }
 793  
 794      if ( $wp_current_db_version < 33055 ) {
 795          upgrade_430();
 796      }
 797  
 798      if ( $wp_current_db_version < 33056 ) {
 799          upgrade_431();
 800      }
 801  
 802      if ( $wp_current_db_version < 35700 ) {
 803          upgrade_440();
 804      }
 805  
 806      if ( $wp_current_db_version < 36686 ) {
 807          upgrade_450();
 808      }
 809  
 810      if ( $wp_current_db_version < 37965 ) {
 811          upgrade_460();
 812      }
 813  
 814      if ( $wp_current_db_version < 44719 ) {
 815          upgrade_510();
 816      }
 817  
 818      maybe_disable_link_manager();
 819  
 820      maybe_disable_automattic_widgets();
 821  
 822      update_option( 'db_version', $wp_db_version );
 823      update_option( 'db_upgraded', true );
 824  }
 825  
 826  /**
 827   * Execute changes made in WordPress 1.0.
 828   *
 829   * @ignore
 830   * @since 1.0.0
 831   *
 832   * @global wpdb $wpdb WordPress database abstraction object.
 833   */
 834  function upgrade_100() {
 835      global $wpdb;
 836  
 837      // Get the title and ID of every post, post_name to check if it already has a value
 838      $posts = $wpdb->get_results( "SELECT ID, post_title, post_name FROM $wpdb->posts WHERE post_name = ''" );
 839      if ( $posts ) {
 840          foreach ( $posts as $post ) {
 841              if ( '' == $post->post_name ) {
 842                  $newtitle = sanitize_title( $post->post_title );
 843                  $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET post_name = %s WHERE ID = %d", $newtitle, $post->ID ) );
 844              }
 845          }
 846      }
 847  
 848      $categories = $wpdb->get_results( "SELECT cat_ID, cat_name, category_nicename FROM $wpdb->categories" );
 849      foreach ( $categories as $category ) {
 850          if ( '' == $category->category_nicename ) {
 851              $newtitle = sanitize_title( $category->cat_name );
 852              $wpdb->update( $wpdb->categories, array( 'category_nicename' => $newtitle ), array( 'cat_ID' => $category->cat_ID ) );
 853          }
 854      }
 855  
 856      $sql = "UPDATE $wpdb->options
 857          SET option_value = REPLACE(option_value, 'wp-links/links-images/', 'wp-images/links/')
 858          WHERE option_name LIKE %s
 859          AND option_value LIKE %s";
 860      $wpdb->query( $wpdb->prepare( $sql, $wpdb->esc_like( 'links_rating_image' ) . '%', $wpdb->esc_like( 'wp-links/links-images/' ) . '%' ) );
 861  
 862      $done_ids = $wpdb->get_results( "SELECT DISTINCT post_id FROM $wpdb->post2cat" );
 863      if ( $done_ids ) :
 864          $done_posts = array();
 865          foreach ( $done_ids as $done_id ) :
 866              $done_posts[] = $done_id->post_id;
 867          endforeach;
 868          $catwhere = ' AND ID NOT IN (' . implode( ',', $done_posts ) . ')';
 869      else :
 870          $catwhere = '';
 871      endif;
 872  
 873      $allposts = $wpdb->get_results( "SELECT ID, post_category FROM $wpdb->posts WHERE post_category != '0' $catwhere" );
 874      if ( $allposts ) :
 875          foreach ( $allposts as $post ) {
 876              // Check to see if it's already been imported
 877              $cat = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->post2cat WHERE post_id = %d AND category_id = %d", $post->ID, $post->post_category ) );
 878              if ( ! $cat && 0 != $post->post_category ) { // If there's no result
 879                  $wpdb->insert(
 880                      $wpdb->post2cat,
 881                      array(
 882                          'post_id'     => $post->ID,
 883                          'category_id' => $post->post_category,
 884                      )
 885                  );
 886              }
 887          }
 888      endif;
 889  }
 890  
 891  /**
 892   * Execute changes made in WordPress 1.0.1.
 893   *
 894   * @ignore
 895   * @since 1.0.1
 896   *
 897   * @global wpdb $wpdb WordPress database abstraction object.
 898   */
 899  function upgrade_101() {
 900      global $wpdb;
 901  
 902      // Clean up indices, add a few
 903      add_clean_index( $wpdb->posts, 'post_name' );
 904      add_clean_index( $wpdb->posts, 'post_status' );
 905      add_clean_index( $wpdb->categories, 'category_nicename' );
 906      add_clean_index( $wpdb->comments, 'comment_approved' );
 907      add_clean_index( $wpdb->comments, 'comment_post_ID' );
 908      add_clean_index( $wpdb->links, 'link_category' );
 909      add_clean_index( $wpdb->links, 'link_visible' );
 910  }
 911  
 912  /**
 913   * Execute changes made in WordPress 1.2.
 914   *
 915   * @ignore
 916   * @since 1.2.0
 917   *
 918   * @global wpdb $wpdb WordPress database abstraction object.
 919   */
 920  function upgrade_110() {
 921      global $wpdb;
 922  
 923      // Set user_nicename.
 924      $users = $wpdb->get_results( "SELECT ID, user_nickname, user_nicename FROM $wpdb->users" );
 925      foreach ( $users as $user ) {
 926          if ( '' == $user->user_nicename ) {
 927              $newname = sanitize_title( $user->user_nickname );
 928              $wpdb->update( $wpdb->users, array( 'user_nicename' => $newname ), array( 'ID' => $user->ID ) );
 929          }
 930      }
 931  
 932      $users = $wpdb->get_results( "SELECT ID, user_pass from $wpdb->users" );
 933      foreach ( $users as $row ) {
 934          if ( ! preg_match( '/^[A-Fa-f0-9]{32}$/', $row->user_pass ) ) {
 935              $wpdb->update( $wpdb->users, array( 'user_pass' => md5( $row->user_pass ) ), array( 'ID' => $row->ID ) );
 936          }
 937      }
 938  
 939      // Get the GMT offset, we'll use that later on
 940      $all_options = get_alloptions_110();
 941  
 942      $time_difference = $all_options->time_difference;
 943  
 944          $server_time = time() + gmdate( 'Z' );
 945      $weblogger_time  = $server_time + $time_difference * HOUR_IN_SECONDS;
 946      $gmt_time        = time();
 947  
 948      $diff_gmt_server       = ( $gmt_time - $server_time ) / HOUR_IN_SECONDS;
 949      $diff_weblogger_server = ( $weblogger_time - $server_time ) / HOUR_IN_SECONDS;
 950      $diff_gmt_weblogger    = $diff_gmt_server - $diff_weblogger_server;
 951      $gmt_offset            = -$diff_gmt_weblogger;
 952  
 953      // Add a gmt_offset option, with value $gmt_offset
 954      add_option( 'gmt_offset', $gmt_offset );
 955  
 956      // Check if we already set the GMT fields (if we did, then
 957      // MAX(post_date_gmt) can't be '0000-00-00 00:00:00'
 958      // <michel_v> I just slapped myself silly for not thinking about it earlier
 959      $got_gmt_fields = ! ( $wpdb->get_var( "SELECT MAX(post_date_gmt) FROM $wpdb->posts" ) == '0000-00-00 00:00:00' );
 960  
 961      if ( ! $got_gmt_fields ) {
 962  
 963          // Add or subtract time to all dates, to get GMT dates
 964          $add_hours   = intval( $diff_gmt_weblogger );
 965          $add_minutes = intval( 60 * ( $diff_gmt_weblogger - $add_hours ) );
 966          $wpdb->query( "UPDATE $wpdb->posts SET post_date_gmt = DATE_ADD(post_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)" );
 967          $wpdb->query( "UPDATE $wpdb->posts SET post_modified = post_date" );
 968          $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'" );
 969          $wpdb->query( "UPDATE $wpdb->comments SET comment_date_gmt = DATE_ADD(comment_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)" );
 970          $wpdb->query( "UPDATE $wpdb->users SET user_registered = DATE_ADD(user_registered, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)" );
 971      }
 972  
 973  }
 974  
 975  /**
 976   * Execute changes made in WordPress 1.5.
 977   *
 978   * @ignore
 979   * @since 1.5.0
 980   *
 981   * @global wpdb $wpdb WordPress database abstraction object.
 982   */
 983  function upgrade_130() {
 984      global $wpdb;
 985  
 986      // Remove extraneous backslashes.
 987      $posts = $wpdb->get_results( "SELECT ID, post_title, post_content, post_excerpt, guid, post_date, post_name, post_status, post_author FROM $wpdb->posts" );
 988      if ( $posts ) {
 989          foreach ( $posts as $post ) {
 990              $post_content = addslashes( deslash( $post->post_content ) );
 991              $post_title   = addslashes( deslash( $post->post_title ) );
 992              $post_excerpt = addslashes( deslash( $post->post_excerpt ) );
 993              if ( empty( $post->guid ) ) {
 994                  $guid = get_permalink( $post->ID );
 995              } else {
 996                  $guid = $post->guid;
 997              }
 998  
 999              $wpdb->update( $wpdb->posts, compact( 'post_title', 'post_content', 'post_excerpt', 'guid' ), array( 'ID' => $post->ID ) );
1000  
1001          }
1002      }
1003  
1004      // Remove extraneous backslashes.
1005      $comments = $wpdb->get_results( "SELECT comment_ID, comment_author, comment_content FROM $wpdb->comments" );
1006      if ( $comments ) {
1007          foreach ( $comments as $comment ) {
1008              $comment_content = deslash( $comment->comment_content );
1009              $comment_author  = deslash( $comment->comment_author );
1010  
1011              $wpdb->update( $wpdb->comments, compact( 'comment_content', 'comment_author' ), array( 'comment_ID' => $comment->comment_ID ) );
1012          }
1013      }
1014  
1015      // Remove extraneous backslashes.
1016      $links = $wpdb->get_results( "SELECT link_id, link_name, link_description FROM $wpdb->links" );
1017      if ( $links ) {
1018          foreach ( $links as $link ) {
1019              $link_name        = deslash( $link->link_name );
1020              $link_description = deslash( $link->link_description );
1021  
1022              $wpdb->update( $wpdb->links, compact( 'link_name', 'link_description' ), array( 'link_id' => $link->link_id ) );
1023          }
1024      }
1025  
1026      $active_plugins = __get_option( 'active_plugins' );
1027  
1028      /*
1029       * If plugins are not stored in an array, they're stored in the old
1030       * newline separated format. Convert to new format.
1031       */
1032      if ( ! is_array( $active_plugins ) ) {
1033          $active_plugins = explode( "\n", trim( $active_plugins ) );
1034          update_option( 'active_plugins', $active_plugins );
1035      }
1036  
1037      // Obsolete tables
1038      $wpdb->query( 'DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optionvalues' );
1039      $wpdb->query( 'DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiontypes' );
1040      $wpdb->query( 'DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiongroups' );
1041      $wpdb->query( 'DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiongroup_options' );
1042  
1043      // Update comments table to use comment_type
1044      $wpdb->query( "UPDATE $wpdb->comments SET comment_type='trackback', comment_content = REPLACE(comment_content, '<trackback />', '') WHERE comment_content LIKE '<trackback />%'" );
1045      $wpdb->query( "UPDATE $wpdb->comments SET comment_type='pingback', comment_content = REPLACE(comment_content, '<pingback />', '') WHERE comment_content LIKE '<pingback />%'" );
1046  
1047      // Some versions have multiple duplicate option_name rows with the same values
1048      $options = $wpdb->get_results( "SELECT option_name, COUNT(option_name) AS dupes FROM `$wpdb->options` GROUP BY option_name" );
1049      foreach ( $options as $option ) {
1050          if ( 1 != $option->dupes ) { // Could this be done in the query?
1051              $limit    = $option->dupes - 1;
1052              $dupe_ids = $wpdb->get_col( $wpdb->prepare( "SELECT option_id FROM $wpdb->options WHERE option_name = %s LIMIT %d", $option->option_name, $limit ) );
1053              if ( $dupe_ids ) {
1054                  $dupe_ids = join( $dupe_ids, ',' );
1055                  $wpdb->query( "DELETE FROM $wpdb->options WHERE option_id IN ($dupe_ids)" );
1056              }
1057          }
1058      }
1059  
1060      make_site_theme();
1061  }
1062  
1063  /**
1064   * Execute changes made in WordPress 2.0.
1065   *
1066   * @ignore
1067   * @since 2.0.0
1068   *
1069   * @global wpdb $wpdb WordPress database abstraction object.
1070   * @global int  $wp_current_db_version
1071   */
1072  function upgrade_160() {
1073      global $wpdb, $wp_current_db_version;
1074  
1075      populate_roles_160();
1076  
1077      $users = $wpdb->get_results( "SELECT * FROM $wpdb->users" );
1078      foreach ( $users as $user ) :
1079          if ( ! empty( $user->user_firstname ) ) {
1080              update_user_meta( $user->ID, 'first_name', wp_slash( $user->user_firstname ) );
1081          }
1082          if ( ! empty( $user->user_lastname ) ) {
1083              update_user_meta( $user->ID, 'last_name', wp_slash( $user->user_lastname ) );
1084          }
1085          if ( ! empty( $user->user_nickname ) ) {
1086              update_user_meta( $user->ID, 'nickname', wp_slash( $user->user_nickname ) );
1087          }
1088          if ( ! empty( $user->user_level ) ) {
1089              update_user_meta( $user->ID, $wpdb->prefix . 'user_level', $user->user_level );
1090          }
1091          if ( ! empty( $user->user_icq ) ) {
1092              update_user_meta( $user->ID, 'icq', wp_slash( $user->user_icq ) );
1093          }
1094          if ( ! empty( $user->user_aim ) ) {
1095              update_user_meta( $user->ID, 'aim', wp_slash( $user->user_aim ) );
1096          }
1097          if ( ! empty( $user->user_msn ) ) {
1098              update_user_meta( $user->ID, 'msn', wp_slash( $user->user_msn ) );
1099          }
1100          if ( ! empty( $user->user_yim ) ) {
1101              update_user_meta( $user->ID, 'yim', wp_slash( $user->user_icq ) );
1102          }
1103          if ( ! empty( $user->user_description ) ) {
1104              update_user_meta( $user->ID, 'description', wp_slash( $user->user_description ) );
1105          }
1106  
1107          if ( isset( $user->user_idmode ) ) :
1108              $idmode = $user->user_idmode;
1109              if ( $idmode == 'nickname' ) {
1110                  $id = $user->user_nickname;
1111              }
1112              if ( $idmode == 'login' ) {
1113                  $id = $user->user_login;
1114              }
1115              if ( $idmode == 'firstname' ) {
1116                  $id = $user->user_firstname;
1117              }
1118              if ( $idmode == 'lastname' ) {
1119                  $id = $user->user_lastname;
1120              }
1121              if ( $idmode == 'namefl' ) {
1122                  $id = $user->user_firstname . ' ' . $user->user_lastname;
1123              }
1124              if ( $idmode == 'namelf' ) {
1125                  $id = $user->user_lastname . ' ' . $user->user_firstname;
1126              }
1127              if ( ! $idmode ) {
1128                  $id = $user->user_nickname;
1129              }
1130              $wpdb->update( $wpdb->users, array( 'display_name' => $id ), array( 'ID' => $user->ID ) );
1131          endif;
1132  
1133          // FIXME: RESET_CAPS is temporary code to reset roles and caps if flag is set.
1134          $caps = get_user_meta( $user->ID, $wpdb->prefix . 'capabilities' );
1135          if ( empty( $caps ) || defined( 'RESET_CAPS' ) ) {
1136              $level = get_user_meta( $user->ID, $wpdb->prefix . 'user_level', true );
1137              $role  = translate_level_to_role( $level );
1138              update_user_meta( $user->ID, $wpdb->prefix . 'capabilities', array( $role => true ) );
1139          }
1140  
1141      endforeach;
1142      $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' );
1143      $wpdb->hide_errors();
1144      foreach ( $old_user_fields as $old ) {
1145          $wpdb->query( "ALTER TABLE $wpdb->users DROP $old" );
1146      }
1147      $wpdb->show_errors();
1148  
1149      // Populate comment_count field of posts table.
1150      $comments = $wpdb->get_results( "SELECT comment_post_ID, COUNT(*) as c FROM $wpdb->comments WHERE comment_approved = '1' GROUP BY comment_post_ID" );
1151      if ( is_array( $comments ) ) {
1152          foreach ( $comments as $comment ) {
1153              $wpdb->update( $wpdb->posts, array( 'comment_count' => $comment->c ), array( 'ID' => $comment->comment_post_ID ) );
1154          }
1155      }
1156  
1157      /*
1158       * Some alpha versions used a post status of object instead of attachment
1159       * and put the mime type in post_type instead of post_mime_type.
1160       */
1161      if ( $wp_current_db_version > 2541 && $wp_current_db_version <= 3091 ) {
1162          $objects = $wpdb->get_results( "SELECT ID, post_type FROM $wpdb->posts WHERE post_status = 'object'" );
1163          foreach ( $objects as $object ) {
1164              $wpdb->update(
1165                  $wpdb->posts,
1166                  array(
1167                      'post_status'    => 'attachment',
1168                      'post_mime_type' => $object->post_type,
1169                      'post_type'      => '',
1170                  ),
1171                  array( 'ID' => $object->ID )
1172              );
1173  
1174              $meta = get_post_meta( $object->ID, 'imagedata', true );
1175              if ( ! empty( $meta['file'] ) ) {
1176                  update_attached_file( $object->ID, $meta['file'] );
1177              }
1178          }
1179      }
1180  }
1181  
1182  /**
1183   * Execute changes made in WordPress 2.1.
1184   *
1185   * @ignore
1186   * @since 2.1.0
1187   *
1188   * @global wpdb $wpdb WordPress database abstraction object.
1189   * @global int  $wp_current_db_version
1190   */
1191  function upgrade_210() {
1192      global $wpdb, $wp_current_db_version;
1193  
1194      if ( $wp_current_db_version < 3506 ) {
1195          // Update status and type.
1196          $posts = $wpdb->get_results( "SELECT ID, post_status FROM $wpdb->posts" );
1197  
1198          if ( ! empty( $posts ) ) {
1199              foreach ( $posts as $post ) {
1200                  $status = $post->post_status;
1201                  $type   = 'post';
1202  
1203                  if ( 'static' == $status ) {
1204                      $status = 'publish';
1205                      $type   = 'page';
1206                  } elseif ( 'attachment' == $status ) {
1207                      $status = 'inherit';
1208                      $type   = 'attachment';
1209                  }
1210  
1211                  $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET post_status = %s, post_type = %s WHERE ID = %d", $status, $type, $post->ID ) );
1212              }
1213          }
1214      }
1215  
1216      if ( $wp_current_db_version < 3845 ) {
1217          populate_roles_210();
1218      }
1219  
1220      if ( $wp_current_db_version < 3531 ) {
1221          // Give future posts a post_status of future.
1222          $now = gmdate( 'Y-m-d H:i:59' );
1223          $wpdb->query( "UPDATE $wpdb->posts SET post_status = 'future' WHERE post_status = 'publish' AND post_date_gmt > '$now'" );
1224  
1225          $posts = $wpdb->get_results( "SELECT ID, post_date FROM $wpdb->posts WHERE post_status ='future'" );
1226          if ( ! empty( $posts ) ) {
1227              foreach ( $posts as $post ) {
1228                  wp_schedule_single_event( mysql2date( 'U', $post->post_date, false ), 'publish_future_post', array( $post->ID ) );
1229              }
1230          }
1231      }
1232  }
1233  
1234  /**
1235   * Execute changes made in WordPress 2.3.
1236   *
1237   * @ignore
1238   * @since 2.3.0
1239   *
1240   * @global wpdb $wpdb WordPress database abstraction object.
1241   * @global int  $wp_current_db_version
1242   */
1243  function upgrade_230() {
1244      global $wp_current_db_version, $wpdb;
1245  
1246      if ( $wp_current_db_version < 5200 ) {
1247          populate_roles_230();
1248      }
1249  
1250      // Convert categories to terms.
1251      $tt_ids     = array();
1252      $have_tags  = false;
1253      $categories = $wpdb->get_results( "SELECT * FROM $wpdb->categories ORDER BY cat_ID" );
1254      foreach ( $categories as $category ) {
1255          $term_id     = (int) $category->cat_ID;
1256          $name        = $category->cat_name;
1257          $description = $category->category_description;
1258          $slug        = $category->category_nicename;
1259          $parent      = $category->category_parent;
1260          $term_group  = 0;
1261  
1262          // Associate terms with the same slug in a term group and make slugs unique.
1263          if ( $exists = $wpdb->get_results( $wpdb->prepare( "SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $slug ) ) ) {
1264              $term_group = $exists[0]->term_group;
1265              $id         = $exists[0]->term_id;
1266              $num        = 2;
1267              do {
1268                  $alt_slug = $slug . "-$num";
1269                  $num++;
1270                  $slug_check = $wpdb->get_var( $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug ) );
1271              } while ( $slug_check );
1272  
1273              $slug = $alt_slug;
1274  
1275              if ( empty( $term_group ) ) {
1276                  $term_group = $wpdb->get_var( "SELECT MAX(term_group) FROM $wpdb->terms GROUP BY term_group" ) + 1;
1277                  $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->terms SET term_group = %d WHERE term_id = %d", $term_group, $id ) );
1278              }
1279          }
1280  
1281          $wpdb->query(
1282              $wpdb->prepare(
1283                  "INSERT INTO $wpdb->terms (term_id, name, slug, term_group) VALUES
1284          (%d, %s, %s, %d)",
1285                  $term_id,
1286                  $name,
1287                  $slug,
1288                  $term_group
1289              )
1290          );
1291  
1292          $count = 0;
1293          if ( ! empty( $category->category_count ) ) {
1294              $count    = (int) $category->category_count;
1295              $taxonomy = 'category';
1296              $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 ) );
1297              $tt_ids[ $term_id ][ $taxonomy ] = (int) $wpdb->insert_id;
1298          }
1299  
1300          if ( ! empty( $category->link_count ) ) {
1301              $count    = (int) $category->link_count;
1302              $taxonomy = 'link_category';
1303              $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 ) );
1304              $tt_ids[ $term_id ][ $taxonomy ] = (int) $wpdb->insert_id;
1305          }
1306  
1307          if ( ! empty( $category->tag_count ) ) {
1308              $have_tags = true;
1309              $count     = (int) $category->tag_count;
1310              $taxonomy  = 'post_tag';
1311              $wpdb->insert( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent', 'count' ) );
1312              $tt_ids[ $term_id ][ $taxonomy ] = (int) $wpdb->insert_id;
1313          }
1314  
1315          if ( empty( $count ) ) {
1316              $count    = 0;
1317              $taxonomy = 'category';
1318              $wpdb->insert( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent', 'count' ) );
1319              $tt_ids[ $term_id ][ $taxonomy ] = (int) $wpdb->insert_id;
1320          }
1321      }
1322  
1323      $select = 'post_id, category_id';
1324      if ( $have_tags ) {
1325          $select .= ', rel_type';
1326      }
1327  
1328      $posts = $wpdb->get_results( "SELECT $select FROM $wpdb->post2cat GROUP BY post_id, category_id" );
1329      foreach ( $posts as $post ) {
1330          $post_id  = (int) $post->post_id;
1331          $term_id  = (int) $post->category_id;
1332          $taxonomy = 'category';
1333          if ( ! empty( $post->rel_type ) && 'tag' == $post->rel_type ) {
1334              $taxonomy = 'tag';
1335          }
1336          $tt_id = $tt_ids[ $term_id ][ $taxonomy ];
1337          if ( empty( $tt_id ) ) {
1338              continue;
1339          }
1340  
1341          $wpdb->insert(
1342              $wpdb->term_relationships,
1343              array(
1344                  'object_id'        => $post_id,
1345                  'term_taxonomy_id' => $tt_id,
1346              )
1347          );
1348      }
1349  
1350      // < 3570 we used linkcategories. >= 3570 we used categories and link2cat.
1351      if ( $wp_current_db_version < 3570 ) {
1352          /*
1353           * Create link_category terms for link categories. Create a map of link
1354           * cat IDs to link_category terms.
1355           */
1356          $link_cat_id_map  = array();
1357          $default_link_cat = 0;
1358          $tt_ids           = array();
1359          $link_cats        = $wpdb->get_results( 'SELECT cat_id, cat_name FROM ' . $wpdb->prefix . 'linkcategories' );
1360          foreach ( $link_cats as $category ) {
1361              $cat_id     = (int) $category->cat_id;
1362              $term_id    = 0;
1363              $name       = wp_slash( $category->cat_name );
1364              $slug       = sanitize_title( $name );
1365              $term_group = 0;
1366  
1367              // Associate terms with the same slug in a term group and make slugs unique.
1368              if ( $exists = $wpdb->get_results( $wpdb->prepare( "SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $slug ) ) ) {
1369                  $term_group = $exists[0]->term_group;
1370                  $term_id    = $exists[0]->term_id;
1371              }
1372  
1373              if ( empty( $term_id ) ) {
1374                  $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) );
1375                  $term_id = (int) $wpdb->insert_id;
1376              }
1377  
1378              $link_cat_id_map[ $cat_id ] = $term_id;
1379              $default_link_cat           = $term_id;
1380  
1381              $wpdb->insert(
1382                  $wpdb->term_taxonomy,
1383                  array(
1384                      'term_id'     => $term_id,
1385                      'taxonomy'    => 'link_category',
1386                      'description' => '',
1387                      'parent'      => 0,
1388                      'count'       => 0,
1389                  )
1390              );
1391              $tt_ids[ $term_id ] = (int) $wpdb->insert_id;
1392          }
1393  
1394          // Associate links to cats.
1395          $links = $wpdb->get_results( "SELECT link_id, link_category FROM $wpdb->links" );
1396          if ( ! empty( $links ) ) {
1397              foreach ( $links as $link ) {
1398                  if ( 0 == $link->link_category ) {
1399                      continue;
1400                  }
1401                  if ( ! isset( $link_cat_id_map[ $link->link_category ] ) ) {
1402                      continue;
1403                  }
1404                  $term_id = $link_cat_id_map[ $link->link_category ];
1405                  $tt_id   = $tt_ids[ $term_id ];
1406                  if ( empty( $tt_id ) ) {
1407                      continue;
1408                  }
1409  
1410                  $wpdb->insert(
1411                      $wpdb->term_relationships,
1412                      array(
1413                          'object_id'        => $link->link_id,
1414                          'term_taxonomy_id' => $tt_id,
1415                      )
1416                  );
1417              }
1418          }
1419  
1420          // Set default to the last category we grabbed during the upgrade loop.
1421          update_option( 'default_link_category', $default_link_cat );
1422      } else {
1423          $links = $wpdb->get_results( "SELECT link_id, category_id FROM $wpdb->link2cat GROUP BY link_id, category_id" );
1424          foreach ( $links as $link ) {
1425              $link_id  = (int) $link->link_id;
1426              $term_id  = (int) $link->category_id;
1427              $taxonomy = 'link_category';
1428              $tt_id    = $tt_ids[ $term_id ][ $taxonomy ];
1429              if ( empty( $tt_id ) ) {
1430                  continue;
1431              }
1432              $wpdb->insert(
1433                  $wpdb->term_relationships,
1434                  array(
1435                      'object_id'        => $link_id,
1436                      'term_taxonomy_id' => $tt_id,
1437                  )
1438              );
1439          }
1440      }
1441  
1442      if ( $wp_current_db_version < 4772 ) {
1443          // Obsolete linkcategories table
1444          $wpdb->query( 'DROP TABLE IF EXISTS ' . $wpdb->prefix . 'linkcategories' );
1445      }
1446  
1447      // Recalculate all counts
1448      $terms = $wpdb->get_results( "SELECT term_taxonomy_id, taxonomy FROM $wpdb->term_taxonomy" );
1449      foreach ( (array) $terms as $term ) {
1450          if ( ( 'post_tag' == $term->taxonomy ) || ( 'category' == $term->taxonomy ) ) {
1451              $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 ) );
1452          } else {
1453              $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term->term_taxonomy_id ) );
1454          }
1455          $wpdb->update( $wpdb->term_taxonomy, array( 'count' => $count ), array( 'term_taxonomy_id' => $term->term_taxonomy_id ) );
1456      }
1457  }
1458  
1459  /**
1460   * Remove old options from the database.
1461   *
1462   * @ignore
1463   * @since 2.3.0
1464   *
1465   * @global wpdb $wpdb WordPress database abstraction object.
1466   */
1467  function upgrade_230_options_table() {
1468      global $wpdb;
1469      $old_options_fields = array( 'option_can_override', 'option_type', 'option_width', 'option_height', 'option_description', 'option_admin_level' );
1470      $wpdb->hide_errors();
1471      foreach ( $old_options_fields as $old ) {
1472          $wpdb->query( "ALTER TABLE $wpdb->options DROP $old" );
1473      }
1474      $wpdb->show_errors();
1475  }
1476  
1477  /**
1478   * Remove old categories, link2cat, and post2cat database tables.
1479   *
1480   * @ignore
1481   * @since 2.3.0
1482   *
1483   * @global wpdb $wpdb WordPress database abstraction object.
1484   */
1485  function upgrade_230_old_tables() {
1486      global $wpdb;
1487      $wpdb->query( 'DROP TABLE IF EXISTS ' . $wpdb->prefix . 'categories' );
1488      $wpdb->query( 'DROP TABLE IF EXISTS ' . $wpdb->prefix . 'link2cat' );
1489      $wpdb->query( 'DROP TABLE IF EXISTS ' . $wpdb->prefix . 'post2cat' );
1490  }
1491  
1492  /**
1493   * Upgrade old slugs made in version 2.2.
1494   *
1495   * @ignore
1496   * @since 2.2.0
1497   *
1498   * @global wpdb $wpdb WordPress database abstraction object.
1499   */
1500  function upgrade_old_slugs() {
1501      // Upgrade people who were using the Redirect Old Slugs plugin.
1502      global $wpdb;
1503      $wpdb->query( "UPDATE $wpdb->postmeta SET meta_key = '_wp_old_slug' WHERE meta_key = 'old_slug'" );
1504  }
1505  
1506  /**
1507   * Execute changes made in WordPress 2.5.0.
1508   *
1509   * @ignore
1510   * @since 2.5.0
1511   *
1512   * @global int $wp_current_db_version
1513   */
1514  function upgrade_250() {
1515      global $wp_current_db_version;
1516  
1517      if ( $wp_current_db_version < 6689 ) {
1518          populate_roles_250();
1519      }
1520  
1521  }
1522  
1523  /**
1524   * Execute changes made in WordPress 2.5.2.
1525   *
1526   * @ignore
1527   * @since 2.5.2
1528   *
1529   * @global wpdb $wpdb WordPress database abstraction object.
1530   */
1531  function upgrade_252() {
1532      global $wpdb;
1533  
1534      $wpdb->query( "UPDATE $wpdb->users SET user_activation_key = ''" );
1535  }
1536  
1537  /**
1538   * Execute changes made in WordPress 2.6.
1539   *
1540   * @ignore
1541   * @since 2.6.0
1542   *
1543   * @global int $wp_current_db_version
1544   */
1545  function upgrade_260() {
1546      global $wp_current_db_version;
1547  
1548      if ( $wp_current_db_version < 8000 ) {
1549          populate_roles_260();
1550      }
1551  }
1552  
1553  /**
1554   * Execute changes made in WordPress 2.7.
1555   *
1556   * @ignore
1557   * @since 2.7.0
1558   *
1559   * @global wpdb $wpdb WordPress database abstraction object.
1560   * @global int  $wp_current_db_version
1561   */
1562  function upgrade_270() {
1563      global $wpdb, $wp_current_db_version;
1564  
1565      if ( $wp_current_db_version < 8980 ) {
1566          populate_roles_270();
1567      }
1568  
1569      // Update post_date for unpublished posts with empty timestamp
1570      if ( $wp_current_db_version < 8921 ) {
1571          $wpdb->query( "UPDATE $wpdb->posts SET post_date = post_modified WHERE post_date = '0000-00-00 00:00:00'" );
1572      }
1573  }
1574  
1575  /**
1576   * Execute changes made in WordPress 2.8.
1577   *
1578   * @ignore
1579   * @since 2.8.0
1580   *
1581   * @global int  $wp_current_db_version
1582   * @global wpdb $wpdb WordPress database abstraction object.
1583   */
1584  function upgrade_280() {
1585      global $wp_current_db_version, $wpdb;
1586  
1587      if ( $wp_current_db_version < 10360 ) {
1588          populate_roles_280();
1589      }
1590      if ( is_multisite() ) {
1591          $start = 0;
1592          while ( $rows = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options ORDER BY option_id LIMIT $start, 20" ) ) {
1593              foreach ( $rows as $row ) {
1594                  $value = $row->option_value;
1595                  if ( ! @unserialize( $value ) ) {
1596                      $value = stripslashes( $value );
1597                  }
1598                  if ( $value !== $row->option_value ) {
1599                      update_option( $row->option_name, $value );
1600                  }
1601              }
1602              $start += 20;
1603          }
1604          clean_blog_cache( get_current_blog_id() );
1605      }
1606  }
1607  
1608  /**
1609   * Execute changes made in WordPress 2.9.
1610   *
1611   * @ignore
1612   * @since 2.9.0
1613   *
1614   * @global int $wp_current_db_version
1615   */
1616  function upgrade_290() {
1617      global $wp_current_db_version;
1618  
1619      if ( $wp_current_db_version < 11958 ) {
1620          // Previously, setting depth to 1 would redundantly disable threading, but now 2 is the minimum depth to avoid confusion
1621          if ( get_option( 'thread_comments_depth' ) == '1' ) {
1622              update_option( 'thread_comments_depth', 2 );
1623              update_option( 'thread_comments', 0 );
1624          }
1625      }
1626  }
1627  
1628  /**
1629   * Execute changes made in WordPress 3.0.
1630   *
1631   * @ignore
1632   * @since 3.0.0
1633   *
1634   * @global int  $wp_current_db_version
1635   * @global wpdb $wpdb WordPress database abstraction object.
1636   */
1637  function upgrade_300() {
1638      global $wp_current_db_version, $wpdb;
1639  
1640      if ( $wp_current_db_version < 15093 ) {
1641          populate_roles_300();
1642      }
1643  
1644      if ( $wp_current_db_version < 14139 && is_multisite() && is_main_site() && ! defined( 'MULTISITE' ) && get_site_option( 'siteurl' ) === false ) {
1645          add_site_option( 'siteurl', '' );
1646      }
1647  
1648      // 3.0 screen options key name changes.
1649      if ( wp_should_upgrade_global_tables() ) {
1650          $sql    = "DELETE FROM $wpdb->usermeta
1651              WHERE meta_key LIKE %s
1652              OR meta_key LIKE %s
1653              OR meta_key LIKE %s
1654              OR meta_key LIKE %s
1655              OR meta_key LIKE %s
1656              OR meta_key LIKE %s
1657              OR meta_key = 'manageedittagscolumnshidden'
1658              OR meta_key = 'managecategoriescolumnshidden'
1659              OR meta_key = 'manageedit-tagscolumnshidden'
1660              OR meta_key = 'manageeditcolumnshidden'
1661              OR meta_key = 'categories_per_page'
1662              OR meta_key = 'edit_tags_per_page'";
1663          $prefix = $wpdb->esc_like( $wpdb->base_prefix );
1664          $wpdb->query(
1665              $wpdb->prepare(
1666                  $sql,
1667                  $prefix . '%' . $wpdb->esc_like( 'meta-box-hidden' ) . '%',
1668                  $prefix . '%' . $wpdb->esc_like( 'closedpostboxes' ) . '%',
1669                  $prefix . '%' . $wpdb->esc_like( 'manage-' ) . '%' . $wpdb->esc_like( '-columns-hidden' ) . '%',
1670                  $prefix . '%' . $wpdb->esc_like( 'meta-box-order' ) . '%',
1671                  $prefix . '%' . $wpdb->esc_like( 'metaboxorder' ) . '%',
1672                  $prefix . '%' . $wpdb->esc_like( 'screen_layout' ) . '%'
1673              )
1674          );
1675      }
1676  
1677  }
1678  
1679  /**
1680   * Execute changes made in WordPress 3.3.
1681   *
1682   * @ignore
1683   * @since 3.3.0
1684   *
1685   * @global int   $wp_current_db_version
1686   * @global wpdb  $wpdb
1687   * @global array $wp_registered_widgets
1688   * @global array $sidebars_widgets
1689   */
1690  function upgrade_330() {
1691      global $wp_current_db_version, $wpdb, $wp_registered_widgets, $sidebars_widgets;
1692  
1693      if ( $wp_current_db_version < 19061 && wp_should_upgrade_global_tables() ) {
1694          $wpdb->query( "DELETE FROM $wpdb->usermeta WHERE meta_key IN ('show_admin_bar_admin', 'plugins_last_view')" );
1695      }
1696  
1697      if ( $wp_current_db_version >= 11548 ) {
1698          return;
1699      }
1700  
1701      $sidebars_widgets  = get_option( 'sidebars_widgets', array() );
1702      $_sidebars_widgets = array();
1703  
1704      if ( isset( $sidebars_widgets['wp_inactive_widgets'] ) || empty( $sidebars_widgets ) ) {
1705          $sidebars_widgets['array_version'] = 3;
1706      } elseif ( ! isset( $sidebars_widgets['array_version'] ) ) {
1707          $sidebars_widgets['array_version'] = 1;
1708      }
1709  
1710      switch ( $sidebars_widgets['array_version'] ) {
1711          case 1:
1712              foreach ( (array) $sidebars_widgets as $index => $sidebar ) {
1713                  if ( is_array( $sidebar ) ) {
1714                      foreach ( (array) $sidebar as $i => $name ) {
1715                          $id = strtolower( $name );
1716                          if ( isset( $wp_registered_widgets[ $id ] ) ) {
1717                              $_sidebars_widgets[ $index ][ $i ] = $id;
1718                              continue;
1719                          }
1720                          $id = sanitize_title( $name );
1721                          if ( isset( $wp_registered_widgets[ $id ] ) ) {
1722                              $_sidebars_widgets[ $index ][ $i ] = $id;
1723                              continue;
1724                          }
1725  
1726                          $found = false;
1727  
1728                          foreach ( $wp_registered_widgets as $widget_id => $widget ) {
1729                              if ( strtolower( $widget['name'] ) == strtolower( $name ) ) {
1730                                  $_sidebars_widgets[ $index ][ $i ] = $widget['id'];
1731                                  $found                             = true;
1732                                  break;
1733                              } elseif ( sanitize_title( $widget['name'] ) == sanitize_title( $name ) ) {
1734                                  $_sidebars_widgets[ $index ][ $i ] = $widget['id'];
1735                                  $found                             = true;
1736                                  break;
1737                              }
1738                          }
1739  
1740                          if ( $found ) {
1741                              continue;
1742                          }
1743  
1744                          unset( $_sidebars_widgets[ $index ][ $i ] );
1745                      }
1746                  }
1747              }
1748              $_sidebars_widgets['array_version'] = 2;
1749              $sidebars_widgets                   = $_sidebars_widgets;
1750              unset( $_sidebars_widgets );
1751  
1752              // intentional fall-through to upgrade to the next version.
1753          case 2:
1754              $sidebars_widgets                  = retrieve_widgets();
1755              $sidebars_widgets['array_version'] = 3;
1756              update_option( 'sidebars_widgets', $sidebars_widgets );
1757      }
1758  }
1759  
1760  /**
1761   * Execute changes made in WordPress 3.4.
1762   *
1763   * @ignore
1764   * @since 3.4.0
1765   *
1766   * @global int   $wp_current_db_version
1767   * @global wpdb  $wpdb
1768   */
1769  function upgrade_340() {
1770      global $wp_current_db_version, $wpdb;
1771  
1772      if ( $wp_current_db_version < 19798 ) {
1773          $wpdb->hide_errors();
1774          $wpdb->query( "ALTER TABLE $wpdb->options DROP COLUMN blog_id" );
1775          $wpdb->show_errors();
1776      }
1777  
1778      if ( $wp_current_db_version < 19799 ) {
1779          $wpdb->hide_errors();
1780          $wpdb->query( "ALTER TABLE $wpdb->comments DROP INDEX comment_approved" );
1781          $wpdb->show_errors();
1782      }
1783  
1784      if ( $wp_current_db_version < 20022 && wp_should_upgrade_global_tables() ) {
1785          $wpdb->query( "DELETE FROM $wpdb->usermeta WHERE meta_key = 'themes_last_view'" );
1786      }
1787  
1788      if ( $wp_current_db_version < 20080 ) {
1789          if ( 'yes' == $wpdb->get_var( "SELECT autoload FROM $wpdb->options WHERE option_name = 'uninstall_plugins'" ) ) {
1790              $uninstall_plugins = get_option( 'uninstall_plugins' );
1791              delete_option( 'uninstall_plugins' );
1792              add_option( 'uninstall_plugins', $uninstall_plugins, null, 'no' );
1793          }
1794      }
1795  }
1796  
1797  /**
1798   * Execute changes made in WordPress 3.5.
1799   *
1800   * @ignore
1801   * @since 3.5.0
1802   *
1803   * @global int   $wp_current_db_version
1804   * @global wpdb  $wpdb
1805   */
1806  function upgrade_350() {
1807      global $wp_current_db_version, $wpdb;
1808  
1809      if ( $wp_current_db_version < 22006 && $wpdb->get_var( "SELECT link_id FROM $wpdb->links LIMIT 1" ) ) {
1810          update_option( 'link_manager_enabled', 1 ); // Previously set to 0 by populate_options()
1811      }
1812  
1813      if ( $wp_current_db_version < 21811 && wp_should_upgrade_global_tables() ) {
1814          $meta_keys = array();
1815          foreach ( array_merge( get_post_types(), get_taxonomies() ) as $name ) {
1816              if ( false !== strpos( $name, '-' ) ) {
1817                  $meta_keys[] = 'edit_' . str_replace( '-', '_', $name ) . '_per_page';
1818              }
1819          }
1820          if ( $meta_keys ) {
1821              $meta_keys = implode( "', '", $meta_keys );
1822              $wpdb->query( "DELETE FROM $wpdb->usermeta WHERE meta_key IN ('$meta_keys')" );
1823          }
1824      }
1825  
1826      if ( $wp_current_db_version < 22422 && $term = get_term_by( 'slug', 'post-format-standard', 'post_format' ) ) {
1827          wp_delete_term( $term->term_id, 'post_format' );
1828      }
1829  }
1830  
1831  /**
1832   * Execute changes made in WordPress 3.7.
1833   *
1834   * @ignore
1835   * @since 3.7.0
1836   *
1837   * @global int $wp_current_db_version
1838   */
1839  function upgrade_370() {
1840      global $wp_current_db_version;
1841      if ( $wp_current_db_version < 25824 ) {
1842          wp_clear_scheduled_hook( 'wp_auto_updates_maybe_update' );
1843      }
1844  }
1845  
1846  /**
1847   * Execute changes made in WordPress 3.7.2.
1848   *
1849   * @ignore
1850   * @since 3.7.2
1851   * @since 3.8.0
1852   *
1853   * @global int $wp_current_db_version
1854   */
1855  function upgrade_372() {
1856      global $wp_current_db_version;
1857      if ( $wp_current_db_version < 26148 ) {
1858          wp_clear_scheduled_hook( 'wp_maybe_auto_update' );
1859      }
1860  }
1861  
1862  /**
1863   * Execute changes made in WordPress 3.8.0.
1864   *
1865   * @ignore
1866   * @since 3.8.0
1867   *
1868   * @global int $wp_current_db_version
1869   */
1870  function upgrade_380() {
1871      global $wp_current_db_version;
1872      if ( $wp_current_db_version < 26691 ) {
1873          deactivate_plugins( array( 'mp6/mp6.php' ), true );
1874      }
1875  }
1876  
1877  /**
1878   * Execute changes made in WordPress 4.0.0.
1879   *
1880   * @ignore
1881   * @since 4.0.0
1882   *
1883   * @global int $wp_current_db_version
1884   */
1885  function upgrade_400() {
1886      global $wp_current_db_version;
1887      if ( $wp_current_db_version < 29630 ) {
1888          if ( ! is_multisite() && false === get_option( 'WPLANG' ) ) {
1889              if ( defined( 'WPLANG' ) && ( '' !== WPLANG ) && in_array( WPLANG, get_available_languages() ) ) {
1890                  update_option( 'WPLANG', WPLANG );
1891              } else {
1892                  update_option( 'WPLANG', '' );
1893              }
1894          }
1895      }
1896  }
1897  
1898  /**
1899   * Execute changes made in WordPress 4.2.0.
1900   *
1901   * @ignore
1902   * @since 4.2.0
1903   *
1904   * @global int   $wp_current_db_version
1905   * @global wpdb  $wpdb
1906   */
1907  function upgrade_420() {}
1908  
1909  /**
1910   * Executes changes made in WordPress 4.3.0.
1911   *
1912   * @ignore
1913   * @since 4.3.0
1914   *
1915   * @global int  $wp_current_db_version Current version.
1916   * @global wpdb $wpdb                  WordPress database abstraction object.
1917   */
1918  function upgrade_430() {
1919      global $wp_current_db_version, $wpdb;
1920  
1921      if ( $wp_current_db_version < 32364 ) {
1922          upgrade_430_fix_comments();
1923      }
1924  
1925      // Shared terms are split in a separate process.
1926      if ( $wp_current_db_version < 32814 ) {
1927          update_option( 'finished_splitting_shared_terms', 0 );
1928          wp_schedule_single_event( time() + ( 1 * MINUTE_IN_SECONDS ), 'wp_split_shared_term_batch' );
1929      }
1930  
1931      if ( $wp_current_db_version < 33055 && 'utf8mb4' === $wpdb->charset ) {
1932          if ( is_multisite() ) {
1933              $tables = $wpdb->tables( 'blog' );
1934          } else {
1935              $tables = $wpdb->tables( 'all' );
1936              if ( ! wp_should_upgrade_global_tables() ) {
1937                  $global_tables = $wpdb->tables( 'global' );
1938                  $tables        = array_diff_assoc( $tables, $global_tables );
1939              }
1940          }
1941  
1942          foreach ( $tables as $table ) {
1943              maybe_convert_table_to_utf8mb4( $table );
1944          }
1945      }
1946  }
1947  
1948  /**
1949   * Executes comments changes made in WordPress 4.3.0.
1950   *
1951   * @ignore
1952   * @since 4.3.0
1953   *
1954   * @global int  $wp_current_db_version Current version.
1955   * @global wpdb $wpdb                  WordPress database abstraction object.
1956   */
1957  function upgrade_430_fix_comments() {
1958      global $wp_current_db_version, $wpdb;
1959  
1960      $content_length = $wpdb->get_col_length( $wpdb->comments, 'comment_content' );
1961  
1962      if ( is_wp_error( $content_length ) ) {
1963          return;
1964      }
1965  
1966      if ( false === $content_length ) {
1967          $content_length = array(
1968              'type'   => 'byte',
1969              'length' => 65535,
1970          );
1971      } elseif ( ! is_array( $content_length ) ) {
1972          $length         = (int) $content_length > 0 ? (int) $content_length : 65535;
1973          $content_length = array(
1974              'type'   => 'byte',
1975              'length' => $length,
1976          );
1977      }
1978  
1979      if ( 'byte' !== $content_length['type'] || 0 === $content_length['length'] ) {
1980          // Sites with malformed DB schemas are on their own.
1981          return;
1982      }
1983  
1984      $allowed_length = intval( $content_length['length'] ) - 10;
1985  
1986      $comments = $wpdb->get_results(
1987          "SELECT `comment_ID` FROM `{$wpdb->comments}`
1988              WHERE `comment_date_gmt` > '2015-04-26'
1989              AND LENGTH( `comment_content` ) >= {$allowed_length}
1990              AND ( `comment_content` LIKE '%<%' OR `comment_content` LIKE '%>%' )"
1991      );
1992  
1993      foreach ( $comments as $comment ) {
1994          wp_delete_comment( $comment->comment_ID, true );
1995      }
1996  }
1997  
1998  /**
1999   * Executes changes made in WordPress 4.3.1.
2000   *
2001   * @ignore
2002   * @since 4.3.1
2003   */
2004  function upgrade_431() {
2005      // Fix incorrect cron entries for term splitting
2006      $cron_array = _get_cron_array();
2007      if ( isset( $cron_array['wp_batch_split_terms'] ) ) {
2008          unset( $cron_array['wp_batch_split_terms'] );
2009          _set_cron_array( $cron_array );
2010      }
2011  }
2012  
2013  /**
2014   * Executes changes made in WordPress 4.4.0.
2015   *
2016   * @ignore
2017   * @since 4.4.0
2018   *
2019   * @global int  $wp_current_db_version Current version.
2020   * @global wpdb $wpdb                  WordPress database abstraction object.
2021   */
2022  function upgrade_440() {
2023      global $wp_current_db_version, $wpdb;
2024  
2025      if ( $wp_current_db_version < 34030 ) {
2026          $wpdb->query( "ALTER TABLE {$wpdb->options} MODIFY option_name VARCHAR(191)" );
2027      }
2028  
2029      // Remove the unused 'add_users' role.
2030      $roles = wp_roles();
2031      foreach ( $roles->role_objects as $role ) {
2032          if ( $role->has_cap( 'add_users' ) ) {
2033              $role->remove_cap( 'add_users' );
2034          }
2035      }
2036  }
2037  
2038  /**
2039   * Executes changes made in WordPress 4.5.0.
2040   *
2041   * @ignore
2042   * @since 4.5.0
2043   *
2044   * @global int  $wp_current_db_version Current database version.
2045   * @global wpdb $wpdb                  WordPress database abstraction object.
2046   */
2047  function upgrade_450() {
2048      global $wp_current_db_version, $wpdb;
2049  
2050      if ( $wp_current_db_version < 36180 ) {
2051          wp_clear_scheduled_hook( 'wp_maybe_auto_update' );
2052      }
2053  
2054      // Remove unused email confirmation options, moved to usermeta.
2055      if ( $wp_current_db_version < 36679 && is_multisite() ) {
2056          $wpdb->query( "DELETE FROM $wpdb->options WHERE option_name REGEXP '^[0-9]+_new_email$'" );
2057      }
2058  
2059      // Remove unused user setting for wpLink.
2060      delete_user_setting( 'wplink' );
2061  }
2062  
2063  /**
2064   * Executes changes made in WordPress 4.6.0.
2065   *
2066   * @ignore
2067   * @since 4.6.0
2068   *
2069   * @global int $wp_current_db_version Current database version.
2070   */
2071  function upgrade_460() {
2072      global $wp_current_db_version;
2073  
2074      // Remove unused post meta.
2075      if ( $wp_current_db_version < 37854 ) {
2076          delete_post_meta_by_key( '_post_restored_from' );
2077      }
2078  
2079      // Remove plugins with callback as an array object/method as the uninstall hook, see #13786.
2080      if ( $wp_current_db_version < 37965 ) {
2081          $uninstall_plugins = get_option( 'uninstall_plugins', array() );
2082  
2083          if ( ! empty( $uninstall_plugins ) ) {
2084              foreach ( $uninstall_plugins as $basename => $callback ) {
2085                  if ( is_array( $callback ) && is_object( $callback[0] ) ) {
2086                      unset( $uninstall_plugins[ $basename ] );
2087                  }
2088              }
2089  
2090              update_option( 'uninstall_plugins', $uninstall_plugins );
2091          }
2092      }
2093  }
2094  
2095  /**
2096   * Executes changes made in WordPress 5.0.0.
2097   *
2098   * @ignore
2099   * @since 5.0.0
2100   * @deprecated 5.1.0
2101   */
2102  function upgrade_500() {
2103  }
2104  
2105  /**
2106   * Executes changes made in WordPress 5.1.0.
2107   *
2108   * @ignore
2109   * @since 5.1.0
2110   */
2111  function upgrade_510() {
2112      delete_site_option( 'upgrade_500_was_gutenberg_active' );
2113  }
2114  
2115  /**
2116   * Executes network-level upgrade routines.
2117   *
2118   * @since 3.0.0
2119   *
2120   * @global int   $wp_current_db_version
2121   * @global wpdb  $wpdb
2122   */
2123  function upgrade_network() {
2124      global $wp_current_db_version, $wpdb;
2125  
2126      // Always clear expired transients
2127      delete_expired_transients( true );
2128  
2129      // 2.8.
2130      if ( $wp_current_db_version < 11549 ) {
2131          $wpmu_sitewide_plugins   = get_site_option( 'wpmu_sitewide_plugins' );
2132          $active_sitewide_plugins = get_site_option( 'active_sitewide_plugins' );
2133          if ( $wpmu_sitewide_plugins ) {
2134              if ( ! $active_sitewide_plugins ) {
2135                  $sitewide_plugins = (array) $wpmu_sitewide_plugins;
2136              } else {
2137                  $sitewide_plugins = array_merge( (array) $active_sitewide_plugins, (array) $wpmu_sitewide_plugins );
2138              }
2139  
2140              update_site_option( 'active_sitewide_plugins', $sitewide_plugins );
2141          }
2142          delete_site_option( 'wpmu_sitewide_plugins' );
2143          delete_site_option( 'deactivated_sitewide_plugins' );
2144  
2145          $start = 0;
2146          while ( $rows = $wpdb->get_results( "SELECT meta_key, meta_value FROM {$wpdb->sitemeta} ORDER BY meta_id LIMIT $start, 20" ) ) {
2147              foreach ( $rows as $row ) {
2148                  $value = $row->meta_value;
2149                  if ( ! @unserialize( $value ) ) {
2150                      $value = stripslashes( $value );
2151                  }
2152                  if ( $value !== $row->meta_value ) {
2153                      update_site_option( $row->meta_key, $value );
2154                  }
2155              }
2156              $start += 20;
2157          }
2158      }
2159  
2160      // 3.0
2161      if ( $wp_current_db_version < 13576 ) {
2162          update_site_option( 'global_terms_enabled', '1' );
2163      }
2164  
2165      // 3.3
2166      if ( $wp_current_db_version < 19390 ) {
2167          update_site_option( 'initial_db_version', $wp_current_db_version );
2168      }
2169  
2170      if ( $wp_current_db_version < 19470 ) {
2171          if ( false === get_site_option( 'active_sitewide_plugins' ) ) {
2172              update_site_option( 'active_sitewide_plugins', array() );
2173          }
2174      }
2175  
2176      // 3.4
2177      if ( $wp_current_db_version < 20148 ) {
2178          // 'allowedthemes' keys things by stylesheet. 'allowed_themes' keyed things by name.
2179          $allowedthemes  = get_site_option( 'allowedthemes' );
2180          $allowed_themes = get_site_option( 'allowed_themes' );
2181          if ( false === $allowedthemes && is_array( $allowed_themes ) && $allowed_themes ) {
2182              $converted = array();
2183              $themes    = wp_get_themes();
2184              foreach ( $themes as $stylesheet => $theme_data ) {
2185                  if ( isset( $allowed_themes[ $theme_data->get( 'Name' ) ] ) ) {
2186                      $converted[ $stylesheet ] = true;
2187                  }
2188              }
2189              update_site_option( 'allowedthemes', $converted );
2190              delete_site_option( 'allowed_themes' );
2191          }
2192      }
2193  
2194      // 3.5
2195      if ( $wp_current_db_version < 21823 ) {
2196          update_site_option( 'ms_files_rewriting', '1' );
2197      }
2198  
2199      // 3.5.2
2200      if ( $wp_current_db_version < 24448 ) {
2201          $illegal_names = get_site_option( 'illegal_names' );
2202          if ( is_array( $illegal_names ) && count( $illegal_names ) === 1 ) {
2203              $illegal_name  = reset( $illegal_names );
2204              $illegal_names = explode( ' ', $illegal_name );
2205              update_site_option( 'illegal_names', $illegal_names );
2206          }
2207      }
2208  
2209      // 4.2
2210      if ( $wp_current_db_version < 31351 && $wpdb->charset === 'utf8mb4' ) {
2211          if ( wp_should_upgrade_global_tables() ) {
2212              $wpdb->query( "ALTER TABLE $wpdb->usermeta DROP INDEX meta_key, ADD INDEX meta_key(meta_key(191))" );
2213              $wpdb->query( "ALTER TABLE $wpdb->site DROP INDEX domain, ADD INDEX domain(domain(140),path(51))" );
2214              $wpdb->query( "ALTER TABLE $wpdb->sitemeta DROP INDEX meta_key, ADD INDEX meta_key(meta_key(191))" );
2215              $wpdb->query( "ALTER TABLE $wpdb->signups DROP INDEX domain_path, ADD INDEX domain_path(domain(140),path(51))" );
2216  
2217              $tables = $wpdb->tables( 'global' );
2218  
2219              // sitecategories may not exist.
2220              if ( ! $wpdb->get_var( "SHOW TABLES LIKE '{$tables['sitecategories']}'" ) ) {
2221                  unset( $tables['sitecategories'] );
2222              }
2223  
2224              foreach ( $tables as $table ) {
2225                  maybe_convert_table_to_utf8mb4( $table );
2226              }
2227          }
2228      }
2229  
2230      // 4.3
2231      if ( $wp_current_db_version < 33055 && 'utf8mb4' === $wpdb->charset ) {
2232          if ( wp_should_upgrade_global_tables() ) {
2233              $upgrade = false;
2234              $indexes = $wpdb->get_results( "SHOW INDEXES FROM $wpdb->signups" );
2235              foreach ( $indexes as $index ) {
2236                  if ( 'domain_path' == $index->Key_name && 'domain' == $index->Column_name && 140 != $index->Sub_part ) {
2237                      $upgrade = true;
2238                      break;
2239                  }
2240              }
2241  
2242              if ( $upgrade ) {
2243                  $wpdb->query( "ALTER TABLE $wpdb->signups DROP INDEX domain_path, ADD INDEX domain_path(domain(140),path(51))" );
2244              }
2245  
2246              $tables = $wpdb->tables( 'global' );
2247  
2248              // sitecategories may not exist.
2249              if ( ! $wpdb->get_var( "SHOW TABLES LIKE '{$tables['sitecategories']}'" ) ) {
2250                  unset( $tables['sitecategories'] );
2251              }
2252  
2253              foreach ( $tables as $table ) {
2254                  maybe_convert_table_to_utf8mb4( $table );
2255              }
2256          }
2257      }
2258  
2259      // 5.1
2260      if ( $wp_current_db_version < 44467 ) {
2261          $network_id = get_main_network_id();
2262          delete_network_option( $network_id, 'site_meta_supported' );
2263          is_site_meta_supported();
2264      }
2265  }
2266  
2267  //
2268  // General functions we use to actually do stuff
2269  //
2270  
2271  /**
2272   * Creates a table in the database if it doesn't already exist.
2273   *
2274   * This method checks for an existing database and creates a new one if it's not
2275   * already present. It doesn't rely on MySQL's "IF NOT EXISTS" statement, but chooses
2276   * to query all tables first and then run the SQL statement creating the table.
2277   *
2278   * @since 1.0.0
2279   *
2280   * @global wpdb  $wpdb
2281   *
2282   * @param string $table_name Database table name to create.
2283   * @param string $create_ddl SQL statement to create table.
2284   * @return bool If table already exists or was created by function.
2285   */
2286  function maybe_create_table( $table_name, $create_ddl ) {
2287      global $wpdb;
2288  
2289      $query = $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $table_name ) );
2290  
2291      if ( $wpdb->get_var( $query ) == $table_name ) {
2292          return true;
2293      }
2294  
2295      // Didn't find it try to create it..
2296      $wpdb->query( $create_ddl );
2297  
2298      // We cannot directly tell that whether this succeeded!
2299      if ( $wpdb->get_var( $query ) == $table_name ) {
2300          return true;
2301      }
2302      return false;
2303  }
2304  
2305  /**
2306   * Drops a specified index from a table.
2307   *
2308   * @since 1.0.1
2309   *
2310   * @global wpdb  $wpdb
2311   *
2312   * @param string $table Database table name.
2313   * @param string $index Index name to drop.
2314   * @return true True, when finished.
2315   */
2316  function drop_index( $table, $index ) {
2317      global $wpdb;
2318      $wpdb->hide_errors();
2319      $wpdb->query( "ALTER TABLE `$table` DROP INDEX `$index`" );
2320      // Now we need to take out all the extra ones we may have created
2321      for ( $i = 0; $i < 25; $i++ ) {
2322          $wpdb->query( "ALTER TABLE `$table` DROP INDEX `{$index}_$i`" );
2323      }
2324      $wpdb->show_errors();
2325      return true;
2326  }
2327  
2328  /**
2329   * Adds an index to a specified table.
2330   *
2331   * @since 1.0.1
2332   *
2333   * @global wpdb  $wpdb
2334   *
2335   * @param string $table Database table name.
2336   * @param string $index Database table index column.
2337   * @return true True, when done with execution.
2338   */
2339  function add_clean_index( $table, $index ) {
2340      global $wpdb;
2341      drop_index( $table, $index );
2342      $wpdb->query( "ALTER TABLE `$table` ADD INDEX ( `$index` )" );
2343      return true;
2344  }
2345  
2346  /**
2347   * Adds column to a database table if it doesn't already exist.
2348   *
2349   * @since 1.3.0
2350   *
2351   * @global wpdb  $wpdb
2352   *
2353   * @param string $table_name  The table name to modify.
2354   * @param string $column_name The column name to add to the table.
2355   * @param string $create_ddl  The SQL statement used to add the column.
2356   * @return bool True if already exists or on successful completion, false on error.
2357   */
2358  function maybe_add_column( $table_name, $column_name, $create_ddl ) {
2359      global $wpdb;
2360      foreach ( $wpdb->get_col( "DESC $table_name", 0 ) as $column ) {
2361          if ( $column == $column_name ) {
2362              return true;
2363          }
2364      }
2365  
2366      // Didn't find it try to create it.
2367      $wpdb->query( $create_ddl );
2368  
2369      // We cannot directly tell that whether this succeeded!
2370      foreach ( $wpdb->get_col( "DESC $table_name", 0 ) as $column ) {
2371          if ( $column == $column_name ) {
2372              return true;
2373          }
2374      }
2375      return false;
2376  }
2377  
2378  /**
2379   * If a table only contains utf8 or utf8mb4 columns, convert it to utf8mb4.
2380   *
2381   * @since 4.2.0
2382   *
2383   * @global wpdb  $wpdb
2384   *
2385   * @param string $table The table to convert.
2386   * @return bool true if the table was converted, false if it wasn't.
2387   */
2388  function maybe_convert_table_to_utf8mb4( $table ) {
2389      global $wpdb;
2390  
2391      $results = $wpdb->get_results( "SHOW FULL COLUMNS FROM `$table`" );
2392      if ( ! $results ) {
2393          return false;
2394      }
2395  
2396      foreach ( $results as $column ) {
2397          if ( $column->Collation ) {
2398              list( $charset ) = explode( '_', $column->Collation );
2399              $charset         = strtolower( $charset );
2400              if ( 'utf8' !== $charset && 'utf8mb4' !== $charset ) {
2401                  // Don't upgrade tables that have non-utf8 columns.
2402                  return false;
2403              }
2404          }
2405      }
2406  
2407      $table_details = $wpdb->get_row( "SHOW TABLE STATUS LIKE '$table'" );
2408      if ( ! $table_details ) {
2409          return false;
2410      }
2411  
2412      list( $table_charset ) = explode( '_', $table_details->Collation );
2413      $table_charset         = strtolower( $table_charset );
2414      if ( 'utf8mb4' === $table_charset ) {
2415          return true;
2416      }
2417  
2418      return $wpdb->query( "ALTER TABLE $table CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci" );
2419  }
2420  
2421  /**
2422   * Retrieve all options as it was for 1.2.
2423   *
2424   * @since 1.2.0
2425   *
2426   * @global wpdb  $wpdb
2427   *
2428   * @return stdClass List of options.
2429   */
2430  function get_alloptions_110() {
2431      global $wpdb;
2432      $all_options = new stdClass;
2433      if ( $options = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options" ) ) {
2434          foreach ( $options as $option ) {
2435              if ( 'siteurl' == $option->option_name || 'home' == $option->option_name || 'category_base' == $option->option_name ) {
2436                  $option->option_value = untrailingslashit( $option->option_value );
2437              }
2438              $all_options->{$option->option_name} = stripslashes( $option->option_value );
2439          }
2440      }
2441      return $all_options;
2442  }
2443  
2444  /**
2445   * Utility version of get_option that is private to installation/upgrade.
2446   *
2447   * @ignore
2448   * @since 1.5.1
2449   * @access private
2450   *
2451   * @global wpdb  $wpdb
2452   *
2453   * @param string $setting Option name.
2454   * @return mixed
2455   */
2456  function __get_option( $setting ) {
2457      global $wpdb;
2458  
2459      if ( $setting == 'home' && defined( 'WP_HOME' ) ) {
2460          return untrailingslashit( WP_HOME );
2461      }
2462  
2463      if ( $setting == 'siteurl' && defined( 'WP_SITEURL' ) ) {
2464          return untrailingslashit( WP_SITEURL );
2465      }
2466  
2467      $option = $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM $wpdb->options WHERE option_name = %s", $setting ) );
2468  
2469      if ( 'home' == $setting && '' == $option ) {
2470          return __get_option( 'siteurl' );
2471      }
2472  
2473      if ( 'siteurl' == $setting || 'home' == $setting || 'category_base' == $setting || 'tag_base' == $setting ) {
2474          $option = untrailingslashit( $option );
2475      }
2476  
2477      return maybe_unserialize( $option );
2478  }
2479  
2480  /**
2481   * Filters for content to remove unnecessary slashes.
2482   *
2483   * @since 1.5.0
2484   *
2485   * @param string $content The content to modify.
2486   * @return string The de-slashed content.
2487   */
2488  function deslash( $content ) {
2489      // Note: \\\ inside a regex denotes a single backslash.
2490  
2491      /*
2492       * Replace one or more backslashes followed by a single quote with
2493       * a single quote.
2494       */
2495      $content = preg_replace( "/\\\+'/", "'", $content );
2496  
2497      /*
2498       * Replace one or more backslashes followed by a double quote with
2499       * a double quote.
2500       */
2501      $content = preg_replace( '/\\\+"/', '"', $content );
2502  
2503      // Replace one or more backslashes with one backslash.
2504      $content = preg_replace( '/\\\+/', '\\', $content );
2505  
2506      return $content;
2507  }
2508  
2509  /**
2510   * Modifies the database based on specified SQL statements.
2511   *
2512   * Useful for creating new tables and updating existing tables to a new structure.
2513   *
2514   * @since 1.5.0
2515   *
2516   * @global wpdb  $wpdb
2517   *
2518   * @param string[]|string $queries Optional. The query to run. Can be multiple queries
2519   *                                 in an array, or a string of queries separated by
2520   *                                 semicolons. Default empty string.
2521   * @param bool            $execute Optional. Whether or not to execute the query right away.
2522   *                                 Default true.
2523   * @return array Strings containing the results of the various update queries.
2524   */
2525  function dbDelta( $queries = '', $execute = true ) {
2526      global $wpdb;
2527  
2528      if ( in_array( $queries, array( '', 'all', 'blog', 'global', 'ms_global' ), true ) ) {
2529          $queries = wp_get_db_schema( $queries );
2530      }
2531  
2532      // Separate individual queries into an array
2533      if ( ! is_array( $queries ) ) {
2534          $queries = explode( ';', $queries );
2535          $queries = array_filter( $queries );
2536      }
2537  
2538      /**
2539       * Filters the dbDelta SQL queries.
2540       *
2541       * @since 3.3.0
2542       *
2543       * @param string[] $queries An array of dbDelta SQL queries.
2544       */
2545      $queries = apply_filters( 'dbdelta_queries', $queries );
2546  
2547      $cqueries   = array(); // Creation Queries
2548      $iqueries   = array(); // Insertion Queries
2549      $for_update = array();
2550  
2551      // Create a tablename index for an array ($cqueries) of queries
2552      foreach ( $queries as $qry ) {
2553          if ( preg_match( '|CREATE TABLE ([^ ]*)|', $qry, $matches ) ) {
2554              $cqueries[ trim( $matches[1], '`' ) ] = $qry;
2555              $for_update[ $matches[1] ]            = 'Created table ' . $matches[1];
2556          } elseif ( preg_match( '|CREATE DATABASE ([^ ]*)|', $qry, $matches ) ) {
2557              array_unshift( $cqueries, $qry );
2558          } elseif ( preg_match( '|INSERT INTO ([^ ]*)|', $qry, $matches ) ) {
2559              $iqueries[] = $qry;
2560          } elseif ( preg_match( '|UPDATE ([^ ]*)|', $qry, $matches ) ) {
2561              $iqueries[] = $qry;
2562          } else {
2563              // Unrecognized query type
2564          }
2565      }
2566  
2567      /**
2568       * Filters the dbDelta SQL queries for creating tables and/or databases.
2569       *
2570       * Queries filterable via this hook contain "CREATE TABLE" or "CREATE DATABASE".
2571       *
2572       * @since 3.3.0
2573       *
2574       * @param string[] $cqueries An array of dbDelta create SQL queries.
2575       */
2576      $cqueries = apply_filters( 'dbdelta_create_queries', $cqueries );
2577  
2578      /**
2579       * Filters the dbDelta SQL queries for inserting or updating.
2580       *
2581       * Queries filterable via this hook contain "INSERT INTO" or "UPDATE".
2582       *
2583       * @since 3.3.0
2584       *
2585       * @param string[] $iqueries An array of dbDelta insert or update SQL queries.
2586       */
2587      $iqueries = apply_filters( 'dbdelta_insert_queries', $iqueries );
2588  
2589      $text_fields = array( 'tinytext', 'text', 'mediumtext', 'longtext' );
2590      $blob_fields = array( 'tinyblob', 'blob', 'mediumblob', 'longblob' );
2591  
2592      $global_tables = $wpdb->tables( 'global' );
2593      foreach ( $cqueries as $table => $qry ) {
2594          // Upgrade global tables only for the main site. Don't upgrade at all if conditions are not optimal.
2595          if ( in_array( $table, $global_tables ) && ! wp_should_upgrade_global_tables() ) {
2596              unset( $cqueries[ $table ], $for_update[ $table ] );
2597              continue;
2598          }
2599  
2600          // Fetch the table column structure from the database
2601          $suppress    = $wpdb->suppress_errors();
2602          $tablefields = $wpdb->get_results( "DESCRIBE {$table};" );
2603          $wpdb->suppress_errors( $suppress );
2604  
2605          if ( ! $tablefields ) {
2606              continue;
2607          }
2608  
2609          // Clear the field and index arrays.
2610          $cfields = $indices = $indices_without_subparts = array();
2611  
2612          // Get all of the field names in the query from between the parentheses.
2613          preg_match( '|\((.*)\)|ms', $qry, $match2 );
2614          $qryline = trim( $match2[1] );
2615  
2616          // Separate field lines into an array.
2617          $flds = explode( "\n", $qryline );
2618  
2619          // For every field line specified in the query.
2620          foreach ( $flds as $fld ) {
2621              $fld = trim( $fld, " \t\n\r\0\x0B," ); // Default trim characters, plus ','.
2622  
2623              // Extract the field name.
2624              preg_match( '|^([^ ]*)|', $fld, $fvals );
2625              $fieldname            = trim( $fvals[1], '`' );
2626              $fieldname_lowercased = strtolower( $fieldname );
2627  
2628              // Verify the found field name.
2629              $validfield = true;
2630              switch ( $fieldname_lowercased ) {
2631                  case '':
2632                  case 'primary':
2633                  case 'index':
2634                  case 'fulltext':
2635                  case 'unique':
2636                  case 'key':
2637                  case 'spatial':
2638                      $validfield = false;
2639  
2640                      /*
2641                       * Normalize the index definition.
2642                       *
2643                       * This is done so the definition can be compared against the result of a
2644                       * `SHOW INDEX FROM $table_name` query which returns the current table
2645                       * index information.
2646                       */
2647  
2648                      // Extract type, name and columns from the definition.
2649                      // phpcs:disable Squiz.Strings.ConcatenationSpacing.PaddingFound -- don't remove regex indentation
2650                      preg_match(
2651                          '/^'
2652                          .   '(?P<index_type>'             // 1) Type of the index.
2653                          .       'PRIMARY\s+KEY|(?:UNIQUE|FULLTEXT|SPATIAL)\s+(?:KEY|INDEX)|KEY|INDEX'
2654                          .   ')'
2655                          .   '\s+'                         // Followed by at least one white space character.
2656                          .   '(?:'                         // Name of the index. Optional if type is PRIMARY KEY.
2657                          .       '`?'                      // Name can be escaped with a backtick.
2658                          .           '(?P<index_name>'     // 2) Name of the index.
2659                          .               '(?:[0-9a-zA-Z$_-]|[\xC2-\xDF][\x80-\xBF])+'
2660                          .           ')'
2661                          .       '`?'                      // Name can be escaped with a backtick.
2662                          .       '\s+'                     // Followed by at least one white space character.
2663                          .   ')*'
2664                          .   '\('                          // Opening bracket for the columns.
2665                          .       '(?P<index_columns>'
2666                          .           '.+?'                 // 3) Column names, index prefixes, and orders.
2667                          .       ')'
2668                          .   '\)'                          // Closing bracket for the columns.
2669                          . '$/im',
2670                          $fld,
2671                          $index_matches
2672                      );
2673                      // phpcs:enable
2674  
2675                      // Uppercase the index type and normalize space characters.
2676                      $index_type = strtoupper( preg_replace( '/\s+/', ' ', trim( $index_matches['index_type'] ) ) );
2677  
2678                      // 'INDEX' is a synonym for 'KEY', standardize on 'KEY'.
2679                      $index_type = str_replace( 'INDEX', 'KEY', $index_type );
2680  
2681                      // Escape the index name with backticks. An index for a primary key has no name.
2682                      $index_name = ( 'PRIMARY KEY' === $index_type ) ? '' : '`' . strtolower( $index_matches['index_name'] ) . '`';
2683  
2684                      // Parse the columns. Multiple columns are separated by a comma.
2685                      $index_columns = $index_columns_without_subparts = array_map( 'trim', explode( ',', $index_matches['index_columns'] ) );
2686  
2687                      // Normalize columns.
2688                      foreach ( $index_columns as $id => &$index_column ) {
2689                          // Extract column name and number of indexed characters (sub_part).
2690                          preg_match(
2691                              '/'
2692                              . '`?'                      // Name can be escaped with a backtick.
2693                              . '(?P<column_name>'    // 1) Name of the column.
2694                              . '(?:[0-9a-zA-Z$_-]|[\xC2-\xDF][\x80-\xBF])+'
2695                              . ')'
2696                              . '`?'                      // Name can be escaped with a backtick.
2697                              . '(?:'                     // Optional sub part.
2698                              . '\s*'                 // Optional white space character between name and opening bracket.
2699                              . '\('                  // Opening bracket for the sub part.
2700                              . '\s*'             // Optional white space character after opening bracket.
2701                              . '(?P<sub_part>'
2702                              . '\d+'         // 2) Number of indexed characters.
2703                              . ')'
2704                              . '\s*'             // Optional white space character before closing bracket.
2705                              . '\)'                 // Closing bracket for the sub part.
2706                              . ')?'
2707                              . '/',
2708                              $index_column,
2709                              $index_column_matches
2710                          );
2711  
2712                          // Escape the column name with backticks.
2713                          $index_column = '`' . $index_column_matches['column_name'] . '`';
2714  
2715                          // We don't need to add the subpart to $index_columns_without_subparts
2716                          $index_columns_without_subparts[ $id ] = $index_column;
2717  
2718                          // Append the optional sup part with the number of indexed characters.
2719                          if ( isset( $index_column_matches['sub_part'] ) ) {
2720                              $index_column .= '(' . $index_column_matches['sub_part'] . ')';
2721                          }
2722                      }
2723  
2724                      // Build the normalized index definition and add it to the list of indices.
2725                      $indices[]                  = "{$index_type} {$index_name} (" . implode( ',', $index_columns ) . ')';
2726                      $indices_without_subparts[] = "{$index_type} {$index_name} (" . implode( ',', $index_columns_without_subparts ) . ')';
2727  
2728                      // Destroy no longer needed variables.
2729                      unset( $index_column, $index_column_matches, $index_matches, $index_type, $index_name, $index_columns, $index_columns_without_subparts );
2730  
2731                      break;
2732              }
2733  
2734              // If it's a valid field, add it to the field array.
2735              if ( $validfield ) {
2736                  $cfields[ $fieldname_lowercased ] = $fld;
2737              }
2738          }
2739  
2740          // For every field in the table.
2741          foreach ( $tablefields as $tablefield ) {
2742              $tablefield_field_lowercased = strtolower( $tablefield->Field );
2743              $tablefield_type_lowercased  = strtolower( $tablefield->Type );
2744  
2745              // If the table field exists in the field array ...
2746              if ( array_key_exists( $tablefield_field_lowercased, $cfields ) ) {
2747  
2748                  // Get the field type from the query.
2749                  preg_match( '|`?' . $tablefield->Field . '`? ([^ ]*( unsigned)?)|i', $cfields[ $tablefield_field_lowercased ], $matches );
2750                  $fieldtype            = $matches[1];
2751                  $fieldtype_lowercased = strtolower( $fieldtype );
2752  
2753                  // Is actual field type different from the field type in query?
2754                  if ( $tablefield->Type != $fieldtype ) {
2755                      $do_change = true;
2756                      if ( in_array( $fieldtype_lowercased, $text_fields ) && in_array( $tablefield_type_lowercased, $text_fields ) ) {
2757                          if ( array_search( $fieldtype_lowercased, $text_fields ) < array_search( $tablefield_type_lowercased, $text_fields ) ) {
2758                              $do_change = false;
2759                          }
2760                      }
2761  
2762                      if ( in_array( $fieldtype_lowercased, $blob_fields ) && in_array( $tablefield_type_lowercased, $blob_fields ) ) {
2763                          if ( array_search( $fieldtype_lowercased, $blob_fields ) < array_search( $tablefield_type_lowercased, $blob_fields ) ) {
2764                              $do_change = false;
2765                          }
2766                      }
2767  
2768                      if ( $do_change ) {
2769                          // Add a query to change the column type.
2770                          $cqueries[]                                      = "ALTER TABLE {$table} CHANGE COLUMN `{$tablefield->Field}` " . $cfields[ $tablefield_field_lowercased ];
2771                          $for_update[ $table . '.' . $tablefield->Field ] = "Changed type of {$table}.{$tablefield->Field} from {$tablefield->Type} to {$fieldtype}";
2772                      }
2773                  }
2774  
2775                  // Get the default value from the array.
2776                  if ( preg_match( "| DEFAULT '(.*?)'|i", $cfields[ $tablefield_field_lowercased ], $matches ) ) {
2777                      $default_value = $matches[1];
2778                      if ( $tablefield->Default != $default_value ) {
2779                          // Add a query to change the column's default value
2780                          $cqueries[]                                      = "ALTER TABLE {$table} ALTER COLUMN `{$tablefield->Field}` SET DEFAULT '{$default_value}'";
2781                          $for_update[ $table . '.' . $tablefield->Field ] = "Changed default value of {$table}.{$tablefield->Field} from {$tablefield->Default} to {$default_value}";
2782                      }
2783                  }
2784  
2785                  // Remove the field from the array (so it's not added).
2786                  unset( $cfields[ $tablefield_field_lowercased ] );
2787              } else {
2788                  // This field exists in the table, but not in the creation queries?
2789              }
2790          }
2791  
2792          // For every remaining field specified for the table.
2793          foreach ( $cfields as $fieldname => $fielddef ) {
2794              // Push a query line into $cqueries that adds the field to that table.
2795              $cqueries[]                              = "ALTER TABLE {$table} ADD COLUMN $fielddef";
2796              $for_update[ $table . '.' . $fieldname ] = 'Added column ' . $table . '.' . $fieldname;
2797          }
2798  
2799          // Index stuff goes here. Fetch the table index structure from the database.
2800          $tableindices = $wpdb->get_results( "SHOW INDEX FROM {$table};" );
2801  
2802          if ( $tableindices ) {
2803              // Clear the index array.
2804              $index_ary = array();
2805  
2806              // For every index in the table.
2807              foreach ( $tableindices as $tableindex ) {
2808  
2809                  // Add the index to the index data array.
2810                  $keyname                             = strtolower( $tableindex->Key_name );
2811                  $index_ary[ $keyname ]['columns'][]  = array(
2812                      'fieldname' => $tableindex->Column_name,
2813                      'subpart'   => $tableindex->Sub_part,
2814                  );
2815                  $index_ary[ $keyname ]['unique']     = ( $tableindex->Non_unique == 0 ) ? true : false;
2816                  $index_ary[ $keyname ]['index_type'] = $tableindex->Index_type;
2817              }
2818  
2819              // For each actual index in the index array.
2820              foreach ( $index_ary as $index_name => $index_data ) {
2821  
2822                  // Build a create string to compare to the query.
2823                  $index_string = '';
2824                  if ( $index_name == 'primary' ) {
2825                      $index_string .= 'PRIMARY ';
2826                  } elseif ( $index_data['unique'] ) {
2827                      $index_string .= 'UNIQUE ';
2828                  }
2829                  if ( 'FULLTEXT' === strtoupper( $index_data['index_type'] ) ) {
2830                      $index_string .= 'FULLTEXT ';
2831                  }
2832                  if ( 'SPATIAL' === strtoupper( $index_data['index_type'] ) ) {
2833                      $index_string .= 'SPATIAL ';
2834                  }
2835                  $index_string .= 'KEY ';
2836                  if ( 'primary' !== $index_name ) {
2837                      $index_string .= '`' . $index_name . '`';
2838                  }
2839                  $index_columns = '';
2840  
2841                  // For each column in the index.
2842                  foreach ( $index_data['columns'] as $column_data ) {
2843                      if ( $index_columns != '' ) {
2844                          $index_columns .= ',';
2845                      }
2846  
2847                      // Add the field to the column list string.
2848                      $index_columns .= '`' . $column_data['fieldname'] . '`';
2849                  }
2850  
2851                  // Add the column list to the index create string.
2852                  $index_string .= " ($index_columns)";
2853  
2854                  // Check if the index definition exists, ignoring subparts.
2855                  if ( ! ( ( $aindex = array_search( $index_string, $indices_without_subparts ) ) === false ) ) {
2856                      // If the index already exists (even with different subparts), we don't need to create it.
2857                      unset( $indices_without_subparts[ $aindex ] );
2858                      unset( $indices[ $aindex ] );
2859                  }
2860              }
2861          }
2862  
2863          // For every remaining index specified for the table.
2864          foreach ( (array) $indices as $index ) {
2865              // Push a query line into $cqueries that adds the index to that table.
2866              $cqueries[]   = "ALTER TABLE {$table} ADD $index";
2867              $for_update[] = 'Added index ' . $table . ' ' . $index;
2868          }
2869  
2870          // Remove the original table creation query from processing.
2871          unset( $cqueries[ $table ], $for_update[ $table ] );
2872      }
2873  
2874      $allqueries = array_merge( $cqueries, $iqueries );
2875      if ( $execute ) {
2876          foreach ( $allqueries as $query ) {
2877              $wpdb->query( $query );
2878          }
2879      }
2880  
2881      return $for_update;
2882  }
2883  
2884  /**
2885   * Updates the database tables to a new schema.
2886   *
2887   * By default, updates all the tables to use the latest defined schema, but can also
2888   * be used to update a specific set of tables in wp_get_db_schema().
2889   *
2890   * @since 1.5.0
2891   *
2892   * @uses dbDelta
2893   *
2894   * @param string $tables Optional. Which set of tables to update. Default is 'all'.
2895   */
2896  function make_db_current( $tables = 'all' ) {
2897      $alterations = dbDelta( $tables );
2898      echo "<ol>\n";
2899      foreach ( $alterations as $alteration ) {
2900          echo "<li>$alteration</li>\n";
2901      }
2902      echo "</ol>\n";
2903  }
2904  
2905  /**
2906   * Updates the database tables to a new schema, but without displaying results.
2907   *
2908   * By default, updates all the tables to use the latest defined schema, but can
2909   * also be used to update a specific set of tables in wp_get_db_schema().
2910   *
2911   * @since 1.5.0
2912   *
2913   * @see make_db_current()
2914   *
2915   * @param string $tables Optional. Which set of tables to update. Default is 'all'.
2916   */
2917  function make_db_current_silent( $tables = 'all' ) {
2918      dbDelta( $tables );
2919  }
2920  
2921  /**
2922   * Creates a site theme from an existing theme.
2923   *
2924   * {@internal Missing Long Description}}
2925   *
2926   * @since 1.5.0
2927   *
2928   * @param string $theme_name The name of the theme.
2929   * @param string $template   The directory name of the theme.
2930   * @return bool
2931   */
2932  function make_site_theme_from_oldschool( $theme_name, $template ) {
2933      $home_path = get_home_path();
2934      $site_dir  = WP_CONTENT_DIR . "/themes/$template";
2935  
2936      if ( ! file_exists( "$home_path/index.php" ) ) {
2937          return false;
2938      }
2939  
2940      /*
2941       * Copy files from the old locations to the site theme.
2942       * TODO: This does not copy arbitrary include dependencies. Only the standard WP files are copied.
2943       */
2944      $files = array(
2945          'index.php'             => 'index.php',
2946          'wp-layout.css'         => 'style.css',
2947          'wp-comments.php'       => 'comments.php',
2948          'wp-comments-popup.php' => 'comments-popup.php',
2949      );
2950  
2951      foreach ( $files as $oldfile => $newfile ) {
2952          if ( $oldfile == 'index.php' ) {
2953              $oldpath = $home_path;
2954          } else {
2955              $oldpath = ABSPATH;
2956          }
2957  
2958          // Check to make sure it's not a new index.
2959          if ( $oldfile == 'index.php' ) {
2960              $index = implode( '', file( "$oldpath/$oldfile" ) );
2961              if ( strpos( $index, 'WP_USE_THEMES' ) !== false ) {
2962                  if ( ! @copy( WP_CONTENT_DIR . '/themes/' . WP_DEFAULT_THEME . '/index.php', "$site_dir/$newfile" ) ) {
2963                      return false;
2964                  }
2965  
2966                  // Don't copy anything.
2967                  continue;
2968              }
2969          }
2970  
2971          if ( ! @copy( "$oldpath/$oldfile", "$site_dir/$newfile" ) ) {
2972              return false;
2973          }
2974  
2975          chmod( "$site_dir/$newfile", 0777 );
2976  
2977          // Update the blog header include in each file.
2978          $lines = explode( "\n", implode( '', file( "$site_dir/$newfile" ) ) );
2979          if ( $lines ) {
2980              $f = fopen( "$site_dir/$newfile", 'w' );
2981  
2982              foreach ( $lines as $line ) {
2983                  if ( preg_match( '/require.*wp-blog-header/', $line ) ) {
2984                      $line = '//' . $line;
2985                  }
2986  
2987                  // Update stylesheet references.
2988                  $line = str_replace( "<?php echo __get_option('siteurl'); ?>/wp-layout.css", "<?php bloginfo('stylesheet_url'); ?>", $line );
2989  
2990                  // Update comments template inclusion.
2991                  $line = str_replace( "<?php include(ABSPATH . 'wp-comments.php'); ?>", '<?php comments_template(); ?>', $line );
2992  
2993                  fwrite( $f, "{$line}\n" );
2994              }
2995              fclose( $f );
2996          }
2997      }
2998  
2999      // Add a theme header.
3000      $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";
3001  
3002      $stylelines = file_get_contents( "$site_dir/style.css" );
3003      if ( $stylelines ) {
3004          $f = fopen( "$site_dir/style.css", 'w' );
3005  
3006          fwrite( $f, $header );
3007          fwrite( $f, $stylelines );
3008          fclose( $f );
3009      }
3010  
3011      return true;
3012  }
3013  
3014  /**
3015   * Creates a site theme from the default theme.
3016   *
3017   * {@internal Missing Long Description}}
3018   *
3019   * @since 1.5.0
3020   *
3021   * @param string $theme_name The name of the theme.
3022   * @param string $template   The directory name of the theme.
3023   * @return false|void
3024   */
3025  function make_site_theme_from_default( $theme_name, $template ) {
3026      $site_dir    = WP_CONTENT_DIR . "/themes/$template";
3027      $default_dir = WP_CONTENT_DIR . '/themes/' . WP_DEFAULT_THEME;
3028  
3029      // Copy files from the default theme to the site theme.
3030      //$files = array('index.php', 'comments.php', 'comments-popup.php', 'footer.php', 'header.php', 'sidebar.php', 'style.css');
3031  
3032      $theme_dir = @ opendir( $default_dir );
3033      if ( $theme_dir ) {
3034          while ( ( $theme_file = readdir( $theme_dir ) ) !== false ) {
3035              if ( is_dir( "$default_dir/$theme_file" ) ) {
3036                  continue;
3037              }
3038              if ( ! @copy( "$default_dir/$theme_file", "$site_dir/$theme_file" ) ) {
3039                  return;
3040              }
3041              chmod( "$site_dir/$theme_file", 0777 );
3042          }
3043      }
3044      @closedir( $theme_dir );
3045  
3046      // Rewrite the theme header.
3047      $stylelines = explode( "\n", implode( '', file( "$site_dir/style.css" ) ) );
3048      if ( $stylelines ) {
3049          $f = fopen( "$site_dir/style.css", 'w' );
3050  
3051          foreach ( $stylelines as $line ) {
3052              if ( strpos( $line, 'Theme Name:' ) !== false ) {
3053                  $line = 'Theme Name: ' . $theme_name;
3054              } elseif ( strpos( $line, 'Theme URI:' ) !== false ) {
3055                  $line = 'Theme URI: ' . __get_option( 'url' );
3056              } elseif ( strpos( $line, 'Description:' ) !== false ) {
3057                  $line = 'Description: Your theme.';
3058              } elseif ( strpos( $line, 'Version:' ) !== false ) {
3059                  $line = 'Version: 1';
3060              } elseif ( strpos( $line, 'Author:' ) !== false ) {
3061                  $line = 'Author: You';
3062              }
3063              fwrite( $f, $line . "\n" );
3064          }
3065          fclose( $f );
3066      }
3067  
3068      // Copy the images.
3069      umask( 0 );
3070      if ( ! mkdir( "$site_dir/images", 0777 ) ) {
3071          return false;
3072      }
3073  
3074      $images_dir = @ opendir( "$default_dir/images" );
3075      if ( $images_dir ) {
3076          while ( ( $image = readdir( $images_dir ) ) !== false ) {
3077              if ( is_dir( "$default_dir/images/$image" ) ) {
3078                  continue;
3079              }
3080              if ( ! @copy( "$default_dir/images/$image", "$site_dir/images/$image" ) ) {
3081                  return;
3082              }
3083              chmod( "$site_dir/images/$image", 0777 );
3084          }
3085      }
3086      @closedir( $images_dir );
3087  }
3088  
3089  /**
3090   * Creates a site theme.
3091   *
3092   * {@internal Missing Long Description}}
3093   *
3094   * @since 1.5.0
3095   *
3096   * @return false|string
3097   */
3098  function make_site_theme() {
3099      // Name the theme after the blog.
3100      $theme_name = __get_option( 'blogname' );
3101      $template   = sanitize_title( $theme_name );
3102      $site_dir   = WP_CONTENT_DIR . "/themes/$template";
3103  
3104      // If the theme already exists, nothing to do.
3105      if ( is_dir( $site_dir ) ) {
3106          return false;
3107      }
3108  
3109      // We must be able to write to the themes dir.
3110      if ( ! is_writable( WP_CONTENT_DIR . '/themes' ) ) {
3111          return false;
3112      }
3113  
3114      umask( 0 );
3115      if ( ! mkdir( $site_dir, 0777 ) ) {
3116          return false;
3117      }
3118  
3119      if ( file_exists( ABSPATH . 'wp-layout.css' ) ) {
3120          if ( ! make_site_theme_from_oldschool( $theme_name, $template ) ) {
3121              // TODO: rm -rf the site theme directory.
3122              return false;
3123          }
3124      } else {
3125          if ( ! make_site_theme_from_default( $theme_name, $template ) ) {
3126              // TODO: rm -rf the site theme directory.
3127              return false;
3128          }
3129      }
3130  
3131      // Make the new site theme active.
3132      $current_template = __get_option( 'template' );
3133      if ( $current_template == WP_DEFAULT_THEME ) {
3134          update_option( 'template', $template );
3135          update_option( 'stylesheet', $template );
3136      }
3137      return $template;
3138  }
3139  
3140  /**
3141   * Translate user level to user role name.
3142   *
3143   * @since 2.0.0
3144   *
3145   * @param int $level User level.
3146   * @return string User role name.
3147   */
3148  function translate_level_to_role( $level ) {
3149      switch ( $level ) {
3150          case 10:
3151          case 9:
3152          case 8:
3153              return 'administrator';
3154          case 7:
3155          case 6:
3156          case 5:
3157              return 'editor';
3158          case 4:
3159          case 3:
3160          case 2:
3161              return 'author';
3162          case 1:
3163              return 'contributor';
3164          case 0:
3165              return 'subscriber';
3166      }
3167  }
3168  
3169  /**
3170   * Checks the version of the installed MySQL binary.
3171   *
3172   * @since 2.1.0
3173   *
3174   * @global wpdb  $wpdb
3175   */
3176  function wp_check_mysql_version() {
3177      global $wpdb;
3178      $result = $wpdb->check_database_version();
3179      if ( is_wp_error( $result ) ) {
3180          wp_die( $result );
3181      }
3182  }
3183  
3184  /**
3185   * Disables the Automattic widgets plugin, which was merged into core.
3186   *
3187   * @since 2.2.0
3188   */
3189  function maybe_disable_automattic_widgets() {
3190      $plugins = __get_option( 'active_plugins' );
3191  
3192      foreach ( (array) $plugins as $plugin ) {
3193          if ( basename( $plugin ) == 'widgets.php' ) {
3194              array_splice( $plugins, array_search( $plugin, $plugins ), 1 );
3195              update_option( 'active_plugins', $plugins );
3196              break;
3197          }
3198      }
3199  }
3200  
3201  /**
3202   * Disables the Link Manager on upgrade if, at the time of upgrade, no links exist in the DB.
3203   *
3204   * @since 3.5.0
3205   *
3206   * @global int  $wp_current_db_version
3207   * @global wpdb $wpdb WordPress database abstraction object.
3208   */
3209  function maybe_disable_link_manager() {
3210      global $wp_current_db_version, $wpdb;
3211  
3212      if ( $wp_current_db_version >= 22006 && get_option( 'link_manager_enabled' ) && ! $wpdb->get_var( "SELECT link_id FROM $wpdb->links LIMIT 1" ) ) {
3213          update_option( 'link_manager_enabled', 0 );
3214      }
3215  }
3216  
3217  /**
3218   * Runs before the schema is upgraded.
3219   *
3220   * @since 2.9.0
3221   *
3222   * @global int  $wp_current_db_version
3223   * @global wpdb $wpdb WordPress database abstraction object.
3224   */
3225  function pre_schema_upgrade() {
3226      global $wp_current_db_version, $wpdb;
3227  
3228      // Upgrade versions prior to 2.9
3229      if ( $wp_current_db_version < 11557 ) {
3230          // Delete duplicate options. Keep the option with the highest option_id.
3231          $wpdb->query( "DELETE o1 FROM $wpdb->options AS o1 JOIN $wpdb->options AS o2 USING (`option_name`) WHERE o2.option_id > o1.option_id" );
3232  
3233          // Drop the old primary key and add the new.
3234          $wpdb->query( "ALTER TABLE $wpdb->options DROP PRIMARY KEY, ADD PRIMARY KEY(option_id)" );
3235  
3236          // Drop the old option_name index. dbDelta() doesn't do the drop.
3237          $wpdb->query( "ALTER TABLE $wpdb->options DROP INDEX option_name" );
3238      }
3239  
3240      // Multisite schema upgrades.
3241      if ( $wp_current_db_version < 25448 && is_multisite() && wp_should_upgrade_global_tables() ) {
3242  
3243          // Upgrade versions prior to 3.7
3244          if ( $wp_current_db_version < 25179 ) {
3245              // New primary key for signups.
3246              $wpdb->query( "ALTER TABLE $wpdb->signups ADD signup_id BIGINT(20) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST" );
3247              $wpdb->query( "ALTER TABLE $wpdb->signups DROP INDEX domain" );
3248          }
3249  
3250          if ( $wp_current_db_version < 25448 ) {
3251              // Convert archived from enum to tinyint.
3252              $wpdb->query( "ALTER TABLE $wpdb->blogs CHANGE COLUMN archived archived varchar(1) NOT NULL default '0'" );
3253              $wpdb->query( "ALTER TABLE $wpdb->blogs CHANGE COLUMN archived archived tinyint(2) NOT NULL default 0" );
3254          }
3255      }
3256  
3257      // Upgrade versions prior to 4.2.
3258      if ( $wp_current_db_version < 31351 ) {
3259          if ( ! is_multisite() && wp_should_upgrade_global_tables() ) {
3260              $wpdb->query( "ALTER TABLE $wpdb->usermeta DROP INDEX meta_key, ADD INDEX meta_key(meta_key(191))" );
3261          }
3262          $wpdb->query( "ALTER TABLE $wpdb->terms DROP INDEX slug, ADD INDEX slug(slug(191))" );
3263          $wpdb->query( "ALTER TABLE $wpdb->terms DROP INDEX name, ADD INDEX name(name(191))" );
3264          $wpdb->query( "ALTER TABLE $wpdb->commentmeta DROP INDEX meta_key, ADD INDEX meta_key(meta_key(191))" );
3265          $wpdb->query( "ALTER TABLE $wpdb->postmeta DROP INDEX meta_key, ADD INDEX meta_key(meta_key(191))" );
3266          $wpdb->query( "ALTER TABLE $wpdb->posts DROP INDEX post_name, ADD INDEX post_name(post_name(191))" );
3267      }
3268  
3269      // Upgrade versions prior to 4.4.
3270      if ( $wp_current_db_version < 34978 ) {
3271          // If compatible termmeta table is found, use it, but enforce a proper index and update collation.
3272          if ( $wpdb->get_var( "SHOW TABLES LIKE '{$wpdb->termmeta}'" ) && $wpdb->get_results( "SHOW INDEX FROM {$wpdb->termmeta} WHERE Column_name = 'meta_key'" ) ) {
3273              $wpdb->query( "ALTER TABLE $wpdb->termmeta DROP INDEX meta_key, ADD INDEX meta_key(meta_key(191))" );
3274              maybe_convert_table_to_utf8mb4( $wpdb->termmeta );
3275          }
3276      }
3277  }
3278  
3279  if ( ! function_exists( 'install_global_terms' ) ) :
3280      /**
3281       * Install global terms.
3282       *
3283       * @since 3.0.0
3284       *
3285       * @global wpdb   $wpdb
3286       * @global string $charset_collate
3287       */
3288  	function install_global_terms() {
3289          global $wpdb, $charset_collate;
3290          $ms_queries = "
3291  CREATE TABLE $wpdb->sitecategories (
3292    cat_ID bigint(20) NOT NULL auto_increment,
3293    cat_name varchar(55) NOT NULL default '',
3294    category_nicename varchar(200) NOT NULL default '',
3295    last_updated timestamp NOT NULL,
3296    PRIMARY KEY  (cat_ID),
3297    KEY category_nicename (category_nicename),
3298    KEY last_updated (last_updated)
3299  ) $charset_collate;
3300  ";
3301          // now create tables
3302          dbDelta( $ms_queries );
3303      }
3304  endif;
3305  
3306  /**
3307   * Determine if global tables should be upgraded.
3308   *
3309   * This function performs a series of checks to ensure the environment allows
3310   * for the safe upgrading of global WordPress database tables. It is necessary
3311   * because global tables will commonly grow to millions of rows on large
3312   * installations, and the ability to control their upgrade routines can be
3313   * critical to the operation of large networks.
3314   *
3315   * In a future iteration, this function may use `wp_is_large_network()` to more-
3316   * intelligently prevent global table upgrades. Until then, we make sure
3317   * WordPress is on the main site of the main network, to avoid running queries
3318   * more than once in multi-site or multi-network environments.
3319   *
3320   * @since 4.3.0
3321   *
3322   * @return bool Whether to run the upgrade routines on global tables.
3323   */
3324  function wp_should_upgrade_global_tables() {
3325  
3326      // Return false early if explicitly not upgrading
3327      if ( defined( 'DO_NOT_UPGRADE_GLOBAL_TABLES' ) ) {
3328          return false;
3329      }
3330  
3331      // Assume global tables should be upgraded
3332      $should_upgrade = true;
3333  
3334      // Set to false if not on main network (does not matter if not multi-network)
3335      if ( ! is_main_network() ) {
3336          $should_upgrade = false;
3337      }
3338  
3339      // Set to false if not on main site of current network (does not matter if not multi-site)
3340      if ( ! is_main_site() ) {
3341          $should_upgrade = false;
3342      }
3343  
3344      /**
3345       * Filters if upgrade routines should be run on global tables.
3346       *
3347       * @param bool $should_upgrade Whether to run the upgrade routines on global tables.
3348       */
3349      return apply_filters( 'wp_should_upgrade_global_tables', $should_upgrade );
3350  }


Generated: Mon Jun 17 08:20:02 2019 Cross-referenced by PHPXref 0.7