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


Generated: Mon Nov 11 01:00:04 2019 Cross-referenced by PHPXref 0.7.1