PageRenderTime 79ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 9ms

/wp-includes/functions.php

https://github.com/schr/wordpress
PHP | 3148 lines | 1517 code | 335 blank | 1296 comment | 342 complexity | c67c6efbd9d9b64ca90437004c74e339 MD5 | raw file

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. global $wp_locale;
  26. $m = $mysqlstring;
  27. if ( empty( $m ) )
  28. return false;
  29. if( 'G' == $dateformatstring ) {
  30. return strtotime( $m . ' +0000' );
  31. }
  32. $i = strtotime( $m );
  33. if( 'U' == $dateformatstring )
  34. return $i;
  35. if ( $translate)
  36. return date_i18n( $dateformatstring, $i );
  37. else
  38. return date( $dateformatstring, $i );
  39. }
  40. /**
  41. * Retrieve the current time based on specified type.
  42. *
  43. * The 'mysql' type will return the time in the format for MySQL DATETIME field.
  44. * The 'timestamp' type will return the current timestamp.
  45. *
  46. * If $gmt is set to either '1' or 'true', then both types will use GMT time.
  47. * if $gmt is false, the output is adjusted with the GMT offset in the WordPress option.
  48. *
  49. * @since 1.0.0
  50. *
  51. * @param string $type Either 'mysql' or 'timestamp'.
  52. * @param int|bool $gmt Optional. Whether to use GMT timezone. Default is false.
  53. * @return int|string String if $type is 'gmt', int if $type is 'timestamp'.
  54. */
  55. function current_time( $type, $gmt = 0 ) {
  56. switch ( $type ) {
  57. case 'mysql':
  58. return ( $gmt ) ? gmdate( 'Y-m-d H:i:s' ) : gmdate( 'Y-m-d H:i:s', ( time() + ( get_option( 'gmt_offset' ) * 3600 ) ) );
  59. break;
  60. case 'timestamp':
  61. return ( $gmt ) ? time() : time() + ( get_option( 'gmt_offset' ) * 3600 );
  62. break;
  63. }
  64. }
  65. /**
  66. * Retrieve the date in localized format, based on timestamp.
  67. *
  68. * If the locale specifies the locale month and weekday, then the locale will
  69. * take over the format for the date. If it isn't, then the date format string
  70. * will be used instead.
  71. *
  72. * @since 0.71
  73. *
  74. * @param string $dateformatstring Format to display the date.
  75. * @param int $unixtimestamp Optional. Unix timestamp.
  76. * @param bool $gmt Optional, default is false. Whether to convert to GMT for time.
  77. * @return string The date, translated if locale specifies it.
  78. */
  79. function date_i18n( $dateformatstring, $unixtimestamp = false, $gmt = false ) {
  80. global $wp_locale;
  81. $i = $unixtimestamp;
  82. // Sanity check for PHP 5.1.0-
  83. if ( false === $i || intval($i) < 0 ) {
  84. if ( ! $gmt )
  85. $i = current_time( 'timestamp' );
  86. else
  87. $i = time();
  88. // we should not let date() interfere with our
  89. // specially computed timestamp
  90. $gmt = true;
  91. }
  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. $j = @$datefunc( $dateformatstring, $i );
  110. return $j;
  111. }
  112. /**
  113. * Convert number to format based on the locale.
  114. *
  115. * @since 2.3.0
  116. *
  117. * @param mixed $number The number to convert based on locale.
  118. * @param int $decimals Precision of the number of decimal places.
  119. * @return string Converted number in string format.
  120. */
  121. function number_format_i18n( $number, $decimals = null ) {
  122. global $wp_locale;
  123. // let the user override the precision only
  124. $decimals = ( is_null( $decimals ) ) ? $wp_locale->number_format['decimals'] : intval( $decimals );
  125. return number_format( $number, $decimals, $wp_locale->number_format['decimal_point'], $wp_locale->number_format['thousands_sep'] );
  126. }
  127. /**
  128. * Convert number of bytes largest unit bytes will fit into.
  129. *
  130. * It is easier to read 1kB than 1024 bytes and 1MB than 1048576 bytes. Converts
  131. * number of bytes to human readable number by taking the number of that unit
  132. * that the bytes will go into it. Supports TB value.
  133. *
  134. * Please note that integers in PHP are limited to 32 bits, unless they are on
  135. * 64 bit architecture, then they have 64 bit size. If you need to place the
  136. * larger size then what PHP integer type will hold, then use a string. It will
  137. * be converted to a double, which should always have 64 bit length.
  138. *
  139. * Technically the correct unit names for powers of 1024 are KiB, MiB etc.
  140. * @link http://en.wikipedia.org/wiki/Byte
  141. *
  142. * @since 2.3.0
  143. *
  144. * @param int|string $bytes Number of bytes. Note max integer size for integers.
  145. * @param int $decimals Precision of number of decimal places.
  146. * @return bool|string False on failure. Number string on success.
  147. */
  148. function size_format( $bytes, $decimals = null ) {
  149. $quant = array(
  150. // ========================= Origin ====
  151. 'TB' => 1099511627776, // pow( 1024, 4)
  152. 'GB' => 1073741824, // pow( 1024, 3)
  153. 'MB' => 1048576, // pow( 1024, 2)
  154. 'kB' => 1024, // pow( 1024, 1)
  155. 'B ' => 1, // pow( 1024, 0)
  156. );
  157. foreach ( $quant as $unit => $mag )
  158. if ( doubleval($bytes) >= $mag )
  159. return number_format_i18n( $bytes / $mag, $decimals ) . ' ' . $unit;
  160. return false;
  161. }
  162. /**
  163. * Get the week start and end from the datetime or date string from mysql.
  164. *
  165. * @since 0.71
  166. *
  167. * @param string $mysqlstring Date or datetime field type from mysql.
  168. * @param int $start_of_week Optional. Start of the week as an integer.
  169. * @return array Keys are 'start' and 'end'.
  170. */
  171. function get_weekstartend( $mysqlstring, $start_of_week = '' ) {
  172. $my = substr( $mysqlstring, 0, 4 ); // Mysql string Year
  173. $mm = substr( $mysqlstring, 8, 2 ); // Mysql string Month
  174. $md = substr( $mysqlstring, 5, 2 ); // Mysql string day
  175. $day = mktime( 0, 0, 0, $md, $mm, $my ); // The timestamp for mysqlstring day.
  176. $weekday = date( 'w', $day ); // The day of the week from the timestamp
  177. $i = 86400; // One day
  178. if( !is_numeric($start_of_week) )
  179. $start_of_week = get_option( 'start_of_week' );
  180. if ( $weekday < $start_of_week )
  181. $weekday = 7 - $start_of_week - $weekday;
  182. while ( $weekday > $start_of_week ) {
  183. $weekday = date( 'w', $day );
  184. if ( $weekday < $start_of_week )
  185. $weekday = 7 - $start_of_week - $weekday;
  186. $day -= 86400;
  187. $i = 0;
  188. }
  189. $week['start'] = $day + 86400 - $i;
  190. $week['end'] = $week['start'] + 604799;
  191. return $week;
  192. }
  193. /**
  194. * Unserialize value only if it was serialized.
  195. *
  196. * @since 2.0.0
  197. *
  198. * @param string $original Maybe unserialized original, if is needed.
  199. * @return mixed Unserialized data can be any type.
  200. */
  201. function maybe_unserialize( $original ) {
  202. if ( is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in
  203. if ( false !== $gm = @unserialize( $original ) )
  204. return $gm;
  205. return $original;
  206. }
  207. /**
  208. * Check value to find if it was serialized.
  209. *
  210. * If $data is not an string, then returned value will always be false.
  211. * Serialized data is always a string.
  212. *
  213. * @since 2.0.5
  214. *
  215. * @param mixed $data Value to check to see if was serialized.
  216. * @return bool False if not serialized and true if it was.
  217. */
  218. function is_serialized( $data ) {
  219. // if it isn't a string, it isn't serialized
  220. if ( !is_string( $data ) )
  221. return false;
  222. $data = trim( $data );
  223. if ( 'N;' == $data )
  224. return true;
  225. if ( !preg_match( '/^([adObis]):/', $data, $badions ) )
  226. return false;
  227. switch ( $badions[1] ) {
  228. case 'a' :
  229. case 'O' :
  230. case 's' :
  231. if ( preg_match( "/^{$badions[1]}:[0-9]+:.*[;}]\$/s", $data ) )
  232. return true;
  233. break;
  234. case 'b' :
  235. case 'i' :
  236. case 'd' :
  237. if ( preg_match( "/^{$badions[1]}:[0-9.E-]+;\$/", $data ) )
  238. return true;
  239. break;
  240. }
  241. return false;
  242. }
  243. /**
  244. * Check whether serialized data is of string type.
  245. *
  246. * @since 2.0.5
  247. *
  248. * @param mixed $data Serialized data
  249. * @return bool False if not a serialized string, true if it is.
  250. */
  251. function is_serialized_string( $data ) {
  252. // if it isn't a string, it isn't a serialized string
  253. if ( !is_string( $data ) )
  254. return false;
  255. $data = trim( $data );
  256. if ( preg_match( '/^s:[0-9]+:.*;$/s', $data ) ) // this should fetch all serialized strings
  257. return true;
  258. return false;
  259. }
  260. /**
  261. * Retrieve option value based on setting name.
  262. *
  263. * If the option does not exist or does not have a value, then the return value
  264. * will be false. This is useful to check whether you need to install an option
  265. * and is commonly used during installation of plugin options and to test
  266. * whether upgrading is required.
  267. *
  268. * You can "short-circuit" the retrieval of the option from the database for
  269. * your plugin or core options that aren't protected. You can do so by hooking
  270. * into the 'pre_option_$option' with the $option being replaced by the option
  271. * name. You should not try to override special options, but you will not be
  272. * prevented from doing so.
  273. *
  274. * There is a second filter called 'option_$option' with the $option being
  275. * replaced with the option name. This gives the value as the only parameter.
  276. *
  277. * If the option was serialized, when the option was added and, or updated, then
  278. * it will be unserialized, when it is returned.
  279. *
  280. * @since 1.5.0
  281. * @package WordPress
  282. * @subpackage Option
  283. * @uses apply_filters() Calls 'pre_option_$optionname' false to allow
  284. * overwriting the option value in a plugin.
  285. * @uses apply_filters() Calls 'option_$optionname' with the option name value.
  286. *
  287. * @param string $setting Name of option to retrieve. Should already be SQL-escaped
  288. * @return mixed Value set for the option.
  289. */
  290. function get_option( $setting, $default = false ) {
  291. global $wpdb;
  292. // Allow plugins to short-circuit options.
  293. $pre = apply_filters( 'pre_option_' . $setting, false );
  294. if ( false !== $pre )
  295. return $pre;
  296. // prevent non-existent options from triggering multiple queries
  297. $notoptions = wp_cache_get( 'notoptions', 'options' );
  298. if ( isset( $notoptions[$setting] ) )
  299. return $default;
  300. $alloptions = wp_load_alloptions();
  301. if ( isset( $alloptions[$setting] ) ) {
  302. $value = $alloptions[$setting];
  303. } else {
  304. $value = wp_cache_get( $setting, 'options' );
  305. if ( false === $value ) {
  306. if ( defined( 'WP_INSTALLING' ) )
  307. $suppress = $wpdb->suppress_errors();
  308. // expected_slashed ($setting)
  309. $row = $wpdb->get_row( "SELECT option_value FROM $wpdb->options WHERE option_name = '$setting' LIMIT 1" );
  310. if ( defined( 'WP_INSTALLING' ) )
  311. $wpdb->suppress_errors($suppress);
  312. if ( is_object( $row) ) { // Has to be get_row instead of get_var because of funkiness with 0, false, null values
  313. $value = $row->option_value;
  314. wp_cache_add( $setting, $value, 'options' );
  315. } else { // option does not exist, so we must cache its non-existence
  316. $notoptions[$setting] = true;
  317. wp_cache_set( 'notoptions', $notoptions, 'options' );
  318. return $default;
  319. }
  320. }
  321. }
  322. // If home is not set use siteurl.
  323. if ( 'home' == $setting && '' == $value )
  324. return get_option( 'siteurl' );
  325. if ( in_array( $setting, array('siteurl', 'home', 'category_base', 'tag_base') ) )
  326. $value = untrailingslashit( $value );
  327. return apply_filters( 'option_' . $setting, maybe_unserialize( $value ) );
  328. }
  329. /**
  330. * Protect WordPress special option from being modified.
  331. *
  332. * Will die if $option is in protected list. Protected options are 'alloptions'
  333. * and 'notoptions' options.
  334. *
  335. * @since 2.2.0
  336. * @package WordPress
  337. * @subpackage Option
  338. *
  339. * @param string $option Option name.
  340. */
  341. function wp_protect_special_option( $option ) {
  342. $protected = array( 'alloptions', 'notoptions' );
  343. if ( in_array( $option, $protected ) )
  344. die( sprintf( __( '%s is a protected WP option and may not be modified' ), wp_specialchars( $option ) ) );
  345. }
  346. /**
  347. * Print option value after sanitizing for forms.
  348. *
  349. * @uses attribute_escape Sanitizes value.
  350. * @since 1.5.0
  351. * @package WordPress
  352. * @subpackage Option
  353. *
  354. * @param string $option Option name.
  355. */
  356. function form_option( $option ) {
  357. echo attribute_escape (get_option( $option ) );
  358. }
  359. /**
  360. * Retrieve all autoload options or all options, if no autoloaded ones exist.
  361. *
  362. * This is different from wp_load_alloptions() in that this function does not
  363. * cache its results and will retrieve all options from the database every time
  364. *
  365. * it is called.
  366. *
  367. * @since 1.0.0
  368. * @package WordPress
  369. * @subpackage Option
  370. * @uses apply_filters() Calls 'pre_option_$optionname' hook with option value as parameter.
  371. * @uses apply_filters() Calls 'all_options' on options list.
  372. *
  373. * @return array List of all options.
  374. */
  375. function get_alloptions() {
  376. global $wpdb;
  377. $show = $wpdb->hide_errors();
  378. if ( !$options = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options WHERE autoload = 'yes'" ) )
  379. $options = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options" );
  380. $wpdb->show_errors($show);
  381. foreach ( (array) $options as $option ) {
  382. // "When trying to design a foolproof system,
  383. // never underestimate the ingenuity of the fools :)" -- Dougal
  384. if ( in_array( $option->option_name, array( 'siteurl', 'home', 'category_base', 'tag_base' ) ) )
  385. $option->option_value = untrailingslashit( $option->option_value );
  386. $value = maybe_unserialize( $option->option_value );
  387. $all_options->{$option->option_name} = apply_filters( 'pre_option_' . $option->option_name, $value );
  388. }
  389. return apply_filters( 'all_options', $all_options );
  390. }
  391. /**
  392. * Loads and caches all autoloaded options, if available or all options.
  393. *
  394. * This is different from get_alloptions(), in that this function will cache the
  395. * options and will return the cached options when called again.
  396. *
  397. * @since 2.2.0
  398. * @package WordPress
  399. * @subpackage Option
  400. *
  401. * @return array List all options.
  402. */
  403. function wp_load_alloptions() {
  404. global $wpdb;
  405. $alloptions = wp_cache_get( 'alloptions', 'options' );
  406. if ( !$alloptions ) {
  407. $suppress = $wpdb->suppress_errors();
  408. if ( !$alloptions_db = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options WHERE autoload = 'yes'" ) )
  409. $alloptions_db = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options" );
  410. $wpdb->suppress_errors($suppress);
  411. $alloptions = array();
  412. foreach ( (array) $alloptions_db as $o )
  413. $alloptions[$o->option_name] = $o->option_value;
  414. wp_cache_add( 'alloptions', $alloptions, 'options' );
  415. }
  416. return $alloptions;
  417. }
  418. /**
  419. * Update the value of an option that was already added.
  420. *
  421. * You do not need to serialize values, if the value needs to be serialize, then
  422. * it will be serialized before it is inserted into the database. Remember,
  423. * resources can not be serialized or added as an option.
  424. *
  425. * If the option does not exist, then the option will be added with the option
  426. * value, but you will not be able to set whether it is autoloaded. If you want
  427. * to set whether an option autoloaded, then you need to use the add_option().
  428. *
  429. * When the option is updated, then the filter named
  430. * 'update_option_$option_name', with the $option_name as the $option_name
  431. * parameter value, will be called. The hook should accept two parameters, the
  432. * first is the old parameter and the second is the new parameter.
  433. *
  434. * @since 1.0.0
  435. * @package WordPress
  436. * @subpackage Option
  437. *
  438. * @param string $option_name Option name. Expected to not be SQL-escaped
  439. * @param mixed $newvalue Option value.
  440. * @return bool False if value was not updated and true if value was updated.
  441. */
  442. function update_option( $option_name, $newvalue ) {
  443. global $wpdb;
  444. wp_protect_special_option( $option_name );
  445. $safe_option_name = $wpdb->escape( $option_name );
  446. $newvalue = sanitize_option( $option_name, $newvalue );
  447. $oldvalue = get_option( $safe_option_name );
  448. $newvalue = apply_filters( 'pre_update_option_' . $option_name, $newvalue, $oldvalue );
  449. // If the new and old values are the same, no need to update.
  450. if ( $newvalue === $oldvalue )
  451. return false;
  452. if ( false === $oldvalue ) {
  453. add_option( $option_name, $newvalue );
  454. return true;
  455. }
  456. $notoptions = wp_cache_get( 'notoptions', 'options' );
  457. if ( is_array( $notoptions ) && isset( $notoptions[$option_name] ) ) {
  458. unset( $notoptions[$option_name] );
  459. wp_cache_set( 'notoptions', $notoptions, 'options' );
  460. }
  461. $_newvalue = $newvalue;
  462. $newvalue = maybe_serialize( $newvalue );
  463. $alloptions = wp_load_alloptions();
  464. if ( isset( $alloptions[$option_name] ) ) {
  465. $alloptions[$option_name] = $newvalue;
  466. wp_cache_set( 'alloptions', $alloptions, 'options' );
  467. } else {
  468. wp_cache_set( $option_name, $newvalue, 'options' );
  469. }
  470. $wpdb->update($wpdb->options, array('option_value' => $newvalue), array('option_name' => $option_name) );
  471. if ( $wpdb->rows_affected == 1 ) {
  472. do_action( "update_option_{$option_name}", $oldvalue, $_newvalue );
  473. return true;
  474. }
  475. return false;
  476. }
  477. /**
  478. * Add a new option.
  479. *
  480. * You do not need to serialize values, if the value needs to be serialize, then
  481. * it will be serialized before it is inserted into the database. Remember,
  482. * resources can not be serialized or added as an option.
  483. *
  484. * You can create options without values and then add values later. Does not
  485. * check whether the option has already been added, but does check that you
  486. * aren't adding a protected WordPress option. Care should be taken to not name
  487. * options, the same as the ones which are protected and to not add options
  488. * that were already added.
  489. *
  490. * The filter named 'add_option_$optionname', with the $optionname being
  491. * replaced with the option's name, will be called. The hook should accept two
  492. * parameters, the first is the option name, and the second is the value.
  493. *
  494. * @package WordPress
  495. * @subpackage Option
  496. * @since 1.0.0
  497. * @link http://alex.vort-x.net/blog/ Thanks Alex Stapleton
  498. *
  499. * @param string $name Option name to add. Expects to NOT be SQL escaped.
  500. * @param mixed $value Optional. Option value, can be anything.
  501. * @param mixed $deprecated Optional. Description. Not used anymore.
  502. * @param bool $autoload Optional. Default is enabled. Whether to load the option when WordPress starts up.
  503. * @return null returns when finished.
  504. */
  505. function add_option( $name, $value = '', $deprecated = '', $autoload = 'yes' ) {
  506. global $wpdb;
  507. wp_protect_special_option( $name );
  508. $safe_name = $wpdb->escape( $name );
  509. $value = sanitize_option( $name, $value );
  510. // Make sure the option doesn't already exist. We can check the 'notoptions' cache before we ask for a db query
  511. $notoptions = wp_cache_get( 'notoptions', 'options' );
  512. if ( !is_array( $notoptions ) || !isset( $notoptions[$name] ) )
  513. if ( false !== get_option( $safe_name ) )
  514. return;
  515. $value = maybe_serialize( $value );
  516. $autoload = ( 'no' === $autoload ) ? 'no' : 'yes';
  517. if ( 'yes' == $autoload ) {
  518. $alloptions = wp_load_alloptions();
  519. $alloptions[$name] = $value;
  520. wp_cache_set( 'alloptions', $alloptions, 'options' );
  521. } else {
  522. wp_cache_set( $name, $value, 'options' );
  523. }
  524. // This option exists now
  525. $notoptions = wp_cache_get( 'notoptions', 'options' ); // yes, again... we need it to be fresh
  526. if ( is_array( $notoptions ) && isset( $notoptions[$name] ) ) {
  527. unset( $notoptions[$name] );
  528. wp_cache_set( 'notoptions', $notoptions, 'options' );
  529. }
  530. $wpdb->insert($wpdb->options, array('option_name' => $name, 'option_value' => $value, 'autoload' => $autoload) );
  531. do_action( "add_option_{$name}", $name, $value );
  532. return;
  533. }
  534. /**
  535. * Removes option by name and prevents removal of protected WordPress options.
  536. *
  537. * @package WordPress
  538. * @subpackage Option
  539. * @since 1.2.0
  540. *
  541. * @param string $name Option name to remove.
  542. * @return bool True, if succeed. False, if failure.
  543. */
  544. function delete_option( $name ) {
  545. global $wpdb;
  546. wp_protect_special_option( $name );
  547. // Get the ID, if no ID then return
  548. // expected_slashed ($name)
  549. $option = $wpdb->get_row( "SELECT option_id, autoload FROM $wpdb->options WHERE option_name = '$name'" );
  550. if ( is_null($option) || !$option->option_id )
  551. return false;
  552. // expected_slashed ($name)
  553. $wpdb->query( "DELETE FROM $wpdb->options WHERE option_name = '$name'" );
  554. if ( 'yes' == $option->autoload ) {
  555. $alloptions = wp_load_alloptions();
  556. if ( isset( $alloptions[$name] ) ) {
  557. unset( $alloptions[$name] );
  558. wp_cache_set( 'alloptions', $alloptions, 'options' );
  559. }
  560. } else {
  561. wp_cache_delete( $name, 'options' );
  562. }
  563. return true;
  564. }
  565. /**
  566. * Delete a transient
  567. *
  568. * @since 2.8.0
  569. * @package WordPress
  570. * @subpackage Transient
  571. *
  572. * @param string $transient Transient name. Expected to not be SQL-escaped
  573. * @return bool true if successful, false otherwise
  574. */
  575. function delete_transient($transient) {
  576. global $_wp_using_ext_object_cache, $wpdb;
  577. if ( $_wp_using_ext_object_cache ) {
  578. return wp_cache_delete($transient, 'transient');
  579. } else {
  580. $transient = '_transient_' . $wpdb->escape($transient);
  581. return delete_option($transient);
  582. }
  583. }
  584. /**
  585. * Get the value of a transient
  586. *
  587. * If the transient does not exist or does not have a value, then the return value
  588. * will be false.
  589. *
  590. * @since 2.8.0
  591. * @package WordPress
  592. * @subpackage Transient
  593. *
  594. * @param string $transient Transient name. Expected to not be SQL-escaped
  595. * @return mixed Value of transient
  596. */
  597. function get_transient($transient) {
  598. global $_wp_using_ext_object_cache, $wpdb;
  599. if ( $_wp_using_ext_object_cache ) {
  600. $value = wp_cache_get($transient, 'transient');
  601. } else {
  602. $transient_option = '_transient_' . $wpdb->escape($transient);
  603. // If option is not in alloptions, it is not autoloaded and thus has a timeout
  604. $alloptions = wp_load_alloptions();
  605. if ( !isset( $alloptions[$transient_option] ) ) {
  606. $transient_timeout = '_transient_timeout_' . $wpdb->escape($transient);
  607. if ( get_option($transient_timeout) < time() ) {
  608. delete_option($transient_option);
  609. delete_option($transient_timeout);
  610. return false;
  611. }
  612. }
  613. $value = get_option($transient_option);
  614. }
  615. return apply_filters('transient_' . $transient, $value);
  616. }
  617. /**
  618. * Set/update the value of a transient
  619. *
  620. * You do not need to serialize values, if the value needs to be serialize, then
  621. * it will be serialized before it is set.
  622. *
  623. * @since 2.8.0
  624. * @package WordPress
  625. * @subpackage Transient
  626. *
  627. * @param string $transient Transient name. Expected to not be SQL-escaped
  628. * @param mixed $value Transient value.
  629. * @param int $expiration Time until expiration in seconds, default 0
  630. * @return bool False if value was not set and true if value was set.
  631. */
  632. function set_transient($transient, $value, $expiration = 0) {
  633. global $_wp_using_ext_object_cache, $wpdb;
  634. if ( $_wp_using_ext_object_cache ) {
  635. return wp_cache_set($transient, $value, 'transient', $expiration);
  636. } else {
  637. $transient_timeout = '_transient_timeout_' . $transient;
  638. $transient = '_transient_' . $transient;
  639. $safe_transient = $wpdb->escape($transient);
  640. if ( false === get_option( $safe_transient ) ) {
  641. $autoload = 'yes';
  642. if ( 0 != $expiration ) {
  643. $autoload = 'no';
  644. add_option($transient_timeout, time() + $expiration, '', 'no');
  645. }
  646. return add_option($transient, $value, '', $autoload);
  647. } else {
  648. if ( 0 != $expiration )
  649. update_option($transient_timeout, time() + $expiration);
  650. return update_option($transient, $value);
  651. }
  652. }
  653. }
  654. /**
  655. * Saves and restores user interface settings stored in a cookie.
  656. *
  657. * Checks if the current user-settings cookie is updated and stores it. When no
  658. * cookie exists (different browser used), adds the last saved cookie restoring
  659. * the settings.
  660. *
  661. * @package WordPress
  662. * @subpackage Option
  663. * @since 2.7.0
  664. */
  665. function wp_user_settings() {
  666. if ( ! is_admin() )
  667. return;
  668. if ( defined('DOING_AJAX') )
  669. return;
  670. if ( ! $user = wp_get_current_user() )
  671. return;
  672. $settings = get_user_option( 'user-settings', $user->ID, false );
  673. if ( isset( $_COOKIE['wp-settings-' . $user->ID] ) ) {
  674. $cookie = preg_replace( '/[^A-Za-z0-9=&_]/', '', $_COOKIE['wp-settings-' . $user->ID] );
  675. if ( ! empty( $cookie ) && strpos( $cookie, '=' ) ) {
  676. if ( $cookie == $settings )
  677. return;
  678. $last_time = (int) get_user_option( 'user-settings-time', $user->ID, false );
  679. $saved = isset( $_COOKIE['wp-settings-time-' . $user->ID]) ? preg_replace( '/[^0-9]/', '', $_COOKIE['wp-settings-time-' . $user->ID] ) : 0;
  680. if ( $saved > $last_time ) {
  681. update_user_option( $user->ID, 'user-settings', $cookie, false );
  682. update_user_option( $user->ID, 'user-settings-time', time() - 5, false );
  683. return;
  684. }
  685. }
  686. }
  687. setcookie( 'wp-settings-' . $user->ID, $settings, time() + 31536000, SITECOOKIEPATH );
  688. setcookie( 'wp-settings-time-' . $user->ID, time(), time() + 31536000, SITECOOKIEPATH );
  689. }
  690. /**
  691. * Retrieve user interface setting value based on setting name.
  692. *
  693. * @package WordPress
  694. * @subpackage Option
  695. * @since 2.7.0
  696. *
  697. * @param string $name The name of the setting.
  698. * @param string $default Optional default value to return when $name is not set.
  699. * @return mixed the last saved user setting or the default value/false if it doesn't exist.
  700. */
  701. function get_user_setting( $name, $default = false ) {
  702. $arr = get_all_user_settings();
  703. return isset($arr[$name]) ? $arr[$name] : $default;
  704. }
  705. /**
  706. * Delete user interface settings.
  707. *
  708. * Deleting settings would reset them to the defaults.
  709. *
  710. * @package WordPress
  711. * @subpackage Option
  712. * @since 2.7.0
  713. *
  714. * @param mixed $names The name or array of names of the setting to be deleted.
  715. */
  716. function delete_user_setting( $names ) {
  717. global $current_user;
  718. $arr = get_all_user_settings();
  719. $names = (array) $names;
  720. foreach ( $names as $name ) {
  721. if ( isset($arr[$name]) ) {
  722. unset($arr[$name]);
  723. $settings = '';
  724. }
  725. }
  726. if ( isset($settings) ) {
  727. foreach ( $arr as $k => $v )
  728. $settings .= $k . '=' . $v . '&';
  729. $settings = rtrim($settings, '&');
  730. update_user_option( $current_user->ID, 'user-settings', $settings );
  731. setcookie('wp-settings-'.$current_user->ID, $settings, time() + 31536000, SITECOOKIEPATH);
  732. }
  733. }
  734. /**
  735. * Retrieve all user interface settings.
  736. *
  737. * @package WordPress
  738. * @subpackage Option
  739. * @since 2.7.0
  740. *
  741. * @return array the last saved user settings or empty array.
  742. */
  743. function get_all_user_settings() {
  744. if ( ! $user = wp_get_current_user() )
  745. return array();
  746. if ( isset($_COOKIE['wp-settings-'.$user->ID]) ) {
  747. $cookie = preg_replace( '/[^A-Za-z0-9=&_]/', '', $_COOKIE['wp-settings-'.$user->ID] );
  748. if ( $cookie && strpos($cookie, '=') ) { // the '=' cannot be 1st char
  749. parse_str($cookie, $arr);
  750. return $arr;
  751. }
  752. }
  753. return array();
  754. }
  755. /**
  756. * Delete the user settings of the current user.
  757. *
  758. * @package WordPress
  759. * @subpackage Option
  760. * @since 2.7.0
  761. */
  762. function delete_all_user_settings() {
  763. if ( ! $user = wp_get_current_user() )
  764. return;
  765. delete_usermeta( $user->ID, 'user-settings' );
  766. setcookie('wp-settings-'.$user->ID, ' ', time() - 31536000, SITECOOKIEPATH);
  767. }
  768. /**
  769. * Serialize data, if needed.
  770. *
  771. * @since 2.0.5
  772. *
  773. * @param mixed $data Data that might be serialized.
  774. * @return mixed A scalar data
  775. */
  776. function maybe_serialize( $data ) {
  777. if ( is_array( $data ) || is_object( $data ) )
  778. return serialize( $data );
  779. if ( is_serialized( $data ) )
  780. return serialize( $data );
  781. return $data;
  782. }
  783. /**
  784. * Strip HTML and put links at the bottom of stripped content.
  785. *
  786. * Searches for all of the links, strips them out of the content, and places
  787. * them at the bottom of the content with numbers.
  788. *
  789. * @since 0.71
  790. *
  791. * @param string $content Content to get links
  792. * @return string HTML stripped out of content with links at the bottom.
  793. */
  794. function make_url_footnote( $content ) {
  795. preg_match_all( '/<a(.+?)href=\"(.+?)\"(.*?)>(.+?)<\/a>/', $content, $matches );
  796. $links_summary = "\n";
  797. for ( $i=0; $i<count($matches[0]); $i++ ) {
  798. $link_match = $matches[0][$i];
  799. $link_number = '['.($i+1).']';
  800. $link_url = $matches[2][$i];
  801. $link_text = $matches[4][$i];
  802. $content = str_replace( $link_match, $link_text . ' ' . $link_number, $content );
  803. $link_url = ( ( strtolower( substr( $link_url, 0, 7 ) ) != 'http://' ) && ( strtolower( substr( $link_url, 0, 8 ) ) != 'https://' ) ) ? get_option( 'home' ) . $link_url : $link_url;
  804. $links_summary .= "\n" . $link_number . ' ' . $link_url;
  805. }
  806. $content = strip_tags( $content );
  807. $content .= $links_summary;
  808. return $content;
  809. }
  810. /**
  811. * Retrieve post title from XMLRPC XML.
  812. *
  813. * If the title element is not part of the XML, then the default post title from
  814. * the $post_default_title will be used instead.
  815. *
  816. * @package WordPress
  817. * @subpackage XMLRPC
  818. * @since 0.71
  819. *
  820. * @global string $post_default_title Default XMLRPC post title.
  821. *
  822. * @param string $content XMLRPC XML Request content
  823. * @return string Post title
  824. */
  825. function xmlrpc_getposttitle( $content ) {
  826. global $post_default_title;
  827. if ( preg_match( '/<title>(.+?)<\/title>/is', $content, $matchtitle ) ) {
  828. $post_title = $matchtitle[0];
  829. $post_title = preg_replace( '/<title>/si', '', $post_title );
  830. $post_title = preg_replace( '/<\/title>/si', '', $post_title );
  831. } else {
  832. $post_title = $post_default_title;
  833. }
  834. return $post_title;
  835. }
  836. /**
  837. * Retrieve the post category or categories from XMLRPC XML.
  838. *
  839. * If the category element is not found, then the default post category will be
  840. * used. The return type then would be what $post_default_category. If the
  841. * category is found, then it will always be an array.
  842. *
  843. * @package WordPress
  844. * @subpackage XMLRPC
  845. * @since 0.71
  846. *
  847. * @global string $post_default_category Default XMLRPC post category.
  848. *
  849. * @param string $content XMLRPC XML Request content
  850. * @return string|array List of categories or category name.
  851. */
  852. function xmlrpc_getpostcategory( $content ) {
  853. global $post_default_category;
  854. if ( preg_match( '/<category>(.+?)<\/category>/is', $content, $matchcat ) ) {
  855. $post_category = trim( $matchcat[1], ',' );
  856. $post_category = explode( ',', $post_category );
  857. } else {
  858. $post_category = $post_default_category;
  859. }
  860. return $post_category;
  861. }
  862. /**
  863. * XMLRPC XML content without title and category elements.
  864. *
  865. * @package WordPress
  866. * @subpackage XMLRPC
  867. * @since 0.71
  868. *
  869. * @param string $content XMLRPC XML Request content
  870. * @return string XMLRPC XML Request content without title and category elements.
  871. */
  872. function xmlrpc_removepostdata( $content ) {
  873. $content = preg_replace( '/<title>(.+?)<\/title>/si', '', $content );
  874. $content = preg_replace( '/<category>(.+?)<\/category>/si', '', $content );
  875. $content = trim( $content );
  876. return $content;
  877. }
  878. /**
  879. * Open the file handle for debugging.
  880. *
  881. * This function is used for XMLRPC feature, but it is general purpose enough
  882. * to be used in anywhere.
  883. *
  884. * @see fopen() for mode options.
  885. * @package WordPress
  886. * @subpackage Debug
  887. * @since 0.71
  888. * @uses $debug Used for whether debugging is enabled.
  889. *
  890. * @param string $filename File path to debug file.
  891. * @param string $mode Same as fopen() mode parameter.
  892. * @return bool|resource File handle. False on failure.
  893. */
  894. function debug_fopen( $filename, $mode ) {
  895. global $debug;
  896. if ( 1 == $debug ) {
  897. $fp = fopen( $filename, $mode );
  898. return $fp;
  899. } else {
  900. return false;
  901. }
  902. }
  903. /**
  904. * Write contents to the file used for debugging.
  905. *
  906. * Technically, this can be used to write to any file handle when the global
  907. * $debug is set to 1 or true.
  908. *
  909. * @package WordPress
  910. * @subpackage Debug
  911. * @since 0.71
  912. * @uses $debug Used for whether debugging is enabled.
  913. *
  914. * @param resource $fp File handle for debugging file.
  915. * @param string $string Content to write to debug file.
  916. */
  917. function debug_fwrite( $fp, $string ) {
  918. global $debug;
  919. if ( 1 == $debug )
  920. fwrite( $fp, $string );
  921. }
  922. /**
  923. * Close the debugging file handle.
  924. *
  925. * Technically, this can be used to close any file handle when the global $debug
  926. * is set to 1 or true.
  927. *
  928. * @package WordPress
  929. * @subpackage Debug
  930. * @since 0.71
  931. * @uses $debug Used for whether debugging is enabled.
  932. *
  933. * @param resource $fp Debug File handle.
  934. */
  935. function debug_fclose( $fp ) {
  936. global $debug;
  937. if ( 1 == $debug )
  938. fclose( $fp );
  939. }
  940. /**
  941. * Check content for video and audio links to add as enclosures.
  942. *
  943. * Will not add enclosures that have already been added. This is called as
  944. * pingbacks and trackbacks.
  945. *
  946. * @package WordPress
  947. * @since 1.5.0
  948. *
  949. * @uses $wpdb
  950. *
  951. * @param string $content Post Content
  952. * @param int $post_ID Post ID
  953. */
  954. function do_enclose( $content, $post_ID ) {
  955. global $wpdb;
  956. include_once( ABSPATH . WPINC . '/class-IXR.php' );
  957. $log = debug_fopen( ABSPATH . 'enclosures.log', 'a' );
  958. $post_links = array();
  959. debug_fwrite( $log, 'BEGIN ' . date( 'YmdHis', time() ) . "\n" );
  960. $pung = get_enclosed( $post_ID );
  961. $ltrs = '\w';
  962. $gunk = '/#~:.?+=&%@!\-';
  963. $punc = '.:?\-';
  964. $any = $ltrs . $gunk . $punc;
  965. preg_match_all( "{\b http : [$any] +? (?= [$punc] * [^$any] | $)}x", $content, $post_links_temp );
  966. debug_fwrite( $log, 'Post contents:' );
  967. debug_fwrite( $log, $content . "\n" );
  968. foreach ( (array) $post_links_temp[0] as $link_test ) {
  969. if ( !in_array( $link_test, $pung ) ) { // If we haven't pung it already
  970. $test = parse_url( $link_test );
  971. if ( isset( $test['query'] ) )
  972. $post_links[] = $link_test;
  973. elseif ( $test['path'] != '/' && $test['path'] != '' )
  974. $post_links[] = $link_test;
  975. }
  976. }
  977. foreach ( (array) $post_links as $url ) {
  978. 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 . '%' ) ) ) {
  979. if ( $headers = wp_get_http_headers( $url) ) {
  980. $len = (int) $headers['content-length'];
  981. $type = $headers['content-type'];
  982. $allowed_types = array( 'video', 'audio' );
  983. if ( in_array( substr( $type, 0, strpos( $type, "/" ) ), $allowed_types ) ) {
  984. $meta_value = "$url\n$len\n$type\n";
  985. $wpdb->insert($wpdb->postmeta, array('post_id' => $post_ID, 'meta_key' => 'enclosure', 'meta_value' => $meta_value) );
  986. }
  987. }
  988. }
  989. }
  990. }
  991. /**
  992. * Perform a HTTP HEAD or GET request.
  993. *
  994. * If $file_path is a writable filename, this will do a GET request and write
  995. * the file to that path.
  996. *
  997. * @since 2.5.0
  998. *
  999. * @param string $url URL to fetch.
  1000. * @param string|bool $file_path Optional. File path to write request to.
  1001. * @param bool $deprecated Deprecated. Not used.
  1002. * @return bool|string False on failure and string of headers if HEAD request.
  1003. */
  1004. function wp_get_http( $url, $file_path = false, $deprecated = false ) {
  1005. @set_time_limit( 60 );
  1006. $options = array();
  1007. $options['redirection'] = 5;
  1008. if ( false == $file_path )
  1009. $options['method'] = 'HEAD';
  1010. else
  1011. $options['method'] = 'GET';
  1012. $response = wp_remote_request($url, $options);
  1013. if ( is_wp_error( $response ) )
  1014. return false;
  1015. $headers = wp_remote_retrieve_headers( $response );
  1016. $headers['response'] = $response['response']['code'];
  1017. if ( false == $file_path )
  1018. return $headers;
  1019. // GET request - write it to the supplied filename
  1020. $out_fp = fopen($file_path, 'w');
  1021. if ( !$out_fp )
  1022. return $headers;
  1023. fwrite( $out_fp, $response['body']);
  1024. fclose($out_fp);
  1025. return $headers;
  1026. }
  1027. /**
  1028. * Retrieve HTTP Headers from URL.
  1029. *
  1030. * @since 1.5.1
  1031. *
  1032. * @param string $url
  1033. * @param bool $deprecated Not Used.
  1034. * @return bool|string False on failure, headers on success.
  1035. */
  1036. function wp_get_http_headers( $url, $deprecated = false ) {
  1037. $response = wp_remote_head( $url );
  1038. if ( is_wp_error( $response ) )
  1039. return false;
  1040. return wp_remote_retrieve_headers( $response );
  1041. }
  1042. /**
  1043. * Whether today is a new day.
  1044. *
  1045. * @since 0.71
  1046. * @uses $day Today
  1047. * @uses $previousday Previous day
  1048. *
  1049. * @return int 1 when new day, 0 if not a new day.
  1050. */
  1051. function is_new_day() {
  1052. global $day, $previousday;
  1053. if ( $day != $previousday )
  1054. return 1;
  1055. else
  1056. return 0;
  1057. }
  1058. /**
  1059. * Build URL query based on an associative and, or indexed array.
  1060. *
  1061. * This is a convenient function for easily building url queries. It sets the
  1062. * separator to '&' and uses _http_build_query() function.
  1063. *
  1064. * @see _http_build_query() Used to build the query
  1065. * @link http://us2.php.net/manual/en/function.http-build-query.php more on what
  1066. * http_build_query() does.
  1067. *
  1068. * @since 2.3.0
  1069. *
  1070. * @param array $data URL-encode key/value pairs.
  1071. * @return string URL encoded string
  1072. */
  1073. function build_query( $data ) {
  1074. return _http_build_query( $data, null, '&', '', false );
  1075. }
  1076. /**
  1077. * Retrieve a modified URL query string.
  1078. *
  1079. * You can rebuild the URL and append a new query variable to the URL query by
  1080. * using this function. You can also retrieve the full URL with query data.
  1081. *
  1082. * Adding a single key & value or an associative array. Setting a key value to
  1083. * emptystring removes the key. Omitting oldquery_or_uri uses the $_SERVER
  1084. * value.
  1085. *
  1086. * @since 1.5.0
  1087. *
  1088. * @param mixed $param1 Either newkey or an associative_array
  1089. * @param mixed $param2 Either newvalue or oldquery or uri
  1090. * @param mixed $param3 Optional. Old query or uri
  1091. * @return string New URL query string.
  1092. */
  1093. function add_query_arg() {
  1094. $ret = '';
  1095. if ( is_array( func_get_arg(0) ) ) {
  1096. if ( @func_num_args() < 2 || false === @func_get_arg( 1 ) )
  1097. $uri = $_SERVER['REQUEST_URI'];
  1098. else
  1099. $uri = @func_get_arg( 1 );
  1100. } else {
  1101. if ( @func_num_args() < 3 || false === @func_get_arg( 2 ) )
  1102. $uri = $_SERVER['REQUEST_URI'];
  1103. else
  1104. $uri = @func_get_arg( 2 );
  1105. }
  1106. if ( $frag = strstr( $uri, '#' ) )
  1107. $uri = substr( $uri, 0, -strlen( $frag ) );
  1108. else
  1109. $frag = '';
  1110. if ( preg_match( '|^https?://|i', $uri, $matches ) ) {
  1111. $protocol = $matches[0];
  1112. $uri = substr( $uri, strlen( $protocol ) );
  1113. } else {
  1114. $protocol = '';
  1115. }
  1116. if ( strpos( $uri, '?' ) !== false ) {
  1117. $parts = explode( '?', $uri, 2 );
  1118. if ( 1 == count( $parts ) ) {
  1119. $base = '?';
  1120. $query = $parts[0];
  1121. } else {
  1122. $base = $parts[0] . '?';
  1123. $query = $parts[1];
  1124. }
  1125. } elseif ( !empty( $protocol ) || strpos( $uri, '=' ) === false ) {
  1126. $base = $uri . '?';
  1127. $query = '';
  1128. } else {
  1129. $base = '';
  1130. $query = $uri;
  1131. }
  1132. wp_parse_str( $query, $qs );
  1133. $qs = urlencode_deep( $qs ); // this re-URL-encodes things that were already in the query string
  1134. if ( is_array( func_get_arg( 0 ) ) ) {
  1135. $kayvees = func_get_arg( 0 );
  1136. $qs = array_merge( $qs, $kayvees );
  1137. } else {
  1138. $qs[func_get_arg( 0 )] = func_get_arg( 1 );
  1139. }
  1140. foreach ( (array) $qs as $k => $v ) {
  1141. if ( $v === false )
  1142. unset( $qs[$k] );
  1143. }
  1144. $ret = build_query( $qs );
  1145. $ret = trim( $ret, '?' );
  1146. $ret = preg_replace( '#=(&|$)#', '$1', $ret );
  1147. $ret = $protocol . $base . $ret . $frag;
  1148. $ret = rtrim( $ret, '?' );
  1149. return $ret;
  1150. }
  1151. /**
  1152. * Removes an item or list from the query string.
  1153. *
  1154. * @since 1.5.0
  1155. *
  1156. * @param string|array $key Query key or keys to remove.
  1157. * @param bool $query When false uses the $_SERVER value.
  1158. * @return string New URL query string.
  1159. */
  1160. function remove_query_arg( $key, $query=false ) {
  1161. if ( is_array( $key ) ) { // removing multiple keys
  1162. foreach ( $key as $k )
  1163. $query = add_query_arg( $k, false, $query );
  1164. return $query;
  1165. }
  1166. return add_query_arg( $key, false, $query );
  1167. }
  1168. /**
  1169. * Walks the array while sanitizing the contents.
  1170. *
  1171. * @uses $wpdb Used to sanitize values
  1172. * @since 0.71
  1173. *
  1174. * @param array $array Array to used to walk while sanitizing contents.
  1175. * @return array Sanitized $array.
  1176. */
  1177. function add_magic_quotes( $array ) {
  1178. global $wpdb;
  1179. foreach ( (array) $array as $k => $v ) {
  1180. if ( is_array( $v ) ) {
  1181. $array[$k] = add_magic_quotes( $v );
  1182. } else {
  1183. $array[$k] = $wpdb->escape( $v );
  1184. }
  1185. }
  1186. return $array;
  1187. }
  1188. /**
  1189. * HTTP request for URI to retrieve content.
  1190. *
  1191. * @since 1.5.1
  1192. * @uses wp_remote_get()
  1193. *
  1194. * @param string $uri URI/URL of web page to retrieve.
  1195. * @return bool|string HTTP content. False on failure.
  1196. */
  1197. function wp_remote_fopen( $uri ) {
  1198. $parsed_url = @parse_url( $uri );
  1199. if ( !$parsed_url || !is_array( $parsed_url ) )
  1200. return false;
  1201. $options = array();
  1202. $options['timeout'] = 10;
  1203. $response = wp_remote_get( $uri, $options );
  1204. if ( is_wp_error( $response ) )
  1205. return false;
  1206. return $response['body'];
  1207. }
  1208. /**
  1209. * Setup the WordPress query.
  1210. *
  1211. * @since 2.0.0
  1212. *
  1213. * @param string $query_vars Default WP_Query arguments.
  1214. */
  1215. function wp( $query_vars = '' ) {
  1216. global $wp, $wp_query, $wp_the_query;
  1217. $wp->main( $query_vars );
  1218. if( !isset($wp_the_query) )
  1219. $wp_the_query = $wp_query;
  1220. }
  1221. /**
  1222. * Retrieve the description for the HTTP status.
  1223. *
  1224. * @since 2.3.0
  1225. *
  1226. * @param int $code HTTP status code.
  1227. * @return string Empty string if not found, or description if found.
  1228. */
  1229. function get_status_header_desc( $code ) {
  1230. global $wp_header_to_desc;
  1231. $code = absint( $code );
  1232. if ( !isset( $wp_header_to_desc ) ) {
  1233. $wp_header_to_desc = array(
  1234. 100 => 'Continue',
  1235. 101 => 'Switching Protocols',
  1236. 102 => 'Processing',
  1237. 200 => 'OK',
  1238. 201 => 'Created',
  1239. 202 => 'Accepted',
  1240. 203 => 'Non-Authoritative Information',
  1241. 204 => 'No Content',
  1242. 205 => 'Reset Content',
  1243. 206 => 'Partial Content',
  1244. 207 => 'Multi-Status',
  1245. 226 => 'IM Used',
  1246. 300 => 'Multiple Choices',
  1247. 301 => 'Moved Permanently',
  1248. 302 => 'Found',
  1249. 303 => 'See Other',
  1250. 304 => 'Not Modified',
  1251. 305 => 'Use Proxy',
  1252. 306 => 'Reserved',
  1253. 307 => 'Temporary Redirect',
  1254. 400 => 'Bad Request',
  1255. 401 => 'Unauthorized',
  1256. 402 => 'Payment Required',
  1257. 403 => 'Forbidden',
  1258. 404 => 'Not Found',
  1259. 405 => 'Method Not Allowed',
  1260. 406 => 'Not Acceptable',
  1261. 407 => 'Proxy Authentication Required',
  1262. 408 => 'Request Timeout',
  1263. 409 => 'Conflict',
  1264. 410 => 'Gone',
  1265. 411 => 'Length Required',
  1266. 412 => 'Precondition Failed',
  1267. 413 => 'Request Entity Too Large',
  1268. 414 => 'Request-URI Too Long',
  1269. 415 => 'Unsupported Media Type',
  1270. 416 => 'Requested Range Not Satisfiable',
  1271. 417 => 'Expectation Failed',
  1272. 422 => 'Unprocessable Entity',
  1273. 423 => 'Locked',
  1274. 424 => 'Failed Dependency',
  1275. 426 => 'Upgrade Required',
  1276. 500 => 'Internal Server Error',
  1277. 501 => 'Not Implemented',
  1278. 502 => 'Bad Gateway',
  1279. 503 => 'Service Unavailable',
  1280. 504 => 'Gateway Timeout',
  1281. 505 => 'HTTP Version Not Supported',
  1282. 506 => 'Variant Also Negotiates',
  1283. 507 => 'Insufficient Storage',
  1284. 510 => 'Not Extended'
  1285. );
  1286. }
  1287. if ( isset( $wp_header_to_desc[$code] ) )
  1288. return $wp_header_to_desc[$code];
  1289. else
  1290. return '';
  1291. }
  1292. /**
  1293. * Set HTTP status header.
  1294. *
  1295. * @since 2.0.0
  1296. * @uses apply_filters() Calls 'status_header' on status header string, HTTP
  1297. * HTTP code, HTTP code description, and protocol string as separate
  1298. * parameters.
  1299. *
  1300. * @param int $header HTTP status code
  1301. * @return null Does not return anything.
  1302. */
  1303. function status_header( $header ) {
  1304. $text = get_status_header_desc( $header );
  1305. if ( empty( $text ) )
  1306. return false;
  1307. $protocol = $_SERVER["SERVER_PROTOCOL"];
  1308. if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol )
  1309. $protocol = 'HTTP/1.0';
  1310. $status_header = "$protocol $header $text";
  1311. if ( function_exists( 'apply_filters' ) )
  1312. $status_header = apply_filters( 'status_header', $status_header, $header, $text, $protocol );
  1313. return @header( $status_header, true, $header );
  1314. }
  1315. /**
  1316. * Gets the header information to prevent caching.
  1317. *
  1318. * The several different headers cover the different ways cache prevention is handled
  1319. * by different browsers
  1320. *
  1321. * @since 2.8
  1322. *
  1323. * @uses apply_filters()
  1324. * @return array The associative array of header names and field values.
  1325. */
  1326. function wp_get_nocache_headers() {
  1327. $headers = array(
  1328. 'Expires' => 'Wed, 11 Jan 1984 05:00:00 GMT',
  1329. 'Last-Modified' => gmdate( 'D, d M Y H:i:s' ) . ' GMT',
  1330. 'Cache-Control' => 'no-cache, must-revalidate, max-age=0',
  1331. 'Pragma' => 'no-cache',
  1332. );
  1333. if ( function_exists('apply_filters') ) {
  1334. $headers = apply_filters('nocache_headers', $headers);
  1335. }
  1336. return $headers;
  1337. }
  1338. /**
  1339. * Sets the headers to prevent caching for the different browsers.
  1340. *
  1341. * Different browsers support different nocache headers, so several headers must
  1342. * be sent so that all of them get the point that no caching should occur.
  1343. *
  1344. * @since 2.0.0
  1345. * @uses wp_get_nocache_headers()
  1346. */
  1347. function nocache_headers() {
  1348. $headers = wp_get_nocache_headers();
  1349. foreach( (array) $headers as $name => $field_value )
  1350. @header("{$name}: {$field_value}");
  1351. }
  1352. /**
  1353. * Set the headers for caching for 10 days with JavaScript content type.
  1354. *
  1355. * @since 2.1.0
  1356. */
  1357. function cache_javascript_headers() {
  1358. $expiresOffset = 864000; // 10 days
  1359. header( "Content-Type: text/javascript; charset=" . get_bloginfo( 'charset' ) );
  1360. header( "Vary: Accept-Encoding" ); // Handle proxies
  1361. header( "Expires: " . gmdate( "D, d M Y H:i:s", time() + $expiresOffset ) . " GMT" );
  1362. }
  1363. /**
  1364. * Retrieve the number of database queries during the WordPress execution.
  1365. *
  1366. * @since 2.0.0
  1367. *
  1368. * @return int Number of database queries
  1369. */
  1370. function get_num_queries() {
  1371. global $wpdb;
  1372. return $wpdb->num_queries;
  1373. }
  1374. /**
  1375. * Whether input is yes or no. Must be 'y' to be true.
  1376. *
  1377. * @since 1.0.0
  1378. *
  1379. * @param string $yn Character string containing either 'y' or 'n'
  1380. * @return bool True if yes, false on anything else
  1381. */
  1382. function bool_from_yn( $yn ) {
  1383. return ( strtolower( $yn ) == 'y' );
  1384. }
  1385. /**
  1386. * Loads the feed template from the use of an action hook.
  1387. *
  1388. * If the feed action does not have a hook, then the function will die with a
  1389. * message telling the visitor that the feed is not valid.
  1390. *
  1391. * It is better to only have one hook for each feed.
  1392. *
  1393. * @since 2.1.0
  1394. * @uses $wp_query Used to tell if the use a comment feed.
  1395. * @uses do_action() Calls 'do_feed_$feed' hook, if a hook exists for the feed.
  1396. */
  1397. function do_feed() {
  1398. global $wp_query;
  1399. $feed = get_query_var( 'feed' );
  1400. // Remove the pad, if present.
  1401. $feed = preg_replace( '/^_+/', '', $feed );
  1402. if ( $feed == '' || $feed == 'feed' )
  1403. $feed = get_default_feed();
  1404. $hook = 'do_feed_' . $feed;
  1405. if ( !has_action($hook) ) {
  1406. $message = sprintf( __( 'ERROR: %s is not a valid feed template' ), wp_specialchars($feed));
  1407. wp_die($message);
  1408. }
  1409. do_action( $hook, $wp_query->is_comment_feed );
  1410. }
  1411. /**
  1412. * Load the RDF RSS 0.91 Feed template.
  1413. *
  1414. * @since 2.1.0
  1415. */
  1416. function do_feed_rdf() {
  1417. load_template( ABSPATH . WPINC . '/feed-rdf.php' );
  1418. }
  1419. /**
  1420. * Load the RSS 1.0 Feed Template
  1421. *
  1422. * @since 2.1.0
  1423. */
  1424. function do_feed_rss() {
  1425. load_template( ABSPATH . WPINC . '/feed-rss.php' );
  1426. }
  1427. /**
  1428. * Load either the RSS2 comment feed or the RSS2 posts feed.
  1429. *
  1430. * @since 2.1.0
  1431. *
  1432. * @param bool $for_comments True for the comment feed, false for normal feed.
  1433. */
  1434. function do_feed_rss2( $for_comments ) {
  1435. if ( $for_comments )
  1436. load_template( ABSPATH . WPINC . '/feed-rss2-comments.php' );
  1437. else
  1438. load_template( ABSPATH . WPINC . '/feed-rss2.php' );
  1439. }
  1440. /**
  1441. * Load either Atom comment feed or Atom posts feed.
  1442. *
  1443. * @since 2.1.0
  1444. *
  1445. * @param bool $for_comments True for the comment feed, false for normal feed.
  1446. */
  1447. function do_feed_atom( $for_comments ) {
  1448. if ($for_comments)
  1449. load_template( ABSPATH . WPINC . '/feed-atom-comments.php');
  1450. else
  1451. load_template( ABSPATH . WPINC . '/feed-atom.php' );
  1452. }
  1453. /**
  1454. * Display the robot.txt file content.
  1455. *
  1456. * The echo content should be with usage of the permalinks or for creating the
  1457. * robot.txt file.
  1458. *
  1459. * @since 2.1.0
  1460. * @uses do_action() Calls 'do_robotstxt' hook for displaying robot.txt rules.
  1461. */
  1462. function do_robots() {
  1463. header( 'Content-Type: text/plain; charset=utf-8' );
  1464. do_action( 'do_robotstxt' );
  1465. if ( '0' == get_option( 'blog_public' ) ) {
  1466. echo "User-agent: *\n";
  1467. echo "Disallow: /\n";
  1468. } else {
  1469. echo "User-agent: *\n";
  1470. echo "Disallow:\n";
  1471. }
  1472. }
  1473. /**
  1474. * Test whether blog is already installed.
  1475. *
  1476. * The cache will be checked first. If you have a cache plugin, which saves the
  1477. * cache values, then this will work. If you use the default WordPress cache,
  1478. * and the database goes away, then you might have problems.
  1479. *
  1480. * Checks for the option siteurl for whether WordPress is installed.
  1481. *
  1482. * @since 2.1.0
  1483. * @uses $wpdb
  1484. *
  1485. * @return bool Whether blog is already installed.
  1486. */
  1487. function is_blog_installed() {
  1488. global $wpdb;
  1489. // Check cache first. If options table goes away and we have true cached, oh well.
  1490. if ( wp_cache_get('is_blog_installed') )
  1491. return true;
  1492. $suppress = $wpdb->suppress_errors();
  1493. $installed = $wpdb->get_var( "SELECT option_value FROM $wpdb->options WHERE option_name = 'siteurl'" );
  1494. $wpdb->suppress_errors($suppress);
  1495. $installed = !empty( $installed ) ? true : false;
  1496. wp_cache_set('is_blog_installed', $installed);
  1497. return $installed;
  1498. }
  1499. /**
  1500. * Retrieve URL with nonce added to URL query.
  1501. *
  1502. * @package WordPress
  1503. * @subpackage Security
  1504. * @since 2.0.4
  1505. *
  1506. * @param string $actionurl URL to add nonce action
  1507. * @param string $action Optional. Nonce action name
  1508. * @return string URL with nonce action added.
  1509. */
  1510. function wp_nonce_url( $actionurl, $action = -1 ) {
  1511. $actionurl = str_replace( '&amp;', '&', $actionurl );
  1512. return wp_specialchars( add_query_arg( '_wpnonce', wp_create_nonce( $action ), $actionurl ) );
  1513. }
  1514. /**
  1515. * Retrieve or display nonce hidden field for forms.
  1516. *
  1517. * The nonce field is used to validate that the contents of the form came from
  1518. * the location on the current site and not somewhere e…

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