[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

title

Body

[close]

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

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


Generated: Fri Oct 25 08:20:01 2019 Cross-referenced by PHPXref 0.7