PageRenderTime 66ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 1ms

/wp-includes/functions.php

https://bitbucket.org/crypticrod/sr_wp_code
PHP | 4552 lines | 2346 code | 504 blank | 1702 comment | 550 complexity | 83ccb0075de6a1255a6b1491c7a2a1f5 MD5 | raw file
Possible License(s): AGPL-1.0, GPL-2.0, LGPL-2.1, GPL-3.0, LGPL-2.0, AGPL-3.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * Main WordPress API
  4. *
  5. * @package WordPress
  6. */
  7. /**
  8. * Converts MySQL DATETIME field to user specified date format.
  9. *
  10. * If $dateformatstring has 'G' value, then gmmktime() function will be used to
  11. * make the time. If $dateformatstring is set to 'U', then mktime() function
  12. * will be used to make the time.
  13. *
  14. * The $translate will only be used, if it is set to true and it is by default
  15. * and if the $wp_locale object has the month and weekday set.
  16. *
  17. * @since 0.71
  18. *
  19. * @param string $dateformatstring Either 'G', 'U', or php date format.
  20. * @param string $mysqlstring Time from mysql DATETIME field.
  21. * @param bool $translate Optional. Default is true. Will switch format to locale.
  22. * @return string Date formated by $dateformatstring or locale (if available).
  23. */
  24. function mysql2date( $dateformatstring, $mysqlstring, $translate = true ) {
  25. $m = $mysqlstring;
  26. if ( empty( $m ) )
  27. return false;
  28. if ( 'G' == $dateformatstring )
  29. return strtotime( $m . ' +0000' );
  30. $i = strtotime( $m );
  31. if ( 'U' == $dateformatstring )
  32. return $i;
  33. if ( $translate )
  34. return date_i18n( $dateformatstring, $i );
  35. else
  36. return date( $dateformatstring, $i );
  37. }
  38. /**
  39. * Retrieve the current time based on specified type.
  40. *
  41. * The 'mysql' type will return the time in the format for MySQL DATETIME field.
  42. * The 'timestamp' type will return the current timestamp.
  43. *
  44. * If $gmt is set to either '1' or 'true', then both types will use GMT time.
  45. * if $gmt is false, the output is adjusted with the GMT offset in the WordPress option.
  46. *
  47. * @since 1.0.0
  48. *
  49. * @param string $type Either 'mysql' or 'timestamp'.
  50. * @param int|bool $gmt Optional. Whether to use GMT timezone. Default is false.
  51. * @return int|string String if $type is 'gmt', int if $type is 'timestamp'.
  52. */
  53. function current_time( $type, $gmt = 0 ) {
  54. switch ( $type ) {
  55. case 'mysql':
  56. return ( $gmt ) ? gmdate( 'Y-m-d H:i:s' ) : gmdate( 'Y-m-d H:i:s', ( time() + ( get_option( 'gmt_offset' ) * 3600 ) ) );
  57. break;
  58. case 'timestamp':
  59. return ( $gmt ) ? time() : time() + ( get_option( 'gmt_offset' ) * 3600 );
  60. break;
  61. }
  62. }
  63. /**
  64. * Retrieve the date in localized format, based on timestamp.
  65. *
  66. * If the locale specifies the locale month and weekday, then the locale will
  67. * take over the format for the date. If it isn't, then the date format string
  68. * will be used instead.
  69. *
  70. * @since 0.71
  71. *
  72. * @param string $dateformatstring Format to display the date.
  73. * @param int $unixtimestamp Optional. Unix timestamp.
  74. * @param bool $gmt Optional, default is false. Whether to convert to GMT for time.
  75. * @return string The date, translated if locale specifies it.
  76. */
  77. function date_i18n( $dateformatstring, $unixtimestamp = false, $gmt = false ) {
  78. global $wp_locale;
  79. $i = $unixtimestamp;
  80. if ( false === $i ) {
  81. if ( ! $gmt )
  82. $i = current_time( 'timestamp' );
  83. else
  84. $i = time();
  85. // we should not let date() interfere with our
  86. // specially computed timestamp
  87. $gmt = true;
  88. }
  89. // store original value for language with untypical grammars
  90. // see http://core.trac.wordpress.org/ticket/9396
  91. $req_format = $dateformatstring;
  92. $datefunc = $gmt? 'gmdate' : 'date';
  93. if ( ( !empty( $wp_locale->month ) ) && ( !empty( $wp_locale->weekday ) ) ) {
  94. $datemonth = $wp_locale->get_month( $datefunc( 'm', $i ) );
  95. $datemonth_abbrev = $wp_locale->get_month_abbrev( $datemonth );
  96. $dateweekday = $wp_locale->get_weekday( $datefunc( 'w', $i ) );
  97. $dateweekday_abbrev = $wp_locale->get_weekday_abbrev( $dateweekday );
  98. $datemeridiem = $wp_locale->get_meridiem( $datefunc( 'a', $i ) );
  99. $datemeridiem_capital = $wp_locale->get_meridiem( $datefunc( 'A', $i ) );
  100. $dateformatstring = ' '.$dateformatstring;
  101. $dateformatstring = preg_replace( "/([^\\\])D/", "\\1" . backslashit( $dateweekday_abbrev ), $dateformatstring );
  102. $dateformatstring = preg_replace( "/([^\\\])F/", "\\1" . backslashit( $datemonth ), $dateformatstring );
  103. $dateformatstring = preg_replace( "/([^\\\])l/", "\\1" . backslashit( $dateweekday ), $dateformatstring );
  104. $dateformatstring = preg_replace( "/([^\\\])M/", "\\1" . backslashit( $datemonth_abbrev ), $dateformatstring );
  105. $dateformatstring = preg_replace( "/([^\\\])a/", "\\1" . backslashit( $datemeridiem ), $dateformatstring );
  106. $dateformatstring = preg_replace( "/([^\\\])A/", "\\1" . backslashit( $datemeridiem_capital ), $dateformatstring );
  107. $dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 );
  108. }
  109. $timezone_formats = array( 'P', 'I', 'O', 'T', 'Z', 'e' );
  110. $timezone_formats_re = implode( '|', $timezone_formats );
  111. if ( preg_match( "/$timezone_formats_re/", $dateformatstring ) ) {
  112. $timezone_string = get_option( 'timezone_string' );
  113. if ( $timezone_string ) {
  114. $timezone_object = timezone_open( $timezone_string );
  115. $date_object = date_create( null, $timezone_object );
  116. foreach( $timezone_formats as $timezone_format ) {
  117. if ( false !== strpos( $dateformatstring, $timezone_format ) ) {
  118. $formatted = date_format( $date_object, $timezone_format );
  119. $dateformatstring = ' '.$dateformatstring;
  120. $dateformatstring = preg_replace( "/([^\\\])$timezone_format/", "\\1" . backslashit( $formatted ), $dateformatstring );
  121. $dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 );
  122. }
  123. }
  124. }
  125. }
  126. $j = @$datefunc( $dateformatstring, $i );
  127. // allow plugins to redo this entirely for languages with untypical grammars
  128. $j = apply_filters('date_i18n', $j, $req_format, $i, $gmt);
  129. return $j;
  130. }
  131. /**
  132. * Convert integer number to format based on the locale.
  133. *
  134. * @since 2.3.0
  135. *
  136. * @param int $number The number to convert based on locale.
  137. * @param int $decimals Precision of the number of decimal places.
  138. * @return string Converted number in string format.
  139. */
  140. function number_format_i18n( $number, $decimals = 0 ) {
  141. global $wp_locale;
  142. $formatted = number_format( $number, absint( $decimals ), $wp_locale->number_format['decimal_point'], $wp_locale->number_format['thousands_sep'] );
  143. return apply_filters( 'number_format_i18n', $formatted );
  144. }
  145. /**
  146. * Convert number of bytes largest unit bytes will fit into.
  147. *
  148. * It is easier to read 1kB than 1024 bytes and 1MB than 1048576 bytes. Converts
  149. * number of bytes to human readable number by taking the number of that unit
  150. * that the bytes will go into it. Supports TB value.
  151. *
  152. * Please note that integers in PHP are limited to 32 bits, unless they are on
  153. * 64 bit architecture, then they have 64 bit size. If you need to place the
  154. * larger size then what PHP integer type will hold, then use a string. It will
  155. * be converted to a double, which should always have 64 bit length.
  156. *
  157. * Technically the correct unit names for powers of 1024 are KiB, MiB etc.
  158. * @link http://en.wikipedia.org/wiki/Byte
  159. *
  160. * @since 2.3.0
  161. *
  162. * @param int|string $bytes Number of bytes. Note max integer size for integers.
  163. * @param int $decimals Precision of number of decimal places. Deprecated.
  164. * @return bool|string False on failure. Number string on success.
  165. */
  166. function size_format( $bytes, $decimals = 0 ) {
  167. $quant = array(
  168. // ========================= Origin ====
  169. 'TB' => 1099511627776, // pow( 1024, 4)
  170. 'GB' => 1073741824, // pow( 1024, 3)
  171. 'MB' => 1048576, // pow( 1024, 2)
  172. 'kB' => 1024, // pow( 1024, 1)
  173. 'B ' => 1, // pow( 1024, 0)
  174. );
  175. foreach ( $quant as $unit => $mag )
  176. if ( doubleval($bytes) >= $mag )
  177. return number_format_i18n( $bytes / $mag, $decimals ) . ' ' . $unit;
  178. return false;
  179. }
  180. /**
  181. * Get the week start and end from the datetime or date string from mysql.
  182. *
  183. * @since 0.71
  184. *
  185. * @param string $mysqlstring Date or datetime field type from mysql.
  186. * @param int $start_of_week Optional. Start of the week as an integer.
  187. * @return array Keys are 'start' and 'end'.
  188. */
  189. function get_weekstartend( $mysqlstring, $start_of_week = '' ) {
  190. $my = substr( $mysqlstring, 0, 4 ); // Mysql string Year
  191. $mm = substr( $mysqlstring, 8, 2 ); // Mysql string Month
  192. $md = substr( $mysqlstring, 5, 2 ); // Mysql string day
  193. $day = mktime( 0, 0, 0, $md, $mm, $my ); // The timestamp for mysqlstring day.
  194. $weekday = date( 'w', $day ); // The day of the week from the timestamp
  195. if ( !is_numeric($start_of_week) )
  196. $start_of_week = get_option( 'start_of_week' );
  197. if ( $weekday < $start_of_week )
  198. $weekday += 7;
  199. $start = $day - 86400 * ( $weekday - $start_of_week ); // The most recent week start day on or before $day
  200. $end = $start + 604799; // $start + 7 days - 1 second
  201. return compact( 'start', 'end' );
  202. }
  203. /**
  204. * Unserialize value only if it was serialized.
  205. *
  206. * @since 2.0.0
  207. *
  208. * @param string $original Maybe unserialized original, if is needed.
  209. * @return mixed Unserialized data can be any type.
  210. */
  211. function maybe_unserialize( $original ) {
  212. if ( is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in
  213. return @unserialize( $original );
  214. return $original;
  215. }
  216. /**
  217. * Check value to find if it was serialized.
  218. *
  219. * If $data is not an string, then returned value will always be false.
  220. * Serialized data is always a string.
  221. *
  222. * @since 2.0.5
  223. *
  224. * @param mixed $data Value to check to see if was serialized.
  225. * @return bool False if not serialized and true if it was.
  226. */
  227. function is_serialized( $data ) {
  228. // if it isn't a string, it isn't serialized
  229. if ( ! is_string( $data ) )
  230. return false;
  231. $data = trim( $data );
  232. if ( 'N;' == $data )
  233. return true;
  234. $length = strlen( $data );
  235. if ( $length < 4 )
  236. return false;
  237. if ( ':' !== $data[1] )
  238. return false;
  239. $lastc = $data[$length-1];
  240. if ( ';' !== $lastc && '}' !== $lastc )
  241. return false;
  242. $token = $data[0];
  243. switch ( $token ) {
  244. case 's' :
  245. if ( '"' !== $data[$length-2] )
  246. return false;
  247. case 'a' :
  248. case 'O' :
  249. return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
  250. case 'b' :
  251. case 'i' :
  252. case 'd' :
  253. return (bool) preg_match( "/^{$token}:[0-9.E-]+;\$/", $data );
  254. }
  255. return false;
  256. }
  257. /**
  258. * Check whether serialized data is of string type.
  259. *
  260. * @since 2.0.5
  261. *
  262. * @param mixed $data Serialized data
  263. * @return bool False if not a serialized string, true if it is.
  264. */
  265. function is_serialized_string( $data ) {
  266. // if it isn't a string, it isn't a serialized string
  267. if ( !is_string( $data ) )
  268. return false;
  269. $data = trim( $data );
  270. $length = strlen( $data );
  271. if ( $length < 4 )
  272. return false;
  273. elseif ( ':' !== $data[1] )
  274. return false;
  275. elseif ( ';' !== $data[$length-1] )
  276. return false;
  277. elseif ( $data[0] !== 's' )
  278. return false;
  279. elseif ( '"' !== $data[$length-2] )
  280. return false;
  281. else
  282. return true;
  283. }
  284. /**
  285. * Retrieve option value based on name of option.
  286. *
  287. * If the option does not exist or does not have a value, then the return value
  288. * will be false. This is useful to check whether you need to install an option
  289. * and is commonly used during installation of plugin options and to test
  290. * whether upgrading is required.
  291. *
  292. * If the option was serialized then it will be unserialized when it is returned.
  293. *
  294. * @since 1.5.0
  295. * @package WordPress
  296. * @subpackage Option
  297. * @uses apply_filters() Calls 'pre_option_$option' before checking the option.
  298. * Any value other than false will "short-circuit" the retrieval of the option
  299. * and return the returned value. You should not try to override special options,
  300. * but you will not be prevented from doing so.
  301. * @uses apply_filters() Calls 'option_$option', after checking the option, with
  302. * the option value.
  303. *
  304. * @param string $option Name of option to retrieve. Expected to not be SQL-escaped.
  305. * @return mixed Value set for the option.
  306. */
  307. function get_option( $option, $default = false ) {
  308. global $wpdb;
  309. // Allow plugins to short-circuit options.
  310. $pre = apply_filters( 'pre_option_' . $option, false );
  311. if ( false !== $pre )
  312. return $pre;
  313. $option = trim($option);
  314. if ( empty($option) )
  315. return false;
  316. if ( defined( 'WP_SETUP_CONFIG' ) )
  317. return false;
  318. if ( ! defined( 'WP_INSTALLING' ) ) {
  319. // prevent non-existent options from triggering multiple queries
  320. $notoptions = wp_cache_get( 'notoptions', 'options' );
  321. if ( isset( $notoptions[$option] ) )
  322. return $default;
  323. $alloptions = wp_load_alloptions();
  324. if ( isset( $alloptions[$option] ) ) {
  325. $value = $alloptions[$option];
  326. } else {
  327. $value = wp_cache_get( $option, 'options' );
  328. if ( false === $value ) {
  329. $row = $wpdb->get_row( $wpdb->prepare( "SELECT option_value FROM $wpdb->options WHERE option_name = %s LIMIT 1", $option ) );
  330. // Has to be get_row instead of get_var because of funkiness with 0, false, null values
  331. if ( is_object( $row ) ) {
  332. $value = $row->option_value;
  333. wp_cache_add( $option, $value, 'options' );
  334. } else { // option does not exist, so we must cache its non-existence
  335. $notoptions[$option] = true;
  336. wp_cache_set( 'notoptions', $notoptions, 'options' );
  337. return $default;
  338. }
  339. }
  340. }
  341. } else {
  342. $suppress = $wpdb->suppress_errors();
  343. $row = $wpdb->get_row( $wpdb->prepare( "SELECT option_value FROM $wpdb->options WHERE option_name = %s LIMIT 1", $option ) );
  344. $wpdb->suppress_errors( $suppress );
  345. if ( is_object( $row ) )
  346. $value = $row->option_value;
  347. else
  348. return $default;
  349. }
  350. // If home is not set use siteurl.
  351. if ( 'home' == $option && '' == $value )
  352. return get_option( 'siteurl' );
  353. if ( in_array( $option, array('siteurl', 'home', 'category_base', 'tag_base') ) )
  354. $value = untrailingslashit( $value );
  355. return apply_filters( 'option_' . $option, maybe_unserialize( $value ) );
  356. }
  357. /**
  358. * Protect WordPress special option from being modified.
  359. *
  360. * Will die if $option is in protected list. Protected options are 'alloptions'
  361. * and 'notoptions' options.
  362. *
  363. * @since 2.2.0
  364. * @package WordPress
  365. * @subpackage Option
  366. *
  367. * @param string $option Option name.
  368. */
  369. function wp_protect_special_option( $option ) {
  370. $protected = array( 'alloptions', 'notoptions' );
  371. if ( in_array( $option, $protected ) )
  372. wp_die( sprintf( __( '%s is a protected WP option and may not be modified' ), esc_html( $option ) ) );
  373. }
  374. /**
  375. * Print option value after sanitizing for forms.
  376. *
  377. * @uses attr Sanitizes value.
  378. * @since 1.5.0
  379. * @package WordPress
  380. * @subpackage Option
  381. *
  382. * @param string $option Option name.
  383. */
  384. function form_option( $option ) {
  385. echo esc_attr( get_option( $option ) );
  386. }
  387. /**
  388. * Loads and caches all autoloaded options, if available or all options.
  389. *
  390. * @since 2.2.0
  391. * @package WordPress
  392. * @subpackage Option
  393. *
  394. * @return array List of all options.
  395. */
  396. function wp_load_alloptions() {
  397. global $wpdb;
  398. if ( !defined( 'WP_INSTALLING' ) || !is_multisite() )
  399. $alloptions = wp_cache_get( 'alloptions', 'options' );
  400. else
  401. $alloptions = false;
  402. if ( !$alloptions ) {
  403. $suppress = $wpdb->suppress_errors();
  404. if ( !$alloptions_db = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options WHERE autoload = 'yes'" ) )
  405. $alloptions_db = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options" );
  406. $wpdb->suppress_errors($suppress);
  407. $alloptions = array();
  408. foreach ( (array) $alloptions_db as $o ) {
  409. $alloptions[$o->option_name] = $o->option_value;
  410. }
  411. if ( !defined( 'WP_INSTALLING' ) || !is_multisite() )
  412. wp_cache_add( 'alloptions', $alloptions, 'options' );
  413. }
  414. return $alloptions;
  415. }
  416. /**
  417. * Loads and caches certain often requested site options if is_multisite() and a peristent cache is not being used.
  418. *
  419. * @since 3.0.0
  420. * @package WordPress
  421. * @subpackage Option
  422. *
  423. * @param int $site_id Optional site ID for which to query the options. Defaults to the current site.
  424. */
  425. function wp_load_core_site_options( $site_id = null ) {
  426. global $wpdb, $_wp_using_ext_object_cache;
  427. if ( !is_multisite() || $_wp_using_ext_object_cache || defined( 'WP_INSTALLING' ) )
  428. return;
  429. if ( empty($site_id) )
  430. $site_id = $wpdb->siteid;
  431. $core_options = array('site_name', 'siteurl', 'active_sitewide_plugins', '_site_transient_timeout_theme_roots', '_site_transient_theme_roots', 'site_admins', 'can_compress_scripts', 'global_terms_enabled' );
  432. $core_options_in = "'" . implode("', '", $core_options) . "'";
  433. $options = $wpdb->get_results( $wpdb->prepare("SELECT meta_key, meta_value FROM $wpdb->sitemeta WHERE meta_key IN ($core_options_in) AND site_id = %d", $site_id) );
  434. foreach ( $options as $option ) {
  435. $key = $option->meta_key;
  436. $cache_key = "{$site_id}:$key";
  437. $option->meta_value = maybe_unserialize( $option->meta_value );
  438. wp_cache_set( $cache_key, $option->meta_value, 'site-options' );
  439. }
  440. }
  441. /**
  442. * Update the value of an option that was already added.
  443. *
  444. * You do not need to serialize values. If the value needs to be serialized, then
  445. * it will be serialized before it is inserted into the database. Remember,
  446. * resources can not be serialized or added as an option.
  447. *
  448. * If the option does not exist, then the option will be added with the option
  449. * value, but you will not be able to set whether it is autoloaded. If you want
  450. * to set whether an option is autoloaded, then you need to use the add_option().
  451. *
  452. * @since 1.0.0
  453. * @package WordPress
  454. * @subpackage Option
  455. *
  456. * @uses apply_filters() Calls 'pre_update_option_$option' hook to allow overwriting the
  457. * option value to be stored.
  458. * @uses do_action() Calls 'update_option' hook before updating the option.
  459. * @uses do_action() Calls 'update_option_$option' and 'updated_option' hooks on success.
  460. *
  461. * @param string $option Option name. Expected to not be SQL-escaped.
  462. * @param mixed $newvalue Option value. Expected to not be SQL-escaped.
  463. * @return bool False if value was not updated and true if value was updated.
  464. */
  465. function update_option( $option, $newvalue ) {
  466. global $wpdb;
  467. $option = trim($option);
  468. if ( empty($option) )
  469. return false;
  470. wp_protect_special_option( $option );
  471. if ( is_object($newvalue) )
  472. $newvalue = clone $newvalue;
  473. $newvalue = sanitize_option( $option, $newvalue );
  474. $oldvalue = get_option( $option );
  475. $newvalue = apply_filters( 'pre_update_option_' . $option, $newvalue, $oldvalue );
  476. // If the new and old values are the same, no need to update.
  477. if ( $newvalue === $oldvalue )
  478. return false;
  479. if ( false === $oldvalue )
  480. return add_option( $option, $newvalue );
  481. $notoptions = wp_cache_get( 'notoptions', 'options' );
  482. if ( is_array( $notoptions ) && isset( $notoptions[$option] ) ) {
  483. unset( $notoptions[$option] );
  484. wp_cache_set( 'notoptions', $notoptions, 'options' );
  485. }
  486. $_newvalue = $newvalue;
  487. $newvalue = maybe_serialize( $newvalue );
  488. do_action( 'update_option', $option, $oldvalue, $_newvalue );
  489. if ( ! defined( 'WP_INSTALLING' ) ) {
  490. $alloptions = wp_load_alloptions();
  491. if ( isset( $alloptions[$option] ) ) {
  492. $alloptions[$option] = $_newvalue;
  493. wp_cache_set( 'alloptions', $alloptions, 'options' );
  494. } else {
  495. wp_cache_set( $option, $_newvalue, 'options' );
  496. }
  497. }
  498. $result = $wpdb->update( $wpdb->options, array( 'option_value' => $newvalue ), array( 'option_name' => $option ) );
  499. if ( $result ) {
  500. do_action( "update_option_{$option}", $oldvalue, $_newvalue );
  501. do_action( 'updated_option', $option, $oldvalue, $_newvalue );
  502. return true;
  503. }
  504. return false;
  505. }
  506. /**
  507. * Add a new option.
  508. *
  509. * You do not need to serialize values. If the value needs to be serialized, then
  510. * it will be serialized before it is inserted into the database. Remember,
  511. * resources can not be serialized or added as an option.
  512. *
  513. * You can create options without values and then add values later. Does not
  514. * check whether the option has already been added, but does check that you
  515. * aren't adding a protected WordPress option. Care should be taken to not name
  516. * options the same as the ones which are protected and to not add options
  517. * that were already added.
  518. *
  519. * @package WordPress
  520. * @subpackage Option
  521. * @since 1.0.0
  522. *
  523. * @uses do_action() Calls 'add_option' hook before adding the option.
  524. * @uses do_action() Calls 'add_option_$option' and 'added_option' hooks on success.
  525. *
  526. * @param string $option Name of option to add. Expected to not be SQL-escaped.
  527. * @param mixed $value Optional. Option value, can be anything. Expected to not be SQL-escaped.
  528. * @param mixed $deprecated Optional. Description. Not used anymore.
  529. * @param bool $autoload Optional. Default is enabled. Whether to load the option when WordPress starts up.
  530. * @return null returns when finished.
  531. */
  532. function add_option( $option, $value = '', $deprecated = '', $autoload = 'yes' ) {
  533. global $wpdb;
  534. if ( !empty( $deprecated ) )
  535. _deprecated_argument( __FUNCTION__, '2.3' );
  536. $option = trim($option);
  537. if ( empty($option) )
  538. return false;
  539. wp_protect_special_option( $option );
  540. if ( is_object($value) )
  541. $value = clone $value;
  542. $value = sanitize_option( $option, $value );
  543. // Make sure the option doesn't already exist. We can check the 'notoptions' cache before we ask for a db query
  544. $notoptions = wp_cache_get( 'notoptions', 'options' );
  545. if ( !is_array( $notoptions ) || !isset( $notoptions[$option] ) )
  546. if ( false !== get_option( $option ) )
  547. return;
  548. $_value = $value;
  549. $value = maybe_serialize( $value );
  550. $autoload = ( 'no' === $autoload ) ? 'no' : 'yes';
  551. do_action( 'add_option', $option, $_value );
  552. if ( ! defined( 'WP_INSTALLING' ) ) {
  553. if ( 'yes' == $autoload ) {
  554. $alloptions = wp_load_alloptions();
  555. $alloptions[$option] = $value;
  556. wp_cache_set( 'alloptions', $alloptions, 'options' );
  557. } else {
  558. wp_cache_set( $option, $value, 'options' );
  559. }
  560. }
  561. // This option exists now
  562. $notoptions = wp_cache_get( 'notoptions', 'options' ); // yes, again... we need it to be fresh
  563. if ( is_array( $notoptions ) && isset( $notoptions[$option] ) ) {
  564. unset( $notoptions[$option] );
  565. wp_cache_set( 'notoptions', $notoptions, 'options' );
  566. }
  567. $result = $wpdb->query( $wpdb->prepare( "INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE `option_name` = VALUES(`option_name`), `option_value` = VALUES(`option_value`), `autoload` = VALUES(`autoload`)", $option, $value, $autoload ) );
  568. if ( $result ) {
  569. do_action( "add_option_{$option}", $option, $_value );
  570. do_action( 'added_option', $option, $_value );
  571. return true;
  572. }
  573. return false;
  574. }
  575. /**
  576. * Removes option by name. Prevents removal of protected WordPress options.
  577. *
  578. * @package WordPress
  579. * @subpackage Option
  580. * @since 1.2.0
  581. *
  582. * @uses do_action() Calls 'delete_option' hook before option is deleted.
  583. * @uses do_action() Calls 'deleted_option' and 'delete_option_$option' hooks on success.
  584. *
  585. * @param string $option Name of option to remove. Expected to not be SQL-escaped.
  586. * @return bool True, if option is successfully deleted. False on failure.
  587. */
  588. function delete_option( $option ) {
  589. global $wpdb;
  590. wp_protect_special_option( $option );
  591. // Get the ID, if no ID then return
  592. $row = $wpdb->get_row( $wpdb->prepare( "SELECT autoload FROM $wpdb->options WHERE option_name = %s", $option ) );
  593. if ( is_null( $row ) )
  594. return false;
  595. do_action( 'delete_option', $option );
  596. $result = $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->options WHERE option_name = %s", $option) );
  597. if ( ! defined( 'WP_INSTALLING' ) ) {
  598. if ( 'yes' == $row->autoload ) {
  599. $alloptions = wp_load_alloptions();
  600. if ( is_array( $alloptions ) && isset( $alloptions[$option] ) ) {
  601. unset( $alloptions[$option] );
  602. wp_cache_set( 'alloptions', $alloptions, 'options' );
  603. }
  604. } else {
  605. wp_cache_delete( $option, 'options' );
  606. }
  607. }
  608. if ( $result ) {
  609. do_action( "delete_option_$option", $option );
  610. do_action( 'deleted_option', $option );
  611. return true;
  612. }
  613. return false;
  614. }
  615. /**
  616. * Delete a transient
  617. *
  618. * @since 2.8.0
  619. * @package WordPress
  620. * @subpackage Transient
  621. *
  622. * @uses do_action() Calls 'delete_transient_$transient' hook before transient is deleted.
  623. * @uses do_action() Calls 'deleted_transient' hook on success.
  624. *
  625. * @param string $transient Transient name. Expected to not be SQL-escaped.
  626. * @return bool true if successful, false otherwise
  627. */
  628. function delete_transient( $transient ) {
  629. global $_wp_using_ext_object_cache;
  630. do_action( 'delete_transient_' . $transient, $transient );
  631. if ( $_wp_using_ext_object_cache ) {
  632. $result = wp_cache_delete( $transient, 'transient' );
  633. } else {
  634. $option_timeout = '_transient_timeout_' . $transient;
  635. $option = '_transient_' . $transient;
  636. $result = delete_option( $option );
  637. if ( $result )
  638. delete_option( $option_timeout );
  639. }
  640. if ( $result )
  641. do_action( 'deleted_transient', $transient );
  642. return $result;
  643. }
  644. /**
  645. * Get the value of a transient
  646. *
  647. * If the transient does not exist or does not have a value, then the return value
  648. * will be false.
  649. *
  650. * @uses apply_filters() Calls 'pre_transient_$transient' hook before checking the transient.
  651. * Any value other than false will "short-circuit" the retrieval of the transient
  652. * and return the returned value.
  653. * @uses apply_filters() Calls 'transient_$option' hook, after checking the transient, with
  654. * the transient value.
  655. *
  656. * @since 2.8.0
  657. * @package WordPress
  658. * @subpackage Transient
  659. *
  660. * @param string $transient Transient name. Expected to not be SQL-escaped
  661. * @return mixed Value of transient
  662. */
  663. function get_transient( $transient ) {
  664. global $_wp_using_ext_object_cache;
  665. $pre = apply_filters( 'pre_transient_' . $transient, false );
  666. if ( false !== $pre )
  667. return $pre;
  668. if ( $_wp_using_ext_object_cache ) {
  669. $value = wp_cache_get( $transient, 'transient' );
  670. } else {
  671. $transient_option = '_transient_' . $transient;
  672. if ( ! defined( 'WP_INSTALLING' ) ) {
  673. // If option is not in alloptions, it is not autoloaded and thus has a timeout
  674. $alloptions = wp_load_alloptions();
  675. if ( !isset( $alloptions[$transient_option] ) ) {
  676. $transient_timeout = '_transient_timeout_' . $transient;
  677. if ( get_option( $transient_timeout ) < time() ) {
  678. delete_option( $transient_option );
  679. delete_option( $transient_timeout );
  680. return false;
  681. }
  682. }
  683. }
  684. $value = get_option( $transient_option );
  685. }
  686. return apply_filters( 'transient_' . $transient, $value );
  687. }
  688. /**
  689. * Set/update the value of a transient
  690. *
  691. * You do not need to serialize values. If the value needs to be serialized, then
  692. * it will be serialized before it is set.
  693. *
  694. * @since 2.8.0
  695. * @package WordPress
  696. * @subpackage Transient
  697. *
  698. * @uses apply_filters() Calls 'pre_set_transient_$transient' hook to allow overwriting the
  699. * transient value to be stored.
  700. * @uses do_action() Calls 'set_transient_$transient' and 'setted_transient' hooks on success.
  701. *
  702. * @param string $transient Transient name. Expected to not be SQL-escaped.
  703. * @param mixed $value Transient value. Expected to not be SQL-escaped.
  704. * @param int $expiration Time until expiration in seconds, default 0
  705. * @return bool False if value was not set and true if value was set.
  706. */
  707. function set_transient( $transient, $value, $expiration = 0 ) {
  708. global $_wp_using_ext_object_cache;
  709. $value = apply_filters( 'pre_set_transient_' . $transient, $value );
  710. if ( $_wp_using_ext_object_cache ) {
  711. $result = wp_cache_set( $transient, $value, 'transient', $expiration );
  712. } else {
  713. $transient_timeout = '_transient_timeout_' . $transient;
  714. $transient = '_transient_' . $transient;
  715. if ( false === get_option( $transient ) ) {
  716. $autoload = 'yes';
  717. if ( $expiration ) {
  718. $autoload = 'no';
  719. add_option( $transient_timeout, time() + $expiration, '', 'no' );
  720. }
  721. $result = add_option( $transient, $value, '', $autoload );
  722. } else {
  723. if ( $expiration )
  724. update_option( $transient_timeout, time() + $expiration );
  725. $result = update_option( $transient, $value );
  726. }
  727. }
  728. if ( $result ) {
  729. do_action( 'set_transient_' . $transient );
  730. do_action( 'setted_transient', $transient );
  731. }
  732. return $result;
  733. }
  734. /**
  735. * Saves and restores user interface settings stored in a cookie.
  736. *
  737. * Checks if the current user-settings cookie is updated and stores it. When no
  738. * cookie exists (different browser used), adds the last saved cookie restoring
  739. * the settings.
  740. *
  741. * @package WordPress
  742. * @subpackage Option
  743. * @since 2.7.0
  744. */
  745. function wp_user_settings() {
  746. if ( ! is_admin() )
  747. return;
  748. if ( defined('DOING_AJAX') )
  749. return;
  750. if ( ! $user = wp_get_current_user() )
  751. return;
  752. $settings = get_user_option( 'user-settings', $user->ID );
  753. if ( isset( $_COOKIE['wp-settings-' . $user->ID] ) ) {
  754. $cookie = preg_replace( '/[^A-Za-z0-9=&_]/', '', $_COOKIE['wp-settings-' . $user->ID] );
  755. if ( ! empty( $cookie ) && strpos( $cookie, '=' ) ) {
  756. if ( $cookie == $settings )
  757. return;
  758. $last_time = (int) get_user_option( 'user-settings-time', $user->ID );
  759. $saved = isset( $_COOKIE['wp-settings-time-' . $user->ID]) ? preg_replace( '/[^0-9]/', '', $_COOKIE['wp-settings-time-' . $user->ID] ) : 0;
  760. if ( $saved > $last_time ) {
  761. update_user_option( $user->ID, 'user-settings', $cookie, false );
  762. update_user_option( $user->ID, 'user-settings-time', time() - 5, false );
  763. return;
  764. }
  765. }
  766. }
  767. setcookie( 'wp-settings-' . $user->ID, $settings, time() + 31536000, SITECOOKIEPATH );
  768. setcookie( 'wp-settings-time-' . $user->ID, time(), time() + 31536000, SITECOOKIEPATH );
  769. $_COOKIE['wp-settings-' . $user->ID] = $settings;
  770. }
  771. /**
  772. * Retrieve user interface setting value based on setting name.
  773. *
  774. * @package WordPress
  775. * @subpackage Option
  776. * @since 2.7.0
  777. *
  778. * @param string $name The name of the setting.
  779. * @param string $default Optional default value to return when $name is not set.
  780. * @return mixed the last saved user setting or the default value/false if it doesn't exist.
  781. */
  782. function get_user_setting( $name, $default = false ) {
  783. $all = get_all_user_settings();
  784. return isset($all[$name]) ? $all[$name] : $default;
  785. }
  786. /**
  787. * Add or update user interface setting.
  788. *
  789. * Both $name and $value can contain only ASCII letters, numbers and underscores.
  790. * This function has to be used before any output has started as it calls setcookie().
  791. *
  792. * @package WordPress
  793. * @subpackage Option
  794. * @since 2.8.0
  795. *
  796. * @param string $name The name of the setting.
  797. * @param string $value The value for the setting.
  798. * @return bool true if set successfully/false if not.
  799. */
  800. function set_user_setting( $name, $value ) {
  801. if ( headers_sent() )
  802. return false;
  803. $all = get_all_user_settings();
  804. $name = preg_replace( '/[^A-Za-z0-9_]+/', '', $name );
  805. if ( empty($name) )
  806. return false;
  807. $all[$name] = $value;
  808. return wp_set_all_user_settings($all);
  809. }
  810. /**
  811. * Delete user interface settings.
  812. *
  813. * Deleting settings would reset them to the defaults.
  814. * This function has to be used before any output has started as it calls setcookie().
  815. *
  816. * @package WordPress
  817. * @subpackage Option
  818. * @since 2.7.0
  819. *
  820. * @param mixed $names The name or array of names of the setting to be deleted.
  821. * @return bool true if deleted successfully/false if not.
  822. */
  823. function delete_user_setting( $names ) {
  824. if ( headers_sent() )
  825. return false;
  826. $all = get_all_user_settings();
  827. $names = (array) $names;
  828. foreach ( $names as $name ) {
  829. if ( isset($all[$name]) ) {
  830. unset($all[$name]);
  831. $deleted = true;
  832. }
  833. }
  834. if ( isset($deleted) )
  835. return wp_set_all_user_settings($all);
  836. return false;
  837. }
  838. /**
  839. * Retrieve all user interface settings.
  840. *
  841. * @package WordPress
  842. * @subpackage Option
  843. * @since 2.7.0
  844. *
  845. * @return array the last saved user settings or empty array.
  846. */
  847. function get_all_user_settings() {
  848. global $_updated_user_settings;
  849. if ( ! $user = wp_get_current_user() )
  850. return array();
  851. if ( isset($_updated_user_settings) && is_array($_updated_user_settings) )
  852. return $_updated_user_settings;
  853. $all = array();
  854. if ( isset($_COOKIE['wp-settings-' . $user->ID]) ) {
  855. $cookie = preg_replace( '/[^A-Za-z0-9=&_]/', '', $_COOKIE['wp-settings-' . $user->ID] );
  856. if ( $cookie && strpos($cookie, '=') ) // the '=' cannot be 1st char
  857. parse_str($cookie, $all);
  858. } else {
  859. $option = get_user_option('user-settings', $user->ID);
  860. if ( $option && is_string($option) )
  861. parse_str( $option, $all );
  862. }
  863. return $all;
  864. }
  865. /**
  866. * Private. Set all user interface settings.
  867. *
  868. * @package WordPress
  869. * @subpackage Option
  870. * @since 2.8.0
  871. *
  872. * @param unknown $all
  873. * @return bool
  874. */
  875. function wp_set_all_user_settings($all) {
  876. global $_updated_user_settings;
  877. if ( ! $user = wp_get_current_user() )
  878. return false;
  879. $_updated_user_settings = $all;
  880. $settings = '';
  881. foreach ( $all as $k => $v ) {
  882. $v = preg_replace( '/[^A-Za-z0-9_]+/', '', $v );
  883. $settings .= $k . '=' . $v . '&';
  884. }
  885. $settings = rtrim($settings, '&');
  886. update_user_option( $user->ID, 'user-settings', $settings, false );
  887. update_user_option( $user->ID, 'user-settings-time', time(), false );
  888. return true;
  889. }
  890. /**
  891. * Delete the user settings of the current user.
  892. *
  893. * @package WordPress
  894. * @subpackage Option
  895. * @since 2.7.0
  896. */
  897. function delete_all_user_settings() {
  898. if ( ! $user = wp_get_current_user() )
  899. return;
  900. update_user_option( $user->ID, 'user-settings', '', false );
  901. setcookie('wp-settings-' . $user->ID, ' ', time() - 31536000, SITECOOKIEPATH);
  902. }
  903. /**
  904. * Serialize data, if needed.
  905. *
  906. * @since 2.0.5
  907. *
  908. * @param mixed $data Data that might be serialized.
  909. * @return mixed A scalar data
  910. */
  911. function maybe_serialize( $data ) {
  912. if ( is_array( $data ) || is_object( $data ) )
  913. return serialize( $data );
  914. if ( is_serialized( $data ) )
  915. return serialize( $data );
  916. return $data;
  917. }
  918. /**
  919. * Retrieve post title from XMLRPC XML.
  920. *
  921. * If the title element is not part of the XML, then the default post title from
  922. * the $post_default_title will be used instead.
  923. *
  924. * @package WordPress
  925. * @subpackage XMLRPC
  926. * @since 0.71
  927. *
  928. * @global string $post_default_title Default XMLRPC post title.
  929. *
  930. * @param string $content XMLRPC XML Request content
  931. * @return string Post title
  932. */
  933. function xmlrpc_getposttitle( $content ) {
  934. global $post_default_title;
  935. if ( preg_match( '/<title>(.+?)<\/title>/is', $content, $matchtitle ) ) {
  936. $post_title = $matchtitle[1];
  937. } else {
  938. $post_title = $post_default_title;
  939. }
  940. return $post_title;
  941. }
  942. /**
  943. * Retrieve the post category or categories from XMLRPC XML.
  944. *
  945. * If the category element is not found, then the default post category will be
  946. * used. The return type then would be what $post_default_category. If the
  947. * category is found, then it will always be an array.
  948. *
  949. * @package WordPress
  950. * @subpackage XMLRPC
  951. * @since 0.71
  952. *
  953. * @global string $post_default_category Default XMLRPC post category.
  954. *
  955. * @param string $content XMLRPC XML Request content
  956. * @return string|array List of categories or category name.
  957. */
  958. function xmlrpc_getpostcategory( $content ) {
  959. global $post_default_category;
  960. if ( preg_match( '/<category>(.+?)<\/category>/is', $content, $matchcat ) ) {
  961. $post_category = trim( $matchcat[1], ',' );
  962. $post_category = explode( ',', $post_category );
  963. } else {
  964. $post_category = $post_default_category;
  965. }
  966. return $post_category;
  967. }
  968. /**
  969. * XMLRPC XML content without title and category elements.
  970. *
  971. * @package WordPress
  972. * @subpackage XMLRPC
  973. * @since 0.71
  974. *
  975. * @param string $content XMLRPC XML Request content
  976. * @return string XMLRPC XML Request content without title and category elements.
  977. */
  978. function xmlrpc_removepostdata( $content ) {
  979. $content = preg_replace( '/<title>(.+?)<\/title>/si', '', $content );
  980. $content = preg_replace( '/<category>(.+?)<\/category>/si', '', $content );
  981. $content = trim( $content );
  982. return $content;
  983. }
  984. /**
  985. * Open the file handle for debugging.
  986. *
  987. * This function is used for XMLRPC feature, but it is general purpose enough
  988. * to be used in anywhere.
  989. *
  990. * @see fopen() for mode options.
  991. * @package WordPress
  992. * @subpackage Debug
  993. * @since 0.71
  994. * @uses $debug Used for whether debugging is enabled.
  995. *
  996. * @param string $filename File path to debug file.
  997. * @param string $mode Same as fopen() mode parameter.
  998. * @return bool|resource File handle. False on failure.
  999. */
  1000. function debug_fopen( $filename, $mode ) {
  1001. global $debug;
  1002. if ( 1 == $debug ) {
  1003. $fp = fopen( $filename, $mode );
  1004. return $fp;
  1005. } else {
  1006. return false;
  1007. }
  1008. }
  1009. /**
  1010. * Write contents to the file used for debugging.
  1011. *
  1012. * Technically, this can be used to write to any file handle when the global
  1013. * $debug is set to 1 or true.
  1014. *
  1015. * @package WordPress
  1016. * @subpackage Debug
  1017. * @since 0.71
  1018. * @uses $debug Used for whether debugging is enabled.
  1019. *
  1020. * @param resource $fp File handle for debugging file.
  1021. * @param string $string Content to write to debug file.
  1022. */
  1023. function debug_fwrite( $fp, $string ) {
  1024. global $debug;
  1025. if ( 1 == $debug )
  1026. fwrite( $fp, $string );
  1027. }
  1028. /**
  1029. * Close the debugging file handle.
  1030. *
  1031. * Technically, this can be used to close any file handle when the global $debug
  1032. * is set to 1 or true.
  1033. *
  1034. * @package WordPress
  1035. * @subpackage Debug
  1036. * @since 0.71
  1037. * @uses $debug Used for whether debugging is enabled.
  1038. *
  1039. * @param resource $fp Debug File handle.
  1040. */
  1041. function debug_fclose( $fp ) {
  1042. global $debug;
  1043. if ( 1 == $debug )
  1044. fclose( $fp );
  1045. }
  1046. /**
  1047. * Check content for video and audio links to add as enclosures.
  1048. *
  1049. * Will not add enclosures that have already been added and will
  1050. * remove enclosures that are no longer in the post. This is called as
  1051. * pingbacks and trackbacks.
  1052. *
  1053. * @package WordPress
  1054. * @since 1.5.0
  1055. *
  1056. * @uses $wpdb
  1057. *
  1058. * @param string $content Post Content
  1059. * @param int $post_ID Post ID
  1060. */
  1061. function do_enclose( $content, $post_ID ) {
  1062. global $wpdb;
  1063. //TODO: Tidy this ghetto code up and make the debug code optional
  1064. include_once( ABSPATH . WPINC . '/class-IXR.php' );
  1065. $log = debug_fopen( ABSPATH . 'enclosures.log', 'a' );
  1066. $post_links = array();
  1067. debug_fwrite( $log, 'BEGIN ' . date( 'YmdHis', time() ) . "\n" );
  1068. $pung = get_enclosed( $post_ID );
  1069. $ltrs = '\w';
  1070. $gunk = '/#~:.?+=&%@!\-';
  1071. $punc = '.:?\-';
  1072. $any = $ltrs . $gunk . $punc;
  1073. preg_match_all( "{\b http : [$any] +? (?= [$punc] * [^$any] | $)}x", $content, $post_links_temp );
  1074. debug_fwrite( $log, 'Post contents:' );
  1075. debug_fwrite( $log, $content . "\n" );
  1076. foreach ( $pung as $link_test ) {
  1077. if ( !in_array( $link_test, $post_links_temp[0] ) ) { // link no longer in post
  1078. $mid = $wpdb->get_col( $wpdb->prepare("SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE (%s)", $post_ID, like_escape( $link_test ) . '%') );
  1079. do_action( 'delete_postmeta', $mid );
  1080. $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->postmeta WHERE meta_id IN(%s)", implode( ',', $mid ) ) );
  1081. do_action( 'deleted_postmeta', $mid );
  1082. }
  1083. }
  1084. foreach ( (array) $post_links_temp[0] as $link_test ) {
  1085. if ( !in_array( $link_test, $pung ) ) { // If we haven't pung it already
  1086. $test = @parse_url( $link_test );
  1087. if ( false === $test )
  1088. continue;
  1089. if ( isset( $test['query'] ) )
  1090. $post_links[] = $link_test;
  1091. elseif ( isset($test['path']) && ( $test['path'] != '/' ) && ($test['path'] != '' ) )
  1092. $post_links[] = $link_test;
  1093. }
  1094. }
  1095. foreach ( (array) $post_links as $url ) {
  1096. if ( $url != '' && !$wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE (%s)", $post_ID, like_escape( $url ) . '%' ) ) ) {
  1097. if ( $headers = wp_get_http_headers( $url) ) {
  1098. $len = (int) $headers['content-length'];
  1099. $type = $headers['content-type'];
  1100. $allowed_types = array( 'video', 'audio' );
  1101. // Check to see if we can figure out the mime type from
  1102. // the extension
  1103. $url_parts = @parse_url( $url );
  1104. if ( false !== $url_parts ) {
  1105. $extension = pathinfo( $url_parts['path'], PATHINFO_EXTENSION );
  1106. if ( !empty( $extension ) ) {
  1107. foreach ( get_allowed_mime_types( ) as $exts => $mime ) {
  1108. if ( preg_match( '!^(' . $exts . ')$!i', $extension ) ) {
  1109. $type = $mime;
  1110. break;
  1111. }
  1112. }
  1113. }
  1114. }
  1115. if ( in_array( substr( $type, 0, strpos( $type, "/" ) ), $allowed_types ) ) {
  1116. $meta_value = "$url\n$len\n$type\n";
  1117. $wpdb->insert($wpdb->postmeta, array('post_id' => $post_ID, 'meta_key' => 'enclosure', 'meta_value' => $meta_value) );
  1118. do_action( 'added_postmeta', $wpdb->insert_id, $post_ID, 'enclosure', $meta_value );
  1119. }
  1120. }
  1121. }
  1122. }
  1123. }
  1124. /**
  1125. * Perform a HTTP HEAD or GET request.
  1126. *
  1127. * If $file_path is a writable filename, this will do a GET request and write
  1128. * the file to that path.
  1129. *
  1130. * @since 2.5.0
  1131. *
  1132. * @param string $url URL to fetch.
  1133. * @param string|bool $file_path Optional. File path to write request to.
  1134. * @param int $red (private) The number of Redirects followed, Upon 5 being hit, returns false.
  1135. * @return bool|string False on failure and string of headers if HEAD request.
  1136. */
  1137. function wp_get_http( $url, $file_path = false, $red = 1 ) {
  1138. @set_time_limit( 60 );
  1139. if ( $red > 5 )
  1140. return false;
  1141. $options = array();
  1142. $options['redirection'] = 5;
  1143. if ( false == $file_path )
  1144. $options['method'] = 'HEAD';
  1145. else
  1146. $options['method'] = 'GET';
  1147. $response = wp_remote_request($url, $options);
  1148. if ( is_wp_error( $response ) )
  1149. return false;
  1150. $headers = wp_remote_retrieve_headers( $response );
  1151. $headers['response'] = wp_remote_retrieve_response_code( $response );
  1152. // WP_HTTP no longer follows redirects for HEAD requests.
  1153. if ( 'HEAD' == $options['method'] && in_array($headers['response'], array(301, 302)) && isset( $headers['location'] ) ) {
  1154. return wp_get_http( $headers['location'], $file_path, ++$red );
  1155. }
  1156. if ( false == $file_path )
  1157. return $headers;
  1158. // GET request - write it to the supplied filename
  1159. $out_fp = fopen($file_path, 'w');
  1160. if ( !$out_fp )
  1161. return $headers;
  1162. fwrite( $out_fp, wp_remote_retrieve_body( $response ) );
  1163. fclose($out_fp);
  1164. clearstatcache();
  1165. return $headers;
  1166. }
  1167. /**
  1168. * Retrieve HTTP Headers from URL.
  1169. *
  1170. * @since 1.5.1
  1171. *
  1172. * @param string $url
  1173. * @param bool $deprecated Not Used.
  1174. * @return bool|string False on failure, headers on success.
  1175. */
  1176. function wp_get_http_headers( $url, $deprecated = false ) {
  1177. if ( !empty( $deprecated ) )
  1178. _deprecated_argument( __FUNCTION__, '2.7' );
  1179. $response = wp_remote_head( $url );
  1180. if ( is_wp_error( $response ) )
  1181. return false;
  1182. return wp_remote_retrieve_headers( $response );
  1183. }
  1184. /**
  1185. * Whether today is a new day.
  1186. *
  1187. * @since 0.71
  1188. * @uses $day Today
  1189. * @uses $previousday Previous day
  1190. *
  1191. * @return int 1 when new day, 0 if not a new day.
  1192. */
  1193. function is_new_day() {
  1194. global $currentday, $previousday;
  1195. if ( $currentday != $previousday )
  1196. return 1;
  1197. else
  1198. return 0;
  1199. }
  1200. /**
  1201. * Build URL query based on an associative and, or indexed array.
  1202. *
  1203. * This is a convenient function for easily building url queries. It sets the
  1204. * separator to '&' and uses _http_build_query() function.
  1205. *
  1206. * @see _http_build_query() Used to build the query
  1207. * @link http://us2.php.net/manual/en/function.http-build-query.php more on what
  1208. * http_build_query() does.
  1209. *
  1210. * @since 2.3.0
  1211. *
  1212. * @param array $data URL-encode key/value pairs.
  1213. * @return string URL encoded string
  1214. */
  1215. function build_query( $data ) {
  1216. return _http_build_query( $data, null, '&', '', false );
  1217. }
  1218. // from php.net (modified by Mark Jaquith to behave like the native PHP5 function)
  1219. function _http_build_query($data, $prefix=null, $sep=null, $key='', $urlencode=true) {
  1220. $ret = array();
  1221. foreach ( (array) $data as $k => $v ) {
  1222. if ( $urlencode)
  1223. $k = urlencode($k);
  1224. if ( is_int($k) && $prefix != null )
  1225. $k = $prefix.$k;
  1226. if ( !empty($key) )
  1227. $k = $key . '%5B' . $k . '%5D';
  1228. if ( $v === NULL )
  1229. continue;
  1230. elseif ( $v === FALSE )
  1231. $v = '0';
  1232. if ( is_array($v) || is_object($v) )
  1233. array_push($ret,_http_build_query($v, '', $sep, $k, $urlencode));
  1234. elseif ( $urlencode )
  1235. array_push($ret, $k.'='.urlencode($v));
  1236. else
  1237. array_push($ret, $k.'='.$v);
  1238. }
  1239. if ( NULL === $sep )
  1240. $sep = ini_get('arg_separator.output');
  1241. return implode($sep, $ret);
  1242. }
  1243. /**
  1244. * Retrieve a modified URL query string.
  1245. *
  1246. * You can rebuild the URL and append a new query variable to the URL query by
  1247. * using this function. You can also retrieve the full URL with query data.
  1248. *
  1249. * Adding a single key & value or an associative array. Setting a key value to
  1250. * emptystring removes the key. Omitting oldquery_or_uri uses the $_SERVER
  1251. * value.
  1252. *
  1253. * @since 1.5.0
  1254. *
  1255. * @param mixed $param1 Either newkey or an associative_array
  1256. * @param mixed $param2 Either newvalue or oldquery or uri
  1257. * @param mixed $param3 Optional. Old query or uri
  1258. * @return string New URL query string.
  1259. */
  1260. function add_query_arg() {
  1261. $ret = '';
  1262. if ( is_array( func_get_arg(0) ) ) {
  1263. if ( @func_num_args() < 2 || false === @func_get_arg( 1 ) )
  1264. $uri = $_SERVER['REQUEST_URI'];
  1265. else
  1266. $uri = @func_get_arg( 1 );
  1267. } else {
  1268. if ( @func_num_args() < 3 || false === @func_get_arg( 2 ) )
  1269. $uri = $_SERVER['REQUEST_URI'];
  1270. else
  1271. $uri = @func_get_arg( 2 );
  1272. }
  1273. if ( $frag = strstr( $uri, '#' ) )
  1274. $uri = substr( $uri, 0, -strlen( $frag ) );
  1275. else
  1276. $frag = '';
  1277. if ( preg_match( '|^https?://|i', $uri, $matches ) ) {
  1278. $protocol = $matches[0];
  1279. $uri = substr( $uri, strlen( $protocol ) );
  1280. } else {
  1281. $protocol = '';
  1282. }
  1283. if ( strpos( $uri, '?' ) !== false ) {
  1284. $parts = explode( '?', $uri, 2 );
  1285. if ( 1 == count( $parts ) ) {
  1286. $base = '?';
  1287. $query = $parts[0];
  1288. } else {
  1289. $base = $parts[0] . '?';
  1290. $query = $parts[1];
  1291. }
  1292. } elseif ( !empty( $protocol ) || strpos( $uri, '=' ) === false ) {
  1293. $base = $uri . '?';
  1294. $query = '';
  1295. } else {
  1296. $base = '';
  1297. $query = $uri;
  1298. }
  1299. wp_parse_str( $query, $qs );
  1300. $qs = urlencode_deep( $qs ); // this re-URL-encodes things that were already in the query string
  1301. if ( is_array( func_get_arg( 0 ) ) ) {
  1302. $kayvees = func_get_arg( 0 );
  1303. $qs = array_merge( $qs, $kayvees );
  1304. } else {
  1305. $qs[func_get_arg( 0 )] = func_get_arg( 1 );
  1306. }
  1307. foreach ( (array) $qs as $k => $v ) {
  1308. if ( $v === false )
  1309. unset( $qs[$k] );
  1310. }
  1311. $ret = build_query( $qs );
  1312. $ret = trim( $ret, '?' );
  1313. $ret = preg_replace( '#=(&|$)#', '$1', $ret );
  1314. $ret = $protocol . $base . $ret . $frag;
  1315. $ret = rtrim( $ret, '?' );
  1316. return $ret;
  1317. }
  1318. /**
  1319. * Removes an item or list from the query string.
  1320. *
  1321. * @since 1.5.0
  1322. *
  1323. * @param string|array $key Query key or keys to remove.
  1324. * @param bool $query When false uses the $_SERVER value.
  1325. * @return string New URL query string.
  1326. */
  1327. function remove_query_arg( $key, $query=false ) {
  1328. if ( is_array( $key ) ) { // removing multiple keys
  1329. foreach ( $key as $k )
  1330. $query = add_query_arg( $k, false, $query );
  1331. return $query;
  1332. }
  1333. return add_query_arg( $key, false, $query );
  1334. }
  1335. /**
  1336. * Walks the array while sanitizing the contents.
  1337. *
  1338. * @since 0.71
  1339. *
  1340. * @param array $array Array to used to walk while sanitizing contents.
  1341. * @return array Sanitized $array.
  1342. */
  1343. function add_magic_quotes( $array ) {
  1344. foreach ( (array) $array as $k => $v ) {
  1345. if ( is_array( $v ) ) {
  1346. $array[$k] = add_magic_quotes( $v );
  1347. } else {
  1348. $array[$k] = addslashes( $v );
  1349. }
  1350. }
  1351. return $array;
  1352. }
  1353. /**
  1354. * HTTP request for URI to retrieve content.
  1355. *
  1356. * @since 1.5.1
  1357. * @uses wp_remote_get()
  1358. *
  1359. * @param string $uri URI/URL of web page to retrieve.
  1360. * @return bool|string HTTP content. False on failure.
  1361. */
  1362. function wp_remote_fopen( $uri ) {
  1363. $parsed_url = @parse_url( $uri );
  1364. if ( !$parsed_url || !is_array( $parsed_url ) )
  1365. return false;
  1366. $options = array();
  1367. $options['timeout'] = 10;
  1368. $response = wp_remote_get( $uri, $options );
  1369. if ( is_wp_error( $response ) )
  1370. return false;
  1371. return wp_remote_retrieve_body( $response );
  1372. }
  1373. /**
  1374. * Set up the WordPress query.
  1375. *
  1376. * @since 2.0.0
  1377. *
  1378. * @param string $query_vars Default WP_Query arguments.
  1379. */
  1380. function wp( $query_vars = '' ) {
  1381. global $wp, $wp_query, $wp_the_query;
  1382. $wp->main( $query_vars );
  1383. if ( !isset($wp_the_query) )
  1384. $wp_the_query = $wp_query;
  1385. }
  1386. /**
  1387. * Retrieve the description for the HTTP status.
  1388. *
  1389. * @since 2.3.0
  1390. *
  1391. * @param int $code HTTP status code.
  1392. * @return string Empty string if not found, or description if found.
  1393. */
  1394. function get_status_header_desc( $code ) {
  1395. global $wp_header_to_desc;
  1396. $code = absint( $code );
  1397. if ( !isset( $wp_header_to_desc ) ) {
  1398. $wp_header_to_desc = array(
  1399. 100 => 'Continue',
  1400. 101 => 'Switching Protocols',
  1401. 102 => 'Processing',
  1402. 200 => 'OK',
  1403. 201 => 'Created',
  1404. 202 => 'Accepted',
  1405. 203 => 'Non-Authoritative Information',
  1406. 204 => 'No Content',
  1407. 205 => 'Reset Content',
  1408. 206 => 'Partial Content',
  1409. 207 => 'Multi-Status',
  1410. 226 => 'IM Used',
  1411. 300 => 'Multiple Choices',
  1412. 301 => 'Moved Permanently',
  1413. 302 => 'Found',
  1414. 303 => 'See Other',
  1415. 304 => 'Not Modified',
  1416. 305 => 'Use Proxy',
  1417. 306 => 'Reserved',
  1418. 307 => 'Temporary Redirect',
  1419. 400 => 'B…

Large files files are truncated, but you can click here to view the full file