[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

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

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


Generated : Wed Apr 8 08:20:02 2020 Cross-referenced by PHPXref