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


Generated: Thu Sep 19 01:00:03 2019 Cross-referenced by PHPXref 0.7.1