Make WordPress Core


Ignore:
Timestamp:
08/26/2014 07:58:33 PM (10 years ago)
Author:
ocean90
Message:

Language packs: No WPLANG anymore.

  • The WPLANG constant is no longer needed. Remove define('WPLANG', ); from wp-config-sample.php. Populate WPLANG option based on the WPLANG constant. When get_option('WPLANG') is an empty string it will override WPLANG.
  • Introduce translations_api() which is available to communicate with the translation API. Move translation install related functions to a new file.
  • Replace mu_dropdown_languages() with wp_dropdown_languages(). wp_dropdown_languages() is now populated by the translation API.
  • Remove wp_install_load_language() and allow load_default_textdomain() to switch a core translation.

fixes #13069, #15677, #19760, #28730, #29281.

File:
1 copied

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-admin/includes/translation-install.php

    r29628 r29630  
    11<?php
    22/**
    3  * WordPress Upgrade API
    4  *
    5  * Most of the functions are pluggable and can be overwritten
     3 * WordPress Translation Install Administration API
    64 *
    75 * @package WordPress
     
    97 */
    108
    11 /** Include user install customize script. */
    12 if ( file_exists(WP_CONTENT_DIR . '/install.php') )
    13     require (WP_CONTENT_DIR . '/install.php');
    14 
    15 /** WordPress Administration API */
    16 require_once(ABSPATH . 'wp-admin/includes/admin.php');
    17 
    18 /** WordPress Schema API */
    19 require_once(ABSPATH . 'wp-admin/includes/schema.php');
    20 
    21 if ( !function_exists('wp_install') ) :
    22 /**
    23  * Installs the blog
    24  *
    25  * {@internal Missing Long Description}}
    26  *
    27  * @since 2.1.0
    28  *
    29  * @param string $blog_title Blog title.
    30  * @param string $user_name User's username.
    31  * @param string $user_email User's email.
    32  * @param bool $public Whether blog is public.
    33  * @param null $deprecated Optional. Not used.
    34  * @param string $user_password Optional. User's chosen password. Will default to a random password.
    35  * @param string $language Optional. Language chosen.
    36  * @return array Array keys 'url', 'user_id', 'password', 'password_message'.
    37  */
    38 function wp_install( $blog_title, $user_name, $user_email, $public, $deprecated = '', $user_password = '', $language = '' ) {
    39     if ( !empty( $deprecated ) )
    40         _deprecated_argument( __FUNCTION__, '2.6' );
    41 
    42     wp_check_mysql_version();
    43     wp_cache_flush();
    44     make_db_current_silent();
    45     populate_options();
    46     populate_roles();
    47 
    48     update_option('blogname', $blog_title);
    49     update_option('admin_email', $user_email);
    50     update_option('blog_public', $public);
    51 
    52     if ( $language ) {
    53         update_option( 'WPLANG', $language );
    54     }
    55 
    56     $guessurl = wp_guess_url();
    57 
    58     update_option('siteurl', $guessurl);
    59 
    60     // If not a public blog, don't ping.
    61     if ( ! $public )
    62         update_option('default_pingback_flag', 0);
    63 
    64     /*
    65      * Create default user. If the user already exists, the user tables are
    66      * being shared among blogs. Just set the role in that case.
     9
     10/**
     11 * Retrieve translations from WordPress Translation API.
     12 *
     13 * @since 4.0.0
     14 *
     15 * @param string       $type Type of translations. Accepts 'plugins', 'themes', 'core'.
     16 * @param array|object $args Translation API arguments. Optional.
     17 * @return object|WP_Error On success an object of translations, WP_Error on failure.
     18 */
     19function translations_api( $type, $args = null ) {
     20    include( ABSPATH . WPINC . '/version.php' ); // include an unmodified $wp_version
     21
     22    if ( ! in_array( $type, array( 'plugins', 'themes', 'core' ) ) ) {
     23        return  new WP_Error( 'invalid_type', __( 'Invalid translation type.' ) );
     24    }
     25
     26    /**
     27     * Allows a plugin to override the WordPress.org Translation Install API entirely.
     28     *
     29     * @since 4.0.0
     30     *
     31     * @param bool|array  $result The result object. Default false.
     32     * @param string      $type   The type of translations being requested.
     33     * @param object      $args   Translation API arguments.
    6734     */
    68     $user_id = username_exists($user_name);
    69     $user_password = trim($user_password);
    70     $email_password = false;
    71     if ( !$user_id && empty($user_password) ) {
    72         $user_password = wp_generate_password( 12, false );
    73         $message = __('<strong><em>Note that password</em></strong> carefully! It is a <em>random</em> password that was generated just for you.');
    74         $user_id = wp_create_user($user_name, $user_password, $user_email);
    75         update_user_option($user_id, 'default_password_nag', true, true);
    76         $email_password = true;
    77     } else if ( !$user_id ) {
    78         // Password has been provided
    79         $message = '<em>'.__('Your chosen password.').'</em>';
    80         $user_id = wp_create_user($user_name, $user_password, $user_email);
    81     } else {
    82         $message = __('User already exists. Password inherited.');
    83     }
    84 
    85     $user = new WP_User($user_id);
    86     $user->set_role('administrator');
    87 
    88     wp_install_defaults($user_id);
    89 
    90     flush_rewrite_rules();
    91 
    92     wp_new_blog_notification($blog_title, $guessurl, $user_id, ($email_password ? $user_password : __('The password you chose during the install.') ) );
    93 
    94     wp_cache_flush();
     35    $res = apply_filters( 'translations_api', false, $type, $args );
     36
     37    if ( false === $res ) {
     38        $url = $http_url = 'http://api.wordpress.org/translations/' . $type . '/1.0/';
     39        if ( $ssl = wp_http_supports( array( 'ssl' ) ) ) {
     40            $url = set_url_scheme( $url, 'https' );
     41        }
     42
     43        $options = array(
     44            'timeout' => 3,
     45            'body' => array(
     46                'wp_version' => $wp_version,
     47                'locale'     => get_locale(),
     48                'version'    => $args['version'], // Version of plugin, theme or core
     49            ),
     50        );
     51
     52        if ( 'core' !== $type ) {
     53            $options['body']['slug'] = $args['slug']; // Plugin or theme slug
     54        }
     55
     56        $request = wp_remote_post( $url, $options );
     57
     58        if ( $ssl && is_wp_error( $request ) ) {
     59            trigger_error( __( 'An unexpected error occurred. Something may be wrong with WordPress.org or this server&#8217;s configuration. If you continue to have problems, please try the <a href="https://wordpress.org/support/">support forums</a>.' ) . ' ' . __( '(WordPress could not establish a secure connection to WordPress.org. Please contact your server administrator.)' ), headers_sent() || WP_DEBUG ? E_USER_WARNING : E_USER_NOTICE );
     60
     61            $request = wp_remote_post( $http_url, $options );
     62        }
     63
     64        if ( is_wp_error( $request ) ) {
     65            $res = new WP_Error( 'translations_api_failed', __( 'An unexpected error occurred. Something may be wrong with WordPress.org or this server&#8217;s configuration. If you continue to have problems, please try the <a href="https://wordpress.org/support/">support forums</a>.' ), $request->get_error_message() );
     66        } else {
     67            $res = json_decode( wp_remote_retrieve_body( $request ), true );
     68            if ( ! is_object( $res ) && ! is_array( $res ) ) {
     69                $res = new WP_Error( 'translations_api_failed', __( 'An unexpected error occurred. Something may be wrong with WordPress.org or this server&#8217;s configuration. If you continue to have problems, please try the <a href="https://wordpress.org/support/">support forums</a>.' ), wp_remote_retrieve_body( $request ) );
     70            }
     71        }
     72    }
    9573
    9674    /**
    97      * Fires after a site is fully installed.
    98      *
    99      * @since 3.9.0
    100      *
    101      * @param WP_User $user The site owner.
     75     * Filter the Translation Install API response results.
     76     *
     77     * @since 4.0.0
     78     *
     79     * @param object|WP_Error $res  Response object or WP_Error.
     80     * @param string          $type The type of translations being requested.
     81     * @param object          $args Translation API arguments.
    10282     */
    103     do_action( 'wp_install', $user );
    104 
    105     return array('url' => $guessurl, 'user_id' => $user_id, 'password' => $user_password, 'password_message' => $message);
    106 }
    107 endif;
    108 
    109 if ( !function_exists('wp_install_defaults') ) :
    110 /**
    111  * {@internal Missing Short Description}}
    112  *
    113  * {@internal Missing Long Description}}
    114  *
    115  * @since 2.1.0
    116  *
    117  * @param int $user_id User ID.
    118  */
    119 function wp_install_defaults( $user_id ) {
    120     global $wpdb, $wp_rewrite, $table_prefix;
    121 
    122     // Default category
    123     $cat_name = __('Uncategorized');
    124     /* translators: Default category slug */
    125     $cat_slug = sanitize_title(_x('Uncategorized', 'Default category slug'));
    126 
    127     if ( global_terms_enabled() ) {
    128         $cat_id = $wpdb->get_var( $wpdb->prepare( "SELECT cat_ID FROM {$wpdb->sitecategories} WHERE category_nicename = %s", $cat_slug ) );
    129         if ( $cat_id == null ) {
    130             $wpdb->insert( $wpdb->sitecategories, array('cat_ID' => 0, 'cat_name' => $cat_name, 'category_nicename' => $cat_slug, 'last_updated' => current_time('mysql', true)) );
    131             $cat_id = $wpdb->insert_id;
    132         }
    133         update_option('default_category', $cat_id);
    134     } else {
    135         $cat_id = 1;
    136     }
    137 
    138     $wpdb->insert( $wpdb->terms, array('term_id' => $cat_id, 'name' => $cat_name, 'slug' => $cat_slug, 'term_group' => 0) );
    139     $wpdb->insert( $wpdb->term_taxonomy, array('term_id' => $cat_id, 'taxonomy' => 'category', 'description' => '', 'parent' => 0, 'count' => 1));
    140     $cat_tt_id = $wpdb->insert_id;
    141 
    142     // First post
    143     $now = date('Y-m-d H:i:s');
    144     $now_gmt = gmdate('Y-m-d H:i:s');
    145     $first_post_guid = get_option('home') . '/?p=1';
    146 
    147     if ( is_multisite() ) {
    148         $first_post = get_site_option( 'first_post' );
    149 
    150         if ( empty($first_post) )
    151             $first_post = __( 'Welcome to <a href="SITE_URL">SITE_NAME</a>. This is your first post. Edit or delete it, then start blogging!' );
    152 
    153         $first_post = str_replace( "SITE_URL", esc_url( network_home_url() ), $first_post );
    154         $first_post = str_replace( "SITE_NAME", get_current_site()->site_name, $first_post );
    155     } else {
    156         $first_post = __('Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!');
    157     }
    158 
    159     $wpdb->insert( $wpdb->posts, array(
    160                                 'post_author' => $user_id,
    161                                 'post_date' => $now,
    162                                 'post_date_gmt' => $now_gmt,
    163                                 'post_content' => $first_post,
    164                                 'post_excerpt' => '',
    165                                 'post_title' => __('Hello world!'),
    166                                 /* translators: Default post slug */
    167                                 'post_name' => sanitize_title( _x('hello-world', 'Default post slug') ),
    168                                 'post_modified' => $now,
    169                                 'post_modified_gmt' => $now_gmt,
    170                                 'guid' => $first_post_guid,
    171                                 'comment_count' => 1,
    172                                 'to_ping' => '',
    173                                 'pinged' => '',
    174                                 'post_content_filtered' => ''
    175                                 ));
    176     $wpdb->insert( $wpdb->term_relationships, array('term_taxonomy_id' => $cat_tt_id, 'object_id' => 1) );
    177 
    178     // Default comment
    179     $first_comment_author = __('Mr WordPress');
    180     $first_comment_url = 'https://wordpress.org/';
    181     $first_comment = __('Hi, this is a comment.
    182 To delete a comment, just log in and view the post&#039;s comments. There you will have the option to edit or delete them.');
    183     if ( is_multisite() ) {
    184         $first_comment_author = get_site_option( 'first_comment_author', $first_comment_author );
    185         $first_comment_url = get_site_option( 'first_comment_url', network_home_url() );
    186         $first_comment = get_site_option( 'first_comment', $first_comment );
    187     }
    188     $wpdb->insert( $wpdb->comments, array(
    189                                 'comment_post_ID' => 1,
    190                                 'comment_author' => $first_comment_author,
    191                                 'comment_author_email' => '',
    192                                 'comment_author_url' => $first_comment_url,
    193                                 'comment_date' => $now,
    194                                 'comment_date_gmt' => $now_gmt,
    195                                 'comment_content' => $first_comment
    196                                 ));
    197 
    198     // First Page
    199     $first_page = sprintf( __( "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:
    200 
    201 <blockquote>Hi there! I'm a bike messenger by day, aspiring actor by night, and this is my blog. I live in Los Angeles, have a great dog named Jack, and I like pi&#241;a coladas. (And gettin' caught in the rain.)</blockquote>
    202 
    203 ...or something like this:
    204 
    205 <blockquote>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.</blockquote>
    206 
    207 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!" ), admin_url() );
    208     if ( is_multisite() )
    209         $first_page = get_site_option( 'first_page', $first_page );
    210     $first_post_guid = get_option('home') . '/?page_id=2';
    211     $wpdb->insert( $wpdb->posts, array(
    212                                 'post_author' => $user_id,
    213                                 'post_date' => $now,
    214                                 'post_date_gmt' => $now_gmt,
    215                                 'post_content' => $first_page,
    216                                 'post_excerpt' => '',
    217                                 'post_title' => __( 'Sample Page' ),
    218                                 /* translators: Default page slug */
    219                                 'post_name' => __( 'sample-page' ),
    220                                 'post_modified' => $now,
    221                                 'post_modified_gmt' => $now_gmt,
    222                                 'guid' => $first_post_guid,
    223                                 'post_type' => 'page',
    224                                 'to_ping' => '',
    225                                 'pinged' => '',
    226                                 'post_content_filtered' => ''
    227                                 ));
    228     $wpdb->insert( $wpdb->postmeta, array( 'post_id' => 2, 'meta_key' => '_wp_page_template', 'meta_value' => 'default' ) );
    229 
    230     // Set up default widgets for default theme.
    231     update_option( 'widget_search', array ( 2 => array ( 'title' => '' ), '_multiwidget' => 1 ) );
    232     update_option( 'widget_recent-posts', array ( 2 => array ( 'title' => '', 'number' => 5 ), '_multiwidget' => 1 ) );
    233     update_option( 'widget_recent-comments', array ( 2 => array ( 'title' => '', 'number' => 5 ), '_multiwidget' => 1 ) );
    234     update_option( 'widget_archives', array ( 2 => array ( 'title' => '', 'count' => 0, 'dropdown' => 0 ), '_multiwidget' => 1 ) );
    235     update_option( 'widget_categories', array ( 2 => array ( 'title' => '', 'count' => 0, 'hierarchical' => 0, 'dropdown' => 0 ), '_multiwidget' => 1 ) );
    236     update_option( 'widget_meta', array ( 2 => array ( 'title' => '' ), '_multiwidget' => 1 ) );
    237     update_option( 'sidebars_widgets', array ( 'wp_inactive_widgets' => array (), 'sidebar-1' => array ( 0 => 'search-2', 1 => 'recent-posts-2', 2 => 'recent-comments-2', 3 => 'archives-2', 4 => 'categories-2', 5 => 'meta-2', ), 'sidebar-2' => array (), 'sidebar-3' => array (), 'array_version' => 3 ) );
    238 
    239     if ( ! is_multisite() )
    240         update_user_meta( $user_id, 'show_welcome_panel', 1 );
    241     elseif ( ! is_super_admin( $user_id ) && ! metadata_exists( 'user', $user_id, 'show_welcome_panel' ) )
    242         update_user_meta( $user_id, 'show_welcome_panel', 2 );
    243 
    244     if ( is_multisite() ) {
    245         // Flush rules to pick up the new page.
    246         $wp_rewrite->init();
    247         $wp_rewrite->flush_rules();
    248 
    249         $user = new WP_User($user_id);
    250         $wpdb->update( $wpdb->options, array('option_value' => $user->user_email), array('option_name' => 'admin_email') );
    251 
    252         // Remove all perms except for the login user.
    253         $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id != %d AND meta_key = %s", $user_id, $table_prefix.'user_level') );
    254         $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id != %d AND meta_key = %s", $user_id, $table_prefix.'capabilities') );
    255 
    256         // Delete any caps that snuck into the previously active blog. (Hardcoded to blog 1 for now.) TODO: Get previous_blog_id.
    257         if ( !is_super_admin( $user_id ) && $user_id != 1 )
    258             $wpdb->delete( $wpdb->usermeta, array( 'user_id' => $user_id , 'meta_key' => $wpdb->base_prefix.'1_capabilities' ) );
    259     }
    260 }
    261 endif;
    262 
    263 if ( !function_exists('wp_new_blog_notification') ) :
    264 /**
    265  * {@internal Missing Short Description}}
    266  *
    267  * {@internal Missing Long Description}}
    268  *
    269  * @since 2.1.0
    270  *
    271  * @param string $blog_title Blog title.
    272  * @param string $blog_url Blog url.
    273  * @param int $user_id User ID.
    274  * @param string $password User's Password.
    275  */
    276 function wp_new_blog_notification($blog_title, $blog_url, $user_id, $password) {
    277     $user = new WP_User( $user_id );
    278     $email = $user->user_email;
    279     $name = $user->user_login;
    280     $message = sprintf(__("Your new WordPress site has been successfully set up at:
    281 
    282 %1\$s
    283 
    284 You can log in to the administrator account with the following information:
    285 
    286 Username: %2\$s
    287 Password: %3\$s
    288 
    289 We hope you enjoy your new site. Thanks!
    290 
    291 --The WordPress Team
    292 https://wordpress.org/
    293 "), $blog_url, $name, $password);
    294 
    295     @wp_mail($email, __('New WordPress Site'), $message);
    296 }
    297 endif;
    298 
    299 if ( !function_exists('wp_upgrade') ) :
    300 /**
    301  * Run WordPress Upgrade functions.
    302  *
    303  * {@internal Missing Long Description}}
    304  *
    305  * @since 2.1.0
    306  *
    307  * @return null
    308  */
    309 function wp_upgrade() {
    310     global $wp_current_db_version, $wp_db_version, $wpdb;
    311 
    312     $wp_current_db_version = __get_option('db_version');
    313 
    314     // We are up-to-date. Nothing to do.
    315     if ( $wp_db_version == $wp_current_db_version )
    316         return;
    317 
    318     if ( ! is_blog_installed() )
    319         return;
    320 
    321     wp_check_mysql_version();
    322     wp_cache_flush();
    323     pre_schema_upgrade();
    324     make_db_current_silent();
    325     upgrade_all();
    326     if ( is_multisite() && is_main_site() )
    327         upgrade_network();
    328     wp_cache_flush();
    329 
    330     if ( is_multisite() ) {
    331         if ( $wpdb->get_row( "SELECT blog_id FROM {$wpdb->blog_versions} WHERE blog_id = '{$wpdb->blogid}'" ) )
    332             $wpdb->query( "UPDATE {$wpdb->blog_versions} SET db_version = '{$wp_db_version}' WHERE blog_id = '{$wpdb->blogid}'" );
    333         else
    334             $wpdb->query( "INSERT INTO {$wpdb->blog_versions} ( `blog_id` , `db_version` , `last_updated` ) VALUES ( '{$wpdb->blogid}', '{$wp_db_version}', NOW());" );
    335     }
    336 
    337     /**
    338      * Fires after a site is fully upgraded.
    339      *
    340      * @since 3.9.0
    341      *
    342      * @param int $wp_db_version         The new $wp_db_version.
    343      * @param int $wp_current_db_version The old (current) $wp_db_version.
    344      */
    345     do_action( 'wp_upgrade', $wp_db_version, $wp_current_db_version );
    346 }
    347 endif;
    348 
    349 /**
    350  * Functions to be called in install and upgrade scripts.
    351  *
    352  * {@internal Missing Long Description}}
    353  *
    354  * @since 1.0.1
    355  */
    356 function upgrade_all() {
    357     global $wp_current_db_version, $wp_db_version;
    358     $wp_current_db_version = __get_option('db_version');
    359 
    360     // We are up-to-date. Nothing to do.
    361     if ( $wp_db_version == $wp_current_db_version )
    362         return;
    363 
    364     // If the version is not set in the DB, try to guess the version.
    365     if ( empty($wp_current_db_version) ) {
    366         $wp_current_db_version = 0;
    367 
    368         // If the template option exists, we have 1.5.
    369         $template = __get_option('template');
    370         if ( !empty($template) )
    371             $wp_current_db_version = 2541;
    372     }
    373 
    374     if ( $wp_current_db_version < 6039 )
    375         upgrade_230_options_table();
    376 
    377     populate_options();
    378 
    379     if ( $wp_current_db_version < 2541 ) {
    380         upgrade_100();
    381         upgrade_101();
    382         upgrade_110();
    383         upgrade_130();
    384     }
    385 
    386     if ( $wp_current_db_version < 3308 )
    387         upgrade_160();
    388 
    389     if ( $wp_current_db_version < 4772 )
    390         upgrade_210();
    391 
    392     if ( $wp_current_db_version < 4351 )
    393         upgrade_old_slugs();
    394 
    395     if ( $wp_current_db_version < 5539 )
    396         upgrade_230();
    397 
    398     if ( $wp_current_db_version < 6124 )
    399         upgrade_230_old_tables();
    400 
    401     if ( $wp_current_db_version < 7499 )
    402         upgrade_250();
    403 
    404     if ( $wp_current_db_version < 7935 )
    405         upgrade_252();
    406 
    407     if ( $wp_current_db_version < 8201 )
    408         upgrade_260();
    409 
    410     if ( $wp_current_db_version < 8989 )
    411         upgrade_270();
    412 
    413     if ( $wp_current_db_version < 10360 )
    414         upgrade_280();
    415 
    416     if ( $wp_current_db_version < 11958 )
    417         upgrade_290();
    418 
    419     if ( $wp_current_db_version < 15260 )
    420         upgrade_300();
    421 
    422     if ( $wp_current_db_version < 19389 )
    423         upgrade_330();
    424 
    425     if ( $wp_current_db_version < 20080 )
    426         upgrade_340();
    427 
    428     if ( $wp_current_db_version < 22422 )
    429         upgrade_350();
    430 
    431     if ( $wp_current_db_version < 25824 )
    432         upgrade_370();
    433 
    434     if ( $wp_current_db_version < 26148 )
    435         upgrade_372();
    436 
    437     if ( $wp_current_db_version < 26691 )
    438         upgrade_380();
    439 
    440     maybe_disable_link_manager();
    441 
    442     maybe_disable_automattic_widgets();
    443 
    444     update_option( 'db_version', $wp_db_version );
    445     update_option( 'db_upgraded', true );
    446 }
    447 
    448 /**
    449  * Execute changes made in WordPress 1.0.
    450  *
    451  * @since 1.0.0
    452  */
    453 function upgrade_100() {
    454     global $wpdb;
    455 
    456     // Get the title and ID of every post, post_name to check if it already has a value
    457     $posts = $wpdb->get_results("SELECT ID, post_title, post_name FROM $wpdb->posts WHERE post_name = ''");
    458     if ($posts) {
    459         foreach($posts as $post) {
    460             if ('' == $post->post_name) {
    461                 $newtitle = sanitize_title($post->post_title);
    462                 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_name = %s WHERE ID = %d", $newtitle, $post->ID) );
    463             }
    464         }
    465     }
    466 
    467     $categories = $wpdb->get_results("SELECT cat_ID, cat_name, category_nicename FROM $wpdb->categories");
    468     foreach ($categories as $category) {
    469         if ('' == $category->category_nicename) {
    470             $newtitle = sanitize_title($category->cat_name);
    471             $wpdb->update( $wpdb->categories, array('category_nicename' => $newtitle), array('cat_ID' => $category->cat_ID) );
    472         }
    473     }
    474 
    475     $sql = "UPDATE $wpdb->options
    476         SET option_value = REPLACE(option_value, 'wp-links/links-images/', 'wp-images/links/')
    477         WHERE option_name LIKE %s
    478         AND option_value LIKE %s";
    479     $wpdb->query( $wpdb->prepare( $sql, $wpdb->esc_like( 'links_rating_image' ) . '%', $wpdb->esc_like( 'wp-links/links-images/' ) . '%' ) );
    480 
    481     $done_ids = $wpdb->get_results("SELECT DISTINCT post_id FROM $wpdb->post2cat");
    482     if ($done_ids) :
    483         foreach ($done_ids as $done_id) :
    484             $done_posts[] = $done_id->post_id;
    485         endforeach;
    486         $catwhere = ' AND ID NOT IN (' . implode(',', $done_posts) . ')';
    487     else:
    488         $catwhere = '';
    489     endif;
    490 
    491     $allposts = $wpdb->get_results("SELECT ID, post_category FROM $wpdb->posts WHERE post_category != '0' $catwhere");
    492     if ($allposts) :
    493         foreach ($allposts as $post) {
    494             // Check to see if it's already been imported
    495             $cat = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->post2cat WHERE post_id = %d AND category_id = %d", $post->ID, $post->post_category) );
    496             if (!$cat && 0 != $post->post_category) { // If there's no result
    497                 $wpdb->insert( $wpdb->post2cat, array('post_id' => $post->ID, 'category_id' => $post->post_category) );
    498             }
    499         }
    500     endif;
    501 }
    502 
    503 /**
    504  * Execute changes made in WordPress 1.0.1.
    505  *
    506  * @since 1.0.1
    507  */
    508 function upgrade_101() {
    509     global $wpdb;
    510 
    511     // Clean up indices, add a few
    512     add_clean_index($wpdb->posts, 'post_name');
    513     add_clean_index($wpdb->posts, 'post_status');
    514     add_clean_index($wpdb->categories, 'category_nicename');
    515     add_clean_index($wpdb->comments, 'comment_approved');
    516     add_clean_index($wpdb->comments, 'comment_post_ID');
    517     add_clean_index($wpdb->links , 'link_category');
    518     add_clean_index($wpdb->links , 'link_visible');
    519 }
    520 
    521 /**
    522  * Execute changes made in WordPress 1.2.
    523  *
    524  * @since 1.2.0
    525  */
    526 function upgrade_110() {
    527     global $wpdb;
    528 
    529     // Set user_nicename.
    530     $users = $wpdb->get_results("SELECT ID, user_nickname, user_nicename FROM $wpdb->users");
    531     foreach ($users as $user) {
    532         if ('' == $user->user_nicename) {
    533             $newname = sanitize_title($user->user_nickname);
    534             $wpdb->update( $wpdb->users, array('user_nicename' => $newname), array('ID' => $user->ID) );
    535         }
    536     }
    537 
    538     $users = $wpdb->get_results("SELECT ID, user_pass from $wpdb->users");
    539     foreach ($users as $row) {
    540         if (!preg_match('/^[A-Fa-f0-9]{32}$/', $row->user_pass)) {
    541             $wpdb->update( $wpdb->users, array('user_pass' => md5($row->user_pass)), array('ID' => $row->ID) );
    542         }
    543     }
    544 
    545     // Get the GMT offset, we'll use that later on
    546     $all_options = get_alloptions_110();
    547 
    548     $time_difference = $all_options->time_difference;
    549 
    550         $server_time = time()+date('Z');
    551     $weblogger_time = $server_time + $time_difference * HOUR_IN_SECONDS;
    552     $gmt_time = time();
    553 
    554     $diff_gmt_server = ($gmt_time - $server_time) / HOUR_IN_SECONDS;
    555     $diff_weblogger_server = ($weblogger_time - $server_time) / HOUR_IN_SECONDS;
    556     $diff_gmt_weblogger = $diff_gmt_server - $diff_weblogger_server;
    557     $gmt_offset = -$diff_gmt_weblogger;
    558 
    559     // Add a gmt_offset option, with value $gmt_offset
    560     add_option('gmt_offset', $gmt_offset);
    561 
    562     // Check if we already set the GMT fields (if we did, then
    563     // MAX(post_date_gmt) can't be '0000-00-00 00:00:00'
    564     // <michel_v> I just slapped myself silly for not thinking about it earlier
    565     $got_gmt_fields = ! ($wpdb->get_var("SELECT MAX(post_date_gmt) FROM $wpdb->posts") == '0000-00-00 00:00:00');
    566 
    567     if (!$got_gmt_fields) {
    568 
    569         // Add or subtract time to all dates, to get GMT dates
    570         $add_hours = intval($diff_gmt_weblogger);
    571         $add_minutes = intval(60 * ($diff_gmt_weblogger - $add_hours));
    572         $wpdb->query("UPDATE $wpdb->posts SET post_date_gmt = DATE_ADD(post_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
    573         $wpdb->query("UPDATE $wpdb->posts SET post_modified = post_date");
    574         $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'");
    575         $wpdb->query("UPDATE $wpdb->comments SET comment_date_gmt = DATE_ADD(comment_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
    576         $wpdb->query("UPDATE $wpdb->users SET user_registered = DATE_ADD(user_registered, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)");
    577     }
    578 
    579 }
    580 
    581 /**
    582  * Execute changes made in WordPress 1.5.
    583  *
    584  * @since 1.5.0
    585  */
    586 function upgrade_130() {
    587     global $wpdb;
    588 
    589     // Remove extraneous backslashes.
    590     $posts = $wpdb->get_results("SELECT ID, post_title, post_content, post_excerpt, guid, post_date, post_name, post_status, post_author FROM $wpdb->posts");
    591     if ($posts) {
    592         foreach($posts as $post) {
    593             $post_content = addslashes(deslash($post->post_content));
    594             $post_title = addslashes(deslash($post->post_title));
    595             $post_excerpt = addslashes(deslash($post->post_excerpt));
    596             if ( empty($post->guid) )
    597                 $guid = get_permalink($post->ID);
    598             else
    599                 $guid = $post->guid;
    600 
    601             $wpdb->update( $wpdb->posts, compact('post_title', 'post_content', 'post_excerpt', 'guid'), array('ID' => $post->ID) );
    602 
    603         }
    604     }
    605 
    606     // Remove extraneous backslashes.
    607     $comments = $wpdb->get_results("SELECT comment_ID, comment_author, comment_content FROM $wpdb->comments");
    608     if ($comments) {
    609         foreach($comments as $comment) {
    610             $comment_content = deslash($comment->comment_content);
    611             $comment_author = deslash($comment->comment_author);
    612 
    613             $wpdb->update($wpdb->comments, compact('comment_content', 'comment_author'), array('comment_ID' => $comment->comment_ID) );
    614         }
    615     }
    616 
    617     // Remove extraneous backslashes.
    618     $links = $wpdb->get_results("SELECT link_id, link_name, link_description FROM $wpdb->links");
    619     if ($links) {
    620         foreach($links as $link) {
    621             $link_name = deslash($link->link_name);
    622             $link_description = deslash($link->link_description);
    623 
    624             $wpdb->update( $wpdb->links, compact('link_name', 'link_description'), array('link_id' => $link->link_id) );
    625         }
    626     }
    627 
    628     $active_plugins = __get_option('active_plugins');
    629 
    630     /*
    631      * If plugins are not stored in an array, they're stored in the old
    632      * newline separated format. Convert to new format.
    633      */
    634     if ( !is_array( $active_plugins ) ) {
    635         $active_plugins = explode("\n", trim($active_plugins));
    636         update_option('active_plugins', $active_plugins);
    637     }
    638 
    639     // Obsolete tables
    640     $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optionvalues');
    641     $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiontypes');
    642     $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiongroups');
    643     $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiongroup_options');
    644 
    645     // Update comments table to use comment_type
    646     $wpdb->query("UPDATE $wpdb->comments SET comment_type='trackback', comment_content = REPLACE(comment_content, '<trackback />', '') WHERE comment_content LIKE '<trackback />%'");
    647     $wpdb->query("UPDATE $wpdb->comments SET comment_type='pingback', comment_content = REPLACE(comment_content, '<pingback />', '') WHERE comment_content LIKE '<pingback />%'");
    648 
    649     // Some versions have multiple duplicate option_name rows with the same values
    650     $options = $wpdb->get_results("SELECT option_name, COUNT(option_name) AS dupes FROM `$wpdb->options` GROUP BY option_name");
    651     foreach ( $options as $option ) {
    652         if ( 1 != $option->dupes ) { // Could this be done in the query?
    653             $limit = $option->dupes - 1;
    654             $dupe_ids = $wpdb->get_col( $wpdb->prepare("SELECT option_id FROM $wpdb->options WHERE option_name = %s LIMIT %d", $option->option_name, $limit) );
    655             if ( $dupe_ids ) {
    656                 $dupe_ids = join($dupe_ids, ',');
    657                 $wpdb->query("DELETE FROM $wpdb->options WHERE option_id IN ($dupe_ids)");
    658             }
    659         }
    660     }
    661 
    662     make_site_theme();
    663 }
    664 
    665 /**
    666  * Execute changes made in WordPress 2.0.
    667  *
    668  * @since 2.0.0
    669  */
    670 function upgrade_160() {
    671     global $wpdb, $wp_current_db_version;
    672 
    673     populate_roles_160();
    674 
    675     $users = $wpdb->get_results("SELECT * FROM $wpdb->users");
    676     foreach ( $users as $user ) :
    677         if ( !empty( $user->user_firstname ) )
    678             update_user_meta( $user->ID, 'first_name', wp_slash($user->user_firstname) );
    679         if ( !empty( $user->user_lastname ) )
    680             update_user_meta( $user->ID, 'last_name', wp_slash($user->user_lastname) );
    681         if ( !empty( $user->user_nickname ) )
    682             update_user_meta( $user->ID, 'nickname', wp_slash($user->user_nickname) );
    683         if ( !empty( $user->user_level ) )
    684             update_user_meta( $user->ID, $wpdb->prefix . 'user_level', $user->user_level );
    685         if ( !empty( $user->user_icq ) )
    686             update_user_meta( $user->ID, 'icq', wp_slash($user->user_icq) );
    687         if ( !empty( $user->user_aim ) )
    688             update_user_meta( $user->ID, 'aim', wp_slash($user->user_aim) );
    689         if ( !empty( $user->user_msn ) )
    690             update_user_meta( $user->ID, 'msn', wp_slash($user->user_msn) );
    691         if ( !empty( $user->user_yim ) )
    692             update_user_meta( $user->ID, 'yim', wp_slash($user->user_icq) );
    693         if ( !empty( $user->user_description ) )
    694             update_user_meta( $user->ID, 'description', wp_slash($user->user_description) );
    695 
    696         if ( isset( $user->user_idmode ) ):
    697             $idmode = $user->user_idmode;
    698             if ($idmode == 'nickname') $id = $user->user_nickname;
    699             if ($idmode == 'login') $id = $user->user_login;
    700             if ($idmode == 'firstname') $id = $user->user_firstname;
    701             if ($idmode == 'lastname') $id = $user->user_lastname;
    702             if ($idmode == 'namefl') $id = $user->user_firstname.' '.$user->user_lastname;
    703             if ($idmode == 'namelf') $id = $user->user_lastname.' '.$user->user_firstname;
    704             if (!$idmode) $id = $user->user_nickname;
    705             $wpdb->update( $wpdb->users, array('display_name' => $id), array('ID' => $user->ID) );
    706         endif;
    707 
    708         // FIXME: RESET_CAPS is temporary code to reset roles and caps if flag is set.
    709         $caps = get_user_meta( $user->ID, $wpdb->prefix . 'capabilities');
    710         if ( empty($caps) || defined('RESET_CAPS') ) {
    711             $level = get_user_meta($user->ID, $wpdb->prefix . 'user_level', true);
    712             $role = translate_level_to_role($level);
    713             update_user_meta( $user->ID, $wpdb->prefix . 'capabilities', array($role => true) );
    714         }
    715 
    716     endforeach;
    717     $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' );
    718     $wpdb->hide_errors();
    719     foreach ( $old_user_fields as $old )
    720         $wpdb->query("ALTER TABLE $wpdb->users DROP $old");
    721     $wpdb->show_errors();
    722 
    723     // Populate comment_count field of posts table.
    724     $comments = $wpdb->get_results( "SELECT comment_post_ID, COUNT(*) as c FROM $wpdb->comments WHERE comment_approved = '1' GROUP BY comment_post_ID" );
    725     if ( is_array( $comments ) )
    726         foreach ($comments as $comment)
    727             $wpdb->update( $wpdb->posts, array('comment_count' => $comment->c), array('ID' => $comment->comment_post_ID) );
    728 
    729     /*
    730      * Some alpha versions used a post status of object instead of attachment
    731      * and put the mime type in post_type instead of post_mime_type.
    732      */
    733     if ( $wp_current_db_version > 2541 && $wp_current_db_version <= 3091 ) {
    734         $objects = $wpdb->get_results("SELECT ID, post_type FROM $wpdb->posts WHERE post_status = 'object'");
    735         foreach ($objects as $object) {
    736             $wpdb->update( $wpdb->posts, array( 'post_status' => 'attachment',
    737                                                 'post_mime_type' => $object->post_type,
    738                                                 'post_type' => ''),
    739                                          array( 'ID' => $object->ID ) );
    740 
    741             $meta = get_post_meta($object->ID, 'imagedata', true);
    742             if ( ! empty($meta['file']) )
    743                 update_attached_file( $object->ID, $meta['file'] );
    744         }
    745     }
    746 }
    747 
    748 /**
    749  * Execute changes made in WordPress 2.1.
    750  *
    751  * @since 2.1.0
    752  */
    753 function upgrade_210() {
    754     global $wpdb, $wp_current_db_version;
    755 
    756     if ( $wp_current_db_version < 3506 ) {
    757         // Update status and type.
    758         $posts = $wpdb->get_results("SELECT ID, post_status FROM $wpdb->posts");
    759 
    760         if ( ! empty($posts) ) foreach ($posts as $post) {
    761             $status = $post->post_status;
    762             $type = 'post';
    763 
    764             if ( 'static' == $status ) {
    765                 $status = 'publish';
    766                 $type = 'page';
    767             } else if ( 'attachment' == $status ) {
    768                 $status = 'inherit';
    769                 $type = 'attachment';
    770             }
    771 
    772             $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_status = %s, post_type = %s WHERE ID = %d", $status, $type, $post->ID) );
    773         }
    774     }
    775 
    776     if ( $wp_current_db_version < 3845 ) {
    777         populate_roles_210();
    778     }
    779 
    780     if ( $wp_current_db_version < 3531 ) {
    781         // Give future posts a post_status of future.
    782         $now = gmdate('Y-m-d H:i:59');
    783         $wpdb->query ("UPDATE $wpdb->posts SET post_status = 'future' WHERE post_status = 'publish' AND post_date_gmt > '$now'");
    784 
    785         $posts = $wpdb->get_results("SELECT ID, post_date FROM $wpdb->posts WHERE post_status ='future'");
    786         if ( !empty($posts) )
    787             foreach ( $posts as $post )
    788                 wp_schedule_single_event(mysql2date('U', $post->post_date, false), 'publish_future_post', array($post->ID));
    789     }
    790 }
    791 
    792 /**
    793  * Execute changes made in WordPress 2.3.
    794  *
    795  * @since 2.3.0
    796  */
    797 function upgrade_230() {
    798     global $wp_current_db_version, $wpdb;
    799 
    800     if ( $wp_current_db_version < 5200 ) {
    801         populate_roles_230();
    802     }
    803 
    804     // Convert categories to terms.
    805     $tt_ids = array();
    806     $have_tags = false;
    807     $categories = $wpdb->get_results("SELECT * FROM $wpdb->categories ORDER BY cat_ID");
    808     foreach ($categories as $category) {
    809         $term_id = (int) $category->cat_ID;
    810         $name = $category->cat_name;
    811         $description = $category->category_description;
    812         $slug = $category->category_nicename;
    813         $parent = $category->category_parent;
    814         $term_group = 0;
    815 
    816         // Associate terms with the same slug in a term group and make slugs unique.
    817         if ( $exists = $wpdb->get_results( $wpdb->prepare("SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $slug) ) ) {
    818             $term_group = $exists[0]->term_group;
    819             $id = $exists[0]->term_id;
    820             $num = 2;
    821             do {
    822                 $alt_slug = $slug . "-$num";
    823                 $num++;
    824                 $slug_check = $wpdb->get_var( $wpdb->prepare("SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug) );
    825             } while ( $slug_check );
    826 
    827             $slug = $alt_slug;
    828 
    829             if ( empty( $term_group ) ) {
    830                 $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms GROUP BY term_group") + 1;
    831                 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->terms SET term_group = %d WHERE term_id = %d", $term_group, $id) );
    832             }
    833         }
    834 
    835         $wpdb->query( $wpdb->prepare("INSERT INTO $wpdb->terms (term_id, name, slug, term_group) VALUES
    836         (%d, %s, %s, %d)", $term_id, $name, $slug, $term_group) );
    837 
    838         $count = 0;
    839         if ( !empty($category->category_count) ) {
    840             $count = (int) $category->category_count;
    841             $taxonomy = 'category';
    842             $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) );
    843             $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
    844         }
    845 
    846         if ( !empty($category->link_count) ) {
    847             $count = (int) $category->link_count;
    848             $taxonomy = 'link_category';
    849             $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) );
    850             $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
    851         }
    852 
    853         if ( !empty($category->tag_count) ) {
    854             $have_tags = true;
    855             $count = (int) $category->tag_count;
    856             $taxonomy = 'post_tag';
    857             $wpdb->insert( $wpdb->term_taxonomy, compact('term_id', 'taxonomy', 'description', 'parent', 'count') );
    858             $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
    859         }
    860 
    861         if ( empty($count) ) {
    862             $count = 0;
    863             $taxonomy = 'category';
    864             $wpdb->insert( $wpdb->term_taxonomy, compact('term_id', 'taxonomy', 'description', 'parent', 'count') );
    865             $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id;
    866         }
    867     }
    868 
    869     $select = 'post_id, category_id';
    870     if ( $have_tags )
    871         $select .= ', rel_type';
    872 
    873     $posts = $wpdb->get_results("SELECT $select FROM $wpdb->post2cat GROUP BY post_id, category_id");
    874     foreach ( $posts as $post ) {
    875         $post_id = (int) $post->post_id;
    876         $term_id = (int) $post->category_id;
    877         $taxonomy = 'category';
    878         if ( !empty($post->rel_type) && 'tag' == $post->rel_type)
    879             $taxonomy = 'tag';
    880         $tt_id = $tt_ids[$term_id][$taxonomy];
    881         if ( empty($tt_id) )
    882             continue;
    883 
    884         $wpdb->insert( $wpdb->term_relationships, array('object_id' => $post_id, 'term_taxonomy_id' => $tt_id) );
    885     }
    886 
    887     // < 3570 we used linkcategories. >= 3570 we used categories and link2cat.
    888     if ( $wp_current_db_version < 3570 ) {
    889         /*
    890          * Create link_category terms for link categories. Create a map of link
    891          * cat IDs to link_category terms.
    892          */
    893         $link_cat_id_map = array();
    894         $default_link_cat = 0;
    895         $tt_ids = array();
    896         $link_cats = $wpdb->get_results("SELECT cat_id, cat_name FROM " . $wpdb->prefix . 'linkcategories');
    897         foreach ( $link_cats as $category) {
    898             $cat_id = (int) $category->cat_id;
    899             $term_id = 0;
    900             $name = wp_slash($category->cat_name);
    901             $slug = sanitize_title($name);
    902             $term_group = 0;
    903 
    904             // Associate terms with the same slug in a term group and make slugs unique.
    905             if ( $exists = $wpdb->get_results( $wpdb->prepare("SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $slug) ) ) {
    906                 $term_group = $exists[0]->term_group;
    907                 $term_id = $exists[0]->term_id;
    908             }
    909 
    910             if ( empty($term_id) ) {
    911                 $wpdb->insert( $wpdb->terms, compact('name', 'slug', 'term_group') );
    912                 $term_id = (int) $wpdb->insert_id;
    913             }
    914 
    915             $link_cat_id_map[$cat_id] = $term_id;
    916             $default_link_cat = $term_id;
    917 
    918             $wpdb->insert( $wpdb->term_taxonomy, array('term_id' => $term_id, 'taxonomy' => 'link_category', 'description' => '', 'parent' => 0, 'count' => 0) );
    919             $tt_ids[$term_id] = (int) $wpdb->insert_id;
    920         }
    921 
    922         // Associate links to cats.
    923         $links = $wpdb->get_results("SELECT link_id, link_category FROM $wpdb->links");
    924         if ( !empty($links) ) foreach ( $links as $link ) {
    925             if ( 0 == $link->link_category )
    926                 continue;
    927             if ( ! isset($link_cat_id_map[$link->link_category]) )
    928                 continue;
    929             $term_id = $link_cat_id_map[$link->link_category];
    930             $tt_id = $tt_ids[$term_id];
    931             if ( empty($tt_id) )
    932                 continue;
    933 
    934             $wpdb->insert( $wpdb->term_relationships, array('object_id' => $link->link_id, 'term_taxonomy_id' => $tt_id) );
    935         }
    936 
    937         // Set default to the last category we grabbed during the upgrade loop.
    938         update_option('default_link_category', $default_link_cat);
    939     } else {
    940         $links = $wpdb->get_results("SELECT link_id, category_id FROM $wpdb->link2cat GROUP BY link_id, category_id");
    941         foreach ( $links as $link ) {
    942             $link_id = (int) $link->link_id;
    943             $term_id = (int) $link->category_id;
    944             $taxonomy = 'link_category';
    945             $tt_id = $tt_ids[$term_id][$taxonomy];
    946             if ( empty($tt_id) )
    947                 continue;
    948             $wpdb->insert( $wpdb->term_relationships, array('object_id' => $link_id, 'term_taxonomy_id' => $tt_id) );
    949         }
    950     }
    951 
    952     if ( $wp_current_db_version < 4772 ) {
    953         // Obsolete linkcategories table
    954         $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'linkcategories');
    955     }
    956 
    957     // Recalculate all counts
    958     $terms = $wpdb->get_results("SELECT term_taxonomy_id, taxonomy FROM $wpdb->term_taxonomy");
    959     foreach ( (array) $terms as $term ) {
    960         if ( ('post_tag' == $term->taxonomy) || ('category' == $term->taxonomy) )
    961             $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) );
    962         else
    963             $count = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term->term_taxonomy_id) );
    964         $wpdb->update( $wpdb->term_taxonomy, array('count' => $count), array('term_taxonomy_id' => $term->term_taxonomy_id) );
    965     }
    966 }
    967 
    968 /**
    969  * Remove old options from the database.
    970  *
    971  * @since 2.3.0
    972  */
    973 function upgrade_230_options_table() {
    974     global $wpdb;
    975     $old_options_fields = array( 'option_can_override', 'option_type', 'option_width', 'option_height', 'option_description', 'option_admin_level' );
    976     $wpdb->hide_errors();
    977     foreach ( $old_options_fields as $old )
    978         $wpdb->query("ALTER TABLE $wpdb->options DROP $old");
    979     $wpdb->show_errors();
    980 }
    981 
    982 /**
    983  * Remove old categories, link2cat, and post2cat database tables.
    984  *
    985  * @since 2.3.0
    986  */
    987 function upgrade_230_old_tables() {
    988     global $wpdb;
    989     $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'categories');
    990     $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'link2cat');
    991     $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'post2cat');
    992 }
    993 
    994 /**
    995  * Upgrade old slugs made in version 2.2.
    996  *
    997  * @since 2.2.0
    998  */
    999 function upgrade_old_slugs() {
    1000     // Upgrade people who were using the Redirect Old Slugs plugin.
    1001     global $wpdb;
    1002     $wpdb->query("UPDATE $wpdb->postmeta SET meta_key = '_wp_old_slug' WHERE meta_key = 'old_slug'");
    1003 }
    1004 
    1005 /**
    1006  * Execute changes made in WordPress 2.5.0.
    1007  *
    1008  * @since 2.5.0
    1009  */
    1010 function upgrade_250() {
    1011     global $wp_current_db_version;
    1012 
    1013     if ( $wp_current_db_version < 6689 ) {
    1014         populate_roles_250();
    1015     }
    1016 
    1017 }
    1018 
    1019 /**
    1020  * Execute changes made in WordPress 2.5.2.
    1021  *
    1022  * @since 2.5.2
    1023  */
    1024 function upgrade_252() {
    1025     global $wpdb;
    1026 
    1027     $wpdb->query("UPDATE $wpdb->users SET user_activation_key = ''");
    1028 }
    1029 
    1030 /**
    1031  * Execute changes made in WordPress 2.6.
    1032  *
    1033  * @since 2.6.0
    1034  */
    1035 function upgrade_260() {
    1036     global $wp_current_db_version;
    1037 
    1038     if ( $wp_current_db_version < 8000 )
    1039         populate_roles_260();
    1040 }
    1041 
    1042 /**
    1043  * Execute changes made in WordPress 2.7.
    1044  *
    1045  * @since 2.7.0
    1046  */
    1047 function upgrade_270() {
    1048     global $wpdb, $wp_current_db_version;
    1049 
    1050     if ( $wp_current_db_version < 8980 )
    1051         populate_roles_270();
    1052 
    1053     // Update post_date for unpublished posts with empty timestamp
    1054     if ( $wp_current_db_version < 8921 )
    1055         $wpdb->query( "UPDATE $wpdb->posts SET post_date = post_modified WHERE post_date = '0000-00-00 00:00:00'" );
    1056 }
    1057 
    1058 /**
    1059  * Execute changes made in WordPress 2.8.
    1060  *
    1061  * @since 2.8.0
    1062  */
    1063 function upgrade_280() {
    1064     global $wp_current_db_version, $wpdb;
    1065 
    1066     if ( $wp_current_db_version < 10360 )
    1067         populate_roles_280();
    1068     if ( is_multisite() ) {
    1069         $start = 0;
    1070         while( $rows = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options ORDER BY option_id LIMIT $start, 20" ) ) {
    1071             foreach( $rows as $row ) {
    1072                 $value = $row->option_value;
    1073                 if ( !@unserialize( $value ) )
    1074                     $value = stripslashes( $value );
    1075                 if ( $value !== $row->option_value ) {
    1076                     update_option( $row->option_name, $value );
    1077                 }
    1078             }
    1079             $start += 20;
    1080         }
    1081         refresh_blog_details( $wpdb->blogid );
    1082     }
    1083 }
    1084 
    1085 /**
    1086  * Execute changes made in WordPress 2.9.
    1087  *
    1088  * @since 2.9.0
    1089  */
    1090 function upgrade_290() {
    1091     global $wp_current_db_version;
    1092 
    1093     if ( $wp_current_db_version < 11958 ) {
    1094         // Previously, setting depth to 1 would redundantly disable threading, but now 2 is the minimum depth to avoid confusion
    1095         if ( get_option( 'thread_comments_depth' ) == '1' ) {
    1096             update_option( 'thread_comments_depth', 2 );
    1097             update_option( 'thread_comments', 0 );
    1098         }
    1099     }
    1100 }
    1101 
    1102 /**
    1103  * Execute changes made in WordPress 3.0.
    1104  *
    1105  * @since 3.0.0
    1106  */
    1107 function upgrade_300() {
    1108     global $wp_current_db_version, $wpdb;
    1109 
    1110     if ( $wp_current_db_version < 15093 )
    1111         populate_roles_300();
    1112 
    1113     if ( $wp_current_db_version < 14139 && is_multisite() && is_main_site() && ! defined( 'MULTISITE' ) && get_site_option( 'siteurl' ) === false )
    1114         add_site_option( 'siteurl', '' );
    1115 
    1116     // 3.0 screen options key name changes.
    1117     if ( is_main_site() && !defined('DO_NOT_UPGRADE_GLOBAL_TABLES') ) {
    1118         $sql = "DELETE FROM $wpdb->usermeta
    1119             WHERE meta_key LIKE %s
    1120             OR meta_key LIKE %s
    1121             OR meta_key LIKE %s
    1122             OR meta_key LIKE %s
    1123             OR meta_key LIKE %s
    1124             OR meta_key LIKE %s
    1125             OR meta_key = 'manageedittagscolumnshidden'
    1126             OR meta_key = 'managecategoriescolumnshidden'
    1127             OR meta_key = 'manageedit-tagscolumnshidden'
    1128             OR meta_key = 'manageeditcolumnshidden'
    1129             OR meta_key = 'categories_per_page'
    1130             OR meta_key = 'edit_tags_per_page'";
    1131         $prefix = $wpdb->esc_like( $wpdb->base_prefix );
    1132         $wpdb->query( $wpdb->prepare( $sql,
    1133             $prefix . '%' . $wpdb->esc_like( 'meta-box-hidden' ) . '%',
    1134             $prefix . '%' . $wpdb->esc_like( 'closedpostboxes' ) . '%',
    1135             $prefix . '%' . $wpdb->esc_like( 'manage-'     ) . '%' . $wpdb->esc_like( '-columns-hidden' ) . '%',
    1136             $prefix . '%' . $wpdb->esc_like( 'meta-box-order'  ) . '%',
    1137             $prefix . '%' . $wpdb->esc_like( 'metaboxorder'    ) . '%',
    1138             $prefix . '%' . $wpdb->esc_like( 'screen_layout'   ) . '%'
    1139         ) );
    1140     }
    1141 
    1142 }
    1143 
    1144 /**
    1145  * Execute changes made in WordPress 3.3.
    1146  *
    1147  * @since 3.3.0
    1148  */
    1149 function upgrade_330() {
    1150     global $wp_current_db_version, $wpdb, $wp_registered_widgets, $sidebars_widgets;
    1151 
    1152     if ( $wp_current_db_version < 19061 && is_main_site() && ! defined( 'DO_NOT_UPGRADE_GLOBAL_TABLES' ) ) {
    1153         $wpdb->query( "DELETE FROM $wpdb->usermeta WHERE meta_key IN ('show_admin_bar_admin', 'plugins_last_view')" );
    1154     }
    1155 
    1156     if ( $wp_current_db_version >= 11548 )
    1157         return;
    1158 
    1159     $sidebars_widgets = get_option( 'sidebars_widgets', array() );
    1160     $_sidebars_widgets = array();
    1161 
    1162     if ( isset($sidebars_widgets['wp_inactive_widgets']) || empty($sidebars_widgets) )
    1163         $sidebars_widgets['array_version'] = 3;
    1164     elseif ( !isset($sidebars_widgets['array_version']) )
    1165         $sidebars_widgets['array_version'] = 1;
    1166 
    1167     switch ( $sidebars_widgets['array_version'] ) {
    1168         case 1 :
    1169             foreach ( (array) $sidebars_widgets as $index => $sidebar )
    1170             if ( is_array($sidebar) )
    1171             foreach ( (array) $sidebar as $i => $name ) {
    1172                 $id = strtolower($name);
    1173                 if ( isset($wp_registered_widgets[$id]) ) {
    1174                     $_sidebars_widgets[$index][$i] = $id;
    1175                     continue;
    1176                 }
    1177                 $id = sanitize_title($name);
    1178                 if ( isset($wp_registered_widgets[$id]) ) {
    1179                     $_sidebars_widgets[$index][$i] = $id;
    1180                     continue;
    1181                 }
    1182 
    1183                 $found = false;
    1184 
    1185                 foreach ( $wp_registered_widgets as $widget_id => $widget ) {
    1186                     if ( strtolower($widget['name']) == strtolower($name) ) {
    1187                         $_sidebars_widgets[$index][$i] = $widget['id'];
    1188                         $found = true;
    1189                         break;
    1190                     } elseif ( sanitize_title($widget['name']) == sanitize_title($name) ) {
    1191                         $_sidebars_widgets[$index][$i] = $widget['id'];
    1192                         $found = true;
    1193                         break;
    1194                     }
    1195                 }
    1196 
    1197                 if ( $found )
    1198                     continue;
    1199 
    1200                 unset($_sidebars_widgets[$index][$i]);
    1201             }
    1202             $_sidebars_widgets['array_version'] = 2;
    1203             $sidebars_widgets = $_sidebars_widgets;
    1204             unset($_sidebars_widgets);
    1205 
    1206         case 2 :
    1207             $sidebars_widgets = retrieve_widgets();
    1208             $sidebars_widgets['array_version'] = 3;
    1209             update_option( 'sidebars_widgets', $sidebars_widgets );
    1210     }
    1211 }
    1212 
    1213 /**
    1214  * Execute changes made in WordPress 3.4.
    1215  *
    1216  * @since 3.4.0
    1217  */
    1218 function upgrade_340() {
    1219     global $wp_current_db_version, $wpdb;
    1220 
    1221     if ( $wp_current_db_version < 19798 ) {
    1222         $wpdb->hide_errors();
    1223         $wpdb->query( "ALTER TABLE $wpdb->options DROP COLUMN blog_id" );
    1224         $wpdb->show_errors();
    1225     }
    1226 
    1227     if ( $wp_current_db_version < 19799 ) {
    1228         $wpdb->hide_errors();
    1229         $wpdb->query("ALTER TABLE $wpdb->comments DROP INDEX comment_approved");
    1230         $wpdb->show_errors();
    1231     }
    1232 
    1233     if ( $wp_current_db_version < 20022 && is_main_site() && ! defined( 'DO_NOT_UPGRADE_GLOBAL_TABLES' ) ) {
    1234         $wpdb->query( "DELETE FROM $wpdb->usermeta WHERE meta_key = 'themes_last_view'" );
    1235     }
    1236 
    1237     if ( $wp_current_db_version < 20080 ) {
    1238         if ( 'yes' == $wpdb->get_var( "SELECT autoload FROM $wpdb->options WHERE option_name = 'uninstall_plugins'" ) ) {
    1239             $uninstall_plugins = get_option( 'uninstall_plugins' );
    1240             delete_option( 'uninstall_plugins' );
    1241             add_option( 'uninstall_plugins', $uninstall_plugins, null, 'no' );
    1242         }
    1243     }
    1244 }
    1245 
    1246 /**
    1247  * Execute changes made in WordPress 3.5.
    1248  *
    1249  * @since 3.5.0
    1250  */
    1251 function upgrade_350() {
    1252     global $wp_current_db_version, $wpdb;
    1253 
    1254     if ( $wp_current_db_version < 22006 && $wpdb->get_var( "SELECT link_id FROM $wpdb->links LIMIT 1" ) )
    1255         update_option( 'link_manager_enabled', 1 ); // Previously set to 0 by populate_options()
    1256 
    1257     if ( $wp_current_db_version < 21811 && is_main_site() && ! defined( 'DO_NOT_UPGRADE_GLOBAL_TABLES' ) ) {
    1258         $meta_keys = array();
    1259         foreach ( array_merge( get_post_types(), get_taxonomies() ) as $name ) {
    1260             if ( false !== strpos( $name, '-' ) )
    1261             $meta_keys[] = 'edit_' . str_replace( '-', '_', $name ) . '_per_page';
    1262         }
    1263         if ( $meta_keys ) {
    1264             $meta_keys = implode( "', '", $meta_keys );
    1265             $wpdb->query( "DELETE FROM $wpdb->usermeta WHERE meta_key IN ('$meta_keys')" );
    1266         }
    1267     }
    1268 
    1269     if ( $wp_current_db_version < 22422 && $term = get_term_by( 'slug', 'post-format-standard', 'post_format' ) )
    1270         wp_delete_term( $term->term_id, 'post_format' );
    1271 }
    1272 
    1273 /**
    1274  * Execute changes made in WordPress 3.7.
    1275  *
    1276  * @since 3.7.0
    1277  */
    1278 function upgrade_370() {
    1279     global $wp_current_db_version;
    1280     if ( $wp_current_db_version < 25824 )
    1281         wp_clear_scheduled_hook( 'wp_auto_updates_maybe_update' );
    1282 }
    1283 
    1284 /**
    1285  * Execute changes made in WordPress 3.7.2.
    1286  *
    1287  * @since 3.7.2
    1288  * @since 3.8.0
    1289  */
    1290 function upgrade_372() {
    1291     global $wp_current_db_version;
    1292     if ( $wp_current_db_version < 26148 )
    1293         wp_clear_scheduled_hook( 'wp_maybe_auto_update' );
    1294 }
    1295 
    1296 /**
    1297  * Execute changes made in WordPress 3.8.0.
    1298  *
    1299  * @since 3.8.0
    1300  */
    1301 function upgrade_380() {
    1302     global $wp_current_db_version;
    1303     if ( $wp_current_db_version < 26691 ) {
    1304         deactivate_plugins( array( 'mp6/mp6.php' ), true );
    1305     }
    1306 }
    1307 /**
    1308  * Execute network level changes
    1309  *
    1310  * @since 3.0.0
    1311  */
    1312 function upgrade_network() {
    1313     global $wp_current_db_version, $wpdb;
    1314 
    1315     // Always.
    1316     if ( is_main_network() ) {
    1317         /*
    1318          * Deletes all expired transients. The multi-table delete syntax is used
    1319          * to delete the transient record from table a, and the corresponding
    1320          * transient_timeout record from table b.
    1321          */
    1322         $time = time();
    1323         $sql = "DELETE a, b FROM $wpdb->sitemeta a, $wpdb->sitemeta b
    1324             WHERE a.meta_key LIKE %s
    1325             AND a.meta_key NOT LIKE %s
    1326             AND b.meta_key = CONCAT( '_site_transient_timeout_', SUBSTRING( a.meta_key, 17 ) )
    1327             AND b.meta_value < %d";
    1328         $wpdb->query( $wpdb->prepare( $sql, $wpdb->esc_like( '_site_transient_' ) . '%', $wpdb->esc_like ( '_site_transient_timeout_' ) . '%', $time ) );
    1329     }
    1330 
    1331     // 2.8.
    1332     if ( $wp_current_db_version < 11549 ) {
    1333         $wpmu_sitewide_plugins = get_site_option( 'wpmu_sitewide_plugins' );
    1334         $active_sitewide_plugins = get_site_option( 'active_sitewide_plugins' );
    1335         if ( $wpmu_sitewide_plugins ) {
    1336             if ( !$active_sitewide_plugins )
    1337                 $sitewide_plugins = (array) $wpmu_sitewide_plugins;
    1338             else
    1339                 $sitewide_plugins = array_merge( (array) $active_sitewide_plugins, (array) $wpmu_sitewide_plugins );
    1340 
    1341             update_site_option( 'active_sitewide_plugins', $sitewide_plugins );
    1342         }
    1343         delete_site_option( 'wpmu_sitewide_plugins' );
    1344         delete_site_option( 'deactivated_sitewide_plugins' );
    1345 
    1346         $start = 0;
    1347         while( $rows = $wpdb->get_results( "SELECT meta_key, meta_value FROM {$wpdb->sitemeta} ORDER BY meta_id LIMIT $start, 20" ) ) {
    1348             foreach( $rows as $row ) {
    1349                 $value = $row->meta_value;
    1350                 if ( !@unserialize( $value ) )
    1351                     $value = stripslashes( $value );
    1352                 if ( $value !== $row->meta_value ) {
    1353                     update_site_option( $row->meta_key, $value );
    1354                 }
    1355             }
    1356             $start += 20;
    1357         }
    1358     }
    1359 
    1360     // 3.0
    1361     if ( $wp_current_db_version < 13576 )
    1362         update_site_option( 'global_terms_enabled', '1' );
    1363 
    1364     // 3.3
    1365     if ( $wp_current_db_version < 19390 )
    1366         update_site_option( 'initial_db_version', $wp_current_db_version );
    1367 
    1368     if ( $wp_current_db_version < 19470 ) {
    1369         if ( false === get_site_option( 'active_sitewide_plugins' ) )
    1370             update_site_option( 'active_sitewide_plugins', array() );
    1371     }
    1372 
    1373     // 3.4
    1374     if ( $wp_current_db_version < 20148 ) {
    1375         // 'allowedthemes' keys things by stylesheet. 'allowed_themes' keyed things by name.
    1376         $allowedthemes  = get_site_option( 'allowedthemes'  );
    1377         $allowed_themes = get_site_option( 'allowed_themes' );
    1378         if ( false === $allowedthemes && is_array( $allowed_themes ) && $allowed_themes ) {
    1379             $converted = array();
    1380             $themes = wp_get_themes();
    1381             foreach ( $themes as $stylesheet => $theme_data ) {
    1382                 if ( isset( $allowed_themes[ $theme_data->get('Name') ] ) )
    1383                     $converted[ $stylesheet ] = true;
    1384             }
    1385             update_site_option( 'allowedthemes', $converted );
    1386             delete_site_option( 'allowed_themes' );
    1387         }
    1388     }
    1389 
    1390     // 3.5
    1391     if ( $wp_current_db_version < 21823 )
    1392         update_site_option( 'ms_files_rewriting', '1' );
    1393 
    1394     // 3.5.2
    1395     if ( $wp_current_db_version < 24448 ) {
    1396         $illegal_names = get_site_option( 'illegal_names' );
    1397         if ( is_array( $illegal_names ) && count( $illegal_names ) === 1 ) {
    1398             $illegal_name = reset( $illegal_names );
    1399             $illegal_names = explode( ' ', $illegal_name );
    1400             update_site_option( 'illegal_names', $illegal_names );
    1401         }
    1402     }
    1403 }
    1404 
    1405 // The functions we use to actually do stuff
    1406 
    1407 // General
    1408 
    1409 /**
    1410  * {@internal Missing Short Description}}
    1411  *
    1412  * {@internal Missing Long Description}}
    1413  *
    1414  * @since 1.0.0
    1415  *
    1416  * @param string $table_name Database table name to create.
    1417  * @param string $create_ddl SQL statement to create table.
    1418  * @return bool If table already exists or was created by function.
    1419  */
    1420 function maybe_create_table($table_name, $create_ddl) {
    1421     global $wpdb;
    1422    
    1423     $query = $wpdb->prepare( "SHOW TABLES LIKE %s", $wpdb->esc_like( $table_name ) );
    1424 
    1425     if ( $wpdb->get_var( $query ) == $table_name ) {
    1426         return true;
    1427     }
    1428 
    1429     // Didn't find it try to create it..
    1430     $wpdb->query($create_ddl);
    1431 
    1432     // We cannot directly tell that whether this succeeded!
    1433     if ( $wpdb->get_var( $query ) == $table_name ) {
    1434         return true;
    1435     }
    1436     return false;
    1437 }
    1438 
    1439 /**
    1440  * {@internal Missing Short Description}}
    1441  *
    1442  * {@internal Missing Long Description}}
    1443  *
    1444  * @since 1.0.1
    1445  *
    1446  * @param string $table Database table name.
    1447  * @param string $index Index name to drop.
    1448  * @return bool True, when finished.
    1449  */
    1450 function drop_index($table, $index) {
    1451     global $wpdb;
    1452     $wpdb->hide_errors();
    1453     $wpdb->query("ALTER TABLE `$table` DROP INDEX `$index`");
    1454     // Now we need to take out all the extra ones we may have created
    1455     for ($i = 0; $i < 25; $i++) {
    1456         $wpdb->query("ALTER TABLE `$table` DROP INDEX `{$index}_$i`");
    1457     }
    1458     $wpdb->show_errors();
    1459     return true;
    1460 }
    1461 
    1462 /**
    1463  * {@internal Missing Short Description}}
    1464  *
    1465  * {@internal Missing Long Description}}
    1466  *
    1467  * @since 1.0.1
    1468  *
    1469  * @param string $table Database table name.
    1470  * @param string $index Database table index column.
    1471  * @return bool True, when done with execution.
    1472  */
    1473 function add_clean_index($table, $index) {
    1474     global $wpdb;
    1475     drop_index($table, $index);
    1476     $wpdb->query("ALTER TABLE `$table` ADD INDEX ( `$index` )");
    1477     return true;
    1478 }
    1479 
    1480 /**
    1481  ** maybe_add_column()
    1482  ** Add column to db table if it doesn't exist.
    1483  ** Returns:  true if already exists or on successful completion
    1484  **           false on error
    1485  */
    1486 function maybe_add_column($table_name, $column_name, $create_ddl) {
    1487     global $wpdb;
    1488     foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) {
    1489         if ($column == $column_name) {
    1490             return true;
    1491         }
    1492     }
    1493 
    1494     // Didn't find it try to create it.
    1495     $wpdb->query($create_ddl);
    1496 
    1497     // We cannot directly tell that whether this succeeded!
    1498     foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) {
    1499         if ($column == $column_name) {
    1500             return true;
    1501         }
    1502     }
    1503     return false;
    1504 }
    1505 
    1506 /**
    1507  * Retrieve all options as it was for 1.2.
    1508  *
    1509  * @since 1.2.0
    1510  *
    1511  * @return array List of options.
    1512  */
    1513 function get_alloptions_110() {
    1514     global $wpdb;
    1515     $all_options = new stdClass;
    1516     if ( $options = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options" ) ) {
    1517         foreach ( $options as $option ) {
    1518             if ( 'siteurl' == $option->option_name || 'home' == $option->option_name || 'category_base' == $option->option_name )
    1519                 $option->option_value = untrailingslashit( $option->option_value );
    1520             $all_options->{$option->option_name} = stripslashes( $option->option_value );
    1521         }
    1522     }
    1523     return $all_options;
    1524 }
    1525 
    1526 /**
    1527  * Version of get_option that is private to install/upgrade.
    1528  *
    1529  * @since 1.5.1
    1530  * @access private
    1531  *
    1532  * @param string $setting Option name.
    1533  * @return mixed
    1534  */
    1535 function __get_option($setting) {
    1536     global $wpdb;
    1537 
    1538     if ( $setting == 'home' && defined( 'WP_HOME' ) )
    1539         return untrailingslashit( WP_HOME );
    1540 
    1541     if ( $setting == 'siteurl' && defined( 'WP_SITEURL' ) )
    1542         return untrailingslashit( WP_SITEURL );
    1543 
    1544     $option = $wpdb->get_var( $wpdb->prepare("SELECT option_value FROM $wpdb->options WHERE option_name = %s", $setting ) );
    1545 
    1546     if ( 'home' == $setting && '' == $option )
    1547         return __get_option( 'siteurl' );
    1548 
    1549     if ( 'siteurl' == $setting || 'home' == $setting || 'category_base' == $setting || 'tag_base' == $setting )
    1550         $option = untrailingslashit( $option );
    1551 
    1552     return maybe_unserialize( $option );
    1553 }
    1554 
    1555 /**
    1556  * {@internal Missing Short Description}}
    1557  *
    1558  * {@internal Missing Long Description}}
    1559  *
    1560  * @since 1.5.0
    1561  *
    1562  * @param string $content
    1563  * @return string
    1564  */
    1565 function deslash($content) {
    1566     // Note: \\\ inside a regex denotes a single backslash.
    1567 
    1568     /*
    1569      * Replace one or more backslashes followed by a single quote with
    1570      * a single quote.
    1571      */
    1572     $content = preg_replace("/\\\+'/", "'", $content);
    1573 
    1574     /*
    1575      * Replace one or more backslashes followed by a double quote with
    1576      * a double quote.
    1577      */
    1578     $content = preg_replace('/\\\+"/', '"', $content);
    1579 
    1580     // Replace one or more backslashes with one backslash.
    1581     $content = preg_replace("/\\\+/", "\\", $content);
    1582 
    1583     return $content;
    1584 }
    1585 
    1586 /**
    1587  * {@internal Missing Short Description}}
    1588  *
    1589  * {@internal Missing Long Description}}
    1590  *
    1591  * @since 1.5.0
    1592  *
    1593  * @param unknown_type $queries
    1594  * @param unknown_type $execute
    1595  * @return unknown
    1596  */
    1597 function dbDelta( $queries = '', $execute = true ) {
    1598     global $wpdb;
    1599 
    1600     if ( in_array( $queries, array( '', 'all', 'blog', 'global', 'ms_global' ), true ) )
    1601         $queries = wp_get_db_schema( $queries );
    1602 
    1603     // Separate individual queries into an array
    1604     if ( !is_array($queries) ) {
    1605         $queries = explode( ';', $queries );
    1606         $queries = array_filter( $queries );
    1607     }
    1608 
    1609     /**
    1610      * Filter the dbDelta SQL queries.
    1611      *
    1612      * @since 3.3.0
    1613      *
    1614      * @param array $queries An array of dbDelta SQL queries.
    1615      */
    1616     $queries = apply_filters( 'dbdelta_queries', $queries );
    1617 
    1618     $cqueries = array(); // Creation Queries
    1619     $iqueries = array(); // Insertion Queries
    1620     $for_update = array();
    1621 
    1622     // Create a tablename index for an array ($cqueries) of queries
    1623     foreach($queries as $qry) {
    1624         if (preg_match("|CREATE TABLE ([^ ]*)|", $qry, $matches)) {
    1625             $cqueries[ trim( $matches[1], '`' ) ] = $qry;
    1626             $for_update[$matches[1]] = 'Created table '.$matches[1];
    1627         } else if (preg_match("|CREATE DATABASE ([^ ]*)|", $qry, $matches)) {
    1628             array_unshift($cqueries, $qry);
    1629         } else if (preg_match("|INSERT INTO ([^ ]*)|", $qry, $matches)) {
    1630             $iqueries[] = $qry;
    1631         } else if (preg_match("|UPDATE ([^ ]*)|", $qry, $matches)) {
    1632             $iqueries[] = $qry;
    1633         } else {
    1634             // Unrecognized query type
    1635         }
    1636     }
    1637 
    1638     /**
    1639      * Filter the dbDelta SQL queries for creating tables and/or databases.
    1640      *
    1641      * Queries filterable via this hook contain "CREATE TABLE" or "CREATE DATABASE".
    1642      *
    1643      * @since 3.3.0
    1644      *
    1645      * @param array $cqueries An array of dbDelta create SQL queries.
    1646      */
    1647     $cqueries = apply_filters( 'dbdelta_create_queries', $cqueries );
    1648 
    1649     /**
    1650      * Filter the dbDelta SQL queries for inserting or updating.
    1651      *
    1652      * Queries filterable via this hook contain "INSERT INTO" or "UPDATE".
    1653      *
    1654      * @since 3.3.0
    1655      *
    1656      * @param array $iqueries An array of dbDelta insert or update SQL queries.
    1657      */
    1658     $iqueries = apply_filters( 'dbdelta_insert_queries', $iqueries );
    1659 
    1660     $global_tables = $wpdb->tables( 'global' );
    1661     foreach ( $cqueries as $table => $qry ) {
    1662         // Upgrade global tables only for the main site. Don't upgrade at all if DO_NOT_UPGRADE_GLOBAL_TABLES is defined.
    1663         if ( in_array( $table, $global_tables ) && ( !is_main_site() || defined( 'DO_NOT_UPGRADE_GLOBAL_TABLES' ) ) ) {
    1664             unset( $cqueries[ $table ], $for_update[ $table ] );
    1665             continue;
    1666         }
    1667 
    1668         // Fetch the table column structure from the database
    1669         $suppress = $wpdb->suppress_errors();
    1670         $tablefields = $wpdb->get_results("DESCRIBE {$table};");
    1671         $wpdb->suppress_errors( $suppress );
    1672 
    1673         if ( ! $tablefields )
    1674             continue;
    1675 
    1676         // Clear the field and index arrays.
    1677         $cfields = $indices = array();
    1678 
    1679         // Get all of the field names in the query from between the parentheses.
    1680         preg_match("|\((.*)\)|ms", $qry, $match2);
    1681         $qryline = trim($match2[1]);
    1682 
    1683         // Separate field lines into an array.
    1684         $flds = explode("\n", $qryline);
    1685 
    1686         // todo: Remove this?
    1687         //echo "<hr/><pre>\n".print_r(strtolower($table), true).":\n".print_r($cqueries, true)."</pre><hr/>";
    1688 
    1689         // For every field line specified in the query.
    1690         foreach ($flds as $fld) {
    1691 
    1692             // Extract the field name.
    1693             preg_match("|^([^ ]*)|", trim($fld), $fvals);
    1694             $fieldname = trim( $fvals[1], '`' );
    1695 
    1696             // Verify the found field name.
    1697             $validfield = true;
    1698             switch (strtolower($fieldname)) {
    1699             case '':
    1700             case 'primary':
    1701             case 'index':
    1702             case 'fulltext':
    1703             case 'unique':
    1704             case 'key':
    1705                 $validfield = false;
    1706                 $indices[] = trim(trim($fld), ", \n");
    1707                 break;
    1708             }
    1709             $fld = trim($fld);
    1710 
    1711             // If it's a valid field, add it to the field array.
    1712             if ($validfield) {
    1713                 $cfields[strtolower($fieldname)] = trim($fld, ", \n");
    1714             }
    1715         }
    1716 
    1717         // For every field in the table.
    1718         foreach ($tablefields as $tablefield) {
    1719 
    1720             // If the table field exists in the field array ...
    1721             if (array_key_exists(strtolower($tablefield->Field), $cfields)) {
    1722 
    1723                 // Get the field type from the query.
    1724                 preg_match("|".$tablefield->Field." ([^ ]*( unsigned)?)|i", $cfields[strtolower($tablefield->Field)], $matches);
    1725                 $fieldtype = $matches[1];
    1726 
    1727                 // Is actual field type different from the field type in query?
    1728                 if ($tablefield->Type != $fieldtype) {
    1729                     // Add a query to change the column type
    1730                     $cqueries[] = "ALTER TABLE {$table} CHANGE COLUMN {$tablefield->Field} " . $cfields[strtolower($tablefield->Field)];
    1731                     $for_update[$table.'.'.$tablefield->Field] = "Changed type of {$table}.{$tablefield->Field} from {$tablefield->Type} to {$fieldtype}";
    1732                 }
    1733 
    1734                 // Get the default value from the array
    1735                     // todo: Remove this?
    1736                     //echo "{$cfields[strtolower($tablefield->Field)]}<br>";
    1737                 if (preg_match("| DEFAULT '(.*?)'|i", $cfields[strtolower($tablefield->Field)], $matches)) {
    1738                     $default_value = $matches[1];
    1739                     if ($tablefield->Default != $default_value) {
    1740                         // Add a query to change the column's default value
    1741                         $cqueries[] = "ALTER TABLE {$table} ALTER COLUMN {$tablefield->Field} SET DEFAULT '{$default_value}'";
    1742                         $for_update[$table.'.'.$tablefield->Field] = "Changed default value of {$table}.{$tablefield->Field} from {$tablefield->Default} to {$default_value}";
    1743                     }
    1744                 }
    1745 
    1746                 // Remove the field from the array (so it's not added).
    1747                 unset($cfields[strtolower($tablefield->Field)]);
    1748             } else {
    1749                 // This field exists in the table, but not in the creation queries?
    1750             }
    1751         }
    1752 
    1753         // For every remaining field specified for the table.
    1754         foreach ($cfields as $fieldname => $fielddef) {
    1755             // Push a query line into $cqueries that adds the field to that table.
    1756             $cqueries[] = "ALTER TABLE {$table} ADD COLUMN $fielddef";
    1757             $for_update[$table.'.'.$fieldname] = 'Added column '.$table.'.'.$fieldname;
    1758         }
    1759 
    1760         // Index stuff goes here. Fetch the table index structure from the database.
    1761         $tableindices = $wpdb->get_results("SHOW INDEX FROM {$table};");
    1762 
    1763         if ($tableindices) {
    1764             // Clear the index array.
    1765             unset($index_ary);
    1766 
    1767             // For every index in the table.
    1768             foreach ($tableindices as $tableindex) {
    1769 
    1770                 // Add the index to the index data array.
    1771                 $keyname = $tableindex->Key_name;
    1772                 $index_ary[$keyname]['columns'][] = array('fieldname' => $tableindex->Column_name, 'subpart' => $tableindex->Sub_part);
    1773                 $index_ary[$keyname]['unique'] = ($tableindex->Non_unique == 0)?true:false;
    1774             }
    1775 
    1776             // For each actual index in the index array.
    1777             foreach ($index_ary as $index_name => $index_data) {
    1778 
    1779                 // Build a create string to compare to the query.
    1780                 $index_string = '';
    1781                 if ($index_name == 'PRIMARY') {
    1782                     $index_string .= 'PRIMARY ';
    1783                 } else if($index_data['unique']) {
    1784                     $index_string .= 'UNIQUE ';
    1785                 }
    1786                 $index_string .= 'KEY ';
    1787                 if ($index_name != 'PRIMARY') {
    1788                     $index_string .= $index_name;
    1789                 }
    1790                 $index_columns = '';
    1791 
    1792                 // For each column in the index.
    1793                 foreach ($index_data['columns'] as $column_data) {
    1794                     if ($index_columns != '') $index_columns .= ',';
    1795 
    1796                     // Add the field to the column list string.
    1797                     $index_columns .= $column_data['fieldname'];
    1798                     if ($column_data['subpart'] != '') {
    1799                         $index_columns .= '('.$column_data['subpart'].')';
    1800                     }
    1801                 }
    1802                 // Add the column list to the index create string.
    1803                 $index_string .= ' ('.$index_columns.')';
    1804                 if (!(($aindex = array_search($index_string, $indices)) === false)) {
    1805                     unset($indices[$aindex]);
    1806                     // todo: Remove this?
    1807                     //echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">{$table}:<br />Found index:".$index_string."</pre>\n";
    1808                 }
    1809                 // todo: Remove this?
    1810                 //else echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">{$table}:<br /><b>Did not find index:</b>".$index_string."<br />".print_r($indices, true)."</pre>\n";
    1811             }
    1812         }
    1813 
    1814         // For every remaining index specified for the table.
    1815         foreach ( (array) $indices as $index ) {
    1816             // Push a query line into $cqueries that adds the index to that table.
    1817             $cqueries[] = "ALTER TABLE {$table} ADD $index";
    1818             $for_update[] = 'Added index ' . $table . ' ' . $index;
    1819         }
    1820 
    1821         // Remove the original table creation query from processing.
    1822         unset( $cqueries[ $table ], $for_update[ $table ] );
    1823     }
    1824 
    1825     $allqueries = array_merge($cqueries, $iqueries);
    1826     if ($execute) {
    1827         foreach ($allqueries as $query) {
    1828             // todo: Remove this?
    1829             //echo "<pre style=\"border:1px solid #ccc;margin-top:5px;\">".print_r($query, true)."</pre>\n";
    1830             $wpdb->query($query);
    1831         }
    1832     }
    1833 
    1834     return $for_update;
    1835 }
    1836 
    1837 /**
    1838  * {@internal Missing Short Description}}
    1839  *
    1840  * {@internal Missing Long Description}}
    1841  *
    1842  * @since 1.5.0
    1843  */
    1844 function make_db_current( $tables = 'all' ) {
    1845     $alterations = dbDelta( $tables );
    1846     echo "<ol>\n";
    1847     foreach($alterations as $alteration) echo "<li>$alteration</li>\n";
    1848     echo "</ol>\n";
    1849 }
    1850 
    1851 /**
    1852  * {@internal Missing Short Description}}
    1853  *
    1854  * {@internal Missing Long Description}}
    1855  *
    1856  * @since 1.5.0
    1857  */
    1858 function make_db_current_silent( $tables = 'all' ) {
    1859     dbDelta( $tables );
    1860 }
    1861 
    1862 /**
    1863  * {@internal Missing Short Description}}
    1864  *
    1865  * {@internal Missing Long Description}}
    1866  *
    1867  * @since 1.5.0
    1868  *
    1869  * @param unknown_type $theme_name
    1870  * @param unknown_type $template
    1871  * @return unknown
    1872  */
    1873 function make_site_theme_from_oldschool($theme_name, $template) {
    1874     $home_path = get_home_path();
    1875     $site_dir = WP_CONTENT_DIR . "/themes/$template";
    1876 
    1877     if (! file_exists("$home_path/index.php"))
    1878         return false;
    1879 
    1880     /*
    1881      * Copy files from the old locations to the site theme.
    1882      * TODO: This does not copy arbitrary include dependencies. Only the standard WP files are copied.
    1883      */
    1884     $files = array('index.php' => 'index.php', 'wp-layout.css' => 'style.css', 'wp-comments.php' => 'comments.php', 'wp-comments-popup.php' => 'comments-popup.php');
    1885 
    1886     foreach ($files as $oldfile => $newfile) {
    1887         if ($oldfile == 'index.php')
    1888             $oldpath = $home_path;
    1889         else
    1890             $oldpath = ABSPATH;
    1891 
    1892         // Check to make sure it's not a new index.
    1893         if ($oldfile == 'index.php') {
    1894             $index = implode('', file("$oldpath/$oldfile"));
    1895             if (strpos($index, 'WP_USE_THEMES') !== false) {
    1896                 if (! @copy(WP_CONTENT_DIR . '/themes/' . WP_DEFAULT_THEME . '/index.php', "$site_dir/$newfile"))
    1897                     return false;
    1898 
    1899                 // Don't copy anything.
    1900                 continue;
    1901                 }
    1902         }
    1903 
    1904         if (! @copy("$oldpath/$oldfile", "$site_dir/$newfile"))
    1905             return false;
    1906 
    1907         chmod("$site_dir/$newfile", 0777);
    1908 
    1909         // Update the blog header include in each file.
    1910         $lines = explode("\n", implode('', file("$site_dir/$newfile")));
    1911         if ($lines) {
    1912             $f = fopen("$site_dir/$newfile", 'w');
    1913 
    1914             foreach ($lines as $line) {
    1915                 if (preg_match('/require.*wp-blog-header/', $line))
    1916                     $line = '//' . $line;
    1917 
    1918                 // Update stylesheet references.
    1919                 $line = str_replace("<?php echo __get_option('siteurl'); ?>/wp-layout.css", "<?php bloginfo('stylesheet_url'); ?>", $line);
    1920 
    1921                 // Update comments template inclusion.
    1922                 $line = str_replace("<?php include(ABSPATH . 'wp-comments.php'); ?>", "<?php comments_template(); ?>", $line);
    1923 
    1924                 fwrite($f, "{$line}\n");
    1925             }
    1926             fclose($f);
    1927         }
    1928     }
    1929 
    1930     // Add a theme header.
    1931     $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";
    1932 
    1933     $stylelines = file_get_contents("$site_dir/style.css");
    1934     if ($stylelines) {
    1935         $f = fopen("$site_dir/style.css", 'w');
    1936 
    1937         fwrite($f, $header);
    1938         fwrite($f, $stylelines);
    1939         fclose($f);
    1940     }
    1941 
    1942     return true;
    1943 }
    1944 
    1945 /**
    1946  * {@internal Missing Short Description}}
    1947  *
    1948  * {@internal Missing Long Description}}
    1949  *
    1950  * @since 1.5.0
    1951  *
    1952  * @param unknown_type $theme_name
    1953  * @param unknown_type $template
    1954  * @return unknown
    1955  */
    1956 function make_site_theme_from_default($theme_name, $template) {
    1957     $site_dir = WP_CONTENT_DIR . "/themes/$template";
    1958     $default_dir = WP_CONTENT_DIR . '/themes/' . WP_DEFAULT_THEME;
    1959 
    1960     // Copy files from the default theme to the site theme.
    1961     //$files = array('index.php', 'comments.php', 'comments-popup.php', 'footer.php', 'header.php', 'sidebar.php', 'style.css');
    1962 
    1963     $theme_dir = @ opendir($default_dir);
    1964     if ($theme_dir) {
    1965         while(($theme_file = readdir( $theme_dir )) !== false) {
    1966             if (is_dir("$default_dir/$theme_file"))
    1967                 continue;
    1968             if (! @copy("$default_dir/$theme_file", "$site_dir/$theme_file"))
    1969                 return;
    1970             chmod("$site_dir/$theme_file", 0777);
    1971         }
    1972     }
    1973     @closedir($theme_dir);
    1974 
    1975     // Rewrite the theme header.
    1976     $stylelines = explode("\n", implode('', file("$site_dir/style.css")));
    1977     if ($stylelines) {
    1978         $f = fopen("$site_dir/style.css", 'w');
    1979 
    1980         foreach ($stylelines as $line) {
    1981             if (strpos($line, 'Theme Name:') !== false) $line = 'Theme Name: ' . $theme_name;
    1982             elseif (strpos($line, 'Theme URI:') !== false) $line = 'Theme URI: ' . __get_option('url');
    1983             elseif (strpos($line, 'Description:') !== false) $line = 'Description: Your theme.';
    1984             elseif (strpos($line, 'Version:') !== false) $line = 'Version: 1';
    1985             elseif (strpos($line, 'Author:') !== false) $line = 'Author: You';
    1986             fwrite($f, $line . "\n");
    1987         }
    1988         fclose($f);
    1989     }
    1990 
    1991     // Copy the images.
    1992     umask(0);
    1993     if (! mkdir("$site_dir/images", 0777)) {
    1994         return false;
    1995     }
    1996 
    1997     $images_dir = @ opendir("$default_dir/images");
    1998     if ($images_dir) {
    1999         while(($image = readdir($images_dir)) !== false) {
    2000             if (is_dir("$default_dir/images/$image"))
    2001                 continue;
    2002             if (! @copy("$default_dir/images/$image", "$site_dir/images/$image"))
    2003                 return;
    2004             chmod("$site_dir/images/$image", 0777);
    2005         }
    2006     }
    2007     @closedir($images_dir);
    2008 }
    2009 
    2010 // Create a site theme from the default theme.
    2011 /**
    2012  * {@internal Missing Short Description}}
    2013  *
    2014  * {@internal Missing Long Description}}
    2015  *
    2016  * @since 1.5.0
    2017  *
    2018  * @return unknown
    2019  */
    2020 function make_site_theme() {
    2021     // Name the theme after the blog.
    2022     $theme_name = __get_option('blogname');
    2023     $template = sanitize_title($theme_name);
    2024     $site_dir = WP_CONTENT_DIR . "/themes/$template";
    2025 
    2026     // If the theme already exists, nothing to do.
    2027     if ( is_dir($site_dir)) {
    2028         return false;
    2029     }
    2030 
    2031     // We must be able to write to the themes dir.
    2032     if (! is_writable(WP_CONTENT_DIR . "/themes")) {
    2033         return false;
    2034     }
    2035 
    2036     umask(0);
    2037     if (! mkdir($site_dir, 0777)) {
    2038         return false;
    2039     }
    2040 
    2041     if (file_exists(ABSPATH . 'wp-layout.css')) {
    2042         if (! make_site_theme_from_oldschool($theme_name, $template)) {
    2043             // TODO: rm -rf the site theme directory.
    2044             return false;
    2045         }
    2046     } else {
    2047         if (! make_site_theme_from_default($theme_name, $template))
    2048             // TODO: rm -rf the site theme directory.
    2049             return false;
    2050     }
    2051 
    2052     // Make the new site theme active.
    2053     $current_template = __get_option('template');
    2054     if ($current_template == WP_DEFAULT_THEME) {
    2055         update_option('template', $template);
    2056         update_option('stylesheet', $template);
    2057     }
    2058     return $template;
    2059 }
    2060 
    2061 /**
    2062  * Translate user level to user role name.
    2063  *
    2064  * @since 2.0.0
    2065  *
    2066  * @param int $level User level.
    2067  * @return string User role name.
    2068  */
    2069 function translate_level_to_role($level) {
    2070     switch ($level) {
    2071     case 10:
    2072     case 9:
    2073     case 8:
    2074         return 'administrator';
    2075     case 7:
    2076     case 6:
    2077     case 5:
    2078         return 'editor';
    2079     case 4:
    2080     case 3:
    2081     case 2:
    2082         return 'author';
    2083     case 1:
    2084         return 'contributor';
    2085     case 0:
    2086         return 'subscriber';
    2087     }
    2088 }
    2089 
    2090 /**
    2091  * {@internal Missing Short Description}}
    2092  *
    2093  * {@internal Missing Long Description}}
    2094  *
    2095  * @since 2.1.0
    2096  */
    2097 function wp_check_mysql_version() {
    2098     global $wpdb;
    2099     $result = $wpdb->check_database_version();
    2100     if ( is_wp_error( $result ) )
    2101         die( $result->get_error_message() );
    2102 }
    2103 
    2104 /**
    2105  * Disables the Automattic widgets plugin, which was merged into core.
    2106  *
    2107  * @since 2.2.0
    2108  */
    2109 function maybe_disable_automattic_widgets() {
    2110     $plugins = __get_option( 'active_plugins' );
    2111 
    2112     foreach ( (array) $plugins as $plugin ) {
    2113         if ( basename( $plugin ) == 'widgets.php' ) {
    2114             array_splice( $plugins, array_search( $plugin, $plugins ), 1 );
    2115             update_option( 'active_plugins', $plugins );
    2116             break;
    2117         }
    2118     }
    2119 }
    2120 
    2121 /**
    2122  * Disables the Link Manager on upgrade, if at the time of upgrade, no links exist in the DB.
    2123  *
    2124  * @since 3.5.0
    2125  */
    2126 function maybe_disable_link_manager() {
    2127     global $wp_current_db_version, $wpdb;
    2128 
    2129     if ( $wp_current_db_version >= 22006 && get_option( 'link_manager_enabled' ) && ! $wpdb->get_var( "SELECT link_id FROM $wpdb->links LIMIT 1" ) )
    2130         update_option( 'link_manager_enabled', 0 );
    2131 }
    2132 
    2133 /**
    2134  * Runs before the schema is upgraded.
    2135  *
    2136  * @since 2.9.0
    2137  */
    2138 function pre_schema_upgrade() {
    2139     global $wp_current_db_version, $wpdb;
    2140 
    2141     // Upgrade versions prior to 2.9
    2142     if ( $wp_current_db_version < 11557 ) {
    2143         // Delete duplicate options. Keep the option with the highest option_id.
    2144         $wpdb->query("DELETE o1 FROM $wpdb->options AS o1 JOIN $wpdb->options AS o2 USING (`option_name`) WHERE o2.option_id > o1.option_id");
    2145 
    2146         // Drop the old primary key and add the new.
    2147         $wpdb->query("ALTER TABLE $wpdb->options DROP PRIMARY KEY, ADD PRIMARY KEY(option_id)");
    2148 
    2149         // Drop the old option_name index. dbDelta() doesn't do the drop.
    2150         $wpdb->query("ALTER TABLE $wpdb->options DROP INDEX option_name");
    2151     }
    2152 
    2153     // Multisite schema upgrades.
    2154     if ( $wp_current_db_version < 25448 && is_multisite() && ! defined( 'DO_NOT_UPGRADE_GLOBAL_TABLES' ) && is_main_network() ) {
    2155 
    2156         // Upgrade verions prior to 3.7
    2157         if ( $wp_current_db_version < 25179 ) {
    2158             // New primary key for signups.
    2159             $wpdb->query( "ALTER TABLE $wpdb->signups ADD signup_id BIGINT(20) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST" );
    2160             $wpdb->query( "ALTER TABLE $wpdb->signups DROP INDEX domain" );
    2161         }
    2162 
    2163         if ( $wp_current_db_version < 25448 ) {
    2164             // Convert archived from enum to tinyint.
    2165             $wpdb->query( "ALTER TABLE $wpdb->blogs CHANGE COLUMN archived archived varchar(1) NOT NULL default '0'" );
    2166             $wpdb->query( "ALTER TABLE $wpdb->blogs CHANGE COLUMN archived archived tinyint(2) NOT NULL default 0" );
    2167         }
    2168     }
    2169 }
    2170 
    2171 /**
    2172  * Install global terms.
    2173  *
    2174  * @since 3.0.0
    2175  *
    2176  */
    2177 if ( !function_exists( 'install_global_terms' ) ) :
    2178 function install_global_terms() {
    2179     global $wpdb, $charset_collate;
    2180     $ms_queries = "
    2181 CREATE TABLE $wpdb->sitecategories (
    2182   cat_ID bigint(20) NOT NULL auto_increment,
    2183   cat_name varchar(55) NOT NULL default '',
    2184   category_nicename varchar(200) NOT NULL default '',
    2185   last_updated timestamp NOT NULL,
    2186   PRIMARY KEY  (cat_ID),
    2187   KEY category_nicename (category_nicename),
    2188   KEY last_updated (last_updated)
    2189 ) $charset_collate;
    2190 ";
    2191 // now create tables
    2192     dbDelta( $ms_queries );
    2193 }
    2194 endif;
    2195 
    2196 /**
    2197  * Output the input fields for the language selection form on the installation screen.
    2198  *
    2199  * @since 4.0.0
    2200  *
    2201  * @see wp_get_available_translations_from_api()
    2202  *
    2203  * @param array $languages Array of available languages (populated via the Translations API).
     83    return apply_filters( 'translations_api_result', $res, $type, $args );
     84}
     85
     86/**
     87 * Get available translations from the WordPress.org API.
     88 *
     89 * @since 4.0.0
     90 *
     91 * @see translations_api()
     92 *
     93 * @return array Array of translations, each an array of data. If the API response results
     94 *               in an error, an empty array will be returned.
     95 */
     96function wp_get_available_translations() {
     97    if ( ! defined( 'WP_INSTALLING' ) && false !== ( $translations = get_site_transient( 'available_translations' ) ) ) {
     98        return $translations;
     99    }
     100
     101    include( ABSPATH . WPINC . '/version.php' ); // include an unmodified $wp_version
     102
     103    $api = translations_api( 'core', array( 'version' => $wp_version ) );
     104
     105    if ( is_wp_error( $api ) || empty( $api['translations'] ) ) {
     106        return array();
     107    }
     108
     109    $translations = array();
     110    // Key the array with the language code for now.
     111    foreach ( $api['translations'] as $translation ) {
     112        $translations[ $translation['language'] ] = $translation;
     113    }
     114
     115    if ( ! defined( 'WP_INSTALLING' ) ) {
     116        set_site_transient( 'available_translations', $translations, 3 * HOUR_IN_SECONDS );
     117    }
     118
     119    return $translations;
     120}
     121
     122/**
     123 * Output the select form for the language selection on the installation screen.
     124 *
     125 * @since 4.0.0
     126 *
     127 * @param array $languages Array of available languages (populated via the Translation API).
    2204128 */
    2205129function wp_install_language_form( $languages ) {
     130    global $wp_local_package;
     131
    2206132    $installed_languages = get_available_languages();
    2207133
     
    2211137    echo "\n";
    2212138
    2213     if ( defined( 'WPLANG' ) && ( '' !== WPLANG ) && ( 'en_US' !== WPLANG ) ) {
    2214         if ( isset( $languages[ WPLANG ] ) ) {
    2215             $language = $languages[ WPLANG ];
     139    if ( ! empty( $wp_local_package ) && isset( $languages[ $wp_local_package ] ) ) {
     140        if ( isset( $languages[ $wp_local_package ] ) ) {
     141            $language = $languages[ $wp_local_package ];
    2216142            echo '<option value="' . esc_attr( $language['language'] ) . '" lang="' . esc_attr( $language['iso'][1] ) . '">' . esc_html( $language['native_name'] ) . "</option>\n";
     143            unset( $languages[ $wp_local_package ] );
    2217144        }
    2218145    }
     
    2231158
    2232159/**
    2233  * Get available translations from the WordPress.org API.
    2234  *
    2235  * @since 4.0.0
    2236  *
    2237  * @see wp_remote_post()
    2238  *
    2239  * @return array Array of translations, each an array of data.
    2240  */
    2241 function wp_get_available_translations_from_api() {
    2242     $url = 'http://api.wordpress.org/translations/core/1.0/';
    2243     if ( wp_http_supports( array( 'ssl' ) ) ) {
    2244         $url = set_url_scheme( $url, 'https' );
    2245     }
    2246 
    2247     $options = array(
    2248         'timeout' => 3,
    2249         'body' => array( 'version' => $GLOBALS['wp_version'] ),
    2250     );
    2251 
    2252     $response = wp_remote_post( $url, $options );
    2253     $body = wp_remote_retrieve_body( $response );
    2254     if ( $body && $body = json_decode( $body, true ) ) {
    2255         $translations = array();
    2256         // Key the array with the language code for now
    2257         foreach ( $body['translations'] as $translation ) {
    2258             $translations[ $translation['language'] ] = $translation;
    2259         }
    2260         return $translations;
    2261     }
    2262     return false;
    2263 }
    2264 
    2265 /**
    2266160 * Download a language pack.
    2267161 *
    2268162 * @since 4.0.0
    2269163 *
    2270  * @see wp_get_available_translations_from_api()
     164 * @see wp_get_available_translations()
    2271165 *
    2272166 * @param string $download Language code to download.
     
    2274168 *                     (or already installed), or false on failure.
    2275169 */
    2276 function wp_install_download_language_pack( $download ) {
     170function wp_download_language_pack( $download ) {
    2277171    // Check if the translation is already installed.
    2278172    if ( in_array( $download, get_available_languages() ) ) {
     
    2280174    }
    2281175
     176    if ( defined( 'DISALLOW_FILE_MODS' ) && DISALLOW_FILE_MODS ) {
     177        return false;
     178    }
     179
    2282180    // Confirm the translation is one we can download.
    2283     $translations = wp_get_available_translations_from_api();
     181    $translations = wp_get_available_translations();
    2284182    if ( ! $translations ) {
    2285183        return false;
     
    2304202     * @todo failures (such as non-direct FS)
    2305203     */
    2306     $upgrader->upgrade( $translation, array( 'clear_update_cache' => false ) );
     204    $result = $upgrader->upgrade( $translation, array( 'clear_update_cache' => false ) );
    2307205    return $translation->language;
    2308206}
    2309 
    2310 /**
    2311  * Load a translation during the install process.
    2312  *
    2313  * @since 4.0.0
    2314  *
    2315  * @see load_textdomain()
    2316  *
    2317  * @param string $translation Translation to load.
    2318  * @return string|bool Returns the language code if successfully loaded,
    2319  *                     or false on failure.
    2320  */
    2321 function wp_install_load_language( $translation ) {
    2322     if ( ! empty( $translation ) ) {
    2323         if ( in_array( $translation, get_available_languages() ) ) {
    2324             $translation_to_load = $translation;
    2325         }
    2326     }
    2327 
    2328     if ( empty( $translation_to_load ) ) {
    2329         return false;
    2330     }
    2331 
    2332     unload_textdomain( 'default' ); // Start over.
    2333     load_textdomain( 'default', WP_LANG_DIR . "/{$translation_to_load}.mo" );
    2334     load_textdomain( 'default', WP_LANG_DIR . "/admin-{$translation_to_load}.mo" );
    2335     return $translation_to_load;
    2336 }
Note: See TracChangeset for help on using the changeset viewer.