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


Generated: Sun Sep 22 08:20:01 2019 Cross-referenced by PHPXref 0.7