[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

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


Generated : Mon Aug 3 08:20:02 2020 Cross-referenced by PHPXref