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


Generated: Wed Jul 24 01:00:02 2019 Cross-referenced by PHPXref 0.7.1