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


Generated : Mon Jul 15 08:20:02 2024 Cross-referenced by PHPXref