-
+ 331BFC449177FB0ED99273CA84B34C12BE2BED4930A07EE3D3005763B2E044348ED7415F5CAA74D355280886E9629F4888D13741428327C1B3F898672EB21C1A
mp-wp/wp-includes/functions.php
(0 . 0)(1 . 2905)
91625 <?php
91626 /**
91627 * Main WordPress API
91628 *
91629 * @package WordPress
91630 */
91631
91632 /**
91633 * Converts MySQL DATETIME field to user specified date format.
91634 *
91635 * If $dateformatstring has 'G' value, then gmmktime() function will be used to
91636 * make the time. If $dateformatstring is set to 'U', then mktime() function
91637 * will be used to make the time.
91638 *
91639 * The $translate will only be used, if it is set to true and it is by default
91640 * and if the $wp_locale object has the month and weekday set.
91641 *
91642 * @since 0.71
91643 *
91644 * @param string $dateformatstring Either 'G', 'U', or php date format.
91645 * @param string $mysqlstring Time from mysql DATETIME field.
91646 * @param bool $translate Optional. Default is true. Will switch format to locale.
91647 * @return string Date formated by $dateformatstring or locale (if available).
91648 */
91649 function mysql2date( $dateformatstring, $mysqlstring, $translate = true ) {
91650 global $wp_locale;
91651 $m = $mysqlstring;
91652 if ( empty( $m ) )
91653 return false;
91654
91655 if( 'G' == $dateformatstring ) {
91656 return gmmktime(
91657 (int) substr( $m, 11, 2 ), (int) substr( $m, 14, 2 ), (int) substr( $m, 17, 2 ),
91658 (int) substr( $m, 5, 2 ), (int) substr( $m, 8, 2 ), (int) substr( $m, 0, 4 )
91659 );
91660 }
91661
91662 $i = mktime(
91663 (int) substr( $m, 11, 2 ), (int) substr( $m, 14, 2 ), (int) substr( $m, 17, 2 ),
91664 (int) substr( $m, 5, 2 ), (int) substr( $m, 8, 2 ), (int) substr( $m, 0, 4 )
91665 );
91666
91667 if( 'U' == $dateformatstring )
91668 return $i;
91669
91670 if ( -1 == $i || false == $i )
91671 $i = 0;
91672
91673 if ( !empty( $wp_locale->month ) && !empty( $wp_locale->weekday ) && $translate ) {
91674 $datemonth = $wp_locale->get_month( date( 'm', $i ) );
91675 $datemonth_abbrev = $wp_locale->get_month_abbrev( $datemonth );
91676 $dateweekday = $wp_locale->get_weekday( date( 'w', $i ) );
91677 $dateweekday_abbrev = $wp_locale->get_weekday_abbrev( $dateweekday );
91678 $datemeridiem = $wp_locale->get_meridiem( date( 'a', $i ) );
91679 $datemeridiem_capital = $wp_locale->get_meridiem( date( 'A', $i ) );
91680 $dateformatstring = ' ' . $dateformatstring;
91681 $dateformatstring = preg_replace( "/([^\\\])D/", "\\1" . backslashit( $dateweekday_abbrev ), $dateformatstring );
91682 $dateformatstring = preg_replace( "/([^\\\])F/", "\\1" . backslashit( $datemonth ), $dateformatstring );
91683 $dateformatstring = preg_replace( "/([^\\\])l/", "\\1" . backslashit( $dateweekday ), $dateformatstring );
91684 $dateformatstring = preg_replace( "/([^\\\])M/", "\\1" . backslashit( $datemonth_abbrev ), $dateformatstring );
91685 $dateformatstring = preg_replace( "/([^\\\])a/", "\\1" . backslashit( $datemeridiem ), $dateformatstring );
91686 $dateformatstring = preg_replace( "/([^\\\])A/", "\\1" . backslashit( $datemeridiem_capital ), $dateformatstring );
91687
91688 $dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 );
91689 }
91690 $j = @date( $dateformatstring, $i );
91691
91692 /*
91693 if ( !$j ) // for debug purposes
91694 echo $i." ".$mysqlstring;
91695 */
91696
91697 return $j;
91698 }
91699
91700 /**
91701 * Retrieve the current time based on specified type.
91702 *
91703 * The 'mysql' type will return the time in the format for MySQL DATETIME field.
91704 * The 'timestamp' type will return the current timestamp.
91705 *
91706 * If the $gmt is set to either '1' or 'true', then both types will use the
91707 * GMT offset in the WordPress option to add the GMT offset to the time.
91708 *
91709 * @since 1.0.0
91710 *
91711 * @param string $type Either 'mysql' or 'timestamp'.
91712 * @param int|bool $gmt Optional. Whether to use $gmt offset. Default is false.
91713 * @return int|string String if $type is 'gmt', int if $type is 'timestamp'.
91714 */
91715 function current_time( $type, $gmt = 0 ) {
91716 switch ( $type ) {
91717 case 'mysql':
91718 return ( $gmt ) ? gmdate( 'Y-m-d H:i:s' ) : gmdate( 'Y-m-d H:i:s', ( time() + ( get_option( 'gmt_offset' ) * 3600 ) ) );
91719 break;
91720 case 'timestamp':
91721 return ( $gmt ) ? time() : time() + ( get_option( 'gmt_offset' ) * 3600 );
91722 break;
91723 }
91724 }
91725
91726 /**
91727 * Retrieve the date in localized format, based on timestamp.
91728 *
91729 * If the locale specifies the locale month and weekday, then the locale will
91730 * take over the format for the date. If it isn't, then the date format string
91731 * will be used instead.
91732 *
91733 * @since 0.71
91734 *
91735 * @param string $dateformatstring Format to display the date
91736 * @param int $unixtimestamp Unix timestamp
91737 * @return string The date, translated if locale specifies it.
91738 */
91739 function date_i18n( $dateformatstring, $unixtimestamp = false, $gmt = false ) {
91740 global $wp_locale;
91741 $i = $unixtimestamp;
91742 // Sanity check for PHP 5.1.0-
91743 if ( false === $i || intval($i) < 0 ) {
91744 if ( ! $gmt )
91745 $i = current_time( 'timestamp' );
91746 else
91747 $i = time();
91748 // we should not let date() interfere with our
91749 // specially computed timestamp
91750 $gmt = true;
91751 }
91752
91753 $datefunc = $gmt? 'gmdate' : 'date';
91754
91755 if ( ( !empty( $wp_locale->month ) ) && ( !empty( $wp_locale->weekday ) ) ) {
91756 $datemonth = $wp_locale->get_month( $datefunc( 'm', $i ) );
91757 $datemonth_abbrev = $wp_locale->get_month_abbrev( $datemonth );
91758 $dateweekday = $wp_locale->get_weekday( $datefunc( 'w', $i ) );
91759 $dateweekday_abbrev = $wp_locale->get_weekday_abbrev( $dateweekday );
91760 $datemeridiem = $wp_locale->get_meridiem( $datefunc( 'a', $i ) );
91761 $datemeridiem_capital = $wp_locale->get_meridiem( $datefunc( 'A', $i ) );
91762 $dateformatstring = ' '.$dateformatstring;
91763 $dateformatstring = preg_replace( "/([^\\\])D/", "\\1" . backslashit( $dateweekday_abbrev ), $dateformatstring );
91764 $dateformatstring = preg_replace( "/([^\\\])F/", "\\1" . backslashit( $datemonth ), $dateformatstring );
91765 $dateformatstring = preg_replace( "/([^\\\])l/", "\\1" . backslashit( $dateweekday ), $dateformatstring );
91766 $dateformatstring = preg_replace( "/([^\\\])M/", "\\1" . backslashit( $datemonth_abbrev ), $dateformatstring );
91767 $dateformatstring = preg_replace( "/([^\\\])a/", "\\1" . backslashit( $datemeridiem ), $dateformatstring );
91768 $dateformatstring = preg_replace( "/([^\\\])A/", "\\1" . backslashit( $datemeridiem_capital ), $dateformatstring );
91769
91770 $dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 );
91771 }
91772 $j = @$datefunc( $dateformatstring, $i );
91773 return $j;
91774 }
91775
91776 /**
91777 * Convert number to format based on the locale.
91778 *
91779 * @since 2.3.0
91780 *
91781 * @param mixed $number The number to convert based on locale.
91782 * @param int $decimals Precision of the number of decimal places.
91783 * @return string Converted number in string format.
91784 */
91785 function number_format_i18n( $number, $decimals = null ) {
91786 global $wp_locale;
91787 // let the user override the precision only
91788 $decimals = ( is_null( $decimals ) ) ? $wp_locale->number_format['decimals'] : intval( $decimals );
91789
91790 return number_format( $number, $decimals, $wp_locale->number_format['decimal_point'], $wp_locale->number_format['thousands_sep'] );
91791 }
91792
91793 /**
91794 * Convert number of bytes largest unit bytes will fit into.
91795 *
91796 * It is easier to read 1kB than 1024 bytes and 1MB than 1048576 bytes. Converts
91797 * number of bytes to human readable number by taking the number of that unit
91798 * that the bytes will go into it. Supports TB value.
91799 *
91800 * Please note that integers in PHP are limited to 32 bits, unless they are on
91801 * 64 bit architecture, then they have 64 bit size. If you need to place the
91802 * larger size then what PHP integer type will hold, then use a string. It will
91803 * be converted to a double, which should always have 64 bit length.
91804 *
91805 * Technically the correct unit names for powers of 1024 are KiB, MiB etc.
91806 * @link http://en.wikipedia.org/wiki/Byte
91807 *
91808 * @since 2.3.0
91809 *
91810 * @param int|string $bytes Number of bytes. Note max integer size for integers.
91811 * @param int $decimals Precision of number of decimal places.
91812 * @return bool|string False on failure. Number string on success.
91813 */
91814 function size_format( $bytes, $decimals = null ) {
91815 $quant = array(
91816 // ========================= Origin ====
91817 'TB' => 1099511627776, // pow( 1024, 4)
91818 'GB' => 1073741824, // pow( 1024, 3)
91819 'MB' => 1048576, // pow( 1024, 2)
91820 'kB' => 1024, // pow( 1024, 1)
91821 'B ' => 1, // pow( 1024, 0)
91822 );
91823
91824 foreach ( $quant as $unit => $mag )
91825 if ( doubleval($bytes) >= $mag )
91826 return number_format_i18n( $bytes / $mag, $decimals ) . ' ' . $unit;
91827
91828 return false;
91829 }
91830
91831 /**
91832 * Get the week start and end from the datetime or date string from mysql.
91833 *
91834 * @since 0.71
91835 *
91836 * @param string $mysqlstring Date or datetime field type from mysql.
91837 * @param int $start_of_week Optional. Start of the week as an integer.
91838 * @return array Keys are 'start' and 'end'.
91839 */
91840 function get_weekstartend( $mysqlstring, $start_of_week = '' ) {
91841 $my = substr( $mysqlstring, 0, 4 ); // Mysql string Year
91842 $mm = substr( $mysqlstring, 8, 2 ); // Mysql string Month
91843 $md = substr( $mysqlstring, 5, 2 ); // Mysql string day
91844 $day = mktime( 0, 0, 0, $md, $mm, $my ); // The timestamp for mysqlstring day.
91845 $weekday = date( 'w', $day ); // The day of the week from the timestamp
91846 $i = 86400; // One day
91847 if( !is_numeric($start_of_week) )
91848 $start_of_week = get_option( 'start_of_week' );
91849
91850 if ( $weekday < $start_of_week )
91851 $weekday = 7 - $start_of_week - $weekday;
91852
91853 while ( $weekday > $start_of_week ) {
91854 $weekday = date( 'w', $day );
91855 if ( $weekday < $start_of_week )
91856 $weekday = 7 - $start_of_week - $weekday;
91857
91858 $day -= 86400;
91859 $i = 0;
91860 }
91861 $week['start'] = $day + 86400 - $i;
91862 $week['end'] = $week['start'] + 604799;
91863 return $week;
91864 }
91865
91866 /**
91867 * Unserialize value only if it was serialized.
91868 *
91869 * @since 2.0.0
91870 *
91871 * @param string $original Maybe unserialized original, if is needed.
91872 * @return mixed Unserialized data can be any type.
91873 */
91874 function maybe_unserialize( $original ) {
91875 if ( is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in
91876 if ( false !== $gm = @unserialize( $original ) )
91877 return $gm;
91878 return $original;
91879 }
91880
91881 /**
91882 * Check value to find if it was serialized.
91883 *
91884 * If $data is not an string, then returned value will always be false.
91885 * Serialized data is always a string.
91886 *
91887 * @since 2.0.5
91888 *
91889 * @param mixed $data Value to check to see if was serialized.
91890 * @return bool False if not serialized and true if it was.
91891 */
91892 function is_serialized( $data ) {
91893 // if it isn't a string, it isn't serialized
91894 if ( !is_string( $data ) )
91895 return false;
91896 $data = trim( $data );
91897 if ( 'N;' == $data )
91898 return true;
91899 if ( !preg_match( '/^([adObis]):/', $data, $badions ) )
91900 return false;
91901 switch ( $badions[1] ) {
91902 case 'a' :
91903 case 'O' :
91904 case 's' :
91905 if ( preg_match( "/^{$badions[1]}:[0-9]+:.*[;}]\$/s", $data ) )
91906 return true;
91907 break;
91908 case 'b' :
91909 case 'i' :
91910 case 'd' :
91911 if ( preg_match( "/^{$badions[1]}:[0-9.E-]+;\$/", $data ) )
91912 return true;
91913 break;
91914 }
91915 return false;
91916 }
91917
91918 /**
91919 * Check whether serialized data is of string type.
91920 *
91921 * @since 2.0.5
91922 *
91923 * @param mixed $data Serialized data
91924 * @return bool False if not a serialized string, true if it is.
91925 */
91926 function is_serialized_string( $data ) {
91927 // if it isn't a string, it isn't a serialized string
91928 if ( !is_string( $data ) )
91929 return false;
91930 $data = trim( $data );
91931 if ( preg_match( '/^s:[0-9]+:.*;$/s', $data ) ) // this should fetch all serialized strings
91932 return true;
91933 return false;
91934 }
91935
91936 /**
91937 * Retrieve option value based on setting name.
91938 *
91939 * If the option does not exist or does not have a value, then the return value
91940 * will be false. This is useful to check whether you need to install an option
91941 * and is commonly used during installation of plugin options and to test
91942 * whether upgrading is required.
91943 *
91944 * You can "short-circuit" the retrieval of the option from the database for
91945 * your plugin or core options that aren't protected. You can do so by hooking
91946 * into the 'pre_option_$option' with the $option being replaced by the option
91947 * name. You should not try to override special options, but you will not be
91948 * prevented from doing so.
91949 *
91950 * There is a second filter called 'option_$option' with the $option being
91951 * replaced with the option name. This gives the value as the only parameter.
91952 *
91953 * If the option was serialized, when the option was added and, or updated, then
91954 * it will be unserialized, when it is returned.
91955 *
91956 * @since 1.5.0
91957 * @package WordPress
91958 * @subpackage Option
91959 * @uses apply_filters() Calls 'pre_option_$optionname' false to allow
91960 * overwriting the option value in a plugin.
91961 * @uses apply_filters() Calls 'option_$optionname' with the option name value.
91962 *
91963 * @param string $setting Name of option to retrieve. Should already be SQL-escaped
91964 * @return mixed Value set for the option.
91965 */
91966 function get_option( $setting, $default = false ) {
91967 global $wpdb;
91968
91969 // Allow plugins to short-circuit options.
91970 $pre = apply_filters( 'pre_option_' . $setting, false );
91971 if ( false !== $pre )
91972 return $pre;
91973
91974 // prevent non-existent options from triggering multiple queries
91975 $notoptions = wp_cache_get( 'notoptions', 'options' );
91976 if ( isset( $notoptions[$setting] ) )
91977 return $default;
91978
91979 $alloptions = wp_load_alloptions();
91980
91981 if ( isset( $alloptions[$setting] ) ) {
91982 $value = $alloptions[$setting];
91983 } else {
91984 $value = wp_cache_get( $setting, 'options' );
91985
91986 if ( false === $value ) {
91987 if ( defined( 'WP_INSTALLING' ) )
91988 $suppress = $wpdb->suppress_errors();
91989 // expected_slashed ($setting)
91990 $row = $wpdb->get_row( "SELECT option_value FROM $wpdb->options WHERE option_name = '$setting' LIMIT 1" );
91991 if ( defined( 'WP_INSTALLING' ) )
91992 $wpdb->suppress_errors($suppress);
91993
91994 if ( is_object( $row) ) { // Has to be get_row instead of get_var because of funkiness with 0, false, null values
91995 $value = $row->option_value;
91996 wp_cache_add( $setting, $value, 'options' );
91997 } else { // option does not exist, so we must cache its non-existence
91998 $notoptions[$setting] = true;
91999 wp_cache_set( 'notoptions', $notoptions, 'options' );
92000 return $default;
92001 }
92002 }
92003 }
92004
92005 // If home is not set use siteurl.
92006 if ( 'home' == $setting && '' == $value )
92007 return get_option( 'siteurl' );
92008
92009 if ( in_array( $setting, array('siteurl', 'home', 'category_base', 'tag_base') ) )
92010 $value = untrailingslashit( $value );
92011
92012 return apply_filters( 'option_' . $setting, maybe_unserialize( $value ) );
92013 }
92014
92015 /**
92016 * Protect WordPress special option from being modified.
92017 *
92018 * Will die if $option is in protected list. Protected options are 'alloptions'
92019 * and 'notoptions' options.
92020 *
92021 * @since 2.2.0
92022 * @package WordPress
92023 * @subpackage Option
92024 *
92025 * @param string $option Option name.
92026 */
92027 function wp_protect_special_option( $option ) {
92028 $protected = array( 'alloptions', 'notoptions' );
92029 if ( in_array( $option, $protected ) )
92030 die( sprintf( __( '%s is a protected WP option and may not be modified' ), wp_specialchars( $option ) ) );
92031 }
92032
92033 /**
92034 * Print option value after sanitizing for forms.
92035 *
92036 * @uses attribute_escape Sanitizes value.
92037 * @since 1.5.0
92038 * @package WordPress
92039 * @subpackage Option
92040 *
92041 * @param string $option Option name.
92042 */
92043 function form_option( $option ) {
92044 echo attribute_escape (get_option( $option ) );
92045 }
92046
92047 /**
92048 * Retrieve all autoload options or all options, if no autoloaded ones exist.
92049 *
92050 * This is different from wp_load_alloptions() in that this function does not
92051 * cache its results and will retrieve all options from the database every time
92052 *
92053 * it is called.
92054 *
92055 * @since 1.0.0
92056 * @package WordPress
92057 * @subpackage Option
92058 * @uses apply_filters() Calls 'pre_option_$optionname' hook with option value as parameter.
92059 * @uses apply_filters() Calls 'all_options' on options list.
92060 *
92061 * @return array List of all options.
92062 */
92063 function get_alloptions() {
92064 global $wpdb;
92065 $show = $wpdb->hide_errors();
92066 if ( !$options = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options WHERE autoload = 'yes'" ) )
92067 $options = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options" );
92068 $wpdb->show_errors($show);
92069
92070 foreach ( (array) $options as $option ) {
92071 // "When trying to design a foolproof system,
92072 // never underestimate the ingenuity of the fools :)" -- Dougal
92073 if ( in_array( $option->option_name, array( 'siteurl', 'home', 'category_base', 'tag_base' ) ) )
92074 $option->option_value = untrailingslashit( $option->option_value );
92075 $value = maybe_unserialize( $option->option_value );
92076 $all_options->{$option->option_name} = apply_filters( 'pre_option_' . $option->option_name, $value );
92077 }
92078 return apply_filters( 'all_options', $all_options );
92079 }
92080
92081 /**
92082 * Loads and caches all autoloaded options, if available or all options.
92083 *
92084 * This is different from get_alloptions(), in that this function will cache the
92085 * options and will return the cached options when called again.
92086 *
92087 * @since 2.2.0
92088 * @package WordPress
92089 * @subpackage Option
92090 *
92091 * @return array List all options.
92092 */
92093 function wp_load_alloptions() {
92094 global $wpdb;
92095
92096 $alloptions = wp_cache_get( 'alloptions', 'options' );
92097
92098 if ( !$alloptions ) {
92099 $suppress = $wpdb->suppress_errors();
92100 if ( !$alloptions_db = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options WHERE autoload = 'yes'" ) )
92101 $alloptions_db = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options" );
92102 $wpdb->suppress_errors($suppress);
92103 $alloptions = array();
92104 foreach ( (array) $alloptions_db as $o )
92105 $alloptions[$o->option_name] = $o->option_value;
92106 wp_cache_add( 'alloptions', $alloptions, 'options' );
92107 }
92108 return $alloptions;
92109 }
92110
92111 /**
92112 * Update the value of an option that was already added.
92113 *
92114 * You do not need to serialize values, if the value needs to be serialize, then
92115 * it will be serialized before it is inserted into the database. Remember,
92116 * resources can not be serialized or added as an option.
92117 *
92118 * If the option does not exist, then the option will be added with the option
92119 * value, but you will not be able to set whether it is autoloaded. If you want
92120 * to set whether an option autoloaded, then you need to use the add_option().
92121 *
92122 * When the option is updated, then the filter named
92123 * 'update_option_$option_name', with the $option_name as the $option_name
92124 * parameter value, will be called. The hook should accept two parameters, the
92125 * first is the old parameter and the second is the new parameter.
92126 *
92127 * @since 1.0.0
92128 * @package WordPress
92129 * @subpackage Option
92130 *
92131 * @param string $option_name Option name. Expected to not be SQL-escaped
92132 * @param mixed $newvalue Option value.
92133 * @return bool False if value was not updated and true if value was updated.
92134 */
92135 function update_option( $option_name, $newvalue ) {
92136 global $wpdb;
92137
92138 wp_protect_special_option( $option_name );
92139
92140 $safe_option_name = $wpdb->escape( $option_name );
92141 $newvalue = sanitize_option( $option_name, $newvalue );
92142
92143 $oldvalue = get_option( $safe_option_name );
92144
92145 $newvalue = apply_filters( 'pre_update_option_' . $option_name, $newvalue, $oldvalue );
92146
92147 // If the new and old values are the same, no need to update.
92148 if ( $newvalue === $oldvalue )
92149 return false;
92150
92151 if ( false === $oldvalue ) {
92152 add_option( $option_name, $newvalue );
92153 return true;
92154 }
92155
92156 $notoptions = wp_cache_get( 'notoptions', 'options' );
92157 if ( is_array( $notoptions ) && isset( $notoptions[$option_name] ) ) {
92158 unset( $notoptions[$option_name] );
92159 wp_cache_set( 'notoptions', $notoptions, 'options' );
92160 }
92161
92162 $_newvalue = $newvalue;
92163 $newvalue = maybe_serialize( $newvalue );
92164
92165 $alloptions = wp_load_alloptions();
92166 if ( isset( $alloptions[$option_name] ) ) {
92167 $alloptions[$option_name] = $newvalue;
92168 wp_cache_set( 'alloptions', $alloptions, 'options' );
92169 } else {
92170 wp_cache_set( $option_name, $newvalue, 'options' );
92171 }
92172
92173 $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->options SET option_value = %s WHERE option_name = %s", $newvalue, $option_name ) );
92174 if ( $wpdb->rows_affected == 1 ) {
92175 do_action( "update_option_{$option_name}", $oldvalue, $_newvalue );
92176 return true;
92177 }
92178 return false;
92179 }
92180
92181 /**
92182 * Add a new option.
92183 *
92184 * You do not need to serialize values, if the value needs to be serialize, then
92185 * it will be serialized before it is inserted into the database. Remember,
92186 * resources can not be serialized or added as an option.
92187 *
92188 * You can create options without values and then add values later. Does not
92189 * check whether the option has already been added, but does check that you
92190 * aren't adding a protected WordPress option. Care should be taken to not name
92191 * options, the same as the ones which are protected and to not add options
92192 * that were already added.
92193 *
92194 * The filter named 'add_option_$optionname', with the $optionname being
92195 * replaced with the option's name, will be called. The hook should accept two
92196 * parameters, the first is the option name, and the second is the value.
92197 *
92198 * @package WordPress
92199 * @subpackage Option
92200 * @since 1.0.0
92201 * @link http://alex.vort-x.net/blog/ Thanks Alex Stapleton
92202 *
92203 * @param string $name Option name to add. Expects to NOT be SQL escaped.
92204 * @param mixed $value Optional. Option value, can be anything.
92205 * @param mixed $deprecated Optional. Description. Not used anymore.
92206 * @param bool $autoload Optional. Default is enabled. Whether to load the option when WordPress starts up.
92207 * @return null returns when finished.
92208 */
92209 function add_option( $name, $value = '', $deprecated = '', $autoload = 'yes' ) {
92210 global $wpdb;
92211
92212 wp_protect_special_option( $name );
92213 $safe_name = $wpdb->escape( $name );
92214 $value = sanitize_option( $name, $value );
92215
92216 // Make sure the option doesn't already exist. We can check the 'notoptions' cache before we ask for a db query
92217 $notoptions = wp_cache_get( 'notoptions', 'options' );
92218 if ( !is_array( $notoptions ) || !isset( $notoptions[$name] ) )
92219 if ( false !== get_option( $safe_name ) )
92220 return;
92221
92222 $value = maybe_serialize( $value );
92223 $autoload = ( 'no' === $autoload ) ? 'no' : 'yes';
92224
92225 if ( 'yes' == $autoload ) {
92226 $alloptions = wp_load_alloptions();
92227 $alloptions[$name] = $value;
92228 wp_cache_set( 'alloptions', $alloptions, 'options' );
92229 } else {
92230 wp_cache_set( $name, $value, 'options' );
92231 }
92232
92233 // This option exists now
92234 $notoptions = wp_cache_get( 'notoptions', 'options' ); // yes, again... we need it to be fresh
92235 if ( is_array( $notoptions ) && isset( $notoptions[$name] ) ) {
92236 unset( $notoptions[$name] );
92237 wp_cache_set( 'notoptions', $notoptions, 'options' );
92238 }
92239
92240 $wpdb->query( $wpdb->prepare( "INSERT INTO $wpdb->options (option_name, option_value, autoload) VALUES (%s, %s, %s)", $name, $value, $autoload ) );
92241
92242 do_action( "add_option_{$name}", $name, $value );
92243 return;
92244 }
92245
92246 /**
92247 * Removes option by name and prevents removal of protected WordPress options.
92248 *
92249 * @package WordPress
92250 * @subpackage Option
92251 * @since 1.2.0
92252 *
92253 * @param string $name Option name to remove.
92254 * @return bool True, if succeed. False, if failure.
92255 */
92256 function delete_option( $name ) {
92257 global $wpdb;
92258
92259 wp_protect_special_option( $name );
92260
92261 // Get the ID, if no ID then return
92262 // expected_slashed ($name)
92263 $option = $wpdb->get_row( "SELECT option_id, autoload FROM $wpdb->options WHERE option_name = '$name'" );
92264 if ( is_null($option) || !$option->option_id )
92265 return false;
92266 // expected_slashed ($name)
92267 $wpdb->query( "DELETE FROM $wpdb->options WHERE option_name = '$name'" );
92268 if ( 'yes' == $option->autoload ) {
92269 $alloptions = wp_load_alloptions();
92270 if ( isset( $alloptions[$name] ) ) {
92271 unset( $alloptions[$name] );
92272 wp_cache_set( 'alloptions', $alloptions, 'options' );
92273 }
92274 } else {
92275 wp_cache_delete( $name, 'options' );
92276 }
92277 return true;
92278 }
92279
92280 /**
92281 * Saves and restores user interface settings stored in a cookie.
92282 *
92283 * Checks if the current user-settings cookie is updated and stores it. When no
92284 * cookie exists (different browser used), adds the last saved cookie restoring
92285 * the settings.
92286 *
92287 * @package WordPress
92288 * @subpackage Option
92289 * @since 2.7.0
92290 */
92291 function wp_user_settings() {
92292
92293 if ( ! is_admin() )
92294 return;
92295
92296 if ( defined('DOING_AJAX') )
92297 return;
92298
92299 if ( ! $user = wp_get_current_user() )
92300 return;
92301
92302 $settings = get_user_option( 'user-settings', $user->ID, false );
92303
92304 if ( isset( $_COOKIE['wp-settings-' . $user->ID] ) ) {
92305 $cookie = preg_replace( '/[^A-Za-z0-9=&_]/', '', $_COOKIE['wp-settings-' . $user->ID] );
92306
92307 if ( ! empty( $cookie ) && strpos( $cookie, '=' ) ) {
92308 if ( $cookie == $settings )
92309 return;
92310
92311 $last_time = (int) get_user_option( 'user-settings-time', $user->ID, false );
92312 $saved = isset( $_COOKIE['wp-settings-time-' . $user->ID]) ? preg_replace( '/[^0-9]/', '', $_COOKIE['wp-settings-time-' . $user->ID] ) : 0;
92313
92314 if ( $saved > $last_time ) {
92315 update_user_option( $user->ID, 'user-settings', $cookie, false );
92316 update_user_option( $user->ID, 'user-settings-time', time() - 5, false );
92317 return;
92318 }
92319 }
92320 }
92321
92322 setcookie( 'wp-settings-' . $user->ID, $settings, time() + 31536000, SITECOOKIEPATH );
92323 setcookie( 'wp-settings-time-' . $user->ID, time(), time() + 31536000, SITECOOKIEPATH );
92324 }
92325
92326 /**
92327 * Retrieve user interface setting value based on setting name.
92328 *
92329 * @package WordPress
92330 * @subpackage Option
92331 * @since 2.7.0
92332 *
92333 * @param string $name The name of the setting.
92334 * @param string $default Optional default value to return when $name is not set.
92335 * @return mixed the last saved user setting or the default value/false if it doesn't exist.
92336 */
92337 function get_user_setting( $name, $default = false ) {
92338
92339 $arr = get_all_user_settings();
92340
92341 return isset($arr[$name]) ? $arr[$name] : $default;
92342 }
92343
92344 /**
92345 * Delete user interface settings.
92346 *
92347 * Deleting settings would reset them to the defaults.
92348 *
92349 * @package WordPress
92350 * @subpackage Option
92351 * @since 2.7.0
92352 *
92353 * @param mixed $names The name or array of names of the setting to be deleted.
92354 */
92355 function delete_user_setting( $names ) {
92356 global $current_user;
92357
92358 $arr = get_all_user_settings();
92359 $names = (array) $names;
92360
92361 foreach ( $names as $name ) {
92362 if ( isset($arr[$name]) ) {
92363 unset($arr[$name]);
92364 $settings = '';
92365 }
92366 }
92367
92368 if ( isset($settings) ) {
92369 foreach ( $arr as $k => $v )
92370 $settings .= $k . '=' . $v . '&';
92371
92372 $settings = rtrim($settings, '&');
92373
92374 update_user_option( $current_user->ID, 'user-settings', $settings );
92375 setcookie('wp-settings-'.$current_user->ID, $settings, time() + 31536000, SITECOOKIEPATH);
92376 }
92377 }
92378
92379 /**
92380 * Retrieve all user interface settings.
92381 *
92382 * @package WordPress
92383 * @subpackage Option
92384 * @since 2.7.0
92385 *
92386 * @return array the last saved user settings or empty array.
92387 */
92388 function get_all_user_settings() {
92389 if ( ! $user = wp_get_current_user() )
92390 return array();
92391
92392 if ( isset($_COOKIE['wp-settings-'.$user->ID]) ) {
92393 $cookie = preg_replace( '/[^A-Za-z0-9=&_]/', '', $_COOKIE['wp-settings-'.$user->ID] );
92394
92395 if ( $cookie && strpos($cookie, '=') ) { // the '=' cannot be 1st char
92396 parse_str($cookie, $arr);
92397 return $arr;
92398 }
92399 }
92400
92401 return array();
92402 }
92403
92404 /**
92405 * Delete the user settings of the current user.
92406 *
92407 * @package WordPress
92408 * @subpackage Option
92409 * @since 2.7.0
92410 */
92411 function delete_all_user_settings() {
92412 if ( ! $user = wp_get_current_user() )
92413 return;
92414
92415 delete_usermeta( $user->ID, 'user-settings' );
92416 setcookie('wp-settings-'.$user->ID, ' ', time() - 31536000, SITECOOKIEPATH);
92417 }
92418
92419 /**
92420 * Serialize data, if needed.
92421 *
92422 * @since 2.0.5
92423 *
92424 * @param mixed $data Data that might be serialized.
92425 * @return mixed A scalar data
92426 */
92427 function maybe_serialize( $data ) {
92428 if ( is_array( $data ) || is_object( $data ) )
92429 return serialize( $data );
92430
92431 if ( is_serialized( $data ) )
92432 return serialize( $data );
92433
92434 return $data;
92435 }
92436
92437 /**
92438 * Strip HTML and put links at the bottom of stripped content.
92439 *
92440 * Searches for all of the links, strips them out of the content, and places
92441 * them at the bottom of the content with numbers.
92442 *
92443 * @since 0.71
92444 *
92445 * @param string $content Content to get links
92446 * @return string HTML stripped out of content with links at the bottom.
92447 */
92448 function make_url_footnote( $content ) {
92449 preg_match_all( '/<a(.+?)href=\"(.+?)\"(.*?)>(.+?)<\/a>/', $content, $matches );
92450 $links_summary = "\n";
92451 for ( $i=0; $i<count($matches[0]); $i++ ) {
92452 $link_match = $matches[0][$i];
92453 $link_number = '['.($i+1).']';
92454 $link_url = $matches[2][$i];
92455 $link_text = $matches[4][$i];
92456 $content = str_replace( $link_match, $link_text . ' ' . $link_number, $content );
92457 $link_url = ( ( strtolower( substr( $link_url, 0, 7 ) ) != 'http://' ) && ( strtolower( substr( $link_url, 0, 8 ) ) != 'https://' ) ) ? get_option( 'home' ) . $link_url : $link_url;
92458 $links_summary .= "\n" . $link_number . ' ' . $link_url;
92459 }
92460 $content = strip_tags( $content );
92461 $content .= $links_summary;
92462 return $content;
92463 }
92464
92465 /**
92466 * Retrieve post title from XMLRPC XML.
92467 *
92468 * If the title element is not part of the XML, then the default post title from
92469 * the $post_default_title will be used instead.
92470 *
92471 * @package WordPress
92472 * @subpackage XMLRPC
92473 * @since 0.71
92474 *
92475 * @global string $post_default_title Default XMLRPC post title.
92476 *
92477 * @param string $content XMLRPC XML Request content
92478 * @return string Post title
92479 */
92480 function xmlrpc_getposttitle( $content ) {
92481 global $post_default_title;
92482 if ( preg_match( '/<title>(.+?)<\/title>/is', $content, $matchtitle ) ) {
92483 $post_title = $matchtitle[0];
92484 $post_title = preg_replace( '/<title>/si', '', $post_title );
92485 $post_title = preg_replace( '/<\/title>/si', '', $post_title );
92486 } else {
92487 $post_title = $post_default_title;
92488 }
92489 return $post_title;
92490 }
92491
92492 /**
92493 * Retrieve the post category or categories from XMLRPC XML.
92494 *
92495 * If the category element is not found, then the default post category will be
92496 * used. The return type then would be what $post_default_category. If the
92497 * category is found, then it will always be an array.
92498 *
92499 * @package WordPress
92500 * @subpackage XMLRPC
92501 * @since 0.71
92502 *
92503 * @global string $post_default_category Default XMLRPC post category.
92504 *
92505 * @param string $content XMLRPC XML Request content
92506 * @return string|array List of categories or category name.
92507 */
92508 function xmlrpc_getpostcategory( $content ) {
92509 global $post_default_category;
92510 if ( preg_match( '/<category>(.+?)<\/category>/is', $content, $matchcat ) ) {
92511 $post_category = trim( $matchcat[1], ',' );
92512 $post_category = explode( ',', $post_category );
92513 } else {
92514 $post_category = $post_default_category;
92515 }
92516 return $post_category;
92517 }
92518
92519 /**
92520 * XMLRPC XML content without title and category elements.
92521 *
92522 * @package WordPress
92523 * @subpackage XMLRPC
92524 * @since 0.71
92525 *
92526 * @param string $content XMLRPC XML Request content
92527 * @return string XMLRPC XML Request content without title and category elements.
92528 */
92529 function xmlrpc_removepostdata( $content ) {
92530 $content = preg_replace( '/<title>(.+?)<\/title>/si', '', $content );
92531 $content = preg_replace( '/<category>(.+?)<\/category>/si', '', $content );
92532 $content = trim( $content );
92533 return $content;
92534 }
92535
92536 /**
92537 * Open the file handle for debugging.
92538 *
92539 * This function is used for XMLRPC feature, but it is general purpose enough
92540 * to be used in anywhere.
92541 *
92542 * @see fopen() for mode options.
92543 * @package WordPress
92544 * @subpackage Debug
92545 * @since 0.71
92546 * @uses $debug Used for whether debugging is enabled.
92547 *
92548 * @param string $filename File path to debug file.
92549 * @param string $mode Same as fopen() mode parameter.
92550 * @return bool|resource File handle. False on failure.
92551 */
92552 function debug_fopen( $filename, $mode ) {
92553 global $debug;
92554 if ( 1 == $debug ) {
92555 $fp = fopen( $filename, $mode );
92556 return $fp;
92557 } else {
92558 return false;
92559 }
92560 }
92561
92562 /**
92563 * Write contents to the file used for debugging.
92564 *
92565 * Technically, this can be used to write to any file handle when the global
92566 * $debug is set to 1 or true.
92567 *
92568 * @package WordPress
92569 * @subpackage Debug
92570 * @since 0.71
92571 * @uses $debug Used for whether debugging is enabled.
92572 *
92573 * @param resource $fp File handle for debugging file.
92574 * @param string $string Content to write to debug file.
92575 */
92576 function debug_fwrite( $fp, $string ) {
92577 global $debug;
92578 if ( 1 == $debug )
92579 fwrite( $fp, $string );
92580 }
92581
92582 /**
92583 * Close the debugging file handle.
92584 *
92585 * Technically, this can be used to close any file handle when the global $debug
92586 * is set to 1 or true.
92587 *
92588 * @package WordPress
92589 * @subpackage Debug
92590 * @since 0.71
92591 * @uses $debug Used for whether debugging is enabled.
92592 *
92593 * @param resource $fp Debug File handle.
92594 */
92595 function debug_fclose( $fp ) {
92596 global $debug;
92597 if ( 1 == $debug )
92598 fclose( $fp );
92599 }
92600
92601 /**
92602 * Check content for video and audio links to add as enclosures.
92603 *
92604 * Will not add enclosures that have already been added. This is called as
92605 * pingbacks and trackbacks.
92606 *
92607 * @package WordPress
92608 * @since 1.5.0
92609 *
92610 * @uses $wpdb
92611 *
92612 * @param string $content Post Content
92613 * @param int $post_ID Post ID
92614 */
92615 function do_enclose( $content, $post_ID ) {
92616 global $wpdb;
92617 include_once( ABSPATH . WPINC . '/class-IXR.php' );
92618
92619 $log = debug_fopen( ABSPATH . 'enclosures.log', 'a' );
92620 $post_links = array();
92621 debug_fwrite( $log, 'BEGIN ' . date( 'YmdHis', time() ) . "\n" );
92622
92623 $pung = get_enclosed( $post_ID );
92624
92625 $ltrs = '\w';
92626 $gunk = '/#~:.?+=&%@!\-';
92627 $punc = '.:?\-';
92628 $any = $ltrs . $gunk . $punc;
92629
92630 preg_match_all( "{\b http : [$any] +? (?= [$punc] * [^$any] | $)}x", $content, $post_links_temp );
92631
92632 debug_fwrite( $log, 'Post contents:' );
92633 debug_fwrite( $log, $content . "\n" );
92634
92635 foreach ( (array) $post_links_temp[0] as $link_test ) {
92636 if ( !in_array( $link_test, $pung ) ) { // If we haven't pung it already
92637 $test = parse_url( $link_test );
92638 if ( isset( $test['query'] ) )
92639 $post_links[] = $link_test;
92640 elseif ( $test['path'] != '/' && $test['path'] != '' )
92641 $post_links[] = $link_test;
92642 }
92643 }
92644
92645 foreach ( (array) $post_links as $url ) {
92646 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 . '%' ) ) ) {
92647 if ( $headers = wp_get_http_headers( $url) ) {
92648 $len = (int) $headers['content-length'];
92649 $type = $wpdb->escape( $headers['content-type'] );
92650 $allowed_types = array( 'video', 'audio' );
92651 if ( in_array( substr( $type, 0, strpos( $type, "/" ) ), $allowed_types ) ) {
92652 $meta_value = "$url\n$len\n$type\n";
92653 $wpdb->query( $wpdb->prepare( "INSERT INTO `$wpdb->postmeta` ( `post_id` , `meta_key` , `meta_value` )
92654 VALUES ( %d, 'enclosure' , %s)", $post_ID, $meta_value ) );
92655 }
92656 }
92657 }
92658 }
92659 }
92660
92661 /**
92662 * Perform a HTTP HEAD or GET request.
92663 *
92664 * If $file_path is a writable filename, this will do a GET request and write
92665 * the file to that path.
92666 *
92667 * @since 2.5.0
92668 *
92669 * @param string $url URL to fetch.
92670 * @param string|bool $file_path Optional. File path to write request to.
92671 * @param bool $deprecated Deprecated. Not used.
92672 * @return bool|string False on failure and string of headers if HEAD request.
92673 */
92674 function wp_get_http( $url, $file_path = false, $deprecated = false ) {
92675 @set_time_limit( 60 );
92676
92677 $options = array();
92678 $options['redirection'] = 5;
92679
92680 if ( false == $file_path )
92681 $options['method'] = 'HEAD';
92682 else
92683 $options['method'] = 'GET';
92684
92685 $response = wp_remote_request($url, $options);
92686
92687 if ( is_wp_error( $response ) )
92688 return false;
92689
92690 $headers = wp_remote_retrieve_headers( $response );
92691 $headers['response'] = $response['response']['code'];
92692
92693 if ( false == $file_path )
92694 return $headers;
92695
92696 // GET request - write it to the supplied filename
92697 $out_fp = fopen($file_path, 'w');
92698 if ( !$out_fp )
92699 return $headers;
92700
92701 fwrite( $out_fp, $response['body']);
92702 fclose($out_fp);
92703
92704 return $headers;
92705 }
92706
92707 /**
92708 * Retrieve HTTP Headers from URL.
92709 *
92710 * @since 1.5.1
92711 *
92712 * @param string $url
92713 * @param bool $deprecated Not Used.
92714 * @return bool|string False on failure, headers on success.
92715 */
92716 function wp_get_http_headers( $url, $deprecated = false ) {
92717 $response = wp_remote_head( $url );
92718
92719 if ( is_wp_error( $response ) )
92720 return false;
92721
92722 return wp_remote_retrieve_headers( $response );
92723 }
92724
92725 /**
92726 * Whether today is a new day.
92727 *
92728 * @since 0.71
92729 * @uses $day Today
92730 * @uses $previousday Previous day
92731 *
92732 * @return int 1 when new day, 0 if not a new day.
92733 */
92734 function is_new_day() {
92735 global $day, $previousday;
92736 if ( $day != $previousday )
92737 return 1;
92738 else
92739 return 0;
92740 }
92741
92742 /**
92743 * Build URL query based on an associative and, or indexed array.
92744 *
92745 * This is a convenient function for easily building url queries. It sets the
92746 * separator to '&' and uses _http_build_query() function.
92747 *
92748 * @see _http_build_query() Used to build the query
92749 * @link http://us2.php.net/manual/en/function.http-build-query.php more on what
92750 * http_build_query() does.
92751 *
92752 * @since 2.3.0
92753 *
92754 * @param array $data URL-encode key/value pairs.
92755 * @return string URL encoded string
92756 */
92757 function build_query( $data ) {
92758 return _http_build_query( $data, null, '&', '', false );
92759 }
92760
92761 /**
92762 * Retrieve a modified URL query string.
92763 *
92764 * You can rebuild the URL and append a new query variable to the URL query by
92765 * using this function. You can also retrieve the full URL with query data.
92766 *
92767 * Adding a single key & value or an associative array. Setting a key value to
92768 * emptystring removes the key. Omitting oldquery_or_uri uses the $_SERVER
92769 * value.
92770 *
92771 * @since 1.5.0
92772 *
92773 * @param mixed $param1 Either newkey or an associative_array
92774 * @param mixed $param2 Either newvalue or oldquery or uri
92775 * @param mixed $param3 Optional. Old query or uri
92776 * @return string New URL query string.
92777 */
92778 function add_query_arg() {
92779 $ret = '';
92780 if ( is_array( func_get_arg(0) ) ) {
92781 if ( @func_num_args() < 2 || false === @func_get_arg( 1 ) )
92782 $uri = $_SERVER['REQUEST_URI'];
92783 else
92784 $uri = @func_get_arg( 1 );
92785 } else {
92786 if ( @func_num_args() < 3 || false === @func_get_arg( 2 ) )
92787 $uri = $_SERVER['REQUEST_URI'];
92788 else
92789 $uri = @func_get_arg( 2 );
92790 }
92791
92792 if ( $frag = strstr( $uri, '#' ) )
92793 $uri = substr( $uri, 0, -strlen( $frag ) );
92794 else
92795 $frag = '';
92796
92797 if ( preg_match( '|^https?://|i', $uri, $matches ) ) {
92798 $protocol = $matches[0];
92799 $uri = substr( $uri, strlen( $protocol ) );
92800 } else {
92801 $protocol = '';
92802 }
92803
92804 if ( strpos( $uri, '?' ) !== false ) {
92805 $parts = explode( '?', $uri, 2 );
92806 if ( 1 == count( $parts ) ) {
92807 $base = '?';
92808 $query = $parts[0];
92809 } else {
92810 $base = $parts[0] . '?';
92811 $query = $parts[1];
92812 }
92813 } elseif ( !empty( $protocol ) || strpos( $uri, '=' ) === false ) {
92814 $base = $uri . '?';
92815 $query = '';
92816 } else {
92817 $base = '';
92818 $query = $uri;
92819 }
92820
92821 wp_parse_str( $query, $qs );
92822 $qs = urlencode_deep( $qs ); // this re-URL-encodes things that were already in the query string
92823 if ( is_array( func_get_arg( 0 ) ) ) {
92824 $kayvees = func_get_arg( 0 );
92825 $qs = array_merge( $qs, $kayvees );
92826 } else {
92827 $qs[func_get_arg( 0 )] = func_get_arg( 1 );
92828 }
92829
92830 foreach ( (array) $qs as $k => $v ) {
92831 if ( $v === false )
92832 unset( $qs[$k] );
92833 }
92834
92835 $ret = build_query( $qs );
92836 $ret = trim( $ret, '?' );
92837 $ret = preg_replace( '#=(&|$)#', '$1', $ret );
92838 $ret = $protocol . $base . $ret . $frag;
92839 $ret = rtrim( $ret, '?' );
92840 return $ret;
92841 }
92842
92843 /**
92844 * Removes an item or list from the query string.
92845 *
92846 * @since 1.5.0
92847 *
92848 * @param string|array $key Query key or keys to remove.
92849 * @param bool $query When false uses the $_SERVER value.
92850 * @return string New URL query string.
92851 */
92852 function remove_query_arg( $key, $query=false ) {
92853 if ( is_array( $key ) ) { // removing multiple keys
92854 foreach ( $key as $k )
92855 $query = add_query_arg( $k, false, $query );
92856 return $query;
92857 }
92858 return add_query_arg( $key, false, $query );
92859 }
92860
92861 /**
92862 * Walks the array while sanitizing the contents.
92863 *
92864 * @uses $wpdb Used to sanitize values
92865 * @since 0.71
92866 *
92867 * @param array $array Array to used to walk while sanitizing contents.
92868 * @return array Sanitized $array.
92869 */
92870 function add_magic_quotes( $array ) {
92871 global $wpdb;
92872
92873 foreach ( (array) $array as $k => $v ) {
92874 if ( is_array( $v ) ) {
92875 $array[$k] = add_magic_quotes( $v );
92876 } else {
92877 $array[$k] = $wpdb->escape( $v );
92878 }
92879 }
92880 return $array;
92881 }
92882
92883 /**
92884 * HTTP request for URI to retrieve content.
92885 *
92886 * @since 1.5.1
92887 * @uses wp_remote_get()
92888 *
92889 * @param string $uri URI/URL of web page to retrieve.
92890 * @return bool|string HTTP content. False on failure.
92891 */
92892 function wp_remote_fopen( $uri ) {
92893 $parsed_url = @parse_url( $uri );
92894
92895 if ( !$parsed_url || !is_array( $parsed_url ) )
92896 return false;
92897
92898 $options = array();
92899 $options['timeout'] = 10;
92900
92901 $response = wp_remote_get( $uri, $options );
92902
92903 if ( is_wp_error( $response ) )
92904 return false;
92905
92906 return $response['body'];
92907 }
92908
92909 /**
92910 * Setup the WordPress query.
92911 *
92912 * @since 2.0.0
92913 *
92914 * @param string $query_vars Default WP_Query arguments.
92915 */
92916 function wp( $query_vars = '' ) {
92917 global $wp, $wp_query, $wp_the_query;
92918 $wp->main( $query_vars );
92919
92920 if( !isset($wp_the_query) )
92921 $wp_the_query = $wp_query;
92922 }
92923
92924 /**
92925 * Retrieve the description for the HTTP status.
92926 *
92927 * @since 2.3.0
92928 *
92929 * @param int $code HTTP status code.
92930 * @return string Empty string if not found, or description if found.
92931 */
92932 function get_status_header_desc( $code ) {
92933 global $wp_header_to_desc;
92934
92935 $code = absint( $code );
92936
92937 if ( !isset( $wp_header_to_desc ) ) {
92938 $wp_header_to_desc = array(
92939 100 => 'Continue',
92940 101 => 'Switching Protocols',
92941
92942 200 => 'OK',
92943 201 => 'Created',
92944 202 => 'Accepted',
92945 203 => 'Non-Authoritative Information',
92946 204 => 'No Content',
92947 205 => 'Reset Content',
92948 206 => 'Partial Content',
92949
92950 300 => 'Multiple Choices',
92951 301 => 'Moved Permanently',
92952 302 => 'Found',
92953 303 => 'See Other',
92954 304 => 'Not Modified',
92955 305 => 'Use Proxy',
92956 307 => 'Temporary Redirect',
92957
92958 400 => 'Bad Request',
92959 401 => 'Unauthorized',
92960 403 => 'Forbidden',
92961 404 => 'Not Found',
92962 405 => 'Method Not Allowed',
92963 406 => 'Not Acceptable',
92964 407 => 'Proxy Authentication Required',
92965 408 => 'Request Timeout',
92966 409 => 'Conflict',
92967 410 => 'Gone',
92968 411 => 'Length Required',
92969 412 => 'Precondition Failed',
92970 413 => 'Request Entity Too Large',
92971 414 => 'Request-URI Too Long',
92972 415 => 'Unsupported Media Type',
92973 416 => 'Requested Range Not Satisfiable',
92974 417 => 'Expectation Failed',
92975
92976 500 => 'Internal Server Error',
92977 501 => 'Not Implemented',
92978 502 => 'Bad Gateway',
92979 503 => 'Service Unavailable',
92980 504 => 'Gateway Timeout',
92981 505 => 'HTTP Version Not Supported'
92982 );
92983 }
92984
92985 if ( isset( $wp_header_to_desc[$code] ) )
92986 return $wp_header_to_desc[$code];
92987 else
92988 return '';
92989 }
92990
92991 /**
92992 * Set HTTP status header.
92993 *
92994 * @since 2.0.0
92995 * @uses apply_filters() Calls 'status_header' on status header string, HTTP
92996 * HTTP code, HTTP code description, and protocol string as separate
92997 * parameters.
92998 *
92999 * @param int $header HTTP status code
93000 * @return null Does not return anything.
93001 */
93002 function status_header( $header ) {
93003 $text = get_status_header_desc( $header );
93004
93005 if ( empty( $text ) )
93006 return false;
93007
93008 $protocol = $_SERVER["SERVER_PROTOCOL"];
93009 if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol )
93010 $protocol = 'HTTP/1.0';
93011 $status_header = "$protocol $header $text";
93012 if ( function_exists( 'apply_filters' ) )
93013 $status_header = apply_filters( 'status_header', $status_header, $header, $text, $protocol );
93014
93015 if ( version_compare( phpversion(), '4.3.0', '>=' ) )
93016 return @header( $status_header, true, $header );
93017 else
93018 return @header( $status_header );
93019 }
93020
93021 /**
93022 * Sets the headers to prevent caching for the different browsers.
93023 *
93024 * Different browsers support different nocache headers, so several headers must
93025 * be sent so that all of them get the point that no caching should occur.
93026 *
93027 * @since 2.0.0
93028 */
93029 function nocache_headers() {
93030 // why are these @-silenced when other header calls aren't?
93031 @header( 'Expires: Wed, 11 Jan 1984 05:00:00 GMT' );
93032 @header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
93033 @header( 'Cache-Control: no-cache, must-revalidate, max-age=0' );
93034 @header( 'Pragma: no-cache' );
93035 }
93036
93037 /**
93038 * Set the headers for caching for 10 days with JavaScript content type.
93039 *
93040 * @since 2.1.0
93041 */
93042 function cache_javascript_headers() {
93043 $expiresOffset = 864000; // 10 days
93044 header( "Content-Type: text/javascript; charset=" . get_bloginfo( 'charset' ) );
93045 header( "Vary: Accept-Encoding" ); // Handle proxies
93046 header( "Expires: " . gmdate( "D, d M Y H:i:s", time() + $expiresOffset ) . " GMT" );
93047 }
93048
93049 /**
93050 * Retrieve the number of database queries during the WordPress execution.
93051 *
93052 * @since 2.0.0
93053 *
93054 * @return int Number of database queries
93055 */
93056 function get_num_queries() {
93057 global $wpdb;
93058 return $wpdb->num_queries;
93059 }
93060
93061 /**
93062 * Whether input is yes or no. Must be 'y' to be true.
93063 *
93064 * @since 1.0.0
93065 *
93066 * @param string $yn Character string containing either 'y' or 'n'
93067 * @return bool True if yes, false on anything else
93068 */
93069 function bool_from_yn( $yn ) {
93070 return ( strtolower( $yn ) == 'y' );
93071 }
93072
93073 /**
93074 * Loads the feed template from the use of an action hook.
93075 *
93076 * If the feed action does not have a hook, then the function will die with a
93077 * message telling the visitor that the feed is not valid.
93078 *
93079 * It is better to only have one hook for each feed.
93080 *
93081 * @since 2.1.0
93082 * @uses $wp_query Used to tell if the use a comment feed.
93083 * @uses do_action() Calls 'do_feed_$feed' hook, if a hook exists for the feed.
93084 */
93085 function do_feed() {
93086 global $wp_query;
93087
93088 $feed = get_query_var( 'feed' );
93089
93090 // Remove the pad, if present.
93091 $feed = preg_replace( '/^_+/', '', $feed );
93092
93093 if ( $feed == '' || $feed == 'feed' )
93094 $feed = get_default_feed();
93095
93096 $hook = 'do_feed_' . $feed;
93097 if ( !has_action($hook) ) {
93098 $message = sprintf( __( 'ERROR: %s is not a valid feed template' ), wp_specialchars($feed));
93099 wp_die($message);
93100 }
93101
93102 do_action( $hook, $wp_query->is_comment_feed );
93103 }
93104
93105 /**
93106 * Load the RDF RSS 0.91 Feed template.
93107 *
93108 * @since 2.1.0
93109 */
93110 function do_feed_rdf() {
93111 load_template( ABSPATH . WPINC . '/feed-rdf.php' );
93112 }
93113
93114 /**
93115 * Load the RSS 1.0 Feed Template
93116 *
93117 * @since 2.1.0
93118 */
93119 function do_feed_rss() {
93120 load_template( ABSPATH . WPINC . '/feed-rss.php' );
93121 }
93122
93123 /**
93124 * Load either the RSS2 comment feed or the RSS2 posts feed.
93125 *
93126 * @since 2.1.0
93127 *
93128 * @param bool $for_comments True for the comment feed, false for normal feed.
93129 */
93130 function do_feed_rss2( $for_comments ) {
93131 if ( $for_comments )
93132 load_template( ABSPATH . WPINC . '/feed-rss2-comments.php' );
93133 else
93134 load_template( ABSPATH . WPINC . '/feed-rss2.php' );
93135 }
93136
93137 /**
93138 * Load either Atom comment feed or Atom posts feed.
93139 *
93140 * @since 2.1.0
93141 *
93142 * @param bool $for_comments True for the comment feed, false for normal feed.
93143 */
93144 function do_feed_atom( $for_comments ) {
93145 if ($for_comments)
93146 load_template( ABSPATH . WPINC . '/feed-atom-comments.php');
93147 else
93148 load_template( ABSPATH . WPINC . '/feed-atom.php' );
93149 }
93150
93151 /**
93152 * Display the robot.txt file content.
93153 *
93154 * The echo content should be with usage of the permalinks or for creating the
93155 * robot.txt file.
93156 *
93157 * @since 2.1.0
93158 * @uses do_action() Calls 'do_robotstxt' hook for displaying robot.txt rules.
93159 */
93160 function do_robots() {
93161 header( 'Content-Type: text/plain; charset=utf-8' );
93162
93163 do_action( 'do_robotstxt' );
93164
93165 if ( '0' == get_option( 'blog_public' ) ) {
93166 echo "User-agent: *\n";
93167 echo "Disallow: /\n";
93168 } else {
93169 echo "User-agent: *\n";
93170 echo "Disallow:\n";
93171 }
93172 }
93173
93174 /**
93175 * Test whether blog is already installed.
93176 *
93177 * The cache will be checked first. If you have a cache plugin, which saves the
93178 * cache values, then this will work. If you use the default WordPress cache,
93179 * and the database goes away, then you might have problems.
93180 *
93181 * Checks for the option siteurl for whether WordPress is installed.
93182 *
93183 * @since 2.1.0
93184 * @uses $wpdb
93185 *
93186 * @return bool Whether blog is already installed.
93187 */
93188 function is_blog_installed() {
93189 global $wpdb;
93190
93191 // Check cache first. If options table goes away and we have true cached, oh well.
93192 if ( wp_cache_get('is_blog_installed') )
93193 return true;
93194
93195 $suppress = $wpdb->suppress_errors();
93196 $installed = $wpdb->get_var( "SELECT option_value FROM $wpdb->options WHERE option_name = 'siteurl'" );
93197 $wpdb->suppress_errors($suppress);
93198
93199 $installed = !empty( $installed ) ? true : false;
93200 wp_cache_set('is_blog_installed', $installed);
93201
93202 return $installed;
93203 }
93204
93205 /**
93206 * Retrieve URL with nonce added to URL query.
93207 *
93208 * @package WordPress
93209 * @subpackage Security
93210 * @since 2.0.4
93211 *
93212 * @param string $actionurl URL to add nonce action
93213 * @param string $action Optional. Nonce action name
93214 * @return string URL with nonce action added.
93215 */
93216 function wp_nonce_url( $actionurl, $action = -1 ) {
93217 $actionurl = str_replace( '&', '&', $actionurl );
93218 return wp_specialchars( add_query_arg( '_wpnonce', wp_create_nonce( $action ), $actionurl ) );
93219 }
93220
93221 /**
93222 * Retrieve or display nonce hidden field for forms.
93223 *
93224 * The nonce field is used to validate that the contents of the form came from
93225 * the location on the current site and not somewhere else. The nonce does not
93226 * offer absolute protection, but should protect against most cases. It is very
93227 * important to use nonce field in forms.
93228 *
93229 * If you set $echo to true and set $referer to true, then you will need to
93230 * retrieve the {@link wp_referer_field() wp referer field}. If you have the
93231 * $referer set to true and are echoing the nonce field, it will also echo the
93232 * referer field.
93233 *
93234 * The $action and $name are optional, but if you want to have better security,
93235 * it is strongly suggested to set those two parameters. It is easier to just
93236 * call the function without any parameters, because validation of the nonce
93237 * doesn't require any parameters, but since crackers know what the default is
93238 * it won't be difficult for them to find a way around your nonce and cause
93239 * damage.
93240 *
93241 * The input name will be whatever $name value you gave. The input value will be
93242 * the nonce creation value.
93243 *
93244 * @package WordPress
93245 * @subpackage Security
93246 * @since 2.0.4
93247 *
93248 * @param string $action Optional. Action name.
93249 * @param string $name Optional. Nonce name.
93250 * @param bool $referer Optional, default true. Whether to set the referer field for validation.
93251 * @param bool $echo Optional, default true. Whether to display or return hidden form field.
93252 * @return string Nonce field.
93253 */
93254 function wp_nonce_field( $action = -1, $name = "_wpnonce", $referer = true , $echo = true ) {
93255 $name = attribute_escape( $name );
93256 $nonce_field = '<input type="hidden" id="' . $name . '" name="' . $name . '" value="' . wp_create_nonce( $action ) . '" />';
93257 if ( $echo )
93258 echo $nonce_field;
93259
93260 if ( $referer )
93261 wp_referer_field( $echo, 'previous' );
93262
93263 return $nonce_field;
93264 }
93265
93266 /**
93267 * Retrieve or display referer hidden field for forms.
93268 *
93269 * The referer link is the current Request URI from the server super global. The
93270 * input name is '_wp_http_referer', in case you wanted to check manually.
93271 *
93272 * @package WordPress
93273 * @subpackage Security
93274 * @since 2.0.4
93275 *
93276 * @param bool $echo Whether to echo or return the referer field.
93277 * @return string Referer field.
93278 */
93279 function wp_referer_field( $echo = true) {
93280 $ref = attribute_escape( $_SERVER['REQUEST_URI'] );
93281 $referer_field = '<input type="hidden" name="_wp_http_referer" value="'. $ref . '" />';
93282
93283 if ( $echo )
93284 echo $referer_field;
93285 return $referer_field;
93286 }
93287
93288 /**
93289 * Retrieve or display original referer hidden field for forms.
93290 *
93291 * The input name is '_wp_original_http_referer' and will be either the same
93292 * value of {@link wp_referer_field()}, if that was posted already or it will
93293 * be the current page, if it doesn't exist.
93294 *
93295 * @package WordPress
93296 * @subpackage Security
93297 * @since 2.0.4
93298 *
93299 * @param bool $echo Whether to echo the original http referer
93300 * @param string $jump_back_to Optional, default is 'current'. Can be 'previous' or page you want to jump back to.
93301 * @return string Original referer field.
93302 */
93303 function wp_original_referer_field( $echo = true, $jump_back_to = 'current' ) {
93304 $jump_back_to = ( 'previous' == $jump_back_to ) ? wp_get_referer() : $_SERVER['REQUEST_URI'];
93305 $ref = ( wp_get_original_referer() ) ? wp_get_original_referer() : $jump_back_to;
93306 $orig_referer_field = '<input type="hidden" name="_wp_original_http_referer" value="' . attribute_escape( stripslashes( $ref ) ) . '" />';
93307 if ( $echo )
93308 echo $orig_referer_field;
93309 return $orig_referer_field;
93310 }
93311
93312 /**
93313 * Retrieve referer from '_wp_http_referer', HTTP referer, or current page respectively.
93314 *
93315 * @package WordPress
93316 * @subpackage Security
93317 * @since 2.0.4
93318 *
93319 * @return string|bool False on failure. Referer URL on success.
93320 */
93321 function wp_get_referer() {
93322 $ref = '';
93323 if ( ! empty( $_REQUEST['_wp_http_referer'] ) )
93324 $ref = $_REQUEST['_wp_http_referer'];
93325 else if ( ! empty( $_SERVER['HTTP_REFERER'] ) )
93326 $ref = $_SERVER['HTTP_REFERER'];
93327
93328 if ( $ref !== $_SERVER['REQUEST_URI'] )
93329 return $ref;
93330 return false;
93331 }
93332
93333 /**
93334 * Retrieve original referer that was posted, if it exists.
93335 *
93336 * @package WordPress
93337 * @subpackage Security
93338 * @since 2.0.4
93339 *
93340 * @return string|bool False if no original referer or original referer if set.
93341 */
93342 function wp_get_original_referer() {
93343 if ( !empty( $_REQUEST['_wp_original_http_referer'] ) )
93344 return $_REQUEST['_wp_original_http_referer'];
93345 return false;
93346 }
93347
93348 /**
93349 * Recursive directory creation based on full path.
93350 *
93351 * Will attempt to set permissions on folders.
93352 *
93353 * @since 2.0.1
93354 *
93355 * @param string $target Full path to attempt to create.
93356 * @return bool Whether the path was created or not. True if path already exists.
93357 */
93358 function wp_mkdir_p( $target ) {
93359 // from php.net/mkdir user contributed notes
93360 $target = str_replace( '//', '/', $target );
93361 if ( file_exists( $target ) )
93362 return @is_dir( $target );
93363
93364 // Attempting to create the directory may clutter up our display.
93365 if ( @mkdir( $target ) ) {
93366 $stat = @stat( dirname( $target ) );
93367 $dir_perms = $stat['mode'] & 0007777; // Get the permission bits.
93368 @chmod( $target, $dir_perms );
93369 return true;
93370 } elseif ( is_dir( dirname( $target ) ) ) {
93371 return false;
93372 }
93373
93374 // If the above failed, attempt to create the parent node, then try again.
93375 if ( ( $target != '/' ) && ( wp_mkdir_p( dirname( $target ) ) ) )
93376 return wp_mkdir_p( $target );
93377
93378 return false;
93379 }
93380
93381 /**
93382 * Test if a give filesystem path is absolute ('/foo/bar', 'c:\windows').
93383 *
93384 * @since 2.5.0
93385 *
93386 * @param string $path File path
93387 * @return bool True if path is absolute, false is not absolute.
93388 */
93389 function path_is_absolute( $path ) {
93390 // this is definitive if true but fails if $path does not exist or contains a symbolic link
93391 if ( realpath($path) == $path )
93392 return true;
93393
93394 if ( strlen($path) == 0 || $path{0} == '.' )
93395 return false;
93396
93397 // windows allows absolute paths like this
93398 if ( preg_match('#^[a-zA-Z]:\\\\#', $path) )
93399 return true;
93400
93401 // a path starting with / or \ is absolute; anything else is relative
93402 return (bool) preg_match('#^[/\\\\]#', $path);
93403 }
93404
93405 /**
93406 * Join two filesystem paths together (e.g. 'give me $path relative to $base').
93407 *
93408 * If the $path is absolute, then it the full path is returned.
93409 *
93410 * @since 2.5.0
93411 *
93412 * @param string $base
93413 * @param string $path
93414 * @return string The path with the base or absolute path.
93415 */
93416 function path_join( $base, $path ) {
93417 if ( path_is_absolute($path) )
93418 return $path;
93419
93420 return rtrim($base, '/') . '/' . ltrim($path, '/');
93421 }
93422
93423 /**
93424 * Get an array containing the current upload directory's path and url.
93425 *
93426 * Checks the 'upload_path' option, which should be from the web root folder,
93427 * and if it isn't empty it will be used. If it is empty, then the path will be
93428 * 'WP_CONTENT_DIR/uploads'. If the 'UPLOADS' constant is defined, then it will
93429 * override the 'upload_path' option and 'WP_CONTENT_DIR/uploads' path.
93430 *
93431 * The upload URL path is set either by the 'upload_url_path' option or by using
93432 * the 'WP_CONTENT_URL' constant and appending '/uploads' to the path.
93433 *
93434 * If the 'uploads_use_yearmonth_folders' is set to true (checkbox if checked in
93435 * the administration settings panel), then the time will be used. The format
93436 * will be year first and then month.
93437 *
93438 * If the path couldn't be created, then an error will be returned with the key
93439 * 'error' containing the error message. The error suggests that the parent
93440 * directory is not writable by the server.
93441 *
93442 * On success, the returned array will have many indices:
93443 * 'path' - base directory and sub directory or full path to upload directory.
93444 * 'url' - base url and sub directory or absolute URL to upload directory.
93445 * 'subdir' - sub directory if uploads use year/month folders option is on.
93446 * 'basedir' - path without subdir.
93447 * 'baseurl' - URL path without subdir.
93448 * 'error' - set to false.
93449 *
93450 * @since 2.0.0
93451 * @uses apply_filters() Calls 'upload_dir' on returned array.
93452 *
93453 * @param string $time Optional. Time formatted in 'yyyy/mm'.
93454 * @return array See above for description.
93455 */
93456 function wp_upload_dir( $time = null ) {
93457 $siteurl = get_option( 'siteurl' );
93458 $upload_path = get_option( 'upload_path' );
93459 $upload_path = trim($upload_path);
93460 if ( empty($upload_path) )
93461 $dir = WP_CONTENT_DIR . '/uploads';
93462 else
93463 $dir = $upload_path;
93464
93465 // $dir is absolute, $path is (maybe) relative to ABSPATH
93466 $dir = path_join( ABSPATH, $dir );
93467
93468 if ( !$url = get_option( 'upload_url_path' ) ) {
93469 if ( empty($upload_path) or ( $upload_path == $dir ) )
93470 $url = WP_CONTENT_URL . '/uploads';
93471 else
93472 $url = trailingslashit( $siteurl ) . $upload_path;
93473 }
93474
93475 if ( defined('UPLOADS') ) {
93476 $dir = ABSPATH . UPLOADS;
93477 $url = trailingslashit( $siteurl ) . UPLOADS;
93478 }
93479
93480 $bdir = $dir;
93481 $burl = $url;
93482
93483 $subdir = '';
93484 if ( get_option( 'uploads_use_yearmonth_folders' ) ) {
93485 // Generate the yearly and monthly dirs
93486 if ( !$time )
93487 $time = current_time( 'mysql' );
93488 $y = substr( $time, 0, 4 );
93489 $m = substr( $time, 5, 2 );
93490 $subdir = "/$y/$m";
93491 }
93492
93493 $dir .= $subdir;
93494 $url .= $subdir;
93495
93496 // Make sure we have an uploads dir
93497 if ( ! wp_mkdir_p( $dir ) ) {
93498 $message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), $dir );
93499 return array( 'error' => $message );
93500 }
93501
93502 $uploads = array( 'path' => $dir, 'url' => $url, 'subdir' => $subdir, 'basedir' => $bdir, 'baseurl' => $burl, 'error' => false );
93503
93504 return apply_filters( 'upload_dir', $uploads );
93505 }
93506
93507 /**
93508 * Get a filename that is sanitized and unique for the given directory.
93509 *
93510 * If the filename is not unique, then a number will be added to the filename
93511 * before the extension, and will continue adding numbers until the filename is
93512 * unique.
93513 *
93514 * The callback must accept two parameters, the first one is the directory and
93515 * the second is the filename. The callback must be a function.
93516 *
93517 * @since 2.5
93518 *
93519 * @param string $dir
93520 * @param string $filename
93521 * @param string $unique_filename_callback Function name, must be a function.
93522 * @return string New filename, if given wasn't unique.
93523 */
93524 function wp_unique_filename( $dir, $filename, $unique_filename_callback = null ) {
93525 $filename = strtolower( $filename );
93526 // separate the filename into a name and extension
93527 $info = pathinfo($filename);
93528 $ext = !empty($info['extension']) ? $info['extension'] : '';
93529 $name = basename($filename, ".{$ext}");
93530
93531 // edge case: if file is named '.ext', treat as an empty name
93532 if( $name === ".$ext" )
93533 $name = '';
93534
93535 // Increment the file number until we have a unique file to save in $dir. Use $override['unique_filename_callback'] if supplied.
93536 if ( $unique_filename_callback && function_exists( $unique_filename_callback ) ) {
93537 $filename = $unique_filename_callback( $dir, $name );
93538 } else {
93539 $number = '';
93540
93541 if ( !empty( $ext ) )
93542 $ext = strtolower( ".$ext" );
93543
93544 $filename = str_replace( $ext, '', $filename );
93545 // Strip % so the server doesn't try to decode entities.
93546 $filename = str_replace('%', '', sanitize_title_with_dashes( $filename ) ) . $ext;
93547
93548 while ( file_exists( $dir . "/$filename" ) ) {
93549 if ( '' == "$number$ext" )
93550 $filename = $filename . ++$number . $ext;
93551 else
93552 $filename = str_replace( "$number$ext", ++$number . $ext, $filename );
93553 }
93554 }
93555
93556 return $filename;
93557 }
93558
93559 /**
93560 * Create a file in the upload folder with given content.
93561 *
93562 * If there is an error, then the key 'error' will exist with the error message.
93563 * If success, then the key 'file' will have the unique file path, the 'url' key
93564 * will have the link to the new file. and the 'error' key will be set to false.
93565 *
93566 * This function will not move an uploaded file to the upload folder. It will
93567 * create a new file with the content in $bits parameter. If you move the upload
93568 * file, read the content of the uploaded file, and then you can give the
93569 * filename and content to this function, which will add it to the upload
93570 * folder.
93571 *
93572 * The permissions will be set on the new file automatically by this function.
93573 *
93574 * @since 2.0.0
93575 *
93576 * @param string $name
93577 * @param null $deprecated Not used. Set to null.
93578 * @param mixed $bits File content
93579 * @param string $time Optional. Time formatted in 'yyyy/mm'.
93580 * @return array
93581 */
93582 function wp_upload_bits( $name, $deprecated, $bits, $time = null ) {
93583 if ( empty( $name ) )
93584 return array( 'error' => __( 'Empty filename' ) );
93585
93586 $wp_filetype = wp_check_filetype( $name );
93587 if ( !$wp_filetype['ext'] )
93588 return array( 'error' => __( 'Invalid file type' ) );
93589
93590 $upload = wp_upload_dir( $time );
93591
93592 if ( $upload['error'] !== false )
93593 return $upload;
93594
93595 $filename = wp_unique_filename( $upload['path'], $name );
93596
93597 $new_file = $upload['path'] . "/$filename";
93598 if ( ! wp_mkdir_p( dirname( $new_file ) ) ) {
93599 $message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), dirname( $new_file ) );
93600 return array( 'error' => $message );
93601 }
93602
93603 $ifp = @ fopen( $new_file, 'wb' );
93604 if ( ! $ifp )
93605 return array( 'error' => sprintf( __( 'Could not write file %s' ), $new_file ) );
93606
93607 @fwrite( $ifp, $bits );
93608 fclose( $ifp );
93609 // Set correct file permissions
93610 $stat = @ stat( dirname( $new_file ) );
93611 $perms = $stat['mode'] & 0007777;
93612 $perms = $perms & 0000666;
93613 @ chmod( $new_file, $perms );
93614
93615 // Compute the URL
93616 $url = $upload['url'] . "/$filename";
93617
93618 return array( 'file' => $new_file, 'url' => $url, 'error' => false );
93619 }
93620
93621 /**
93622 * Retrieve the file type based on the extension name.
93623 *
93624 * @package WordPress
93625 * @since 2.5.0
93626 * @uses apply_filters() Calls 'ext2type' hook on default supported types.
93627 *
93628 * @param string $ext The extension to search.
93629 * @return string|null The file type, example: audio, video, document, spreadsheet, etc. Null if not found.
93630 */
93631 function wp_ext2type( $ext ) {
93632 $ext2type = apply_filters('ext2type', array(
93633 'audio' => array('aac','ac3','aif','aiff','mp1','mp2','mp3','m3a','m4a','m4b','ogg','ram','wav','wma'),
93634 'video' => array('asf','avi','divx','dv','mov','mpg','mpeg','mp4','mpv','ogm','qt','rm','vob','wmv'),
93635 'document' => array('doc','docx','pages','odt','rtf','pdf'),
93636 'spreadsheet' => array('xls','xlsx','numbers','ods'),
93637 'interactive' => array('ppt','pptx','key','odp','swf'),
93638 'text' => array('txt'),
93639 'archive' => array('tar','bz2','gz','cab','dmg','rar','sea','sit','sqx','zip'),
93640 'code' => array('css','html','php','js'),
93641 ));
93642 foreach ( $ext2type as $type => $exts )
93643 if ( in_array($ext, $exts) )
93644 return $type;
93645 }
93646
93647 /**
93648 * Retrieve the file type from the file name.
93649 *
93650 * You can optionally define the mime array, if needed.
93651 *
93652 * @since 2.0.4
93653 *
93654 * @param string $filename File name or path.
93655 * @param array $mimes Optional. Key is the file extension with value as the mime type.
93656 * @return array Values with extension first and mime type.
93657 */
93658 function wp_check_filetype( $filename, $mimes = null ) {
93659 // Accepted MIME types are set here as PCRE unless provided.
93660 $mimes = ( is_array( $mimes ) ) ? $mimes : apply_filters( 'upload_mimes', array(
93661 'jpg|jpeg|jpe' => 'image/jpeg',
93662 'gif' => 'image/gif',
93663 'png' => 'image/png',
93664 'bmp' => 'image/bmp',
93665 'tif|tiff' => 'image/tiff',
93666 'ico' => 'image/x-icon',
93667 'asf|asx|wax|wmv|wmx' => 'video/asf',
93668 'avi' => 'video/avi',
93669 'divx' => 'video/divx',
93670 'mov|qt' => 'video/quicktime',
93671 'mpeg|mpg|mpe|mp4' => 'video/mpeg',
93672 'txt|c|cc|h' => 'text/plain',
93673 'rtx' => 'text/richtext',
93674 'css' => 'text/css',
93675 'htm|html' => 'text/html',
93676 'mp3|m4a' => 'audio/mpeg',
93677 'ra|ram' => 'audio/x-realaudio',
93678 'wav' => 'audio/wav',
93679 'ogg' => 'audio/ogg',
93680 'mid|midi' => 'audio/midi',
93681 'wma' => 'audio/wma',
93682 'rtf' => 'application/rtf',
93683 'js' => 'application/javascript',
93684 'pdf' => 'application/pdf',
93685 'doc|docx' => 'application/msword',
93686 'pot|pps|ppt|pptx' => 'application/vnd.ms-powerpoint',
93687 'wri' => 'application/vnd.ms-write',
93688 'xla|xls|xlsx|xlt|xlw' => 'application/vnd.ms-excel',
93689 'mdb' => 'application/vnd.ms-access',
93690 'mpp' => 'application/vnd.ms-project',
93691 'swf' => 'application/x-shockwave-flash',
93692 'class' => 'application/java',
93693 'tar' => 'application/x-tar',
93694 'zip' => 'application/zip',
93695 'gz|gzip' => 'application/x-gzip',
93696 'exe' => 'application/x-msdownload',
93697 // openoffice formats
93698 'odt' => 'application/vnd.oasis.opendocument.text',
93699 'odp' => 'application/vnd.oasis.opendocument.presentation',
93700 'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
93701 'odg' => 'application/vnd.oasis.opendocument.graphics',
93702 'odc' => 'application/vnd.oasis.opendocument.chart',
93703 'odb' => 'application/vnd.oasis.opendocument.database',
93704 'odf' => 'application/vnd.oasis.opendocument.formula',
93705 )
93706 );
93707
93708 $type = false;
93709 $ext = false;
93710
93711 foreach ( $mimes as $ext_preg => $mime_match ) {
93712 $ext_preg = '!\.(' . $ext_preg . ')$!i';
93713 if ( preg_match( $ext_preg, $filename, $ext_matches ) ) {
93714 $type = $mime_match;
93715 $ext = $ext_matches[1];
93716 break;
93717 }
93718 }
93719
93720 return compact( 'ext', 'type' );
93721 }
93722
93723 /**
93724 * Retrieve nonce action "Are you sure" message.
93725 *
93726 * The action is split by verb and noun. The action format is as follows:
93727 * verb-action_extra. The verb is before the first dash and has the format of
93728 * letters and no spaces and numbers. The noun is after the dash and before the
93729 * underscore, if an underscore exists. The noun is also only letters.
93730 *
93731 * The filter will be called for any action, which is not defined by WordPress.
93732 * You may use the filter for your plugin to explain nonce actions to the user,
93733 * when they get the "Are you sure?" message. The filter is in the format of
93734 * 'explain_nonce_$verb-$noun' with the $verb replaced by the found verb and the
93735 * $noun replaced by the found noun. The two parameters that are given to the
93736 * hook are the localized "Are you sure you want to do this?" message with the
93737 * extra text (the text after the underscore).
93738 *
93739 * @package WordPress
93740 * @subpackage Security
93741 * @since 2.0.4
93742 *
93743 * @param string $action Nonce action.
93744 * @return string Are you sure message.
93745 */
93746 function wp_explain_nonce( $action ) {
93747 if ( $action !== -1 && preg_match( '/([a-z]+)-([a-z]+)(_(.+))?/', $action, $matches ) ) {
93748 $verb = $matches[1];
93749 $noun = $matches[2];
93750
93751 $trans = array();
93752 $trans['update']['attachment'] = array( __( 'Your attempt to edit this attachment: "%s" has failed.' ), 'get_the_title' );
93753
93754 $trans['add']['category'] = array( __( 'Your attempt to add this category has failed.' ), false );
93755 $trans['delete']['category'] = array( __( 'Your attempt to delete this category: "%s" has failed.' ), 'get_catname' );
93756 $trans['update']['category'] = array( __( 'Your attempt to edit this category: "%s" has failed.' ), 'get_catname' );
93757
93758 $trans['delete']['comment'] = array( __( 'Your attempt to delete this comment: "%s" has failed.' ), 'use_id' );
93759 $trans['unapprove']['comment'] = array( __( 'Your attempt to unapprove this comment: "%s" has failed.' ), 'use_id' );
93760 $trans['approve']['comment'] = array( __( 'Your attempt to approve this comment: "%s" has failed.' ), 'use_id' );
93761 $trans['update']['comment'] = array( __( 'Your attempt to edit this comment: "%s" has failed.' ), 'use_id' );
93762 $trans['bulk']['comments'] = array( __( 'Your attempt to bulk modify comments has failed.' ), false );
93763 $trans['moderate']['comments'] = array( __( 'Your attempt to moderate comments has failed.' ), false );
93764
93765 $trans['add']['bookmark'] = array( __( 'Your attempt to add this link has failed.' ), false );
93766 $trans['delete']['bookmark'] = array( __( 'Your attempt to delete this link: "%s" has failed.' ), 'use_id' );
93767 $trans['update']['bookmark'] = array( __( 'Your attempt to edit this link: "%s" has failed.' ), 'use_id' );
93768 $trans['bulk']['bookmarks'] = array( __( 'Your attempt to bulk modify links has failed.' ), false );
93769
93770 $trans['add']['page'] = array( __( 'Your attempt to add this page has failed.' ), false );
93771 $trans['delete']['page'] = array( __( 'Your attempt to delete this page: "%s" has failed.' ), 'get_the_title' );
93772 $trans['update']['page'] = array( __( 'Your attempt to edit this page: "%s" has failed.' ), 'get_the_title' );
93773
93774 $trans['edit']['plugin'] = array( __( 'Your attempt to edit this plugin file: "%s" has failed.' ), 'use_id' );
93775 $trans['activate']['plugin'] = array( __( 'Your attempt to activate this plugin: "%s" has failed.' ), 'use_id' );
93776 $trans['deactivate']['plugin'] = array( __( 'Your attempt to deactivate this plugin: "%s" has failed.' ), 'use_id' );
93777 $trans['upgrade']['plugin'] = array( __( 'Your attempt to upgrade this plugin: "%s" has failed.' ), 'use_id' );
93778
93779 $trans['add']['post'] = array( __( 'Your attempt to add this post has failed.' ), false );
93780 $trans['delete']['post'] = array( __( 'Your attempt to delete this post: "%s" has failed.' ), 'get_the_title' );
93781 $trans['update']['post'] = array( __( 'Your attempt to edit this post: "%s" has failed.' ), 'get_the_title' );
93782
93783 $trans['add']['user'] = array( __( 'Your attempt to add this user has failed.' ), false );
93784 $trans['delete']['users'] = array( __( 'Your attempt to delete users has failed.' ), false );
93785 $trans['bulk']['users'] = array( __( 'Your attempt to bulk modify users has failed.' ), false );
93786 $trans['update']['user'] = array( __( 'Your attempt to edit this user: "%s" has failed.' ), 'get_author_name' );
93787 $trans['update']['profile'] = array( __( 'Your attempt to modify the profile for: "%s" has failed.' ), 'get_author_name' );
93788
93789 $trans['update']['options'] = array( __( 'Your attempt to edit your settings has failed.' ), false );
93790 $trans['update']['permalink'] = array( __( 'Your attempt to change your permalink structure to: %s has failed.' ), 'use_id' );
93791 $trans['edit']['file'] = array( __( 'Your attempt to edit this file: "%s" has failed.' ), 'use_id' );
93792 $trans['edit']['theme'] = array( __( 'Your attempt to edit this theme file: "%s" has failed.' ), 'use_id' );
93793 $trans['switch']['theme'] = array( __( 'Your attempt to switch to this theme: "%s" has failed.' ), 'use_id' );
93794
93795 $trans['log']['out'] = array( sprintf( __( 'You are attempting to log out of %s' ), get_bloginfo( 'sitename' ) ), false );
93796
93797 if ( isset( $trans[$verb][$noun] ) ) {
93798 if ( !empty( $trans[$verb][$noun][1] ) ) {
93799 $lookup = $trans[$verb][$noun][1];
93800 $object = $matches[4];
93801 if ( 'use_id' != $lookup )
93802 $object = call_user_func( $lookup, $object );
93803 return sprintf( $trans[$verb][$noun][0], wp_specialchars($object) );
93804 } else {
93805 return $trans[$verb][$noun][0];
93806 }
93807 }
93808 }
93809
93810 return apply_filters( 'explain_nonce_' . $verb . '-' . $noun, __( 'Are you sure you want to do this?' ), $matches[4] );
93811 }
93812
93813 /**
93814 * Display "Are You Sure" message to confirm the action being taken.
93815 *
93816 * If the action has the nonce explain message, then it will be displayed along
93817 * with the "Are you sure?" message.
93818 *
93819 * @package WordPress
93820 * @subpackage Security
93821 * @since 2.0.4
93822 *
93823 * @param string $action The nonce action.
93824 */
93825 function wp_nonce_ays( $action ) {
93826 $title = __( 'WordPress Failure Notice' );
93827 $html = wp_specialchars( wp_explain_nonce( $action ) );
93828 if ( wp_get_referer() )
93829 $html .= "</p><p><a href='" . remove_query_arg( 'updated', clean_url( wp_get_referer() ) ) . "'>" . __( 'Please try again.' ) . "</a>";
93830 elseif ( 'log-out' == $action )
93831 $html .= "</p><p>" . sprintf( __( "Do you really want to <a href='%s'>log out</a>?"), wp_nonce_url( site_url('wp-login.php?action=logout', 'login'), 'log-out' ) );
93832
93833 wp_die( $html, $title);
93834 }
93835
93836 /**
93837 * Kill WordPress execution and display HTML message with error message.
93838 *
93839 * Call this function complements the die() PHP function. The difference is that
93840 * HTML will be displayed to the user. It is recommended to use this function
93841 * only, when the execution should not continue any further. It is not
93842 * recommended to call this function very often and try to handle as many errors
93843 * as possible siliently.
93844 *
93845 * @since 2.0.4
93846 *
93847 * @param string $message Error message.
93848 * @param string $title Error title.
93849 * @param string|array $args Optional arguements to control behaviour.
93850 */
93851 function wp_die( $message, $title = '', $args = array() ) {
93852 global $wp_locale;
93853
93854 $defaults = array( 'response' => 500 );
93855 $r = wp_parse_args($args, $defaults);
93856
93857 if ( function_exists( 'is_wp_error' ) && is_wp_error( $message ) ) {
93858 if ( empty( $title ) ) {
93859 $error_data = $message->get_error_data();
93860 if ( is_array( $error_data ) && isset( $error_data['title'] ) )
93861 $title = $error_data['title'];
93862 }
93863 $errors = $message->get_error_messages();
93864 switch ( count( $errors ) ) :
93865 case 0 :
93866 $message = '';
93867 break;
93868 case 1 :
93869 $message = "<p>{$errors[0]}</p>";
93870 break;
93871 default :
93872 $message = "<ul>\n\t\t<li>" . join( "</li>\n\t\t<li>", $errors ) . "</li>\n\t</ul>";
93873 break;
93874 endswitch;
93875 } elseif ( is_string( $message ) ) {
93876 $message = "<p>$message</p>";
93877 }
93878
93879 if ( defined( 'WP_SITEURL' ) && '' != WP_SITEURL )
93880 $admin_dir = WP_SITEURL . '/wp-admin/';
93881 elseif ( function_exists( 'get_bloginfo' ) && '' != get_bloginfo( 'wpurl' ) )
93882 $admin_dir = get_bloginfo( 'wpurl' ) . '/wp-admin/';
93883 elseif ( strpos( $_SERVER['PHP_SELF'], 'wp-admin' ) !== false )
93884 $admin_dir = '';
93885 else
93886 $admin_dir = 'wp-admin/';
93887
93888 if ( !function_exists( 'did_action' ) || !did_action( 'admin_head' ) ) :
93889 if( !headers_sent() ){
93890 status_header( $r['response'] );
93891 nocache_headers();
93892 header( 'Content-Type: text/html; charset=utf-8' );
93893 }
93894
93895 if ( empty($title) ) {
93896 if ( function_exists( '__' ) )
93897 $title = __( 'WordPress › Error' );
93898 else
93899 $title = 'WordPress › Error';
93900 }
93901
93902 ?>
93903 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
93904 <html xmlns="http://www.w3.org/1999/xhtml" <?php if ( function_exists( 'language_attributes' ) ) language_attributes(); ?>>
93905 <head>
93906 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
93907 <title><?php echo $title ?></title>
93908 <link rel="stylesheet" href="<?php echo $admin_dir; ?>css/install.css" type="text/css" />
93909 <?php
93910 if ( ( $wp_locale ) && ( 'rtl' == $wp_locale->text_direction ) ) : ?>
93911 <link rel="stylesheet" href="<?php echo $admin_dir; ?>css/install-rtl.css" type="text/css" />
93912 <?php endif; ?>
93913 </head>
93914 <body id="error-page">
93915 <?php endif; ?>
93916 <?php echo $message; ?>
93917 <?php if ( strlen($message) < 512) echo str_repeat(' ', 512-strlen($message)); ?>
93918 </body>
93919 </html>
93920 <?php
93921 die();
93922 }
93923
93924 /**
93925 * Retrieve the WordPress home page URL.
93926 *
93927 * If the constant named 'WP_HOME' exists, then it willl be used and returned by
93928 * the function. This can be used to counter the redirection on your local
93929 * development environment.
93930 *
93931 * @access private
93932 * @package WordPress
93933 * @since 2.2.0
93934 *
93935 * @param string $url URL for the home location
93936 * @return string Homepage location.
93937 */
93938 function _config_wp_home( $url = '' ) {
93939 if ( defined( 'WP_HOME' ) )
93940 return WP_HOME;
93941 return $url;
93942 }
93943
93944 /**
93945 * Retrieve the WordPress site URL.
93946 *
93947 * If the constant named 'WP_SITEURL' is defined, then the value in that
93948 * constant will always be returned. This can be used for debugging a site on
93949 * your localhost while not having to change the database to your URL.
93950 *
93951 * @access private
93952 * @package WordPress
93953 * @since 2.2.0
93954 *
93955 * @param string $url URL to set the WordPress site location.
93956 * @return string The WordPress Site URL
93957 */
93958 function _config_wp_siteurl( $url = '' ) {
93959 if ( defined( 'WP_SITEURL' ) )
93960 return WP_SITEURL;
93961 return $url;
93962 }
93963
93964 /**
93965 * Set the localized direction for MCE plugin.
93966 *
93967 * Will only set the direction to 'rtl', if the WordPress locale has the text
93968 * direction set to 'rtl'.
93969 *
93970 * Fills in the 'directionality', 'plugins', and 'theme_advanced_button1' array
93971 * keys. These keys are then returned in the $input array.
93972 *
93973 * @access private
93974 * @package WordPress
93975 * @subpackage MCE
93976 * @since 2.1.0
93977 *
93978 * @param array $input MCE plugin array.
93979 * @return array Direction set for 'rtl', if needed by locale.
93980 */
93981 function _mce_set_direction( $input ) {
93982 global $wp_locale;
93983
93984 if ( 'rtl' == $wp_locale->text_direction ) {
93985 $input['directionality'] = 'rtl';
93986 $input['plugins'] .= ',directionality';
93987 $input['theme_advanced_buttons1'] .= ',ltr';
93988 }
93989
93990 return $input;
93991 }
93992
93993 /**
93994 * Convert smiley code to the icon graphic file equivalent.
93995 *
93996 * You can turn off smilies, by going to the write setting screen and unchecking
93997 * the box, or by setting 'use_smilies' option to false or removing the option.
93998 *
93999 * Plugins may override the default smiley list by setting the $wpsmiliestrans
94000 * to an array, with the key the code the blogger types in and the value the
94001 * image file.
94002 *
94003 * The $wp_smiliessearch global is for the regular expression array and is
94004 * set each time the function is called. The $wp_smiliesreplace is the full
94005 * replacement. Supposely, the $wp_smiliessearch array is looped over using
94006 * preg_replace() or just setting the array of $wp_smiliessearch along with the
94007 * array of $wp_smiliesreplace in the search and replace parameters of
94008 * preg_replace(), which would be faster and less overhead. Either way, both are
94009 * used with preg_replace() and can be defined after the function is called.
94010 *
94011 * The full list of smilies can be found in the function and won't be listed in
94012 * the description. Probably should create a Codex page for it, so that it is
94013 * available.
94014 *
94015 * @global array $wpsmiliestrans
94016 * @global array $wp_smiliesreplace
94017 * @global array $wp_smiliessearch
94018 * @since 2.2.0
94019 */
94020 function smilies_init() {
94021 global $wpsmiliestrans, $wp_smiliessearch, $wp_smiliesreplace;
94022
94023 // don't bother setting up smilies if they are disabled
94024 if ( !get_option( 'use_smilies' ) )
94025 return;
94026
94027 if ( !isset( $wpsmiliestrans ) ) {
94028 $wpsmiliestrans = array(
94029 ':mrgreen:' => 'icon_mrgreen.gif',
94030 ':neutral:' => 'icon_neutral.gif',
94031 ':twisted:' => 'icon_twisted.gif',
94032 ':arrow:' => 'icon_arrow.gif',
94033 ':shock:' => 'icon_eek.gif',
94034 ':smile:' => 'icon_smile.gif',
94035 ':???:' => 'icon_confused.gif',
94036 ':cool:' => 'icon_cool.gif',
94037 ':evil:' => 'icon_evil.gif',
94038 ':grin:' => 'icon_biggrin.gif',
94039 ':idea:' => 'icon_idea.gif',
94040 ':oops:' => 'icon_redface.gif',
94041 ':razz:' => 'icon_razz.gif',
94042 ':roll:' => 'icon_rolleyes.gif',
94043 ':wink:' => 'icon_wink.gif',
94044 ':cry:' => 'icon_cry.gif',
94045 ':eek:' => 'icon_surprised.gif',
94046 ':lol:' => 'icon_lol.gif',
94047 ':mad:' => 'icon_mad.gif',
94048 ':sad:' => 'icon_sad.gif',
94049 '8-)' => 'icon_cool.gif',
94050 '8-O' => 'icon_eek.gif',
94051 ':-(' => 'icon_sad.gif',
94052 ':-)' => 'icon_smile.gif',
94053 ':-?' => 'icon_confused.gif',
94054 ':-D' => 'icon_biggrin.gif',
94055 ':-P' => 'icon_razz.gif',
94056 ':-o' => 'icon_surprised.gif',
94057 ':-x' => 'icon_mad.gif',
94058 ':-|' => 'icon_neutral.gif',
94059 ';-)' => 'icon_wink.gif',
94060 '8)' => 'icon_cool.gif',
94061 '8O' => 'icon_eek.gif',
94062 ':(' => 'icon_sad.gif',
94063 ':)' => 'icon_smile.gif',
94064 ':?' => 'icon_confused.gif',
94065 ':D' => 'icon_biggrin.gif',
94066 ':P' => 'icon_razz.gif',
94067 ':o' => 'icon_surprised.gif',
94068 ':x' => 'icon_mad.gif',
94069 ':|' => 'icon_neutral.gif',
94070 ';)' => 'icon_wink.gif',
94071 ':!:' => 'icon_exclaim.gif',
94072 ':?:' => 'icon_question.gif',
94073 );
94074 }
94075
94076 $siteurl = get_option( 'siteurl' );
94077 foreach ( (array) $wpsmiliestrans as $smiley => $img ) {
94078 $wp_smiliessearch[] = '/(\s|^)' . preg_quote( $smiley, '/' ) . '(\s|$)/';
94079 $smiley_masked = attribute_escape( trim( $smiley ) );
94080 $wp_smiliesreplace[] = " <img src='$siteurl/wp-includes/images/smilies/$img' alt='$smiley_masked' class='wp-smiley' /> ";
94081 }
94082 }
94083
94084 /**
94085 * Merge user defined arguments into defaults array.
94086 *
94087 * This function is used throughout WordPress to allow for both string or array
94088 * to be merged into another array.
94089 *
94090 * @since 2.2.0
94091 *
94092 * @param string|array $args Value to merge with $defaults
94093 * @param array $defaults Array that serves as the defaults.
94094 * @return array Merged user defined values with defaults.
94095 */
94096 function wp_parse_args( $args, $defaults = '' ) {
94097 if ( is_object( $args ) )
94098 $r = get_object_vars( $args );
94099 elseif ( is_array( $args ) )
94100 $r =& $args;
94101 else
94102 wp_parse_str( $args, $r );
94103
94104 if ( is_array( $defaults ) )
94105 return array_merge( $defaults, $r );
94106 return $r;
94107 }
94108
94109 /**
94110 * Determines if Widgets library should be loaded.
94111 *
94112 * Checks to make sure that the widgets library hasn't already been loaded. If
94113 * it hasn't, then it will load the widgets library and run an action hook.
94114 *
94115 * @since 2.2.0
94116 * @uses add_action() Calls '_admin_menu' hook with 'wp_widgets_add_menu' value.
94117 */
94118 function wp_maybe_load_widgets() {
94119 if ( !function_exists( 'dynamic_sidebar' ) ) {
94120 require_once( ABSPATH . WPINC . '/widgets.php' );
94121 add_action( '_admin_menu', 'wp_widgets_add_menu' );
94122 }
94123 }
94124
94125 /**
94126 * Append the Widgets menu to the themes main menu.
94127 *
94128 * @since 2.2.0
94129 * @uses $submenu The administration submenu list.
94130 */
94131 function wp_widgets_add_menu() {
94132 global $submenu;
94133 $submenu['themes.php'][7] = array( __( 'Widgets' ), 'switch_themes', 'widgets.php' );
94134 ksort( $submenu['themes.php'], SORT_NUMERIC );
94135 }
94136
94137 /**
94138 * Flush all output buffers for PHP 5.2.
94139 *
94140 * Make sure all output buffers are flushed before our singletons our destroyed.
94141 *
94142 * @since 2.2.0
94143 */
94144 function wp_ob_end_flush_all() {
94145 while ( @ob_end_flush() );
94146 }
94147
94148 /**
94149 * Load the correct database class file.
94150 *
94151 * This function is used to load the database class file either at runtime or by
94152 * wp-admin/setup-config.php We must globalise $wpdb to ensure that it is
94153 * defined globally by the inline code in wp-db.php.
94154 *
94155 * @since 2.5.0
94156 * @global $wpdb WordPress Database Object
94157 */
94158 function require_wp_db() {
94159 global $wpdb;
94160 if ( file_exists( WP_CONTENT_DIR . '/db.php' ) )
94161 require_once( WP_CONTENT_DIR . '/db.php' );
94162 else
94163 require_once( ABSPATH . WPINC . '/wp-db.php' );
94164 }
94165
94166 /**
94167 * Load custom DB error or display WordPress DB error.
94168 *
94169 * If a file exists in the wp-content directory named db-error.php, then it will
94170 * be loaded instead of displaying the WordPress DB error. If it is not found,
94171 * then the WordPress DB error will be displayed instead.
94172 *
94173 * The WordPress DB error sets the HTTP status header to 500 to try to prevent
94174 * search engines from caching the message. Custom DB messages should do the
94175 * same.
94176 *
94177 * This function was backported to the the WordPress 2.3.2, but originally was
94178 * added in WordPress 2.5.0.
94179 *
94180 * @since 2.3.2
94181 * @uses $wpdb
94182 */
94183 function dead_db() {
94184 global $wpdb;
94185
94186 // Load custom DB error template, if present.
94187 if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
94188 require_once( WP_CONTENT_DIR . '/db-error.php' );
94189 die();
94190 }
94191
94192 // If installing or in the admin, provide the verbose message.
94193 if ( defined('WP_INSTALLING') || defined('WP_ADMIN') )
94194 wp_die($wpdb->error);
94195
94196 // Otherwise, be terse.
94197 status_header( 500 );
94198 nocache_headers();
94199 header( 'Content-Type: text/html; charset=utf-8' );
94200 ?>
94201 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
94202 <html xmlns="http://www.w3.org/1999/xhtml" <?php if ( function_exists( 'language_attributes' ) ) language_attributes(); ?>>
94203 <head>
94204 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
94205 <title>Database Error</title>
94206
94207 </head>
94208 <body>
94209 <h1>Error establishing a database connection</h1>
94210 </body>
94211 </html>
94212 <?php
94213 die();
94214 }
94215
94216 /**
94217 * Converts value to positive integer.
94218 *
94219 * @since 2.5.0
94220 *
94221 * @param mixed $maybeint Data you wish to have convered to an absolute integer
94222 * @return int An absolute integer
94223 */
94224 function absint( $maybeint ) {
94225 return abs( intval( $maybeint ) );
94226 }
94227
94228 /**
94229 * Determines if the blog can be accessed over SSL.
94230 *
94231 * Determines if blog can be accessed over SSL by using cURL to access the site
94232 * using the https in the siteurl. Requires cURL extension to work correctly.
94233 *
94234 * @since 2.5.0
94235 *
94236 * @return bool Whether or not SSL access is available
94237 */
94238 function url_is_accessable_via_ssl($url)
94239 {
94240 if (in_array('curl', get_loaded_extensions())) {
94241 $ssl = preg_replace( '/^http:\/\//', 'https://', $url );
94242
94243 $ch = curl_init();
94244 curl_setopt($ch, CURLOPT_URL, $ssl);
94245 curl_setopt($ch, CURLOPT_FAILONERROR, true);
94246 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
94247 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
94248
94249 curl_exec($ch);
94250
94251 $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
94252 curl_close ($ch);
94253
94254 if ($status == 200 || $status == 401) {
94255 return true;
94256 }
94257 }
94258 return false;
94259 }
94260
94261 /**
94262 * Secure URL, if available or the given URL.
94263 *
94264 * @since 2.5.0
94265 *
94266 * @param string $url Complete URL path with transport.
94267 * @return string Secure or regular URL path.
94268 */
94269 function atom_service_url_filter($url)
94270 {
94271 if ( url_is_accessable_via_ssl($url) )
94272 return preg_replace( '/^http:\/\//', 'https://', $url );
94273 else
94274 return $url;
94275 }
94276
94277 /**
94278 * Marks a function as deprecated and informs when it has been used.
94279 *
94280 * There is a hook deprecated_function_run that will be called that can be used
94281 * to get the backtrace up to what file and function called the deprecated
94282 * function.
94283 *
94284 * The current behavior is to trigger an user error if WP_DEBUG is defined and
94285 * is true.
94286 *
94287 * This function is to be used in every function in depreceated.php
94288 *
94289 * @package WordPress
94290 * @package Debug
94291 * @since 2.5.0
94292 * @access private
94293 *
94294 * @uses do_action() Calls 'deprecated_function_run' and passes the function name and what to use instead.
94295 * @uses apply_filters() Calls 'deprecated_function_trigger_error' and expects boolean value of true to do trigger or false to not trigger error.
94296 *
94297 * @param string $function The function that was called
94298 * @param string $version The version of WordPress that deprecated the function
94299 * @param string $replacement Optional. The function that should have been called
94300 */
94301 function _deprecated_function($function, $version, $replacement=null) {
94302
94303 do_action('deprecated_function_run', $function, $replacement);
94304
94305 // Allow plugin to filter the output error trigger
94306 if( defined('WP_DEBUG') && ( true === WP_DEBUG ) && apply_filters( 'deprecated_function_trigger_error', true )) {
94307 if( !is_null($replacement) )
94308 trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.'), $function, $version, $replacement ) );
94309 else
94310 trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.'), $function, $version ) );
94311 }
94312 }
94313
94314 /**
94315 * Marks a file as deprecated and informs when it has been used.
94316 *
94317 * There is a hook deprecated_file_included that will be called that can be used
94318 * to get the backtrace up to what file and function included the deprecated
94319 * file.
94320 *
94321 * The current behavior is to trigger an user error if WP_DEBUG is defined and
94322 * is true.
94323 *
94324 * This function is to be used in every file that is depreceated
94325 *
94326 * @package WordPress
94327 * @package Debug
94328 * @since 2.5.0
94329 * @access private
94330 *
94331 * @uses do_action() Calls 'deprecated_file_included' and passes the file name and what to use instead.
94332 * @uses apply_filters() Calls 'deprecated_file_trigger_error' and expects boolean value of true to do trigger or false to not trigger error.
94333 *
94334 * @param string $file The file that was included
94335 * @param string $version The version of WordPress that deprecated the function
94336 * @param string $replacement Optional. The function that should have been called
94337 */
94338 function _deprecated_file($file, $version, $replacement=null) {
94339
94340 do_action('deprecated_file_included', $file, $replacement);
94341
94342 // Allow plugin to filter the output error trigger
94343 if( defined('WP_DEBUG') && ( true === WP_DEBUG ) && apply_filters( 'deprecated_file_trigger_error', true )) {
94344 if( !is_null($replacement) )
94345 trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.'), $file, $version, $replacement ) );
94346 else
94347 trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.'), $file, $version ) );
94348 }
94349 }
94350
94351 /**
94352 * Is the server running earlier than 1.5.0 version of lighttpd
94353 *
94354 * @since 2.5.0
94355 *
94356 * @return bool Whether the server is running lighttpd < 1.5.0
94357 */
94358 function is_lighttpd_before_150() {
94359 $server_parts = explode( '/', isset( $_SERVER['SERVER_SOFTWARE'] )? $_SERVER['SERVER_SOFTWARE'] : '' );
94360 $server_parts[1] = isset( $server_parts[1] )? $server_parts[1] : '';
94361 return 'lighttpd' == $server_parts[0] && -1 == version_compare( $server_parts[1], '1.5.0' );
94362 }
94363
94364 /**
94365 * Does the specified module exist in the apache config?
94366 *
94367 * @since 2.5.0
94368 *
94369 * @param string $mod e.g. mod_rewrite
94370 * @param bool $default The default return value if the module is not found
94371 * @return bool
94372 */
94373 function apache_mod_loaded($mod, $default = false) {
94374 global $is_apache;
94375
94376 if ( !$is_apache )
94377 return false;
94378
94379 if ( function_exists('apache_get_modules') ) {
94380 $mods = apache_get_modules();
94381 if ( in_array($mod, $mods) )
94382 return true;
94383 } elseif ( function_exists('phpinfo') ) {
94384 ob_start();
94385 phpinfo(8);
94386 $phpinfo = ob_get_clean();
94387 if ( false !== strpos($phpinfo, $mod) )
94388 return true;
94389 }
94390 return $default;
94391 }
94392
94393 /**
94394 * File validates against allowed set of defined rules.
94395 *
94396 * A return value of '1' means that the $file contains either '..' or './'. A
94397 * return value of '2' means that the $file contains ':' after the first
94398 * character. A return value of '3' means that the file is not in the allowed
94399 * files list.
94400 *
94401 * @since 1.2.0
94402 *
94403 * @param string $file File path.
94404 * @param array $allowed_files List of allowed files.
94405 * @return int 0 means nothing is wrong, greater than 0 means something was wrong.
94406 */
94407 function validate_file( $file, $allowed_files = '' ) {
94408 if ( false !== strpos( $file, '..' ))
94409 return 1;
94410
94411 if ( false !== strpos( $file, './' ))
94412 return 1;
94413
94414 if (':' == substr( $file, 1, 1 ))
94415 return 2;
94416
94417 if (!empty ( $allowed_files ) && (!in_array( $file, $allowed_files ) ) )
94418 return 3;
94419
94420 return 0;
94421 }
94422
94423 /**
94424 * Determine if SSL is used.
94425 *
94426 * @since 2.6.0
94427 *
94428 * @return bool True if SSL, false if not used.
94429 */
94430 function is_ssl() {
94431 return ( isset($_SERVER['HTTPS']) && 'on' == strtolower($_SERVER['HTTPS']) ) ? true : false;
94432 }
94433
94434 /**
94435 * Whether SSL login should be forced.
94436 *
94437 * @since 2.6.0
94438 *
94439 * @param string|bool $force Optional.
94440 * @return bool True if forced, false if not forced.
94441 */
94442 function force_ssl_login($force = '') {
94443 static $forced;
94444
94445 if ( '' != $force ) {
94446 $old_forced = $forced;
94447 $forced = $force;
94448 return $old_forced;
94449 }
94450
94451 return $forced;
94452 }
94453
94454 /**
94455 * Whether to force SSL used for the Administration Panels.
94456 *
94457 * @since 2.6.0
94458 *
94459 * @param string|bool $force
94460 * @return bool True if forced, false if not forced.
94461 */
94462 function force_ssl_admin($force = '') {
94463 static $forced;
94464
94465 if ( '' != $force ) {
94466 $old_forced = $forced;
94467 $forced = $force;
94468 return $old_forced;
94469 }
94470
94471 return $forced;
94472 }
94473
94474 /**
94475 * Guess the URL for the site.
94476 *
94477 * Will remove wp-admin links to retrieve only return URLs not in the wp-admin
94478 * directory.
94479 *
94480 * @since 2.6.0
94481 *
94482 * @return string
94483 */
94484 function wp_guess_url() {
94485 if ( defined('WP_SITEURL') && '' != WP_SITEURL ) {
94486 $url = WP_SITEURL;
94487 } else {
94488 $schema = ( isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ) ? 'https://' : 'http://';
94489 $url = preg_replace('|/wp-admin/.*|i', '', $schema . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
94490 }
94491 return $url;
94492 }
94493
94494 /**
94495 * Suspend cache invalidation.
94496 *
94497 * Turns cache invalidation on and off. Useful during imports where you don't wont to do invalidations
94498 * every time a post is inserted. Callers must be sure that what they are doing won't lead to an inconsistent
94499 * cache when invalidation is suspended.
94500 *
94501 * @since 2.7.0
94502 *
94503 * @param bool $suspend Whether to suspend or enable cache invalidation
94504 * @return bool The current suspend setting
94505 */
94506 function wp_suspend_cache_invalidation($suspend = true) {
94507 global $_wp_suspend_cache_invalidation;
94508
94509 $current_suspend = $_wp_suspend_cache_invalidation;
94510 $_wp_suspend_cache_invalidation = $suspend;
94511 return $current_suspend;
94512 }
94513
94514 /**
94515 * Copy an object.
94516 *
94517 * Returns a cloned copy of an object.
94518 *
94519 * @since 2.7.0
94520 *
94521 * @param object $object The object to clone
94522 * @return object The cloned object
94523 */
94524 function wp_clone($object) {
94525 return version_compare(phpversion(), '5.0') < 0 ? $object : clone($object);
94526 }
94527
94528
94529 ?>