[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

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

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


Generated: Thu Jun 4 01:00:04 2020 Cross-referenced by PHPXref 0.7.1