]> scripts.mit.edu Git - autoinstalls/wordpress.git/blobdiff - wp-includes/functions.php
WordPress 3.3.2-scripts
[autoinstalls/wordpress.git] / wp-includes / functions.php
index 8cd9ba79c95e8767c9880a2f3cf5e9c4795c7b06..521b0dd01c0137dcd36128914c2591a56fe41155 100644 (file)
  * @param string $dateformatstring Either 'G', 'U', or php date format.
  * @param string $mysqlstring Time from mysql DATETIME field.
  * @param bool $translate Optional. Default is true. Will switch format to locale.
- * @return string Date formated by $dateformatstring or locale (if available).
+ * @return string Date formatted by $dateformatstring or locale (if available).
  */
 function mysql2date( $dateformatstring, $mysqlstring, $translate = true ) {
        $m = $mysqlstring;
        if ( empty( $m ) )
                return false;
 
-       if ( 'G' == $dateformatstring ) {
+       if ( 'G' == $dateformatstring )
                return strtotime( $m . ' +0000' );
-       }
 
        $i = strtotime( $m );
 
        if ( 'U' == $dateformatstring )
                return $i;
 
-       if ( $translate)
-           return date_i18n( $dateformatstring, $i );
+       if ( $translate )
+               return date_i18n( $dateformatstring, $i );
        else
-           return date( $dateformatstring, $i );
+               return date( $dateformatstring, $i );
 }
 
 /**
@@ -85,8 +84,8 @@ function current_time( $type, $gmt = 0 ) {
 function date_i18n( $dateformatstring, $unixtimestamp = false, $gmt = false ) {
        global $wp_locale;
        $i = $unixtimestamp;
-       // Sanity check for PHP 5.1.0-
-       if ( false === $i || intval($i) < 0 ) {
+
+       if ( false === $i ) {
                if ( ! $gmt )
                        $i = current_time( 'timestamp' );
                else
@@ -119,6 +118,23 @@ function date_i18n( $dateformatstring, $unixtimestamp = false, $gmt = false ) {
 
                $dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 );
        }
+       $timezone_formats = array( 'P', 'I', 'O', 'T', 'Z', 'e' );
+       $timezone_formats_re = implode( '|', $timezone_formats );
+       if ( preg_match( "/$timezone_formats_re/", $dateformatstring ) ) {
+               $timezone_string = get_option( 'timezone_string' );
+               if ( $timezone_string ) {
+                       $timezone_object = timezone_open( $timezone_string );
+                       $date_object = date_create( null, $timezone_object );
+                       foreach( $timezone_formats as $timezone_format ) {
+                               if ( false !== strpos( $dateformatstring, $timezone_format ) ) {
+                                       $formatted = date_format( $date_object, $timezone_format );
+                                       $dateformatstring = ' '.$dateformatstring;
+                                       $dateformatstring = preg_replace( "/([^\\\])$timezone_format/", "\\1" . backslashit( $formatted ), $dateformatstring );
+                                       $dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 );
+                               }
+                       }
+               }
+       }
        $j = @$datefunc( $dateformatstring, $i );
        // allow plugins to redo this entirely for languages with untypical grammars
        $j = apply_filters('date_i18n', $j, $req_format, $i, $gmt);
@@ -230,26 +246,31 @@ function maybe_unserialize( $original ) {
  */
 function is_serialized( $data ) {
        // if it isn't a string, it isn't serialized
-       if ( !is_string( $data ) )
+       if ( ! is_string( $data ) )
                return false;
        $data = trim( $data );
-       if ( 'N;' == $data )
+       if ( 'N;' == $data )
                return true;
-       if ( !preg_match( '/^([adObis]):/', $data, $badions ) )
+       $length = strlen( $data );
+       if ( $length < 4 )
+               return false;
+       if ( ':' !== $data[1] )
+               return false;
+       $lastc = $data[$length-1];
+       if ( ';' !== $lastc && '}' !== $lastc )
                return false;
-       switch ( $badions[1] ) {
+       $token = $data[0];
+       switch ( $token ) {
+               case 's' :
+                       if ( '"' !== $data[$length-2] )
+                               return false;
                case 'a' :
                case 'O' :
-               case 's' :
-                       if ( preg_match( "/^{$badions[1]}:[0-9]+:.*[;}]\$/s", $data ) )
-                               return true;
-                       break;
+                       return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
                case 'b' :
                case 'i' :
                case 'd' :
-                       if ( preg_match( "/^{$badions[1]}:[0-9.E-]+;\$/", $data ) )
-                               return true;
-                       break;
+                       return (bool) preg_match( "/^{$token}:[0-9.E-]+;\$/", $data );
        }
        return false;
 }
@@ -267,9 +288,19 @@ function is_serialized_string( $data ) {
        if ( !is_string( $data ) )
                return false;
        $data = trim( $data );
-       if ( preg_match( '/^s:[0-9]+:.*;$/s', $data ) ) // this should fetch all serialized strings
+       $length = strlen( $data );
+       if ( $length < 4 )
+               return false;
+       elseif ( ':' !== $data[1] )
+               return false;
+       elseif ( ';' !== $data[$length-1] )
+               return false;
+       elseif ( $data[0] !== 's' )
+               return false;
+       elseif ( '"' !== $data[$length-2] )
+               return false;
+       else
                return true;
-       return false;
 }
 
 /**
@@ -293,6 +324,7 @@ function is_serialized_string( $data ) {
  *     the option value.
  *
  * @param string $option Name of option to retrieve. Expected to not be SQL-escaped.
+ * @param mixed $default Optional. Default value to return if the option does not exist.
  * @return mixed Value set for the option.
  */
 function get_option( $option, $default = false ) {
@@ -412,17 +444,18 @@ function wp_load_alloptions() {
                        $alloptions_db = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options" );
                $wpdb->suppress_errors($suppress);
                $alloptions = array();
-               foreach ( (array) $alloptions_db as $o )
+               foreach ( (array) $alloptions_db as $o ) {
                        $alloptions[$o->option_name] = $o->option_value;
-                       if ( !defined( 'WP_INSTALLING' ) || !is_multisite() )
-                               wp_cache_add( 'alloptions', $alloptions, 'options' );
+               }
+               if ( !defined( 'WP_INSTALLING' ) || !is_multisite() )
+                       wp_cache_add( 'alloptions', $alloptions, 'options' );
        }
 
        return $alloptions;
 }
 
 /**
- * Loads and caches certain often requested site options if is_multisite() and a peristent cache is not being used.
+ * Loads and caches certain often requested site options if is_multisite() and a persistent cache is not being used.
  *
  * @since 3.0.0
  * @package WordPress
@@ -439,7 +472,7 @@ function wp_load_core_site_options( $site_id = null ) {
        if ( empty($site_id) )
                $site_id = $wpdb->siteid;
 
-       $core_options = array('site_name', 'siteurl', 'active_sitewide_plugins', '_site_transient_timeout_theme_roots', '_site_transient_theme_roots', 'site_admins', 'dashboard_blog', 'can_compress_scripts', 'global_terms_enabled' );
+       $core_options = array('site_name', 'siteurl', 'active_sitewide_plugins', '_site_transient_timeout_theme_roots', '_site_transient_theme_roots', 'site_admins', 'can_compress_scripts', 'global_terms_enabled' );
 
        $core_options_in = "'" . implode("', '", $core_options) . "'";
        $options = $wpdb->get_results( $wpdb->prepare("SELECT meta_key, meta_value FROM $wpdb->sitemeta WHERE meta_key IN ($core_options_in) AND site_id = %d", $site_id) );
@@ -487,7 +520,7 @@ function update_option( $option, $newvalue ) {
        wp_protect_special_option( $option );
 
        if ( is_object($newvalue) )
-               $newvalue = wp_clone($newvalue);
+               $newvalue = clone $newvalue;
 
        $newvalue = sanitize_option( $option, $newvalue );
        $oldvalue = get_option( $option );
@@ -537,16 +570,14 @@ function update_option( $option, $newvalue ) {
  * it will be serialized before it is inserted into the database. Remember,
  * resources can not be serialized or added as an option.
  *
- * You can create options without values and then add values later. Does not
- * check whether the option has already been added, but does check that you
+ * You can create options without values and then update the values later.
+ * Existing options will not be updated and checks are performed to ensure that you
  * aren't adding a protected WordPress option. Care should be taken to not name
- * options the same as the ones which are protected and to not add options
- * that were already added.
+ * options the same as the ones which are protected.
  *
  * @package WordPress
  * @subpackage Option
  * @since 1.0.0
- * @link http://alex.vort-x.net/blog/ Thanks Alex Stapleton
  *
  * @uses do_action() Calls 'add_option' hook before adding the option.
  * @uses do_action() Calls 'add_option_$option' and 'added_option' hooks on success.
@@ -555,7 +586,7 @@ function update_option( $option, $newvalue ) {
  * @param mixed $value Optional. Option value, can be anything. Expected to not be SQL-escaped.
  * @param mixed $deprecated Optional. Description. Not used anymore.
  * @param bool $autoload Optional. Default is enabled. Whether to load the option when WordPress starts up.
- * @return null returns when finished.
+ * @return bool False if option was not added and true if option was added.
  */
 function add_option( $option, $value = '', $deprecated = '', $autoload = 'yes' ) {
        global $wpdb;
@@ -570,7 +601,7 @@ function add_option( $option, $value = '', $deprecated = '', $autoload = 'yes' )
        wp_protect_special_option( $option );
 
        if ( is_object($value) )
-               $value = wp_clone($value);
+               $value = clone $value;
 
        $value = sanitize_option( $option, $value );
 
@@ -578,7 +609,7 @@ function add_option( $option, $value = '', $deprecated = '', $autoload = 'yes' )
        $notoptions = wp_cache_get( 'notoptions', 'options' );
        if ( !is_array( $notoptions ) || !isset( $notoptions[$option] ) )
                if ( false !== get_option( $option ) )
-                       return;
+                       return false;
 
        $_value = $value;
        $value = maybe_serialize( $value );
@@ -655,7 +686,7 @@ function delete_option( $option ) {
 }
 
 /**
- * Delete a transient
+ * Delete a transient.
  *
  * @since 2.8.0
  * @package WordPress
@@ -670,7 +701,7 @@ function delete_option( $option ) {
 function delete_transient( $transient ) {
        global $_wp_using_ext_object_cache;
 
-    do_action( 'delete_transient_' . $transient, $transient );
+       do_action( 'delete_transient_' . $transient, $transient );
 
        if ( $_wp_using_ext_object_cache ) {
                $result = wp_cache_delete( $transient, 'transient' );
@@ -688,7 +719,7 @@ function delete_transient( $transient ) {
 }
 
 /**
- * Get the value of a transient
+ * Get the value of a transient.
  *
  * If the transient does not exist or does not have a value, then the return value
  * will be false.
@@ -737,7 +768,7 @@ function get_transient( $transient ) {
 }
 
 /**
- * Set/update the value of a transient
+ * Set/update the value of a transient.
  *
  * You do not need to serialize values. If the value needs to be serialized, then
  * it will be serialized before it is set.
@@ -758,7 +789,7 @@ function get_transient( $transient ) {
 function set_transient( $transient, $value, $expiration = 0 ) {
        global $_wp_using_ext_object_cache;
 
-    $value = apply_filters( 'pre_set_transient_' . $transient, $value );
+       $value = apply_filters( 'pre_set_transient_' . $transient, $value );
 
        if ( $_wp_using_ext_object_cache ) {
                $result = wp_cache_set( $transient, $value, 'transient', $expiration );
@@ -1006,6 +1037,8 @@ function maybe_serialize( $data ) {
        if ( is_array( $data ) || is_object( $data ) )
                return serialize( $data );
 
+       // Double serialization is required for backward compatibility.
+       // See http://core.trac.wordpress.org/ticket/12930
        if ( is_serialized( $data ) )
                return serialize( $data );
 
@@ -1163,6 +1196,8 @@ function debug_fclose( $fp ) {
  */
 function do_enclose( $content, $post_ID ) {
        global $wpdb;
+
+       //TODO: Tidy this ghetto code up and make the debug code optional
        include_once( ABSPATH . WPINC . '/class-IXR.php' );
 
        $log = debug_fopen( ABSPATH . 'enclosures.log', 'a' );
@@ -1183,7 +1218,7 @@ function do_enclose( $content, $post_ID ) {
 
        foreach ( $pung as $link_test ) {
                if ( !in_array( $link_test, $post_links_temp[0] ) ) { // link no longer in post
-                       $mid = $wpdb->get_col( $wpdb->prepare("SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE (%s)", $post_ID, $link_test . '%') );
+                       $mid = $wpdb->get_col( $wpdb->prepare("SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE (%s)", $post_ID, like_escape( $link_test ) . '%') );
                        do_action( 'delete_postmeta', $mid );
                        $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->postmeta WHERE meta_id IN(%s)", implode( ',', $mid ) ) );
                        do_action( 'deleted_postmeta', $mid );
@@ -1197,13 +1232,13 @@ function do_enclose( $content, $post_ID ) {
                                continue;
                        if ( isset( $test['query'] ) )
                                $post_links[] = $link_test;
-                       elseif ( $test['path'] != '/' && $test['path'] != '' )
+                       elseif ( isset($test['path']) && ( $test['path'] != '/' ) &&  ($test['path'] != '' ) )
                                $post_links[] = $link_test;
                }
        }
 
        foreach ( (array) $post_links as $url ) {
-               if ( $url != '' && !$wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE (%s)", $post_ID, $url . '%' ) ) ) {
+               if ( $url != '' && !$wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE (%s)", $post_ID, like_escape( $url ) . '%' ) ) ) {
 
                        if ( $headers = wp_get_http_headers( $url) ) {
                                $len = (int) $headers['content-length'];
@@ -1268,7 +1303,7 @@ function wp_get_http( $url, $file_path = false, $red = 1 ) {
                return false;
 
        $headers = wp_remote_retrieve_headers( $response );
-       $headers['response'] = $response['response']['code'];
+       $headers['response'] = wp_remote_retrieve_response_code( $response );
 
        // WP_HTTP no longer follows redirects for HEAD requests.
        if ( 'HEAD' == $options['method'] && in_array($headers['response'], array(301, 302)) && isset( $headers['location'] ) ) {
@@ -1283,7 +1318,7 @@ function wp_get_http( $url, $file_path = false, $red = 1 ) {
        if ( !$out_fp )
                return $headers;
 
-       fwrite( $out_fp,  $response['body']);
+       fwrite( $out_fp,  wp_remote_retrieve_body( $response ) );
        fclose($out_fp);
        clearstatcache();
 
@@ -1321,8 +1356,8 @@ function wp_get_http_headers( $url, $deprecated = false ) {
  * @return int 1 when new day, 0 if not a new day.
  */
 function is_new_day() {
-       global $day, $previousday;
-       if ( $day != $previousday )
+       global $currentday, $previousday;
+       if ( $currentday != $previousday )
                return 1;
        else
                return 0;
@@ -1347,6 +1382,36 @@ function build_query( $data ) {
        return _http_build_query( $data, null, '&', '', false );
 }
 
+// from php.net (modified by Mark Jaquith to behave like the native PHP5 function)
+function _http_build_query($data, $prefix=null, $sep=null, $key='', $urlencode=true) {
+       $ret = array();
+
+       foreach ( (array) $data as $k => $v ) {
+               if ( $urlencode)
+                       $k = urlencode($k);
+               if ( is_int($k) && $prefix != null )
+                       $k = $prefix.$k;
+               if ( !empty($key) )
+                       $k = $key . '%5B' . $k . '%5D';
+               if ( $v === NULL )
+                       continue;
+               elseif ( $v === FALSE )
+                       $v = '0';
+
+               if ( is_array($v) || is_object($v) )
+                       array_push($ret,_http_build_query($v, '', $sep, $k, $urlencode));
+               elseif ( $urlencode )
+                       array_push($ret, $k.'='.urlencode($v));
+               else
+                       array_push($ret, $k.'='.$v);
+       }
+
+       if ( NULL === $sep )
+               $sep = ini_get('arg_separator.output');
+
+       return implode($sep, $ret);
+}
+
 /**
  * Retrieve a modified URL query string.
  *
@@ -1354,8 +1419,9 @@ function build_query( $data ) {
  * using this function. You can also retrieve the full URL with query data.
  *
  * Adding a single key & value or an associative array. Setting a key value to
- * emptystring removes the key. Omitting oldquery_or_uri uses the $_SERVER
- * value.
+ * an empty string removes the key. Omitting oldquery_or_uri uses the $_SERVER
+ * value. Additional values provided are expected to be encoded appropriately
+ * with urlencode() or rawurlencode().
  *
  * @since 1.5.0
  *
@@ -1489,7 +1555,7 @@ function wp_remote_fopen( $uri ) {
        if ( is_wp_error( $response ) )
                return false;
 
-       return $response['body'];
+       return wp_remote_retrieve_body( $response );
 }
 
 /**
@@ -1619,7 +1685,7 @@ function status_header( $header ) {
  * The several different headers cover the different ways cache prevention is handled
  * by different browsers
  *
- * @since 2.8
+ * @since 2.8.0
  *
  * @uses apply_filters()
  * @return array The associative array of header names and field values.
@@ -1633,7 +1699,7 @@ function wp_get_nocache_headers() {
        );
 
        if ( function_exists('apply_filters') ) {
-               $headers = apply_filters('nocache_headers', $headers);
+               $headers = (array) apply_filters('nocache_headers', $headers);
        }
        return $headers;
 }
@@ -1649,7 +1715,7 @@ function wp_get_nocache_headers() {
  */
 function nocache_headers() {
        $headers = wp_get_nocache_headers();
-       foreach( (array) $headers as $name => $field_value )
+       foreach( $headers as $name => $field_value )
                @header("{$name}: {$field_value}");
 }
 
@@ -1731,7 +1797,7 @@ function do_feed_rdf() {
 }
 
 /**
- * Load the RSS 1.0 Feed Template
+ * Load the RSS 1.0 Feed Template.
  *
  * @since 2.1.0
  */
@@ -1768,27 +1834,28 @@ function do_feed_atom( $for_comments ) {
 }
 
 /**
- * Display the robot.txt file content.
+ * Display the robots.txt file content.
  *
  * The echo content should be with usage of the permalinks or for creating the
- * robot.txt file.
+ * robots.txt file.
  *
  * @since 2.1.0
- * @uses do_action() Calls 'do_robotstxt' hook for displaying robot.txt rules.
+ * @uses do_action() Calls 'do_robotstxt' hook for displaying robots.txt rules.
  */
 function do_robots() {
        header( 'Content-Type: text/plain; charset=utf-8' );
 
        do_action( 'do_robotstxt' );
 
-       $output = '';
+       $output = "User-agent: *\n";
        $public = get_option( 'blog_public' );
-       if ( '0' ==  $public ) {
-               $output .= "User-agent: *\n";
+       if ( '0' == $public ) {
                $output .= "Disallow: /\n";
        } else {
-               $output .= "User-agent: *\n";
-               $output .= "Disallow:\n";
+               $site_url = parse_url( site_url() );
+               $path = ( !empty( $site_url['path'] ) ) ? $site_url['path'] : '';
+               $output .= "Disallow: $path/wp-admin/\n";
+               $output .= "Disallow: $path/wp-includes/\n";
        }
 
        echo apply_filters('robots_txt', $output, $public);
@@ -1832,32 +1899,35 @@ function is_blog_installed() {
        if ( $installed )
                return true;
 
+       // If visiting repair.php, return true and let it take over.
+       if ( defined( 'WP_REPAIRING' ) )
+               return true;
+
        $suppress = $wpdb->suppress_errors();
-       $tables = $wpdb->get_col('SHOW TABLES');
-       $wpdb->suppress_errors( $suppress );
 
-       $wp_tables = $wpdb->tables();
        // Loop over the WP tables.  If none exist, then scratch install is allowed.
        // If one or more exist, suggest table repair since we got here because the options
        // table could not be accessed.
+       $wp_tables = $wpdb->tables();
        foreach ( $wp_tables as $table ) {
-               // If one of the WP tables exist, then we are in an insane state.
-               if ( in_array( $table, $tables ) ) {
-                       // The existence of custom user tables shouldn't suggest an insane state or prevent a clean install.
-                       if ( defined( 'CUSTOM_USER_TABLE' ) && CUSTOM_USER_TABLE == $table )
-                               continue;
-                       if ( defined( 'CUSTOM_USER_META_TABLE' ) && CUSTOM_USER_META_TABLE == $table )
-                               continue;
+               // The existence of custom user tables shouldn't suggest an insane state or prevent a clean install.
+               if ( defined( 'CUSTOM_USER_TABLE' ) && CUSTOM_USER_TABLE == $table )
+                       continue;
+               if ( defined( 'CUSTOM_USER_META_TABLE' ) && CUSTOM_USER_META_TABLE == $table )
+                       continue;
 
-                       // If visiting repair.php, return true and let it take over.
-                       if ( defined('WP_REPAIRING') )
-                               return true;
-                       // Die with a DB error.
-                       $wpdb->error = sprintf( /*WP_I18N_NO_TABLES*/'One or more database tables are unavailable.  The database may need to be <a href="%s">repaired</a>.'/*/WP_I18N_NO_TABLES*/, 'maint/repair.php?referrer=is_blog_installed' );
-                       dead_db();
-               }
+               if ( ! $wpdb->get_results( "DESCRIBE $table;" ) )
+                       continue;
+
+               // One or more tables exist. We are insane.
+
+               // Die with a DB error.
+               $wpdb->error = sprintf( /*WP_I18N_NO_TABLES*/'One or more database tables are unavailable.  The database may need to be <a href="%s">repaired</a>.'/*/WP_I18N_NO_TABLES*/, 'maint/repair.php?referrer=is_blog_installed' );
+               dead_db();
        }
 
+       $wpdb->suppress_errors( $suppress );
+
        wp_cache_set( 'is_blog_installed', false );
 
        return false;
@@ -1887,11 +1957,6 @@ function wp_nonce_url( $actionurl, $action = -1 ) {
  * offer absolute protection, but should protect against most cases. It is very
  * important to use nonce field in forms.
  *
- * If you set $echo to true and set $referer to true, then you will need to
- * retrieve the {@link wp_referer_field() wp referer field}. If you have the
- * $referer set to true and are echoing the nonce field, it will also echo the
- * referer field.
- *
  * The $action and $name are optional, but if you want to have better security,
  * it is strongly suggested to set those two parameters. It is easier to just
  * call the function without any parameters, because validation of the nonce
@@ -1915,11 +1980,12 @@ function wp_nonce_url( $actionurl, $action = -1 ) {
 function wp_nonce_field( $action = -1, $name = "_wpnonce", $referer = true , $echo = true ) {
        $name = esc_attr( $name );
        $nonce_field = '<input type="hidden" id="' . $name . '" name="' . $name . '" value="' . wp_create_nonce( $action ) . '" />';
-       if ( $echo )
-               echo $nonce_field;
 
        if ( $referer )
-               wp_referer_field( $echo );
+               $nonce_field .= wp_referer_field( false );
+
+       if ( $echo )
+               echo $nonce_field;
 
        return $nonce_field;
 }
@@ -1971,7 +2037,8 @@ function wp_original_referer_field( $echo = true, $jump_back_to = 'current' ) {
 }
 
 /**
- * Retrieve referer from '_wp_http_referer', HTTP referer, or current page respectively.
+ * Retrieve referer from '_wp_http_referer' or HTTP referer. If it's the same
+ * as the current request URL, will return false.
  *
  * @package WordPress
  * @subpackage Security
@@ -1980,13 +2047,13 @@ function wp_original_referer_field( $echo = true, $jump_back_to = 'current' ) {
  * @return string|bool False on failure. Referer URL on success.
  */
 function wp_get_referer() {
-       $ref = '';
+       $ref = false;
        if ( ! empty( $_REQUEST['_wp_http_referer'] ) )
                $ref = $_REQUEST['_wp_http_referer'];
        else if ( ! empty( $_SERVER['HTTP_REFERER'] ) )
                $ref = $_SERVER['HTTP_REFERER'];
 
-       if ( $ref !== $_SERVER['REQUEST_URI'] )
+       if ( $ref && $ref !== $_SERVER['REQUEST_URI'] )
                return $ref;
        return false;
 }
@@ -2058,7 +2125,7 @@ function path_is_absolute( $path ) {
        if ( realpath($path) == $path )
                return true;
 
-       if ( strlen($path) == 0 || $path{0} == '.' )
+       if ( strlen($path) == 0 || $path[0] == '.' )
                return false;
 
        // windows allows absolute paths like this
@@ -2066,7 +2133,7 @@ function path_is_absolute( $path ) {
                return true;
 
        // a path starting with / or \ is absolute; anything else is relative
-       return (bool) preg_match('#^[/\\\\]#', $path);
+       return ( $path[0] == '/' || $path[0] == '\\' );
 }
 
 /**
@@ -2087,6 +2154,42 @@ function path_join( $base, $path ) {
        return rtrim($base, '/') . '/' . ltrim($path, '/');
 }
 
+/**
+ * Determines a writable directory for temporary files.
+ * Function's preference is to WP_CONTENT_DIR followed by the return value of <code>sys_get_temp_dir()</code>, before finally defaulting to /tmp/
+ *
+ * In the event that this function does not find a writable location, It may be overridden by the <code>WP_TEMP_DIR</code> constant in your <code>wp-config.php</code> file.
+ *
+ * @since 2.5.0
+ *
+ * @return string Writable temporary directory
+ */
+function get_temp_dir() {
+       static $temp;
+       if ( defined('WP_TEMP_DIR') )
+               return trailingslashit(WP_TEMP_DIR);
+
+       if ( $temp )
+               return trailingslashit($temp);
+
+       $temp = WP_CONTENT_DIR . '/';
+       if ( is_dir($temp) && @is_writable($temp) )
+               return $temp;
+
+       if  ( function_exists('sys_get_temp_dir') ) {
+               $temp = sys_get_temp_dir();
+               if ( @is_writable($temp) )
+                       return trailingslashit($temp);
+       }
+
+       $temp = ini_get('upload_tmp_dir');
+       if ( is_dir($temp) && @is_writable($temp) )
+               return trailingslashit($temp);
+
+       $temp = '/tmp/';
+       return $temp;
+}
+
 /**
  * Get an array containing the current upload directory's path and url.
  *
@@ -2190,14 +2293,14 @@ function wp_upload_dir( $time = null ) {
  * before the extension, and will continue adding numbers until the filename is
  * unique.
  *
- * The callback must accept two parameters, the first one is the directory and
- * the second is the filename. The callback must be a function.
+ * The callback is passed three parameters, the first one is the directory, the
+ * second is the filename, and the third is the extension.
  *
- * @since 2.5
+ * @since 2.5.0
  *
  * @param string $dir
  * @param string $filename
- * @param string $unique_filename_callback Function name, must be a function.
+ * @param mixed $unique_filename_callback Callback.
  * @return string New filename, if given wasn't unique.
  */
 function wp_unique_filename( $dir, $filename, $unique_filename_callback = null ) {
@@ -2213,9 +2316,9 @@ function wp_unique_filename( $dir, $filename, $unique_filename_callback = null )
        if ( $name === $ext )
                $name = '';
 
-       // Increment the file number until we have a unique file to save in $dir. Use $override['unique_filename_callback'] if supplied.
+       // Increment the file number until we have a unique file to save in $dir. Use callback if supplied.
        if ( $unique_filename_callback && is_callable( $unique_filename_callback ) ) {
-               $filename = $unique_filename_callback( $dir, $name );
+               $filename = call_user_func( $unique_filename_callback, $dir, $name, $ext );
        } else {
                $number = '';
 
@@ -2337,7 +2440,7 @@ function wp_ext2type( $ext ) {
                'spreadsheet' => array( 'numbers',     'ods',  'xls',  'xlsx', 'xlsb',  'xlsm' ),
                'interactive' => array( 'key', 'ppt',  'pptx', 'pptm', 'odp',  'swf' ),
                'text'        => array( 'asc', 'csv',  'tsv',  'txt' ),
-               'archive'     => array( 'bz2', 'cab',  'dmg',  'gz',   'rar',  'sea',   'sit', 'sqx', 'tar', 'tgz',  'zip' ),
+               'archive'     => array( 'bz2', 'cab',  'dmg',  'gz',   'rar',  'sea',   'sit', 'sqx', 'tar', 'tgz',  'zip', '7z' ),
                'code'        => array( 'css', 'htm',  'html', 'php',  'js' ),
        ));
        foreach ( $ext2type as $type => $exts )
@@ -2470,6 +2573,7 @@ function get_allowed_mime_types() {
                'txt|asc|c|cc|h' => 'text/plain',
                'csv' => 'text/csv',
                'tsv' => 'text/tab-separated-values',
+               'ics' => 'text/calendar',
                'rtx' => 'text/richtext',
                'css' => 'text/css',
                'htm|html' => 'text/html',
@@ -2502,6 +2606,8 @@ function get_allowed_mime_types() {
                'tar' => 'application/x-tar',
                'zip' => 'application/zip',
                'gz|gzip' => 'application/x-gzip',
+               'rar' => 'application/rar',
+               '7z' => 'application/x-7z-compressed',
                'exe' => 'application/x-msdownload',
                // openoffice formats
                'odt' => 'application/vnd.oasis.opendocument.text',
@@ -2573,7 +2679,7 @@ function wp_explain_nonce( $action ) {
                $trans['edit']['plugin']       = array( __( 'Your attempt to edit this plugin file: &#8220;%s&#8221; has failed.' ), 'use_id' );
                $trans['activate']['plugin']   = array( __( 'Your attempt to activate this plugin: &#8220;%s&#8221; has failed.' ), 'use_id' );
                $trans['deactivate']['plugin'] = array( __( 'Your attempt to deactivate this plugin: &#8220;%s&#8221; has failed.' ), 'use_id' );
-               $trans['upgrade']['plugin']    = array( __( 'Your attempt to upgrade this plugin: &#8220;%s&#8221; has failed.' ), 'use_id' );
+               $trans['upgrade']['plugin']    = array( __( 'Your attempt to update this plugin: &#8220;%s&#8221; has failed.' ), 'use_id' );
 
                $trans['add']['post']          = array( __( 'Your attempt to add this post has failed.' ), false );
                $trans['delete']['post']       = array( __( 'Your attempt to delete this post: &#8220;%s&#8221; has failed.' ), 'get_the_title' );
@@ -2648,18 +2754,21 @@ function wp_nonce_ays( $action ) {
  * HTML will be displayed to the user. It is recommended to use this function
  * only, when the execution should not continue any further. It is not
  * recommended to call this function very often and try to handle as many errors
- * as possible siliently.
+ * as possible silently.
  *
  * @since 2.0.4
  *
  * @param string $message Error message.
  * @param string $title Error title.
- * @param string|array $args Optional arguements to control behaviour.
+ * @param string|array $args Optional arguments to control behavior.
  */
 function wp_die( $message, $title = '', $args = array() ) {
+       if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
+               die('-1');
+
        if ( function_exists( 'apply_filters' ) ) {
                $function = apply_filters( 'wp_die_handler', '_default_wp_die_handler');
-       }else {
+       } else {
                $function = '_default_wp_die_handler';
        }
 
@@ -2677,7 +2786,7 @@ function wp_die( $message, $title = '', $args = array() ) {
  *
  * @param string $message Error message.
  * @param string $title Error title.
- * @param string|array $args Optional arguements to control behaviour.
+ * @param string|array $args Optional arguments to control behavior.
  */
 function _default_wp_die_handler( $message, $title = '', $args = array() ) {
        $defaults = array( 'response' => 500 );
@@ -2709,48 +2818,114 @@ function _default_wp_die_handler( $message, $title = '', $args = array() ) {
 
        if ( isset( $r['back_link'] ) && $r['back_link'] ) {
                $back_text = $have_gettext? __('&laquo; Back') : '&laquo; Back';
-               $message .= "\n<p><a href='javascript:history.back()'>$back_text</p>";
+               $message .= "\n<p><a href='javascript:history.back()'>$back_text</a></p>";
        }
 
-       if ( defined( 'WP_SITEURL' ) && '' != WP_SITEURL )
-               $admin_dir = WP_SITEURL . '/wp-admin/';
-       elseif ( function_exists( 'get_bloginfo' ) && '' != get_bloginfo( 'wpurl' ) )
-               $admin_dir = get_bloginfo( 'wpurl' ) . '/wp-admin/';
-       elseif ( strpos( $_SERVER['PHP_SELF'], 'wp-admin' ) !== false )
-               $admin_dir = '';
-       else
-               $admin_dir = 'wp-admin/';
-
        if ( !function_exists( 'did_action' ) || !did_action( 'admin_head' ) ) :
-       if ( !headers_sent() ) {
-               status_header( $r['response'] );
-               nocache_headers();
-               header( 'Content-Type: text/html; charset=utf-8' );
-       }
+               if ( !headers_sent() ) {
+                       status_header( $r['response'] );
+                       nocache_headers();
+                       header( 'Content-Type: text/html; charset=utf-8' );
+               }
 
-       if ( empty($title) )
-               $title = $have_gettext ? __('WordPress &rsaquo; Error') : 'WordPress &rsaquo; Error';
+               if ( empty($title) )
+                       $title = $have_gettext ? __('WordPress &rsaquo; Error') : 'WordPress &rsaquo; Error';
 
-       $text_direction = 'ltr';
-       if ( isset($r['text_direction']) && 'rtl' == $r['text_direction'] )
-               $text_direction = 'rtl';
-       elseif ( function_exists( 'is_rtl' ) && is_rtl() )
-               $text_direction = 'rtl';
+               $text_direction = 'ltr';
+               if ( isset($r['text_direction']) && 'rtl' == $r['text_direction'] )
+                       $text_direction = 'rtl';
+               elseif ( function_exists( 'is_rtl' ) && is_rtl() )
+                       $text_direction = 'rtl';
 ?>
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-<!-- Ticket #11289, IE bug fix: always pad the error page with enough characters such that it is greater than 512 bytes, even after gzip compression abcdefghijklmnopqrstuvwxyz1234567890aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz11223344556677889900abacbcbdcdcededfefegfgfhghgihihjijikjkjlklkmlmlnmnmononpopoqpqprqrqsrsrtstsubcbcdcdedefefgfabcadefbghicjkldmnoepqrfstugvwxhyz1i234j567k890laabmbccnddeoeffpgghqhiirjjksklltmmnunoovppqwqrrxsstytuuzvvw0wxx1yyz2z113223434455666777889890091abc2def3ghi4jkl5mno6pqr7stu8vwx9yz11aab2bcc3dd4ee5ff6gg7hh8ii9j0jk1kl2lmm3nnoo4p5pq6qrr7ss8tt9uuvv0wwx1x2yyzz13aba4cbcb5dcdc6dedfef8egf9gfh0ghg1ihi2hji3jik4jkj5lkl6kml7mln8mnm9ono -->
-<html xmlns="http://www.w3.org/1999/xhtml" <?php if ( function_exists( 'language_attributes' ) ) language_attributes(); ?>>
+<!DOCTYPE html>
+<!-- Ticket #11289, IE bug fix: always pad the error page with enough characters such that it is greater than 512 bytes, even after gzip compression abcdefghijklmnopqrstuvwxyz1234567890aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz11223344556677889900abacbcbdcdcededfefegfgfhghgihihjijikjkjlklkmlmlnmnmononpopoqpqprqrqsrsrtstsubcbcdcdedefefgfabcadefbghicjkldmnoepqrfstugvwxhyz1i234j567k890laabmbccnddeoeffpgghqhiirjjksklltmmnunoovppqwqrrxsstytuuzvvw0wxx1yyz2z113223434455666777889890091abc2def3ghi4jkl5mno6pqr7stu8vwx9yz11aab2bcc3dd4ee5ff6gg7hh8ii9j0jk1kl2lmm3nnoo4p5pq6qrr7ss8tt9uuvv0wwx1x2yyzz13aba4cbcb5dcdc6dedfef8egf9gfh0ghg1ihi2hji3jik4jkj5lkl6kml7mln8mnm9ono
+-->
+<html xmlns="http://www.w3.org/1999/xhtml" <?php if ( function_exists( 'language_attributes' ) && function_exists( 'is_rtl' ) ) language_attributes(); else echo "dir='$text_direction'"; ?>>
 <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title><?php echo $title ?></title>
-       <link rel="stylesheet" href="<?php echo $admin_dir; ?>css/install.css" type="text/css" />
-<?php
-if ( 'rtl' == $text_direction ) : ?>
-       <link rel="stylesheet" href="<?php echo $admin_dir; ?>css/install-rtl.css" type="text/css" />
-<?php endif; ?>
+       <style type="text/css">
+               html {
+                       background: #f9f9f9;
+               }
+               body {
+                       background: #fff;
+                       color: #333;
+                       font-family: sans-serif;
+                       margin: 2em auto;
+                       padding: 1em 2em;
+                       -webkit-border-radius: 3px;
+                       border-radius: 3px;
+                       border: 1px solid #dfdfdf;
+                       max-width: 700px;
+               }
+               #error-page {
+                       margin-top: 50px;
+               }
+               #error-page p {
+                       font-size: 14px;
+                       line-height: 1.5;
+                       margin: 25px 0 20px;
+               }
+               #error-page code {
+                       font-family: Consolas, Monaco, monospace;
+               }
+               ul li {
+                       margin-bottom: 10px;
+                       font-size: 14px ;
+               }
+               a {
+                       color: #21759B;
+                       text-decoration: none;
+               }
+               a:hover {
+                       color: #D54E21;
+               }
+
+               .button {
+                       font-family: sans-serif;
+                       text-decoration: none;
+                       font-size: 14px !important;
+                       line-height: 16px;
+                       padding: 6px 12px;
+                       cursor: pointer;
+                       border: 1px solid #bbb;
+                       color: #464646;
+                       -webkit-border-radius: 15px;
+                       border-radius: 15px;
+                       -moz-box-sizing: content-box;
+                       -webkit-box-sizing: content-box;
+                       box-sizing: content-box;
+                       background-color: #f5f5f5;
+                       background-image: -ms-linear-gradient(top, #ffffff, #f2f2f2);
+                       background-image: -moz-linear-gradient(top, #ffffff, #f2f2f2);
+                       background-image: -o-linear-gradient(top, #ffffff, #f2f2f2);
+                       background-image: -webkit-gradient(linear, left top, left bottom, from(#ffffff), to(#f2f2f2));
+                       background-image: -webkit-linear-gradient(top, #ffffff, #f2f2f2);
+                       background-image: linear-gradient(top, #ffffff, #f2f2f2);
+               }
+
+               .button:hover {
+                       color: #000;
+                       border-color: #666;
+               }
+
+               .button:active {
+                       background-image: -ms-linear-gradient(top, #f2f2f2, #ffffff);
+                       background-image: -moz-linear-gradient(top, #f2f2f2, #ffffff);
+                       background-image: -o-linear-gradient(top, #f2f2f2, #ffffff);
+                       background-image: -webkit-gradient(linear, left top, left bottom, from(#f2f2f2), to(#ffffff));
+                       background-image: -webkit-linear-gradient(top, #f2f2f2, #ffffff);
+                       background-image: linear-gradient(top, #f2f2f2, #ffffff);
+               }
+
+               <?php if ( 'rtl' == $text_direction ) : ?>
+               body { font-family: Tahoma, Arial; }
+               <?php endif; ?>
+       </style>
 </head>
 <body id="error-page">
-<?php endif; ?>
+<?php endif; // !function_exists( 'did_action' ) || !did_action( 'admin_head' ) ?>
        <?php echo $message; ?>
 </body>
 </html>
@@ -2758,10 +2933,46 @@ if ( 'rtl' == $text_direction ) : ?>
        die();
 }
 
+/**
+ * Kill WordPress execution and display XML message with error message.
+ *
+ * This is the handler for wp_die when processing XMLRPC requests.
+ *
+ * @since 3.2.0
+ * @access private
+ *
+ * @param string $message Error message.
+ * @param string $title Error title.
+ * @param string|array $args Optional arguments to control behavior.
+ */
+function _xmlrpc_wp_die_handler( $message, $title = '', $args = array() ) {
+       global $wp_xmlrpc_server;
+       $defaults = array( 'response' => 500 );
+
+       $r = wp_parse_args($args, $defaults);
+
+       if ( $wp_xmlrpc_server ) {
+               $error = new IXR_Error( $r['response'] , $message);
+               $wp_xmlrpc_server->output( $error->getXml() );
+       }
+       die();
+}
+
+/**
+ * Filter to enable special wp_die handler for xmlrpc requests.
+ *
+ * @since 3.2.0
+ * @access private
+ */
+function _xmlrpc_wp_die_filter() {
+       return '_xmlrpc_wp_die_handler';
+}
+
+
 /**
  * Retrieve the WordPress home page URL.
  *
- * If the constant named 'WP_HOME' exists, then it willl be used and returned by
+ * If the constant named 'WP_HOME' exists, then it will be used and returned by
  * the function. This can be used to counter the redirection on your local
  * development environment.
  *
@@ -2774,7 +2985,7 @@ if ( 'rtl' == $text_direction ) : ?>
  */
 function _config_wp_home( $url = '' ) {
        if ( defined( 'WP_HOME' ) )
-               return WP_HOME;
+               return untrailingslashit( WP_HOME );
        return $url;
 }
 
@@ -2794,7 +3005,7 @@ function _config_wp_home( $url = '' ) {
  */
 function _config_wp_siteurl( $url = '' ) {
        if ( defined( 'WP_SITEURL' ) )
-               return WP_SITEURL;
+               return untrailingslashit( WP_SITEURL );
        return $url;
 }
 
@@ -2963,7 +3174,7 @@ function wp_parse_args( $args, $defaults = '' ) {
 }
 
 /**
- * Clean up an array, comma- or space-separated list of IDs
+ * Clean up an array, comma- or space-separated list of IDs.
  *
  * @since 3.0.0
  *
@@ -2978,7 +3189,25 @@ function wp_parse_id_list( $list ) {
 }
 
 /**
- * Filters a list of objects, based on a set of key => value arguments
+ * Extract a slice of an array, given a list of keys.
+ *
+ * @since 3.1.0
+ *
+ * @param array $array The original array
+ * @param array $keys The list of keys
+ * @return array The array slice
+ */
+function wp_array_slice_assoc( $array, $keys ) {
+       $slice = array();
+       foreach ( $keys as $key )
+               if ( isset( $array[ $key ] ) )
+                       $slice[ $key ] = $array[ $key ];
+
+       return $slice;
+}
+
+/**
+ * Filters a list of objects, based on a set of key => value arguments.
  *
  * @since 3.0.0
  *
@@ -2990,26 +3219,55 @@ function wp_parse_id_list( $list ) {
  * @return array A list of objects or object fields
  */
 function wp_filter_object_list( $list, $args = array(), $operator = 'and', $field = false ) {
-       if ( !is_array($list) )
+       if ( ! is_array( $list ) )
                return array();
 
-       if ( empty($args) )
-               $args = array();
+       $list = wp_list_filter( $list, $args, $operator );
 
-       if ( empty($args) && !$field )
-               return $list;   // nothing to do
+       if ( $field )
+               $list = wp_list_pluck( $list, $field );
 
-       $count = count($args);
+       return $list;
+}
 
+/**
+ * Filters a list of objects, based on a set of key => value arguments.
+ *
+ * @since 3.1.0
+ *
+ * @param array $list An array of objects to filter
+ * @param array $args An array of key => value arguments to match against each object
+ * @param string $operator The logical operation to perform:
+ *    'AND' means all elements from the array must match;
+ *    'OR' means only one element needs to match;
+ *    'NOT' means no elements may match.
+ *   The default is 'AND'.
+ * @return array
+ */
+function wp_list_filter( $list, $args = array(), $operator = 'AND' ) {
+       if ( ! is_array( $list ) )
+               return array();
+
+       if ( empty( $args ) )
+               return $list;
+
+       $operator = strtoupper( $operator );
+       $count = count( $args );
        $filtered = array();
 
        foreach ( $list as $key => $obj ) {
-               $matched = count(array_intersect_assoc(get_object_vars($obj), $args));
-               if ( ('and' == $operator && $matched == $count) || ('or' == $operator && $matched <= $count) ) {
-                       if ( $field )
-                               $filtered[] = $obj->$field;
-                       else
-                               $filtered[$key] = $obj;
+               $to_match = (array) $obj;
+
+               $matched = 0;
+               foreach ( $args as $m_key => $m_value ) {
+                       if ( $m_value == $to_match[ $m_key ] )
+                               $matched++;
+               }
+
+               if ( ( 'AND' == $operator && $matched == $count )
+                 || ( 'OR' == $operator && $matched > 0 )
+                 || ( 'NOT' == $operator && 0 == $matched ) ) {
+                       $filtered[$key] = $obj;
                }
        }
 
@@ -3017,17 +3275,23 @@ function wp_filter_object_list( $list, $args = array(), $operator = 'and', $fiel
 }
 
 /**
- * Determines if default embed handlers should be loaded.
+ * Pluck a certain field out of each object in a list.
  *
- * Checks to make sure that the embeds library hasn't already been loaded. If
- * it hasn't, then it will load the embeds library.
+ * @since 3.1.0
  *
- * @since 2.9.0
+ * @param array $list A list of objects or arrays
+ * @param int|string $field A field from the object to place instead of the entire object
+ * @return array
  */
-function wp_maybe_load_embeds() {
-       if ( ! apply_filters('load_default_embeds', true) )
-               return;
-       require_once( ABSPATH . WPINC . '/default-embeds.php' );
+function wp_list_pluck( $list, $field ) {
+       foreach ( $list as $key => $value ) {
+               if ( is_object( $value ) )
+                       $list[ $key ] = $value->$field;
+               else
+                       $list[ $key ] = $value[ $field ];
+       }
+
+       return $list;
 }
 
 /**
@@ -3071,24 +3335,6 @@ function wp_ob_end_flush_all() {
                ob_end_flush();
 }
 
-/**
- * Load the correct database class file.
- *
- * This function is used to load the database class file either at runtime or by
- * wp-admin/setup-config.php We must globalise $wpdb to ensure that it is
- * defined globally by the inline code in wp-db.php.
- *
- * @since 2.5.0
- * @global $wpdb WordPress Database Object
- */
-function require_wp_db() {
-       global $wpdb;
-       if ( file_exists( WP_CONTENT_DIR . '/db.php' ) )
-               require_once( WP_CONTENT_DIR . '/db.php' );
-       else
-               require_once( ABSPATH . WPINC . '/wp-db.php' );
-}
-
 /**
  * Load custom DB error or display WordPress DB error.
  *
@@ -3124,15 +3370,15 @@ function dead_db() {
        nocache_headers();
        header( 'Content-Type: text/html; charset=utf-8' );
 ?>
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<!DOCTYPE html>
 <html xmlns="http://www.w3.org/1999/xhtml" <?php if ( function_exists( 'language_attributes' ) ) language_attributes(); ?>>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-       <title>Database Error</title>
+       <title><?php echo /*WP_I18N_DB_ERROR*/'Database Error'/*/WP_I18N_DB_ERROR*/; ?></title>
 
 </head>
 <body>
-       <h1>Error establishing a database connection</h1>
+       <h1><?php echo /*WP_I18N_DB_CONNECTION_ERROR*/'Error establishing a database connection'/*/WP_I18N_DB_CONNECTION_ERROR*/; ?></h1>
 </body>
 </html>
 <?php
@@ -3144,7 +3390,7 @@ function dead_db() {
  *
  * @since 2.5.0
  *
- * @param mixed $maybeint Data you wish to have convered to an nonnegative integer
+ * @param mixed $maybeint Data you wish to have converted to a nonnegative integer
  * @return int An nonnegative integer
  */
 function absint( $maybeint ) {
@@ -3186,22 +3432,6 @@ function url_is_accessable_via_ssl($url)
        return false;
 }
 
-/**
- * Secure URL, if available or the given URL.
- *
- * @since 2.5.0
- *
- * @param string $url Complete URL path with transport.
- * @return string Secure or regular URL path.
- */
-function atom_service_url_filter($url)
-{
-       if ( url_is_accessable_via_ssl($url) )
-               return preg_replace( '/^http:\/\//', 'https://',  $url );
-       else
-               return $url;
-}
-
 /**
  * Marks a function as deprecated and informs when it has been used.
  *
@@ -3209,9 +3439,9 @@ function atom_service_url_filter($url)
  * to get the backtrace up to what file and function called the deprecated
  * function.
  *
- * The current behavior is to trigger an user error if WP_DEBUG is true.
+ * The current behavior is to trigger a user error if WP_DEBUG is true.
  *
- * This function is to be used in every function in depreceated.php
+ * This function is to be used in every function that is deprecated.
  *
  * @package WordPress
  * @subpackage Debug
@@ -3227,7 +3457,7 @@ function atom_service_url_filter($url)
  * @param string $version The version of WordPress that deprecated the function
  * @param string $replacement Optional. The function that should have been called
  */
-function _deprecated_function( $function, $version, $replacement=null ) {
+function _deprecated_function( $function, $version, $replacement = null ) {
 
        do_action( 'deprecated_function_run', $function, $replacement, $version );
 
@@ -3247,9 +3477,9 @@ function _deprecated_function( $function, $version, $replacement=null ) {
  * to get the backtrace up to what file and function included the deprecated
  * file.
  *
- * The current behavior is to trigger an user error if WP_DEBUG is true.
+ * The current behavior is to trigger a user error if WP_DEBUG is true.
  *
- * This function is to be used in every file that is depreceated
+ * This function is to be used in every file that is deprecated.
  *
  * @package WordPress
  * @subpackage Debug
@@ -3295,7 +3525,7 @@ function _deprecated_file( $file, $version, $replacement = null, $message = '' )
  * to get the backtrace up to what file and function used the deprecated
  * argument.
  *
- * The current behavior is to trigger an user error if WP_DEBUG is true.
+ * The current behavior is to trigger a user error if WP_DEBUG is true.
  *
  * @package WordPress
  * @subpackage Debug
@@ -3325,7 +3555,41 @@ function _deprecated_argument( $function, $version, $message = null ) {
 }
 
 /**
- * Is the server running earlier than 1.5.0 version of lighttpd
+ * Marks something as being incorrectly called.
+ *
+ * There is a hook doing_it_wrong_run that will be called that can be used
+ * to get the backtrace up to what file and function called the deprecated
+ * function.
+ *
+ * The current behavior is to trigger a user error if WP_DEBUG is true.
+ *
+ * @package WordPress
+ * @subpackage Debug
+ * @since 3.1.0
+ * @access private
+ *
+ * @uses do_action() Calls 'doing_it_wrong_run' and passes the function arguments.
+ * @uses apply_filters() Calls 'doing_it_wrong_trigger_error' and expects boolean value of true to do
+ *   trigger or false to not trigger error.
+ *
+ * @param string $function The function that was called.
+ * @param string $message A message explaining what has been done incorrectly.
+ * @param string $version The version of WordPress where the message was added.
+ */
+function _doing_it_wrong( $function, $message, $version ) {
+
+       do_action( 'doing_it_wrong_run', $function, $message, $version );
+
+       // Allow plugin to filter the output error trigger
+       if ( WP_DEBUG && apply_filters( 'doing_it_wrong_trigger_error', true ) ) {
+               $version = is_null( $version ) ? '' : sprintf( __( '(This message was added in version %s.)' ), $version );
+               $message .= ' ' . __( 'Please see <a href="http://codex.wordpress.org/Debugging_in_WordPress">Debugging in WordPress</a> for more information.' );
+               trigger_error( sprintf( __( '%1$s was called <strong>incorrectly</strong>. %2$s %3$s' ), $function, $message, $version ) );
+       }
+}
+
+/**
+ * Is the server running earlier than 1.5.0 version of lighttpd?
  *
  * @since 2.5.0
  *
@@ -3338,7 +3602,7 @@ function is_lighttpd_before_150() {
 }
 
 /**
- * Does the specified module exist in the apache config?
+ * Does the specified module exist in the Apache config?
  *
  * @since 2.5.0
  *
@@ -3366,6 +3630,34 @@ function apache_mod_loaded($mod, $default = false) {
        return $default;
 }
 
+/**
+ * Check if IIS 7 supports pretty permalinks.
+ *
+ * @since 2.8.0
+ *
+ * @return bool
+ */
+function iis7_supports_permalinks() {
+       global $is_iis7;
+
+       $supports_permalinks = false;
+       if ( $is_iis7 ) {
+               /* First we check if the DOMDocument class exists. If it does not exist,
+                * which is the case for PHP 4.X, then we cannot easily update the xml configuration file,
+                * hence we just bail out and tell user that pretty permalinks cannot be used.
+                * This is not a big issue because PHP 4.X is going to be deprecated and for IIS it
+                * is recommended to use PHP 5.X NTS.
+                * Next we check if the URL Rewrite Module 1.1 is loaded and enabled for the web site. When
+                * URL Rewrite 1.1 is loaded it always sets a server variable called 'IIS_UrlRewriteModule'.
+                * Lastly we make sure that PHP is running via FastCGI. This is important because if it runs
+                * via ISAPI then pretty permalinks will not work.
+                */
+               $supports_permalinks = class_exists('DOMDocument') && isset($_SERVER['IIS_UrlRewriteModule']) && ( php_sapi_name() == 'cgi-fcgi' );
+       }
+
+       return apply_filters('iis7_supports_permalinks', $supports_permalinks);
+}
+
 /**
  * File validates against allowed set of defined rules.
  *
@@ -3381,16 +3673,16 @@ function apache_mod_loaded($mod, $default = false) {
  * @return int 0 means nothing is wrong, greater than 0 means something was wrong.
  */
 function validate_file( $file, $allowed_files = '' ) {
-       if ( false !== strpos( $file, '..' ))
+       if ( false !== strpos( $file, '..' ) )
                return 1;
 
-       if ( false !== strpos( $file, './' ))
+       if ( false !== strpos( $file, './' ) )
                return 1;
 
-       if (!empty ( $allowed_files ) && (!in_array( $file, $allowed_files ) ) )
+       if ( ! empty( $allowed_files ) && ! in_array( $file, $allowed_files ) )
                return 3;
 
-       if (':' == substr( $file, 1, 1 ))
+       if (':' == substr( $file, 1, 1 ) )
                return 2;
 
        return 0;
@@ -3436,7 +3728,7 @@ function force_ssl_login( $force = null ) {
 }
 
 /**
- * Whether to force SSL used for the Administration Panels.
+ * Whether to force SSL used for the Administration Screens.
  *
  * @since 2.6.0
  *
@@ -3472,7 +3764,31 @@ function wp_guess_url() {
                $schema = is_ssl() ? 'https://' : 'http://';
                $url = preg_replace('|/wp-admin/.*|i', '', $schema . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
        }
-       return $url;
+       return rtrim($url, '/');
+}
+
+/**
+ * Temporarily suspend cache additions.
+ *
+ * Stops more data being added to the cache, but still allows cache retrieval.
+ * This is useful for actions, such as imports, when a lot of data would otherwise
+ * be almost uselessly added to the cache.
+ *
+ * Suspension lasts for a single page load at most. Remember to call this
+ * function again if you wish to re-enable cache adds earlier.
+ *
+ * @since 3.3.0
+ *
+ * @param bool $suspend Optional. Suspends additions if true, re-enables them if false.
+ * @return bool The current suspend setting
+ */
+function wp_suspend_cache_addition( $suspend = null ) {
+       static $_suspend = false;
+
+       if ( is_bool( $suspend ) )
+               $_suspend = $suspend;
+
+       return $_suspend;
 }
 
 /**
@@ -3533,14 +3849,13 @@ function get_site_option( $option, $default = false, $use_cache = true ) {
                        $row = $wpdb->get_row( $wpdb->prepare("SELECT meta_value FROM $wpdb->sitemeta WHERE meta_key = %s AND site_id = %d", $option, $wpdb->siteid ) );
 
                        // Has to be get_row instead of get_var because of funkiness with 0, false, null values
-                       if ( is_object( $row ) )
+                       if ( is_object( $row ) ) {
                                $value = $row->meta_value;
-                       else
+                               $value = maybe_unserialize( $value );
+                               wp_cache_set( $cache_key, $value, 'site-options' );
+                       } else {
                                $value = $default;
-
-                       $value = maybe_unserialize( $value );
-
-                       wp_cache_set( $cache_key, $value, 'site-options' );
+                       }
                }
        }
 
@@ -3550,6 +3865,8 @@ function get_site_option( $option, $default = false, $use_cache = true ) {
 /**
  * Add a new site option.
  *
+ * Existing options will not be updated. Note that prior to 3.3 this wasn't the case.
+ *
  * @see add_option()
  * @package WordPress
  * @subpackage Option
@@ -3573,22 +3890,24 @@ function add_site_option( $option, $value ) {
        } else {
                $cache_key = "{$wpdb->siteid}:$option";
 
-               if ( $wpdb->get_row( $wpdb->prepare( "SELECT meta_value FROM $wpdb->sitemeta WHERE meta_key = %s AND site_id = %d", $option, $wpdb->siteid ) ) )
-                       return update_site_option( $option, $value );
+               if ( false !== get_site_option( $option ) )
+                       return false;
 
                $value = sanitize_option( $option, $value );
                wp_cache_set( $cache_key, $value, 'site-options' );
 
                $_value = $value;
-               $value = maybe_serialize($value);
+               $value = maybe_serialize( $value );
                $result = $wpdb->insert( $wpdb->sitemeta, array('site_id' => $wpdb->siteid, 'meta_key' => $option, 'meta_value' => $value ) );
                $value = $_value;
        }
 
-       do_action( "add_site_option_{$option}", $option, $value );
-       do_action( "add_site_option", $option, $value );
-
-       return $result;
+       if ( $result ) {
+               do_action( "add_site_option_{$option}", $option, $value );
+               do_action( "add_site_option", $option, $value );
+               return true;
+       }
+       return false;
 }
 
 /**
@@ -3658,14 +3977,14 @@ function update_site_option( $option, $value ) {
        if ( $value === $oldvalue )
                return false;
 
+       if ( false === $oldvalue )
+               return add_site_option( $option, $value );
+
        if ( !is_multisite() ) {
                $result = update_option( $option, $value );
        } else {
-               $cache_key = "{$wpdb->siteid}:$option";
-
-               if ( $value && !$wpdb->get_row( $wpdb->prepare( "SELECT meta_value FROM $wpdb->sitemeta WHERE meta_key = %s AND site_id = %d", $option, $wpdb->siteid ) ) )
-                       return add_site_option( $option, $value );
                $value = sanitize_option( $option, $value );
+               $cache_key = "{$wpdb->siteid}:$option";
                wp_cache_set( $cache_key, $value, 'site-options' );
 
                $_value = $value;
@@ -3675,15 +3994,15 @@ function update_site_option( $option, $value ) {
        }
 
        if ( $result ) {
-               do_action( "update_site_option_{$option}", $option, $value );
-               do_action( "update_site_option", $option, $value );
+               do_action( "update_site_option_{$option}", $option, $value, $oldvalue );
+               do_action( "update_site_option", $option, $value, $oldvalue );
                return true;
        }
        return false;
 }
 
 /**
- * Delete a site transient
+ * Delete a site transient.
  *
  * @since 2.9.0
  * @package WordPress
@@ -3714,7 +4033,7 @@ function delete_site_transient( $transient ) {
 }
 
 /**
- * Get the value of a site transient
+ * Get the value of a site transient.
  *
  * If the transient does not exist or does not have a value, then the return value
  * will be false.
@@ -3763,7 +4082,7 @@ function get_site_transient( $transient ) {
 }
 
 /**
- * Set/update the value of a site transient
+ * Set/update the value of a site transient.
  *
  * You do not need to serialize values, if the value needs to be serialize, then
  * it will be serialized before it is set.
@@ -3785,7 +4104,7 @@ function get_site_transient( $transient ) {
 function set_site_transient( $transient, $value, $expiration = 0 ) {
        global $_wp_using_ext_object_cache;
 
-    $value = apply_filters( 'pre_set_site_transient_' . $transient, $value );
+       $value = apply_filters( 'pre_set_site_transient_' . $transient, $value );
 
        if ( $_wp_using_ext_object_cache ) {
                $result = wp_cache_set( $transient, $value, 'site-transient', $expiration );
@@ -3810,7 +4129,7 @@ function set_site_transient( $transient, $value, $expiration = 0 ) {
 }
 
 /**
- * is main site
+ * Is main site?
  *
  *
  * @since 3.0.0
@@ -3856,18 +4175,15 @@ function global_terms_enabled() {
 }
 
 /**
- * gmt_offset modification for smart timezone handling
+ * gmt_offset modification for smart timezone handling.
  *
- * Overrides the gmt_offset option if we have a timezone_string available
+ * Overrides the gmt_offset option if we have a timezone_string available.
  *
  * @since 2.8.0
  *
  * @return float|bool
  */
 function wp_timezone_override_offset() {
-       if ( !wp_timezone_supported() ) {
-               return false;
-       }
        if ( !$timezone_string = get_option( 'timezone_string' ) ) {
                return false;
        }
@@ -3880,27 +4196,6 @@ function wp_timezone_override_offset() {
        return round( timezone_offset_get( $timezone_object, $datetime_object ) / 3600, 2 );
 }
 
-/**
- * Check for PHP timezone support
- *
- * @since 2.9.0
- *
- * @return bool
- */
-function wp_timezone_supported() {
-       $support = false;
-       if (
-               function_exists( 'date_create' ) &&
-               function_exists( 'date_default_timezone_set' ) &&
-               function_exists( 'timezone_identifiers_list' ) &&
-               function_exists( 'timezone_open' ) &&
-               function_exists( 'timezone_offset_get' )
-       ) {
-               $support = true;
-       }
-       return apply_filters( 'timezone_support', $support );
-}
-
 /**
  * {@internal Missing Short Description}}
  *
@@ -3949,7 +4244,7 @@ function _wp_timezone_choice_usort_callback( $a, $b ) {
 }
 
 /**
- * Gives a nicely formatted list of timezone strings // temporary! Not in final
+ * Gives a nicely formatted list of timezone strings. // temporary! Not in final
  *
  * @since 2.9.0
  *
@@ -4078,7 +4373,7 @@ function wp_timezone_choice( $selected_zone ) {
 }
 
 /**
- * Strip close comment and close php tags from file headers used by WP
+ * Strip close comment and close php tags from file headers used by WP.
  * See http://core.trac.wordpress.org/ticket/8497
  *
  * @since 2.8.0
@@ -4136,29 +4431,21 @@ function wp_scheduled_delete() {
 }
 
 /**
- * Parse the file contents to retrieve its metadata.
- *
- * Searches for metadata for a file, such as a plugin or theme.  Each piece of
- * metadata must be on its own line. For a field spanning multple lines, it
- * must not have any newlines or only parts of it will be displayed.
+ * Retrieve metadata from a file.
  *
- * Some users have issues with opening large files and manipulating the contents
- * for want is usually the first 1kiB or 2kiB. This function stops pulling in
- * the file contents when it has all of the required data.
+ * Searches for metadata in the first 8kiB of a file, such as a plugin or theme.
+ * Each piece of metadata must be on its own line. Fields can not span multiple
+ * lines, the value will get cut at the end of the first line.
  *
- * The first 8kiB of the file will be pulled in and if the file data is not
- * within that first 8kiB, then the author should correct their plugin file
- * and move the data headers to the top.
+ * If the file data is not within that first 8kiB, then the author should correct
+ * their plugin file and move the data headers to the top.
  *
- * The file is assumed to have permissions to allow for scripts to read
- * the file. This is not checked however and the file is only opened for
- * reading.
+ * @see http://codex.wordpress.org/File_Header
  *
  * @since 2.9.0
- *
  * @param string $file Path to the file
- * @param bool $markup If the returned data should have HTML markup applied
- * @param string $context If specified adds filter hook "extra_<$context>_headers"
+ * @param array $default_headers List of headers, in the format array('HeaderKey' => 'Header Name')
+ * @param string $context If specified adds filter hook "extra_{$context}_headers"
  */
 function get_file_data( $file, $default_headers, $context = '' ) {
        // We don't need to write to the file, so just open for reading.
@@ -4171,20 +4458,19 @@ function get_file_data( $file, $default_headers, $context = '' ) {
        fclose( $fp );
 
        if ( $context != '' ) {
-               $extra_headers = apply_filters( "extra_$context".'_headers', array() );
+               $extra_headers = apply_filters( "extra_{$context}_headers", array() );
 
                $extra_headers = array_flip( $extra_headers );
                foreach( $extra_headers as $key=>$value ) {
                        $extra_headers[$key] = $key;
                }
-               $all_headers = array_merge($extra_headers, $default_headers);
+               $all_headers = array_merge( $extra_headers, (array) $default_headers );
        } else {
                $all_headers = $default_headers;
        }
 
-
        foreach ( $all_headers as $field => $regex ) {
-               preg_match( '/' . preg_quote( $regex, '/' ) . ':(.*)$/mi', $file_data, ${$field});
+               preg_match( '/^[ \t\/*#@]*' . preg_quote( $regex, '/' ) . ':(.*)$/mi', $file_data, ${$field});
                if ( !empty( ${$field} ) )
                        ${$field} = _cleanup_header_comment( ${$field}[1] );
                else
@@ -4195,8 +4481,9 @@ function get_file_data( $file, $default_headers, $context = '' ) {
 
        return $file_data;
 }
-/*
- * Used internally to tidy up the search terms
+
+/**
+ * Used internally to tidy up the search terms.
  *
  * @access private
  * @since 2.9.0
@@ -4209,9 +4496,9 @@ function _search_terms_tidy($t) {
 }
 
 /**
- * Returns true
+ * Returns true.
  *
- * Useful for returning true to filters easily
+ * Useful for returning true to filters easily.
  *
  * @since 3.0.0
  * @see __return_false()
@@ -4222,9 +4509,9 @@ function __return_true() {
 }
 
 /**
- * Returns false
+ * Returns false.
  *
- * Useful for returning false to filters easily
+ * Useful for returning false to filters easily.
  *
  * @since 3.0.0
  * @see __return_true()
@@ -4235,9 +4522,9 @@ function __return_false() {
 }
 
 /**
- * Returns 0
+ * Returns 0.
  *
- * Useful for returning 0 to filters easily
+ * Useful for returning 0 to filters easily.
  *
  * @since 3.0.0
  * @see __return_zero()
@@ -4248,9 +4535,9 @@ function __return_zero() {
 }
 
 /**
- * Returns an empty array
+ * Returns an empty array.
  *
- * Useful for returning an empty array to filters easily
+ * Useful for returning an empty array to filters easily.
  *
  * @since 3.0.0
  * @see __return_zero()
@@ -4297,4 +4584,102 @@ function _wp_mysql_week( $column ) {
        }
 }
 
+/**
+ * Finds hierarchy loops using a callback function that maps object IDs to parent IDs.
+ *
+ * @since 3.1.0
+ * @access private
+ *
+ * @param callback $callback function that accepts ( ID, $callback_args ) and outputs parent_ID
+ * @param int $start The ID to start the loop check at
+ * @param int $start_parent the parent_ID of $start to use instead of calling $callback( $start ). Use null to always use $callback
+ * @param array $callback_args optional additional arguments to send to $callback
+ * @return array IDs of all members of loop
+ */
+function wp_find_hierarchy_loop( $callback, $start, $start_parent, $callback_args = array() ) {
+       $override = is_null( $start_parent ) ? array() : array( $start => $start_parent );
+
+       if ( !$arbitrary_loop_member = wp_find_hierarchy_loop_tortoise_hare( $callback, $start, $override, $callback_args ) )
+               return array();
+
+       return wp_find_hierarchy_loop_tortoise_hare( $callback, $arbitrary_loop_member, $override, $callback_args, true );
+}
+
+/**
+ * Uses the "The Tortoise and the Hare" algorithm to detect loops.
+ *
+ * For every step of the algorithm, the hare takes two steps and the tortoise one.
+ * If the hare ever laps the tortoise, there must be a loop.
+ *
+ * @since 3.1.0
+ * @access private
+ *
+ * @param callback $callback function that accepts ( ID, callback_arg, ... ) and outputs parent_ID
+ * @param int $start The ID to start the loop check at
+ * @param array $override an array of ( ID => parent_ID, ... ) to use instead of $callback
+ * @param array $callback_args optional additional arguments to send to $callback
+ * @param bool $_return_loop Return loop members or just detect presence of loop?
+ *             Only set to true if you already know the given $start is part of a loop
+ *             (otherwise the returned array might include branches)
+ * @return mixed scalar ID of some arbitrary member of the loop, or array of IDs of all members of loop if $_return_loop
+ */
+function wp_find_hierarchy_loop_tortoise_hare( $callback, $start, $override = array(), $callback_args = array(), $_return_loop = false ) {
+       $tortoise = $hare = $evanescent_hare = $start;
+       $return = array();
+
+       // Set evanescent_hare to one past hare
+       // Increment hare two steps
+       while (
+               $tortoise
+       &&
+               ( $evanescent_hare = isset( $override[$hare] ) ? $override[$hare] : call_user_func_array( $callback, array_merge( array( $hare ), $callback_args ) ) )
+       &&
+               ( $hare = isset( $override[$evanescent_hare] ) ? $override[$evanescent_hare] : call_user_func_array( $callback, array_merge( array( $evanescent_hare ), $callback_args ) ) )
+       ) {
+               if ( $_return_loop )
+                       $return[$tortoise] = $return[$evanescent_hare] = $return[$hare] = true;
+
+               // tortoise got lapped - must be a loop
+               if ( $tortoise == $evanescent_hare || $tortoise == $hare )
+                       return $_return_loop ? $return : $tortoise;
+
+               // Increment tortoise by one step
+               $tortoise = isset( $override[$tortoise] ) ? $override[$tortoise] : call_user_func_array( $callback, array_merge( array( $tortoise ), $callback_args ) );
+       }
+
+       return false;
+}
+
+/**
+ * Send a HTTP header to limit rendering of pages to same origin iframes.
+ *
+ * @link https://developer.mozilla.org/en/the_x-frame-options_response_header
+ *
+ * @since 3.1.3
+ * @return none
+ */
+function send_frame_options_header() {
+       @header( 'X-Frame-Options: SAMEORIGIN' );
+}
+
+/**
+ * Retrieve a list of protocols to allow in HTML attributes.
+ *
+ * @since 3.3.0
+ * @see wp_kses()
+ * @see esc_url()
+ *
+ * @return array Array of allowed protocols
+ */
+function wp_allowed_protocols() {
+       static $protocols;
+
+       if ( empty( $protocols ) ) {
+               $protocols = array( 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn' );
+               $protocols = apply_filters( 'kses_allowed_protocols', $protocols );
+       }
+
+       return $protocols;
+}
+
 ?>