[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

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

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


Generated: Sat Jan 18 01:00:03 2020 Cross-referenced by PHPXref 0.7.1