[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

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

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


Generated: Sun Jan 16 01:00:03 2022 Cross-referenced by PHPXref 0.7.1