PageRenderTime 83ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/functions.php

https://bitbucket.org/MaheshDhaduk/androidmobiles
PHP | 4300 lines | 2176 code | 476 blank | 1648 comment | 519 complexity | 9bf6be16656df5268f8f5cb79836d83f MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1, AGPL-1.0
  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. }
  31. $i = strtotime( $m );
  32. if ( 'U' == $dateformatstring )
  33. return $i;
  34. if ( $translate)
  35. return date_i18n( $dateformatstring, $i );
  36. else
  37. return date( $dateformatstring, $i );
  38. }
  39. /**
  40. * Retrieve the current time based on specified type.
  41. *
  42. * The 'mysql' type will return the time in the format for MySQL DATETIME field.
  43. * The 'timestamp' type will return the current timestamp.
  44. *
  45. * If $gmt is set to either '1' or 'true', then both types will use GMT time.
  46. * if $gmt is false, the output is adjusted with the GMT offset in the WordPress option.
  47. *
  48. * @since 1.0.0
  49. *
  50. * @param string $type Either 'mysql' or 'timestamp'.
  51. * @param int|bool $gmt Optional. Whether to use GMT timezone. Default is false.
  52. * @return int|string String if $type is 'gmt', int if $type is 'timestamp'.
  53. */
  54. function current_time( $type, $gmt = 0 ) {
  55. switch ( $type ) {
  56. case 'mysql':
  57. return ( $gmt ) ? gmdate( 'Y-m-d H:i:s' ) : gmdate( 'Y-m-d H:i:s', ( time() + ( get_option( 'gmt_offset' ) * 3600 ) ) );
  58. break;
  59. case 'timestamp':
  60. return ( $gmt ) ? time() : time() + ( get_option( 'gmt_offset' ) * 3600 );
  61. break;
  62. }
  63. }
  64. /**
  65. * Retrieve the date in localized format, based on timestamp.
  66. *
  67. * If the locale specifies the locale month and weekday, then the locale will
  68. * take over the format for the date. If it isn't, then the date format string
  69. * will be used instead.
  70. *
  71. * @since 0.71
  72. *
  73. * @param string $dateformatstring Format to display the date.
  74. * @param int $unixtimestamp Optional. Unix timestamp.
  75. * @param bool $gmt Optional, default is false. Whether to convert to GMT for time.
  76. * @return string The date, translated if locale specifies it.
  77. */
  78. function date_i18n( $dateformatstring, $unixtimestamp = false, $gmt = false ) {
  79. global $wp_locale;
  80. $i = $unixtimestamp;
  81. // Sanity check for PHP 5.1.0-
  82. if ( false === $i || intval($i) < 0 ) {
  83. if ( ! $gmt )
  84. $i = current_time( 'timestamp' );
  85. else
  86. $i = time();
  87. // we should not let date() interfere with our
  88. // specially computed timestamp
  89. $gmt = true;
  90. }
  91. // store original value for language with untypical grammars
  92. // see http://core.trac.wordpress.org/ticket/9396
  93. $req_format = $dateformatstring;
  94. $datefunc = $gmt? 'gmdate' : 'date';
  95. if ( ( !empty( $wp_locale->month ) ) && ( !empty( $wp_locale->weekday ) ) ) {
  96. $datemonth = $wp_locale->get_month( $datefunc( 'm', $i ) );
  97. $datemonth_abbrev = $wp_locale->get_month_abbrev( $datemonth );
  98. $dateweekday = $wp_locale->get_weekday( $datefunc( 'w', $i ) );
  99. $dateweekday_abbrev = $wp_locale->get_weekday_abbrev( $dateweekday );
  100. $datemeridiem = $wp_locale->get_meridiem( $datefunc( 'a', $i ) );
  101. $datemeridiem_capital = $wp_locale->get_meridiem( $datefunc( 'A', $i ) );
  102. $dateformatstring = ' '.$dateformatstring;
  103. $dateformatstring = preg_replace( "/([^\\\])D/", "\\1" . backslashit( $dateweekday_abbrev ), $dateformatstring );
  104. $dateformatstring = preg_replace( "/([^\\\])F/", "\\1" . backslashit( $datemonth ), $dateformatstring );
  105. $dateformatstring = preg_replace( "/([^\\\])l/", "\\1" . backslashit( $dateweekday ), $dateformatstring );
  106. $dateformatstring = preg_replace( "/([^\\\])M/", "\\1" . backslashit( $datemonth_abbrev ), $dateformatstring );
  107. $dateformatstring = preg_replace( "/([^\\\])a/", "\\1" . backslashit( $datemeridiem ), $dateformatstring );
  108. $dateformatstring = preg_replace( "/([^\\\])A/", "\\1" . backslashit( $datemeridiem_capital ), $dateformatstring );
  109. $dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 );
  110. }
  111. $j = @$datefunc( $dateformatstring, $i );
  112. // allow plugins to redo this entirely for languages with untypical grammars
  113. $j = apply_filters('date_i18n', $j, $req_format, $i, $gmt);
  114. return $j;
  115. }
  116. /**
  117. * Convert integer number to format based on the locale.
  118. *
  119. * @since 2.3.0
  120. *
  121. * @param int $number The number to convert based on locale.
  122. * @param int $decimals Precision of the number of decimal places.
  123. * @return string Converted number in string format.
  124. */
  125. function number_format_i18n( $number, $decimals = 0 ) {
  126. global $wp_locale;
  127. $formatted = number_format( $number, absint( $decimals ), $wp_locale->number_format['decimal_point'], $wp_locale->number_format['thousands_sep'] );
  128. return apply_filters( 'number_format_i18n', $formatted );
  129. }
  130. /**
  131. * Convert number of bytes largest unit bytes will fit into.
  132. *
  133. * It is easier to read 1kB than 1024 bytes and 1MB than 1048576 bytes. Converts
  134. * number of bytes to human readable number by taking the number of that unit
  135. * that the bytes will go into it. Supports TB value.
  136. *
  137. * Please note that integers in PHP are limited to 32 bits, unless they are on
  138. * 64 bit architecture, then they have 64 bit size. If you need to place the
  139. * larger size then what PHP integer type will hold, then use a string. It will
  140. * be converted to a double, which should always have 64 bit length.
  141. *
  142. * Technically the correct unit names for powers of 1024 are KiB, MiB etc.
  143. * @link http://en.wikipedia.org/wiki/Byte
  144. *
  145. * @since 2.3.0
  146. *
  147. * @param int|string $bytes Number of bytes. Note max integer size for integers.
  148. * @param int $decimals Precision of number of decimal places. Deprecated.
  149. * @return bool|string False on failure. Number string on success.
  150. */
  151. function size_format( $bytes, $decimals = 0 ) {
  152. $quant = array(
  153. // ========================= Origin ====
  154. 'TB' => 1099511627776, // pow( 1024, 4)
  155. 'GB' => 1073741824, // pow( 1024, 3)
  156. 'MB' => 1048576, // pow( 1024, 2)
  157. 'kB' => 1024, // pow( 1024, 1)
  158. 'B ' => 1, // pow( 1024, 0)
  159. );
  160. foreach ( $quant as $unit => $mag )
  161. if ( doubleval($bytes) >= $mag )
  162. return number_format_i18n( $bytes / $mag, $decimals ) . ' ' . $unit;
  163. return false;
  164. }
  165. /**
  166. * Get the week start and end from the datetime or date string from mysql.
  167. *
  168. * @since 0.71
  169. *
  170. * @param string $mysqlstring Date or datetime field type from mysql.
  171. * @param int $start_of_week Optional. Start of the week as an integer.
  172. * @return array Keys are 'start' and 'end'.
  173. */
  174. function get_weekstartend( $mysqlstring, $start_of_week = '' ) {
  175. $my = substr( $mysqlstring, 0, 4 ); // Mysql string Year
  176. $mm = substr( $mysqlstring, 8, 2 ); // Mysql string Month
  177. $md = substr( $mysqlstring, 5, 2 ); // Mysql string day
  178. $day = mktime( 0, 0, 0, $md, $mm, $my ); // The timestamp for mysqlstring day.
  179. $weekday = date( 'w', $day ); // The day of the week from the timestamp
  180. if ( !is_numeric($start_of_week) )
  181. $start_of_week = get_option( 'start_of_week' );
  182. if ( $weekday < $start_of_week )
  183. $weekday += 7;
  184. $start = $day - 86400 * ( $weekday - $start_of_week ); // The most recent week start day on or before $day
  185. $end = $start + 604799; // $start + 7 days - 1 second
  186. return compact( 'start', 'end' );
  187. }
  188. /**
  189. * Unserialize value only if it was serialized.
  190. *
  191. * @since 2.0.0
  192. *
  193. * @param string $original Maybe unserialized original, if is needed.
  194. * @return mixed Unserialized data can be any type.
  195. */
  196. function maybe_unserialize( $original ) {
  197. if ( is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in
  198. return @unserialize( $original );
  199. return $original;
  200. }
  201. /**
  202. * Check value to find if it was serialized.
  203. *
  204. * If $data is not an string, then returned value will always be false.
  205. * Serialized data is always a string.
  206. *
  207. * @since 2.0.5
  208. *
  209. * @param mixed $data Value to check to see if was serialized.
  210. * @return bool False if not serialized and true if it was.
  211. */
  212. function is_serialized( $data ) {
  213. // if it isn't a string, it isn't serialized
  214. if ( !is_string( $data ) )
  215. return false;
  216. $data = trim( $data );
  217. if ( 'N;' == $data )
  218. return true;
  219. if ( !preg_match( '/^([adObis]):/', $data, $badions ) )
  220. return false;
  221. switch ( $badions[1] ) {
  222. case 'a' :
  223. case 'O' :
  224. case 's' :
  225. if ( preg_match( "/^{$badions[1]}:[0-9]+:.*[;}]\$/s", $data ) )
  226. return true;
  227. break;
  228. case 'b' :
  229. case 'i' :
  230. case 'd' :
  231. if ( preg_match( "/^{$badions[1]}:[0-9.E-]+;\$/", $data ) )
  232. return true;
  233. break;
  234. }
  235. return false;
  236. }
  237. /**
  238. * Check whether serialized data is of string type.
  239. *
  240. * @since 2.0.5
  241. *
  242. * @param mixed $data Serialized data
  243. * @return bool False if not a serialized string, true if it is.
  244. */
  245. function is_serialized_string( $data ) {
  246. // if it isn't a string, it isn't a serialized string
  247. if ( !is_string( $data ) )
  248. return false;
  249. $data = trim( $data );
  250. if ( preg_match( '/^s:[0-9]+:.*;$/s', $data ) ) // this should fetch all serialized strings
  251. return true;
  252. return false;
  253. }
  254. /**
  255. * Retrieve option value based on name of option.
  256. *
  257. * If the option does not exist or does not have a value, then the return value
  258. * will be false. This is useful to check whether you need to install an option
  259. * and is commonly used during installation of plugin options and to test
  260. * whether upgrading is required.
  261. *
  262. * If the option was serialized then it will be unserialized when it is returned.
  263. *
  264. * @since 1.5.0
  265. * @package WordPress
  266. * @subpackage Option
  267. * @uses apply_filters() Calls 'pre_option_$option' before checking the option.
  268. * Any value other than false will "short-circuit" the retrieval of the option
  269. * and return the returned value. You should not try to override special options,
  270. * but you will not be prevented from doing so.
  271. * @uses apply_filters() Calls 'option_$option', after checking the option, with
  272. * the option value.
  273. *
  274. * @param string $option Name of option to retrieve. Expected to not be SQL-escaped.
  275. * @return mixed Value set for the option.
  276. */
  277. function get_option( $option, $default = false ) {
  278. global $wpdb;
  279. // Allow plugins to short-circuit options.
  280. $pre = apply_filters( 'pre_option_' . $option, false );
  281. if ( false !== $pre )
  282. return $pre;
  283. $option = trim($option);
  284. if ( empty($option) )
  285. return false;
  286. if ( defined( 'WP_SETUP_CONFIG' ) )
  287. return false;
  288. if ( ! defined( 'WP_INSTALLING' ) ) {
  289. // prevent non-existent options from triggering multiple queries
  290. $notoptions = wp_cache_get( 'notoptions', 'options' );
  291. if ( isset( $notoptions[$option] ) )
  292. return $default;
  293. $alloptions = wp_load_alloptions();
  294. if ( isset( $alloptions[$option] ) ) {
  295. $value = $alloptions[$option];
  296. } else {
  297. $value = wp_cache_get( $option, 'options' );
  298. if ( false === $value ) {
  299. $row = $wpdb->get_row( $wpdb->prepare( "SELECT option_value FROM $wpdb->options WHERE option_name = %s LIMIT 1", $option ) );
  300. // Has to be get_row instead of get_var because of funkiness with 0, false, null values
  301. if ( is_object( $row ) ) {
  302. $value = $row->option_value;
  303. wp_cache_add( $option, $value, 'options' );
  304. } else { // option does not exist, so we must cache its non-existence
  305. $notoptions[$option] = true;
  306. wp_cache_set( 'notoptions', $notoptions, 'options' );
  307. return $default;
  308. }
  309. }
  310. }
  311. } else {
  312. $suppress = $wpdb->suppress_errors();
  313. $row = $wpdb->get_row( $wpdb->prepare( "SELECT option_value FROM $wpdb->options WHERE option_name = %s LIMIT 1", $option ) );
  314. $wpdb->suppress_errors( $suppress );
  315. if ( is_object( $row ) )
  316. $value = $row->option_value;
  317. else
  318. return $default;
  319. }
  320. // If home is not set use siteurl.
  321. if ( 'home' == $option && '' == $value )
  322. return get_option( 'siteurl' );
  323. if ( in_array( $option, array('siteurl', 'home', 'category_base', 'tag_base') ) )
  324. $value = untrailingslashit( $value );
  325. return apply_filters( 'option_' . $option, maybe_unserialize( $value ) );
  326. }
  327. /**
  328. * Protect WordPress special option from being modified.
  329. *
  330. * Will die if $option is in protected list. Protected options are 'alloptions'
  331. * and 'notoptions' options.
  332. *
  333. * @since 2.2.0
  334. * @package WordPress
  335. * @subpackage Option
  336. *
  337. * @param string $option Option name.
  338. */
  339. function wp_protect_special_option( $option ) {
  340. $protected = array( 'alloptions', 'notoptions' );
  341. if ( in_array( $option, $protected ) )
  342. wp_die( sprintf( __( '%s is a protected WP option and may not be modified' ), esc_html( $option ) ) );
  343. }
  344. /**
  345. * Print option value after sanitizing for forms.
  346. *
  347. * @uses attr Sanitizes value.
  348. * @since 1.5.0
  349. * @package WordPress
  350. * @subpackage Option
  351. *
  352. * @param string $option Option name.
  353. */
  354. function form_option( $option ) {
  355. echo esc_attr( get_option( $option ) );
  356. }
  357. /**
  358. * Loads and caches all autoloaded options, if available or all options.
  359. *
  360. * @since 2.2.0
  361. * @package WordPress
  362. * @subpackage Option
  363. *
  364. * @return array List of all options.
  365. */
  366. function wp_load_alloptions() {
  367. global $wpdb;
  368. if ( !defined( 'WP_INSTALLING' ) || !is_multisite() )
  369. $alloptions = wp_cache_get( 'alloptions', 'options' );
  370. else
  371. $alloptions = false;
  372. if ( !$alloptions ) {
  373. $suppress = $wpdb->suppress_errors();
  374. if ( !$alloptions_db = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options WHERE autoload = 'yes'" ) )
  375. $alloptions_db = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options" );
  376. $wpdb->suppress_errors($suppress);
  377. $alloptions = array();
  378. foreach ( (array) $alloptions_db as $o )
  379. $alloptions[$o->option_name] = $o->option_value;
  380. if ( !defined( 'WP_INSTALLING' ) || !is_multisite() )
  381. wp_cache_add( 'alloptions', $alloptions, 'options' );
  382. }
  383. return $alloptions;
  384. }
  385. /**
  386. * Loads and caches certain often requested site options if is_multisite() and a peristent cache is not being used.
  387. *
  388. * @since 3.0.0
  389. * @package WordPress
  390. * @subpackage Option
  391. *
  392. * @param int $site_id Optional site ID for which to query the options. Defaults to the current site.
  393. */
  394. function wp_load_core_site_options( $site_id = null ) {
  395. global $wpdb, $_wp_using_ext_object_cache;
  396. if ( !is_multisite() || $_wp_using_ext_object_cache || defined( 'WP_INSTALLING' ) )
  397. return;
  398. if ( empty($site_id) )
  399. $site_id = $wpdb->siteid;
  400. $core_options = array('site_name', 'siteurl', 'active_sitewide_plugins', '_site_transient_timeout_theme_roots', '_site_transient_theme_roots', 'site_admins', 'dashboard_blog', 'can_compress_scripts', 'global_terms_enabled' );
  401. $core_options_in = "'" . implode("', '", $core_options) . "'";
  402. $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) );
  403. foreach ( $options as $option ) {
  404. $key = $option->meta_key;
  405. $cache_key = "{$site_id}:$key";
  406. $option->meta_value = maybe_unserialize( $option->meta_value );
  407. wp_cache_set( $cache_key, $option->meta_value, 'site-options' );
  408. }
  409. }
  410. /**
  411. * Update the value of an option that was already added.
  412. *
  413. * You do not need to serialize values. If the value needs to be serialized, then
  414. * it will be serialized before it is inserted into the database. Remember,
  415. * resources can not be serialized or added as an option.
  416. *
  417. * If the option does not exist, then the option will be added with the option
  418. * value, but you will not be able to set whether it is autoloaded. If you want
  419. * to set whether an option is autoloaded, then you need to use the add_option().
  420. *
  421. * @since 1.0.0
  422. * @package WordPress
  423. * @subpackage Option
  424. *
  425. * @uses apply_filters() Calls 'pre_update_option_$option' hook to allow overwriting the
  426. * option value to be stored.
  427. * @uses do_action() Calls 'update_option' hook before updating the option.
  428. * @uses do_action() Calls 'update_option_$option' and 'updated_option' hooks on success.
  429. *
  430. * @param string $option Option name. Expected to not be SQL-escaped.
  431. * @param mixed $newvalue Option value. Expected to not be SQL-escaped.
  432. * @return bool False if value was not updated and true if value was updated.
  433. */
  434. function update_option( $option, $newvalue ) {
  435. global $wpdb;
  436. $option = trim($option);
  437. if ( empty($option) )
  438. return false;
  439. wp_protect_special_option( $option );
  440. if ( is_object($newvalue) )
  441. $newvalue = wp_clone($newvalue);
  442. $newvalue = sanitize_option( $option, $newvalue );
  443. $oldvalue = get_option( $option );
  444. $newvalue = apply_filters( 'pre_update_option_' . $option, $newvalue, $oldvalue );
  445. // If the new and old values are the same, no need to update.
  446. if ( $newvalue === $oldvalue )
  447. return false;
  448. if ( false === $oldvalue )
  449. return add_option( $option, $newvalue );
  450. $notoptions = wp_cache_get( 'notoptions', 'options' );
  451. if ( is_array( $notoptions ) && isset( $notoptions[$option] ) ) {
  452. unset( $notoptions[$option] );
  453. wp_cache_set( 'notoptions', $notoptions, 'options' );
  454. }
  455. $_newvalue = $newvalue;
  456. $newvalue = maybe_serialize( $newvalue );
  457. do_action( 'update_option', $option, $oldvalue, $_newvalue );
  458. if ( ! defined( 'WP_INSTALLING' ) ) {
  459. $alloptions = wp_load_alloptions();
  460. if ( isset( $alloptions[$option] ) ) {
  461. $alloptions[$option] = $_newvalue;
  462. wp_cache_set( 'alloptions', $alloptions, 'options' );
  463. } else {
  464. wp_cache_set( $option, $_newvalue, 'options' );
  465. }
  466. }
  467. $result = $wpdb->update( $wpdb->options, array( 'option_value' => $newvalue ), array( 'option_name' => $option ) );
  468. if ( $result ) {
  469. do_action( "update_option_{$option}", $oldvalue, $_newvalue );
  470. do_action( 'updated_option', $option, $oldvalue, $_newvalue );
  471. return true;
  472. }
  473. return false;
  474. }
  475. /**
  476. * Add a new option.
  477. *
  478. * You do not need to serialize values. If the value needs to be serialized, then
  479. * it will be serialized before it is inserted into the database. Remember,
  480. * resources can not be serialized or added as an option.
  481. *
  482. * You can create options without values and then add values later. Does not
  483. * check whether the option has already been added, but does check that you
  484. * aren't adding a protected WordPress option. Care should be taken to not name
  485. * options the same as the ones which are protected and to not add options
  486. * that were already added.
  487. *
  488. * @package WordPress
  489. * @subpackage Option
  490. * @since 1.0.0
  491. * @link http://alex.vort-x.net/blog/ Thanks Alex Stapleton
  492. *
  493. * @uses do_action() Calls 'add_option' hook before adding the option.
  494. * @uses do_action() Calls 'add_option_$option' and 'added_option' hooks on success.
  495. *
  496. * @param string $option Name of option to add. Expected to not be SQL-escaped.
  497. * @param mixed $value Optional. Option value, can be anything. Expected to not be SQL-escaped.
  498. * @param mixed $deprecated Optional. Description. Not used anymore.
  499. * @param bool $autoload Optional. Default is enabled. Whether to load the option when WordPress starts up.
  500. * @return null returns when finished.
  501. */
  502. function add_option( $option, $value = '', $deprecated = '', $autoload = 'yes' ) {
  503. global $wpdb;
  504. if ( !empty( $deprecated ) )
  505. _deprecated_argument( __FUNCTION__, '2.3' );
  506. $option = trim($option);
  507. if ( empty($option) )
  508. return false;
  509. wp_protect_special_option( $option );
  510. if ( is_object($value) )
  511. $value = wp_clone($value);
  512. $value = sanitize_option( $option, $value );
  513. // Make sure the option doesn't already exist. We can check the 'notoptions' cache before we ask for a db query
  514. $notoptions = wp_cache_get( 'notoptions', 'options' );
  515. if ( !is_array( $notoptions ) || !isset( $notoptions[$option] ) )
  516. if ( false !== get_option( $option ) )
  517. return;
  518. $_value = $value;
  519. $value = maybe_serialize( $value );
  520. $autoload = ( 'no' === $autoload ) ? 'no' : 'yes';
  521. do_action( 'add_option', $option, $_value );
  522. if ( ! defined( 'WP_INSTALLING' ) ) {
  523. if ( 'yes' == $autoload ) {
  524. $alloptions = wp_load_alloptions();
  525. $alloptions[$option] = $value;
  526. wp_cache_set( 'alloptions', $alloptions, 'options' );
  527. } else {
  528. wp_cache_set( $option, $value, 'options' );
  529. }
  530. }
  531. // This option exists now
  532. $notoptions = wp_cache_get( 'notoptions', 'options' ); // yes, again... we need it to be fresh
  533. if ( is_array( $notoptions ) && isset( $notoptions[$option] ) ) {
  534. unset( $notoptions[$option] );
  535. wp_cache_set( 'notoptions', $notoptions, 'options' );
  536. }
  537. $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 ) );
  538. if ( $result ) {
  539. do_action( "add_option_{$option}", $option, $_value );
  540. do_action( 'added_option', $option, $_value );
  541. return true;
  542. }
  543. return false;
  544. }
  545. /**
  546. * Removes option by name. Prevents removal of protected WordPress options.
  547. *
  548. * @package WordPress
  549. * @subpackage Option
  550. * @since 1.2.0
  551. *
  552. * @uses do_action() Calls 'delete_option' hook before option is deleted.
  553. * @uses do_action() Calls 'deleted_option' and 'delete_option_$option' hooks on success.
  554. *
  555. * @param string $option Name of option to remove. Expected to not be SQL-escaped.
  556. * @return bool True, if option is successfully deleted. False on failure.
  557. */
  558. function delete_option( $option ) {
  559. global $wpdb;
  560. wp_protect_special_option( $option );
  561. // Get the ID, if no ID then return
  562. $row = $wpdb->get_row( $wpdb->prepare( "SELECT autoload FROM $wpdb->options WHERE option_name = %s", $option ) );
  563. if ( is_null( $row ) )
  564. return false;
  565. do_action( 'delete_option', $option );
  566. $result = $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->options WHERE option_name = %s", $option) );
  567. if ( ! defined( 'WP_INSTALLING' ) ) {
  568. if ( 'yes' == $row->autoload ) {
  569. $alloptions = wp_load_alloptions();
  570. if ( is_array( $alloptions ) && isset( $alloptions[$option] ) ) {
  571. unset( $alloptions[$option] );
  572. wp_cache_set( 'alloptions', $alloptions, 'options' );
  573. }
  574. } else {
  575. wp_cache_delete( $option, 'options' );
  576. }
  577. }
  578. if ( $result ) {
  579. do_action( "delete_option_$option", $option );
  580. do_action( 'deleted_option', $option );
  581. return true;
  582. }
  583. return false;
  584. }
  585. /**
  586. * Delete a transient
  587. *
  588. * @since 2.8.0
  589. * @package WordPress
  590. * @subpackage Transient
  591. *
  592. * @uses do_action() Calls 'delete_transient_$transient' hook before transient is deleted.
  593. * @uses do_action() Calls 'deleted_transient' hook on success.
  594. *
  595. * @param string $transient Transient name. Expected to not be SQL-escaped.
  596. * @return bool true if successful, false otherwise
  597. */
  598. function delete_transient( $transient ) {
  599. global $_wp_using_ext_object_cache;
  600. do_action( 'delete_transient_' . $transient, $transient );
  601. if ( $_wp_using_ext_object_cache ) {
  602. $result = wp_cache_delete( $transient, 'transient' );
  603. } else {
  604. $option_timeout = '_transient_timeout_' . $transient;
  605. $option = '_transient_' . $transient;
  606. $result = delete_option( $option );
  607. if ( $result )
  608. delete_option( $option_timeout );
  609. }
  610. if ( $result )
  611. do_action( 'deleted_transient', $transient );
  612. return $result;
  613. }
  614. /**
  615. * Get the value of a transient
  616. *
  617. * If the transient does not exist or does not have a value, then the return value
  618. * will be false.
  619. *
  620. * @uses apply_filters() Calls 'pre_transient_$transient' hook before checking the transient.
  621. * Any value other than false will "short-circuit" the retrieval of the transient
  622. * and return the returned value.
  623. * @uses apply_filters() Calls 'transient_$option' hook, after checking the transient, with
  624. * the transient value.
  625. *
  626. * @since 2.8.0
  627. * @package WordPress
  628. * @subpackage Transient
  629. *
  630. * @param string $transient Transient name. Expected to not be SQL-escaped
  631. * @return mixed Value of transient
  632. */
  633. function get_transient( $transient ) {
  634. global $_wp_using_ext_object_cache;
  635. $pre = apply_filters( 'pre_transient_' . $transient, false );
  636. if ( false !== $pre )
  637. return $pre;
  638. if ( $_wp_using_ext_object_cache ) {
  639. $value = wp_cache_get( $transient, 'transient' );
  640. } else {
  641. $transient_option = '_transient_' . $transient;
  642. if ( ! defined( 'WP_INSTALLING' ) ) {
  643. // If option is not in alloptions, it is not autoloaded and thus has a timeout
  644. $alloptions = wp_load_alloptions();
  645. if ( !isset( $alloptions[$transient_option] ) ) {
  646. $transient_timeout = '_transient_timeout_' . $transient;
  647. if ( get_option( $transient_timeout ) < time() ) {
  648. delete_option( $transient_option );
  649. delete_option( $transient_timeout );
  650. return false;
  651. }
  652. }
  653. }
  654. $value = get_option( $transient_option );
  655. }
  656. return apply_filters( 'transient_' . $transient, $value );
  657. }
  658. /**
  659. * Set/update the value of a transient
  660. *
  661. * You do not need to serialize values. If the value needs to be serialized, then
  662. * it will be serialized before it is set.
  663. *
  664. * @since 2.8.0
  665. * @package WordPress
  666. * @subpackage Transient
  667. *
  668. * @uses apply_filters() Calls 'pre_set_transient_$transient' hook to allow overwriting the
  669. * transient value to be stored.
  670. * @uses do_action() Calls 'set_transient_$transient' and 'setted_transient' hooks on success.
  671. *
  672. * @param string $transient Transient name. Expected to not be SQL-escaped.
  673. * @param mixed $value Transient value. Expected to not be SQL-escaped.
  674. * @param int $expiration Time until expiration in seconds, default 0
  675. * @return bool False if value was not set and true if value was set.
  676. */
  677. function set_transient( $transient, $value, $expiration = 0 ) {
  678. global $_wp_using_ext_object_cache;
  679. $value = apply_filters( 'pre_set_transient_' . $transient, $value );
  680. if ( $_wp_using_ext_object_cache ) {
  681. $result = wp_cache_set( $transient, $value, 'transient', $expiration );
  682. } else {
  683. $transient_timeout = '_transient_timeout_' . $transient;
  684. $transient = '_transient_' . $transient;
  685. if ( false === get_option( $transient ) ) {
  686. $autoload = 'yes';
  687. if ( $expiration ) {
  688. $autoload = 'no';
  689. add_option( $transient_timeout, time() + $expiration, '', 'no' );
  690. }
  691. $result = add_option( $transient, $value, '', $autoload );
  692. } else {
  693. if ( $expiration )
  694. update_option( $transient_timeout, time() + $expiration );
  695. $result = update_option( $transient, $value );
  696. }
  697. }
  698. if ( $result ) {
  699. do_action( 'set_transient_' . $transient );
  700. do_action( 'setted_transient', $transient );
  701. }
  702. return $result;
  703. }
  704. /**
  705. * Saves and restores user interface settings stored in a cookie.
  706. *
  707. * Checks if the current user-settings cookie is updated and stores it. When no
  708. * cookie exists (different browser used), adds the last saved cookie restoring
  709. * the settings.
  710. *
  711. * @package WordPress
  712. * @subpackage Option
  713. * @since 2.7.0
  714. */
  715. function wp_user_settings() {
  716. if ( ! is_admin() )
  717. return;
  718. if ( defined('DOING_AJAX') )
  719. return;
  720. if ( ! $user = wp_get_current_user() )
  721. return;
  722. $settings = get_user_option( 'user-settings', $user->ID );
  723. if ( isset( $_COOKIE['wp-settings-' . $user->ID] ) ) {
  724. $cookie = preg_replace( '/[^A-Za-z0-9=&_]/', '', $_COOKIE['wp-settings-' . $user->ID] );
  725. if ( ! empty( $cookie ) && strpos( $cookie, '=' ) ) {
  726. if ( $cookie == $settings )
  727. return;
  728. $last_time = (int) get_user_option( 'user-settings-time', $user->ID );
  729. $saved = isset( $_COOKIE['wp-settings-time-' . $user->ID]) ? preg_replace( '/[^0-9]/', '', $_COOKIE['wp-settings-time-' . $user->ID] ) : 0;
  730. if ( $saved > $last_time ) {
  731. update_user_option( $user->ID, 'user-settings', $cookie, false );
  732. update_user_option( $user->ID, 'user-settings-time', time() - 5, false );
  733. return;
  734. }
  735. }
  736. }
  737. setcookie( 'wp-settings-' . $user->ID, $settings, time() + 31536000, SITECOOKIEPATH );
  738. setcookie( 'wp-settings-time-' . $user->ID, time(), time() + 31536000, SITECOOKIEPATH );
  739. $_COOKIE['wp-settings-' . $user->ID] = $settings;
  740. }
  741. /**
  742. * Retrieve user interface setting value based on setting name.
  743. *
  744. * @package WordPress
  745. * @subpackage Option
  746. * @since 2.7.0
  747. *
  748. * @param string $name The name of the setting.
  749. * @param string $default Optional default value to return when $name is not set.
  750. * @return mixed the last saved user setting or the default value/false if it doesn't exist.
  751. */
  752. function get_user_setting( $name, $default = false ) {
  753. $all = get_all_user_settings();
  754. return isset($all[$name]) ? $all[$name] : $default;
  755. }
  756. /**
  757. * Add or update user interface setting.
  758. *
  759. * Both $name and $value can contain only ASCII letters, numbers and underscores.
  760. * This function has to be used before any output has started as it calls setcookie().
  761. *
  762. * @package WordPress
  763. * @subpackage Option
  764. * @since 2.8.0
  765. *
  766. * @param string $name The name of the setting.
  767. * @param string $value The value for the setting.
  768. * @return bool true if set successfully/false if not.
  769. */
  770. function set_user_setting( $name, $value ) {
  771. if ( headers_sent() )
  772. return false;
  773. $all = get_all_user_settings();
  774. $name = preg_replace( '/[^A-Za-z0-9_]+/', '', $name );
  775. if ( empty($name) )
  776. return false;
  777. $all[$name] = $value;
  778. return wp_set_all_user_settings($all);
  779. }
  780. /**
  781. * Delete user interface settings.
  782. *
  783. * Deleting settings would reset them to the defaults.
  784. * This function has to be used before any output has started as it calls setcookie().
  785. *
  786. * @package WordPress
  787. * @subpackage Option
  788. * @since 2.7.0
  789. *
  790. * @param mixed $names The name or array of names of the setting to be deleted.
  791. * @return bool true if deleted successfully/false if not.
  792. */
  793. function delete_user_setting( $names ) {
  794. if ( headers_sent() )
  795. return false;
  796. $all = get_all_user_settings();
  797. $names = (array) $names;
  798. foreach ( $names as $name ) {
  799. if ( isset($all[$name]) ) {
  800. unset($all[$name]);
  801. $deleted = true;
  802. }
  803. }
  804. if ( isset($deleted) )
  805. return wp_set_all_user_settings($all);
  806. return false;
  807. }
  808. /**
  809. * Retrieve all user interface settings.
  810. *
  811. * @package WordPress
  812. * @subpackage Option
  813. * @since 2.7.0
  814. *
  815. * @return array the last saved user settings or empty array.
  816. */
  817. function get_all_user_settings() {
  818. global $_updated_user_settings;
  819. if ( ! $user = wp_get_current_user() )
  820. return array();
  821. if ( isset($_updated_user_settings) && is_array($_updated_user_settings) )
  822. return $_updated_user_settings;
  823. $all = array();
  824. if ( isset($_COOKIE['wp-settings-' . $user->ID]) ) {
  825. $cookie = preg_replace( '/[^A-Za-z0-9=&_]/', '', $_COOKIE['wp-settings-' . $user->ID] );
  826. if ( $cookie && strpos($cookie, '=') ) // the '=' cannot be 1st char
  827. parse_str($cookie, $all);
  828. } else {
  829. $option = get_user_option('user-settings', $user->ID);
  830. if ( $option && is_string($option) )
  831. parse_str( $option, $all );
  832. }
  833. return $all;
  834. }
  835. /**
  836. * Private. Set all user interface settings.
  837. *
  838. * @package WordPress
  839. * @subpackage Option
  840. * @since 2.8.0
  841. *
  842. * @param unknown $all
  843. * @return bool
  844. */
  845. function wp_set_all_user_settings($all) {
  846. global $_updated_user_settings;
  847. if ( ! $user = wp_get_current_user() )
  848. return false;
  849. $_updated_user_settings = $all;
  850. $settings = '';
  851. foreach ( $all as $k => $v ) {
  852. $v = preg_replace( '/[^A-Za-z0-9_]+/', '', $v );
  853. $settings .= $k . '=' . $v . '&';
  854. }
  855. $settings = rtrim($settings, '&');
  856. update_user_option( $user->ID, 'user-settings', $settings, false );
  857. update_user_option( $user->ID, 'user-settings-time', time(), false );
  858. return true;
  859. }
  860. /**
  861. * Delete the user settings of the current user.
  862. *
  863. * @package WordPress
  864. * @subpackage Option
  865. * @since 2.7.0
  866. */
  867. function delete_all_user_settings() {
  868. if ( ! $user = wp_get_current_user() )
  869. return;
  870. update_user_option( $user->ID, 'user-settings', '', false );
  871. setcookie('wp-settings-' . $user->ID, ' ', time() - 31536000, SITECOOKIEPATH);
  872. }
  873. /**
  874. * Serialize data, if needed.
  875. *
  876. * @since 2.0.5
  877. *
  878. * @param mixed $data Data that might be serialized.
  879. * @return mixed A scalar data
  880. */
  881. function maybe_serialize( $data ) {
  882. if ( is_array( $data ) || is_object( $data ) )
  883. return serialize( $data );
  884. if ( is_serialized( $data ) )
  885. return serialize( $data );
  886. return $data;
  887. }
  888. /**
  889. * Retrieve post title from XMLRPC XML.
  890. *
  891. * If the title element is not part of the XML, then the default post title from
  892. * the $post_default_title will be used instead.
  893. *
  894. * @package WordPress
  895. * @subpackage XMLRPC
  896. * @since 0.71
  897. *
  898. * @global string $post_default_title Default XMLRPC post title.
  899. *
  900. * @param string $content XMLRPC XML Request content
  901. * @return string Post title
  902. */
  903. function xmlrpc_getposttitle( $content ) {
  904. global $post_default_title;
  905. if ( preg_match( '/<title>(.+?)<\/title>/is', $content, $matchtitle ) ) {
  906. $post_title = $matchtitle[1];
  907. } else {
  908. $post_title = $post_default_title;
  909. }
  910. return $post_title;
  911. }
  912. /**
  913. * Retrieve the post category or categories from XMLRPC XML.
  914. *
  915. * If the category element is not found, then the default post category will be
  916. * used. The return type then would be what $post_default_category. If the
  917. * category is found, then it will always be an array.
  918. *
  919. * @package WordPress
  920. * @subpackage XMLRPC
  921. * @since 0.71
  922. *
  923. * @global string $post_default_category Default XMLRPC post category.
  924. *
  925. * @param string $content XMLRPC XML Request content
  926. * @return string|array List of categories or category name.
  927. */
  928. function xmlrpc_getpostcategory( $content ) {
  929. global $post_default_category;
  930. if ( preg_match( '/<category>(.+?)<\/category>/is', $content, $matchcat ) ) {
  931. $post_category = trim( $matchcat[1], ',' );
  932. $post_category = explode( ',', $post_category );
  933. } else {
  934. $post_category = $post_default_category;
  935. }
  936. return $post_category;
  937. }
  938. /**
  939. * XMLRPC XML content without title and category elements.
  940. *
  941. * @package WordPress
  942. * @subpackage XMLRPC
  943. * @since 0.71
  944. *
  945. * @param string $content XMLRPC XML Request content
  946. * @return string XMLRPC XML Request content without title and category elements.
  947. */
  948. function xmlrpc_removepostdata( $content ) {
  949. $content = preg_replace( '/<title>(.+?)<\/title>/si', '', $content );
  950. $content = preg_replace( '/<category>(.+?)<\/category>/si', '', $content );
  951. $content = trim( $content );
  952. return $content;
  953. }
  954. /**
  955. * Open the file handle for debugging.
  956. *
  957. * This function is used for XMLRPC feature, but it is general purpose enough
  958. * to be used in anywhere.
  959. *
  960. * @see fopen() for mode options.
  961. * @package WordPress
  962. * @subpackage Debug
  963. * @since 0.71
  964. * @uses $debug Used for whether debugging is enabled.
  965. *
  966. * @param string $filename File path to debug file.
  967. * @param string $mode Same as fopen() mode parameter.
  968. * @return bool|resource File handle. False on failure.
  969. */
  970. function debug_fopen( $filename, $mode ) {
  971. global $debug;
  972. if ( 1 == $debug ) {
  973. $fp = fopen( $filename, $mode );
  974. return $fp;
  975. } else {
  976. return false;
  977. }
  978. }
  979. /**
  980. * Write contents to the file used for debugging.
  981. *
  982. * Technically, this can be used to write to any file handle when the global
  983. * $debug is set to 1 or true.
  984. *
  985. * @package WordPress
  986. * @subpackage Debug
  987. * @since 0.71
  988. * @uses $debug Used for whether debugging is enabled.
  989. *
  990. * @param resource $fp File handle for debugging file.
  991. * @param string $string Content to write to debug file.
  992. */
  993. function debug_fwrite( $fp, $string ) {
  994. global $debug;
  995. if ( 1 == $debug )
  996. fwrite( $fp, $string );
  997. }
  998. /**
  999. * Close the debugging file handle.
  1000. *
  1001. * Technically, this can be used to close any file handle when the global $debug
  1002. * is set to 1 or true.
  1003. *
  1004. * @package WordPress
  1005. * @subpackage Debug
  1006. * @since 0.71
  1007. * @uses $debug Used for whether debugging is enabled.
  1008. *
  1009. * @param resource $fp Debug File handle.
  1010. */
  1011. function debug_fclose( $fp ) {
  1012. global $debug;
  1013. if ( 1 == $debug )
  1014. fclose( $fp );
  1015. }
  1016. /**
  1017. * Check content for video and audio links to add as enclosures.
  1018. *
  1019. * Will not add enclosures that have already been added and will
  1020. * remove enclosures that are no longer in the post. This is called as
  1021. * pingbacks and trackbacks.
  1022. *
  1023. * @package WordPress
  1024. * @since 1.5.0
  1025. *
  1026. * @uses $wpdb
  1027. *
  1028. * @param string $content Post Content
  1029. * @param int $post_ID Post ID
  1030. */
  1031. function do_enclose( $content, $post_ID ) {
  1032. global $wpdb;
  1033. include_once( ABSPATH . WPINC . '/class-IXR.php' );
  1034. $log = debug_fopen( ABSPATH . 'enclosures.log', 'a' );
  1035. $post_links = array();
  1036. debug_fwrite( $log, 'BEGIN ' . date( 'YmdHis', time() ) . "\n" );
  1037. $pung = get_enclosed( $post_ID );
  1038. $ltrs = '\w';
  1039. $gunk = '/#~:.?+=&%@!\-';
  1040. $punc = '.:?\-';
  1041. $any = $ltrs . $gunk . $punc;
  1042. preg_match_all( "{\b http : [$any] +? (?= [$punc] * [^$any] | $)}x", $content, $post_links_temp );
  1043. debug_fwrite( $log, 'Post contents:' );
  1044. debug_fwrite( $log, $content . "\n" );
  1045. foreach ( $pung as $link_test ) {
  1046. if ( !in_array( $link_test, $post_links_temp[0] ) ) { // link no longer in post
  1047. $mid = $wpdb->get_col( $wpdb->prepare("SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE (%s)", $post_ID, $link_test . '%') );
  1048. do_action( 'delete_postmeta', $mid );
  1049. $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->postmeta WHERE meta_id IN(%s)", implode( ',', $mid ) ) );
  1050. do_action( 'deleted_postmeta', $mid );
  1051. }
  1052. }
  1053. foreach ( (array) $post_links_temp[0] as $link_test ) {
  1054. if ( !in_array( $link_test, $pung ) ) { // If we haven't pung it already
  1055. $test = @parse_url( $link_test );
  1056. if ( false === $test )
  1057. continue;
  1058. if ( isset( $test['query'] ) )
  1059. $post_links[] = $link_test;
  1060. elseif ( $test['path'] != '/' && $test['path'] != '' )
  1061. $post_links[] = $link_test;
  1062. }
  1063. }
  1064. foreach ( (array) $post_links as $url ) {
  1065. 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 . '%' ) ) ) {
  1066. if ( $headers = wp_get_http_headers( $url) ) {
  1067. $len = (int) $headers['content-length'];
  1068. $type = $headers['content-type'];
  1069. $allowed_types = array( 'video', 'audio' );
  1070. // Check to see if we can figure out the mime type from
  1071. // the extension
  1072. $url_parts = @parse_url( $url );
  1073. if ( false !== $url_parts ) {
  1074. $extension = pathinfo( $url_parts['path'], PATHINFO_EXTENSION );
  1075. if ( !empty( $extension ) ) {
  1076. foreach ( get_allowed_mime_types( ) as $exts => $mime ) {
  1077. if ( preg_match( '!^(' . $exts . ')$!i', $extension ) ) {
  1078. $type = $mime;
  1079. break;
  1080. }
  1081. }
  1082. }
  1083. }
  1084. if ( in_array( substr( $type, 0, strpos( $type, "/" ) ), $allowed_types ) ) {
  1085. $meta_value = "$url\n$len\n$type\n";
  1086. $wpdb->insert($wpdb->postmeta, array('post_id' => $post_ID, 'meta_key' => 'enclosure', 'meta_value' => $meta_value) );
  1087. do_action( 'added_postmeta', $wpdb->insert_id, $post_ID, 'enclosure', $meta_value );
  1088. }
  1089. }
  1090. }
  1091. }
  1092. }
  1093. /**
  1094. * Perform a HTTP HEAD or GET request.
  1095. *
  1096. * If $file_path is a writable filename, this will do a GET request and write
  1097. * the file to that path.
  1098. *
  1099. * @since 2.5.0
  1100. *
  1101. * @param string $url URL to fetch.
  1102. * @param string|bool $file_path Optional. File path to write request to.
  1103. * @param int $red (private) The number of Redirects followed, Upon 5 being hit, returns false.
  1104. * @return bool|string False on failure and string of headers if HEAD request.
  1105. */
  1106. function wp_get_http( $url, $file_path = false, $red = 1 ) {
  1107. @set_time_limit( 60 );
  1108. if ( $red > 5 )
  1109. return false;
  1110. $options = array();
  1111. $options['redirection'] = 5;
  1112. if ( false == $file_path )
  1113. $options['method'] = 'HEAD';
  1114. else
  1115. $options['method'] = 'GET';
  1116. $response = wp_remote_request($url, $options);
  1117. if ( is_wp_error( $response ) )
  1118. return false;
  1119. $headers = wp_remote_retrieve_headers( $response );
  1120. $headers['response'] = $response['response']['code'];
  1121. // WP_HTTP no longer follows redirects for HEAD requests.
  1122. if ( 'HEAD' == $options['method'] && in_array($headers['response'], array(301, 302)) && isset( $headers['location'] ) ) {
  1123. return wp_get_http( $headers['location'], $file_path, ++$red );
  1124. }
  1125. if ( false == $file_path )
  1126. return $headers;
  1127. // GET request - write it to the supplied filename
  1128. $out_fp = fopen($file_path, 'w');
  1129. if ( !$out_fp )
  1130. return $headers;
  1131. fwrite( $out_fp, $response['body']);
  1132. fclose($out_fp);
  1133. clearstatcache();
  1134. return $headers;
  1135. }
  1136. /**
  1137. * Retrieve HTTP Headers from URL.
  1138. *
  1139. * @since 1.5.1
  1140. *
  1141. * @param string $url
  1142. * @param bool $deprecated Not Used.
  1143. * @return bool|string False on failure, headers on success.
  1144. */
  1145. function wp_get_http_headers( $url, $deprecated = false ) {
  1146. if ( !empty( $deprecated ) )
  1147. _deprecated_argument( __FUNCTION__, '2.7' );
  1148. $response = wp_remote_head( $url );
  1149. if ( is_wp_error( $response ) )
  1150. return false;
  1151. return wp_remote_retrieve_headers( $response );
  1152. }
  1153. /**
  1154. * Whether today is a new day.
  1155. *
  1156. * @since 0.71
  1157. * @uses $day Today
  1158. * @uses $previousday Previous day
  1159. *
  1160. * @return int 1 when new day, 0 if not a new day.
  1161. */
  1162. function is_new_day() {
  1163. global $day, $previousday;
  1164. if ( $day != $previousday )
  1165. return 1;
  1166. else
  1167. return 0;
  1168. }
  1169. /**
  1170. * Build URL query based on an associative and, or indexed array.
  1171. *
  1172. * This is a convenient function for easily building url queries. It sets the
  1173. * separator to '&' and uses _http_build_query() function.
  1174. *
  1175. * @see _http_build_query() Used to build the query
  1176. * @link http://us2.php.net/manual/en/function.http-build-query.php more on what
  1177. * http_build_query() does.
  1178. *
  1179. * @since 2.3.0
  1180. *
  1181. * @param array $data URL-encode key/value pairs.
  1182. * @return string URL encoded string
  1183. */
  1184. function build_query( $data ) {
  1185. return _http_build_query( $data, null, '&', '', false );
  1186. }
  1187. /**
  1188. * Retrieve a modified URL query string.
  1189. *
  1190. * You can rebuild the URL and append a new query variable to the URL query by
  1191. * using this function. You can also retrieve the full URL with query data.
  1192. *
  1193. * Adding a single key & value or an associative array. Setting a key value to
  1194. * emptystring removes the key. Omitting oldquery_or_uri uses the $_SERVER
  1195. * value.
  1196. *
  1197. * @since 1.5.0
  1198. *
  1199. * @param mixed $param1 Either newkey or an associative_array
  1200. * @param mixed $param2 Either newvalue or oldquery or uri
  1201. * @param mixed $param3 Optional. Old query or uri
  1202. * @return string New URL query string.
  1203. */
  1204. function add_query_arg() {
  1205. $ret = '';
  1206. if ( is_array( func_get_arg(0) ) ) {
  1207. if ( @func_num_args() < 2 || false === @func_get_arg( 1 ) )
  1208. $uri = $_SERVER['REQUEST_URI'];
  1209. else
  1210. $uri = @func_get_arg( 1 );
  1211. } else {
  1212. if ( @func_num_args() < 3 || false === @func_get_arg( 2 ) )
  1213. $uri = $_SERVER['REQUEST_URI'];
  1214. else
  1215. $uri = @func_get_arg( 2 );
  1216. }
  1217. if ( $frag = strstr( $uri, '#' ) )
  1218. $uri = substr( $uri, 0, -strlen( $frag ) );
  1219. else
  1220. $frag = '';
  1221. if ( preg_match( '|^https?://|i', $uri, $matches ) ) {
  1222. $protocol = $matches[0];
  1223. $uri = substr( $uri, strlen( $protocol ) );
  1224. } else {
  1225. $protocol = '';
  1226. }
  1227. if ( strpos( $uri, '?' ) !== false ) {
  1228. $parts = explode( '?', $uri, 2 );
  1229. if ( 1 == count( $parts ) ) {
  1230. $base = '?';
  1231. $query = $parts[0];
  1232. } else {
  1233. $base = $parts[0] . '?';
  1234. $query = $parts[1];
  1235. }
  1236. } elseif ( !empty( $protocol ) || strpos( $uri, '=' ) === false ) {
  1237. $base = $uri . '?';
  1238. $query = '';
  1239. } else {
  1240. $base = '';
  1241. $query = $uri;
  1242. }
  1243. wp_parse_str( $query, $qs );
  1244. $qs = urlencode_deep( $qs ); // this re-URL-encodes things that were already in the query string
  1245. if ( is_array( func_get_arg( 0 ) ) ) {
  1246. $kayvees = func_get_arg( 0 );
  1247. $qs = array_merge( $qs, $kayvees );
  1248. } else {
  1249. $qs[func_get_arg( 0 )] = func_get_arg( 1 );
  1250. }
  1251. foreach ( (array) $qs as $k => $v ) {
  1252. if ( $v === false )
  1253. unset( $qs[$k] );
  1254. }
  1255. $ret = build_query( $qs );
  1256. $ret = trim( $ret, '?' );
  1257. $ret = preg_replace( '#=(&|$)#', '$1', $ret );
  1258. $ret = $protocol . $base . $ret . $frag;
  1259. $ret = rtrim( $ret, '?' );
  1260. return $ret;
  1261. }
  1262. /**
  1263. * Removes an item or list from the query string.
  1264. *
  1265. * @since 1.5.0
  1266. *
  1267. * @param string|array $key Query key or keys to remove.
  1268. * @param bool $query When false uses the $_SERVER value.
  1269. * @return string New URL query string.
  1270. */
  1271. function remove_query_arg( $key, $query=false ) {
  1272. if ( is_array( $key ) ) { // removing multiple keys
  1273. foreach ( $key as $k )
  1274. $query = add_query_arg( $k, false, $query );
  1275. return $query;
  1276. }
  1277. return add_query_arg( $key, false, $query );
  1278. }
  1279. /**
  1280. * Walks the array while sanitizing the contents.
  1281. *
  1282. * @since 0.71
  1283. *
  1284. * @param array $array Array to used to walk while sanitizing contents.
  1285. * @return array Sanitized $array.
  1286. */
  1287. function add_magic_quotes( $array ) {
  1288. foreach ( (array) $array as $k => $v ) {
  1289. if ( is_array( $v ) ) {
  1290. $array[$k] = add_magic_quotes( $v );
  1291. } else {
  1292. $array[$k] = addslashes( $v );
  1293. }
  1294. }
  1295. return $array;
  1296. }
  1297. /**
  1298. * HTTP request for URI to retrieve content.
  1299. *
  1300. * @since 1.5.1
  1301. * @uses wp_remote_get()
  1302. *
  1303. * @param string $uri URI/URL of web page to retrieve.
  1304. * @return bool|string HTTP content. False on failure.
  1305. */
  1306. function wp_remote_fopen( $uri ) {
  1307. $parsed_url = @parse_url( $uri );
  1308. if ( !$parsed_url || !is_array( $parsed_url ) )
  1309. return false;
  1310. $options = array();
  1311. $options['timeout'] = 10;
  1312. $response = wp_remote_get( $uri, $options );
  1313. if ( is_wp_error( $response ) )
  1314. return false;
  1315. return $response['body'];
  1316. }
  1317. /**
  1318. * Set up the WordPress query.
  1319. *
  1320. * @since 2.0.0
  1321. *
  1322. * @param string $query_vars Default WP_Query arguments.
  1323. */
  1324. function wp( $query_vars = '' ) {
  1325. global $wp, $wp_query, $wp_the_query;
  1326. $wp->main( $query_vars );
  1327. if ( !isset($wp_the_query) )
  1328. $wp_the_query = $wp_query;
  1329. }
  1330. /**
  1331. * Retrieve the description for the HTTP status.
  1332. *
  1333. * @since 2.3.0
  1334. *
  1335. * @param int $code HTTP status code.
  1336. * @return string Empty string if not found, or description if found.
  1337. */
  1338. function get_status_header_desc( $code ) {
  1339. global $wp_header_to_desc;
  1340. $code = absint( $code );
  1341. if ( !isset( $wp_header_to_desc ) ) {
  1342. $wp_header_to_desc = array(
  1343. 100 => 'Continue',
  1344. 101 => 'Switching Protocols',
  1345. 102 => 'Processing',
  1346. 200 => 'OK',
  1347. 201 => 'Created',
  1348. 202 => 'Accepted',
  1349. 203 => 'Non-Authoritative Information',
  1350. 204 => 'No Content',
  1351. 205 => 'Reset Content',
  1352. 206 => 'Partial Content',
  1353. 207 => 'Multi-Status',
  1354. 226 => 'IM Used',
  1355. 300 => 'Multiple Choices',
  1356. 301 => 'Moved Permanently',
  1357. 302 => 'Found',
  1358. 303 => 'See Other',
  1359. 304 => 'Not Modified',
  1360. 305 => 'Use Proxy',
  1361. 306 => 'Reserved',
  1362. 307 => 'Temporary Redirect',
  1363. 400 => 'Bad Request',
  1364. 401 => 'Unauthorized',
  1365. 402 => 'Payment Required',
  1366. 403 => 'Forbidden',
  1367. 404 => 'Not Found',
  1368. 405 => 'Method Not Allowed',
  1369. 406 => 'Not Acceptable',
  1370. 407 => 'Proxy Authentication Required',
  1371. 408 => 'Request Timeout',
  1372. 409 => 'Conflict',
  1373. 410 => 'Gone',
  1374. 411 => 'Length Required',
  1375. 412 => 'Precondition Failed',
  1376. 413 => 'Request Entity Too Large',
  1377. 414 => 'Request-URI Too Long',
  1378. 415 => 'Unsupported Media Type',
  1379. 416 => 'Requested Range Not Satisfiable',
  1380. 417 => 'Expectation Failed',
  1381. 422 => 'Unprocessable Entity',
  1382. 423 => 'Locked',
  1383. 424 => 'Failed Dependency',
  1384. 426 => 'Upgrade Required',
  1385. 500 => 'Internal Server Error',
  1386. 501 => 'Not Implemented',
  1387. 502 => 'Bad Gateway',
  1388. 503 => 'Service Unavailable',
  1389. 504 => 'Gateway Timeout',
  1390. 505 => 'HTTP Version Not Supported',
  1391. 506 => 'Variant Also Negotiates',
  1392. 507 => 'Insufficient Storage',
  1393. 510 => 'Not Extended'
  1394. );
  1395. }
  1396. if ( isset( $wp_header_to_desc[$code] ) )
  1397. return $wp_header_to_desc[$code];
  1398. else
  1399. return '';
  1400. }
  1401. /**
  1402. * Set HTTP status header.
  1403. *
  1404. * @since 2.0.0
  1405. * @uses apply_filters() Calls 'status_header' on status header string, HTTP
  1406. * HTTP code, HTTP code description, and protocol string as separate
  1407. * parameters.
  1408. *
  1409. * @param int $header HTTP status code
  1410. * @return unknown
  1411. */
  1412. function status_header( $header ) {
  1413. $text = get_status_header_desc( $header );
  1414. if ( empty( $text ) )
  1415. return false;
  1416. $protocol = $_SERVER["SERVER_PROTOCOL"];
  1417. if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol )
  1418. $protocol = 'HTTP/1.0';
  1419. $status_header = "$protocol $header $text";
  1420. if ( function_exists( 'apply_filters' ) )
  1421. $status_header = apply_filters( 'status_header', $status_header, $header, $text, $protocol );
  1422. return @header( $status_header, true, $header );
  1423. }
  1424. /**
  1425. * Gets the header information to prevent caching.
  1426. *
  1427. * The several different headers cover the different ways cache prevention is handled
  1428. * by different browsers
  1429. *
  1430. * @since 2.8
  1431. *
  1432. * @uses apply_filters()
  1433. * @return array The associative array of header names and field values.
  1434. */
  1435. function wp_get_nocache_headers() {
  1436. $headers = array(
  1437. 'Expires' => 'Wed, 11 Jan 1984 05:00:00 GMT',
  1438. 'Last-Modified' => gmdate( 'D, d M Y H:i:s' ) . ' GMT',
  1439. 'Cache-Control' => 'no-cache, must-revalidate, max-age=0',
  1440. 'Pragma' => 'no-cache',
  1441. );
  1442. if ( function_exists('apply_filters') ) {
  1443. $headers = apply_filters('nocache_headers', $headers);
  1444. }
  1445. return $headers;
  1446. }
  1447. /**
  1448. * Sets the headers to prevent caching for the different browsers.
  1449. *
  1450. * Different browsers support different nocache headers, so several headers must
  1451. * be sent so that all of them get the point that no caching should occur.
  1452. *
  1453. * @since 2.0.0
  1454. * @uses wp_get_nocache_headers()
  1455. */
  1456. function nocache_headers() {
  1457. $headers = wp_get_nocache_headers();
  1458. foreach( (array) $headers as $name => $field_value )
  1459. @header("{$name}: {$field_value}");
  1460. }
  1461. /**
  1462. * Set the headers for caching for 10 days with JavaScript content type.
  1463. *
  1464. * @since 2.1.0
  1465. */
  1466. function cache_javascript_headers() {
  1467. $expiresOffset = 864000; // 10 days
  1468. header( "Content-Type: text/javascript; charset=" . get_bloginfo( 'charset' ) );
  1469. header( "Vary: Accept-Encoding" ); // Handle proxies
  1470. header( "Expires: " . gmdate( "D, d M Y H:i:s", time() + $expiresOffset ) . " GMT" );
  1471. }
  1472. /**
  1473. * Retrieve the number of database queries during the WordPress execution.
  1474. *
  1475. * @since 2.0.0
  1476. *
  1477. * @return int Number of database queries
  1478. */
  1479. function get_num_queries() {
  1480. global $wpdb;
  1481. return $wpdb->num_queries;
  1482. }
  1483. /**
  1484. * Whether input is yes or no. Must be 'y' to be true.
  1485. *
  1486. * @since 1.0.0
  1487. *
  1488. * @param string $yn Character string containing either 'y' or 'n'
  1489. * @return bool True if yes, false on anything else
  1490. */
  1491. function bool_from_yn( $yn ) {
  1492. return ( strtolower( $yn ) == 'y' );
  1493. }
  1494. /**
  1495. * Loads the feed template from the use of an action hook.
  1496. *
  1497. * If the feed action does not have a hook, then the function will die with a
  1498. * message telling the visitor that the feed is not valid.
  1499. *
  1500. * It is better to only have one hook for each feed.
  1501. *
  1502. * @since 2.1.0
  1503. * @uses $wp_query Used to tell if the use a comment feed.
  1504. * @uses do_action() Calls 'do_feed_$feed' hook, if a hook exists for the feed.
  1505. */
  1506. function do_feed() {
  1507. global $wp_query;
  1508. $feed = get_query_var( 'feed' );
  1509. // Remove the pad, if present.
  1510. $feed = preg_replace( '/^_+/', '', $feed );
  1511. if ( $feed == '' || $feed == 'feed' )
  1512. $feed = get_default_feed();
  1513. $hook = 'do_feed_' . $feed;
  1514. if ( !has_action($hook) ) {
  1515. $message = sprintf( __( 'ERROR: %s is not a valid feed template.' ), esc_html($feed));
  1516. wp_die( $message, '', array( 'response' => 404 ) );
  1517. }
  1518. do_action( $hook, $wp_query->is_comment_feed );
  1519. }
  1520. /**
  1521. * Load the RDF RSS 0.91 Feed template.
  1522. *
  1523. * @since 2.1.0
  1524. */
  1525. function do_feed_rdf() {
  1526. load_template( ABSPATH . WPINC . '/feed-rdf.php' );
  1527. }
  1528. /**
  1529. * Load the RSS 1.0 Feed Template
  1530. *
  1531. * @since 2.1.0
  1532. */
  1533. function do_feed_rss() {
  1534. load_template( ABSPATH . WPINC . '/feed-rss.php' );
  1535. }
  1536. /**
  1537. * Load either the RSS2 comment feed or the RSS2 posts feed.
  1538. *
  1539. * @since 2.1.0
  1540. *
  1541. * @param bool $for_comments True for the comment feed, false for normal feed.
  1542. */
  1543. function do_feed_rss2( $for_comments ) {
  1544. if ( $for_comments )
  1545. load_template( ABSPATH . WPINC . '/feed-rss2-comments.php' );
  1546. else
  1547. load_template( ABSPATH . WPINC . '/feed-rss2.php' );
  1548. }
  1549. /**
  1550. * Load either Atom comment feed or Atom posts feed.
  1551. *
  1552. * @since 2.1.0
  1553. *
  1554. * @param bool $for_comments True for the comment feed, false for normal feed.
  1555. */
  1556. function do_feed_atom( $for_comments ) {
  1557. if ($for_comments)
  1558. load_template( ABSPATH . WPINC . '/feed-atom-comments.php');
  1559. else
  1560. load_template( ABSPATH . WPINC . '/feed-atom.php' );
  1561. }
  1562. /**
  1563. * Display the robot.txt file content.
  1564. *
  1565. * The echo content should be with usage of the permalinks or for creating the
  1566. * robot.txt file.
  1567. *
  1568. * @since 2.1.0
  1569. * @uses do_action() Calls 'do_robotstxt' hook for displaying robot.txt rules.
  1570. */
  1571. function do_robots() {
  1572. header( 'Content-Type: text/plain; charset=utf-8' );
  1573. do_action( 'do_robotstxt' );
  1574. $output = '';
  1575. $public = get_option( 'blog_public' );
  1576. if ( '0' == $public ) {
  1577. $output .= "User-agent: *\n";
  1578. $output .= "Disallow: /\n";
  1579. } else {
  1580. $output .= "User-agent: *\n";
  1581. $output .= "Disallow:\n";
  1582. }
  1583. echo apply_filters('robots_txt', $output, $public);
  1584. }
  1585. /**
  1586. * Test whether blog is already installed.
  1587. *
  1588. * The cache will be checked first. If you have a cache plugin, which saves the
  1589. * cache values, then this will work. If you use the default WordPress cache,
  1590. * and the database goes away, then you might have problems.
  1591. *
  1592. * Checks for the option siteurl for whether WordPress is installed.
  1593. *
  1594. * @since 2.1.0
  1595. * @uses $wpdb
  1596. *
  1597. * @return bool Whether blog is already installed.
  1598. */
  1599. function is_blog_installed() {
  1600. global $wpdb;
  1601. // Check cache first. If options table goes away and we have true cached, oh well.
  1602. if ( wp_cache_get( 'is_blog_installed' ) )
  1603. return true;
  1604. $suppress = $wpdb->suppress_errors();
  1605. if ( ! defined( 'WP_INSTALLING' ) ) {
  1606. $alloptions = wp_load_alloptions();
  1607. }
  1608. // If siteurl is not set to autoload, check it specifically
  1609. if ( !isset( $alloptions['siteurl'] ) )
  1610. $installed = $wpdb->get_var( "SELECT option_value FROM $wpdb->options WHERE option_name = 'siteurl'" );
  1611. else
  1612. $installed = $alloptions['siteurl'];
  1613. $wpdb->suppress_errors( $suppress );
  1614. $installed = !empty( $installed );
  1615. wp_cache_set( 'is_blog_installed', $installed );
  1616. if ( $installed )
  1617. return true;
  1618. $suppress = $wpdb->suppress_errors();
  1619. $tables = $wpdb->get_col('SHOW TABLES');
  1620. $wpdb->suppress_errors( $suppress );
  1621. $wp_tables = $wpdb->tables();
  1622. // Loop over the WP tables. If none exist, then scratch install is allowed.
  1623. // If one or more exist, suggest table repair since we got here because the options
  1624. // table could not be accessed.
  1625. foreach ( $wp_tables as $table ) {
  1626. // If one of the WP tables exist, then we are in an insane state.
  1627. if ( in_array( $table, $tables ) ) {
  1628. // The existence of custom user tables shouldn't suggest an insane state or prevent a clean install.
  1629. if ( defined( 'CUSTOM_USER_TABLE' ) && CUSTOM_USER_TABLE == $table )
  1630. continue;
  1631. if ( defined( 'CUSTOM_USER_META_TABLE' ) && CUSTOM_USER_META_TABLE == $table )
  1632. continue;
  1633. // If visiting repair.php, return true and let it take over.
  1634. if ( defined('WP_REPAIRING') )
  1635. return true;
  1636. // Die with a DB error.
  1637. $wpdb->error = sprintf( /*WP_I18N_NO_TABLES*/'One or more database tables are unavailable. The database may need to be <a href="%s">repaired</a>.'/*/WP_I18N_NO_TABLES*/, 'maint/repair.php?referrer=is_blog_installed' );
  1638. dead_db();
  1639. }
  1640. }
  1641. wp_cache_set( 'is_blog_installed', false );
  1642. return false;
  1643. }
  1644. /**
  1645. * Retrieve URL with nonce added to URL query.
  1646. *
  1647. * @package WordPress
  1648. * @subpackage Security
  1649. * @since 2.0.4
  1650. *
  1651. * @param string $actionurl URL to add nonce action
  1652. * @param string $action Optional. Nonce action name
  1653. * @return string URL with nonce action added.
  1654. */
  1655. function wp_nonce_url( $actionurl, $action = -1 ) {
  1656. $actionurl = str_replace( '&amp;', '&', $actionurl );
  1657. return esc_html( add_query_arg( '_wpnonce', wp_create_nonce( $action ), $actionurl ) );
  1658. }
  1659. /**
  1660. * Retrieve or display nonce hidden field for forms.
  1661. *
  1662. * The nonce field is used to validate that the contents of the form came from
  1663. * the location on the current site and not somewhere else. The nonce does not
  1664. * offer absolute protection, but should protect against most cases. It is very
  1665. * important to use nonce field in forms.
  1666. *
  1667. * If you set $echo to true and set $referer to true, then you will need to
  1668. * retrieve the {@link wp_referer_field() wp referer field}. If you have the
  1669. * $referer set to true and are echoing the nonce field, it will also echo the
  1670. * referer field.
  1671. *
  1672. * The $action and $name are optional, but if you want to have better security,
  1673. * it is strongly suggested to set those two parameters. It is easier to just
  1674. * call the function without any parameters, because validation of the nonce
  1675. * doesn't require any parameters, but since crackers know what the default is
  1676. * it won't be difficult for them to find a way around your nonce and cause
  1677. * damage.
  1678. *
  1679. * The input name will be whatever $name value you gave. The input value will be
  1680. * the nonce creation value.
  1681. *
  1682. * @package WordPress
  1683. * @subpackage Security
  1684. * @since 2.0.4
  1685. *
  1686. * @param string $action Optional. Action name.
  1687. * @param string $name Optional. Nonce name.
  1688. * @param bool $referer Optional, default true. Whether to set the referer field for validation.
  1689. * @param bool $echo Optional, default true. Whether to display or return hidden form field.
  1690. * @return string Nonce field.
  1691. */
  1692. function wp_nonce_field( $action = -1, $name = "_wpnonce", $referer = true , $echo = true ) {
  1693. $name = esc_attr( $name );
  1694. $nonce_field = '<input type="hidden" id="' . $name . '" name="' . $name . '" value="' . wp_create_nonce( $action ) . '" />';
  1695. if ( $echo )
  1696. echo $nonce_field;
  1697. if ( $referer )
  1698. wp_referer_field( $echo );
  1699. return $nonce_field;
  1700. }
  1701. /**
  1702. * Retrieve or display referer hidden field for forms.
  1703. *
  1704. * The referer link is the current Request URI from the server super global. The
  1705. * input name is '_wp_http_referer', in case you wanted to check manually.
  1706. *
  1707. * @package WordPress
  1708. * @subpackage Security
  1709. * @since 2.0.4
  1710. *
  1711. * @param bool $echo Whether to echo or return the referer field.
  1712. * @return string Referer field.
  1713. */
  1714. function wp_referer_field( $echo = true ) {
  1715. $ref = esc_attr( $_SERVER['REQUEST_URI'] );
  1716. $referer_field = '<input type="hidden" name="_wp_http_referer" value="'. $ref . '" />';
  1717. if ( $echo )
  1718. echo $referer_field;
  1719. return $referer_field;
  1720. }
  1721. /**
  1722. * Retrieve or display original referer hidden field for forms.
  1723. *
  1724. * The input name is '_wp_original_http_referer' and will be either the same
  1725. * value of {@link wp_referer_field()}, if that was posted already or it will
  1726. * be the current page, if it doesn't exist.
  1727. *
  1728. * @package WordPress
  1729. * @subpackage Security
  1730. * @since 2.0.4
  1731. *
  1732. * @param bool $echo Whether to echo the original http referer
  1733. * @param string $jump_back_to Optional, default is 'current'. Can be 'previous' or page you want to jump back to.
  1734. * @return string Original referer field.
  1735. */
  1736. function wp_original_referer_field( $echo = true, $jump_back_to = 'current' ) {
  1737. $jump_back_to = ( 'previous' == $jump_back_to ) ? wp_get_referer() : $_SERVER['REQUEST_URI'];
  1738. $ref = ( wp_get_original_referer() ) ? wp_get_original_referer() : $jump_back_to;
  1739. $orig_referer_field = '<input type="hidden" name="_wp_original_http_referer" value="' . esc_attr( stripslashes( $ref ) ) . '" />';
  1740. if ( $echo )
  1741. echo $orig_referer_field;
  1742. return $orig_referer_field;
  1743. }
  1744. /**
  1745. * Retrieve referer from '_wp_http_referer', HTTP referer, or current page respectively.
  1746. *
  1747. * @package WordPress
  1748. * @subpackage Security
  1749. * @since 2.0.4
  1750. *
  1751. * @return string|bool False on failure. Referer URL on success.
  1752. */
  1753. function wp_get_referer() {
  1754. $ref = '';
  1755. if ( ! empty( $_REQUEST['_wp_http_referer'] ) )
  1756. $ref = $_REQUEST['_wp_http_referer'];
  1757. else if ( ! empty( $_SERVER['HTTP_REFERER'] ) )
  1758. $ref = $_SERVER['HTTP_REFERER'];
  1759. if ( $ref !== $_SERVER['REQUEST_URI'] )
  1760. return $ref;
  1761. return false;
  1762. }
  1763. /**
  1764. * Retrieve original referer that was posted, if it exists.
  1765. *
  1766. * @package WordPress
  1767. * @subpackage Security
  1768. * @since 2.0.4
  1769. *
  1770. * @return string|bool False if no original referer or original referer if set.
  1771. */
  1772. function wp_get_original_referer() {
  1773. if ( !empty( $_REQUEST['_wp_original_http_referer'] ) )
  1774. return $_REQUEST['_wp_original_http_referer'];
  1775. return false;
  1776. }
  1777. /**
  1778. * Recursive directory creation based on full path.
  1779. *
  1780. * Will attempt to set permissions on folders.
  1781. *
  1782. * @since 2.0.1
  1783. *
  1784. * @param string $target Full path to attempt to create.
  1785. * @return bool Whether the path was created. True if path already exists.
  1786. */
  1787. function wp_mkdir_p( $target ) {
  1788. // from php.net/mkdir user contributed notes
  1789. $target = str_replace( '//', '/', $target );
  1790. // safe mode fails with a trailing slash under certain PHP versions.
  1791. $target = rtrim($target, '/'); // Use rtrim() instead of untrailingslashit to avoid formatting.php dependency.
  1792. if ( empty($target) )
  1793. $target = '/';
  1794. if ( file_exists( $target ) )
  1795. return @is_dir( $target );
  1796. // Attempting to create the directory may clutter up our display.
  1797. if ( @mkdir( $target ) ) {
  1798. $stat = @stat( dirname( $target ) );
  1799. $dir_perms = $stat['mode'] & 0007777; // Get the permission bits.
  1800. @chmod( $target, $dir_perms );
  1801. return true;
  1802. } elseif ( is_dir( dirname( $target ) ) ) {
  1803. return false;
  1804. }
  1805. // If the above failed, attempt to create the parent node, then try again.
  1806. if ( ( $target != '/' ) && ( wp_mkdir_p( dirname( $target ) ) ) )
  1807. return wp_mkdir_p( $target );
  1808. return false;
  1809. }
  1810. /**
  1811. * Test if a give filesystem path is absolute ('/foo/bar', 'c:\windows').
  1812. *
  1813. * @since 2.5.0
  1814. *
  1815. * @param string $path File path
  1816. * @return bool True if path is absolute, false is not absolute.
  1817. */
  1818. function path_is_absolute( $path ) {
  1819. // this is definitive if true but fails if $path does not exist or contains a symbolic link
  1820. if ( realpath($path) == $path )
  1821. return true;
  1822. if ( strlen($path) == 0 || $path{0} == '.' )
  1823. return false;
  1824. // windows allows absolute paths like this
  1825. if ( preg_match('#^[a-zA-Z]:\\\\#', $path) )
  1826. return true;
  1827. // a path starting with / or \ is absolute; anything else is relative
  1828. return (bool) preg_match('#^[/\\\\]#', $path);
  1829. }
  1830. /**
  1831. * Join two filesystem paths together (e.g. 'give me $path relative to $base').
  1832. *
  1833. * If the $path is absolute, then it the full path is returned.
  1834. *
  1835. * @since 2.5.0
  1836. *
  1837. * @param string $base
  1838. * @param string $path
  1839. * @return string The path with the base or absolute path.
  1840. */
  1841. function path_join( $base, $path ) {
  1842. if ( path_is_absolute($path) )
  1843. return $path;
  1844. return rtrim($base, '/') . '/' . ltrim($path, '/');
  1845. }
  1846. /**
  1847. * Get an array containing the current upload directory's path and url.
  1848. *
  1849. * Checks the 'upload_path' option, which should be from the web root folder,
  1850. * and if it isn't empty it will be used. If it is empty, then the path will be
  1851. * 'WP_CONTENT_DIR/uploads'. If the 'UPLOADS' constant is defined, then it will
  1852. * override the 'upload_path' option and 'WP_CONTENT_DIR/uploads' path.
  1853. *
  1854. * The upload URL path is set either by the 'upload_url_path' option or by using
  1855. * the 'WP_CONTENT_URL' constant and appending '/uploads' to the path.
  1856. *
  1857. * If the 'uploads_use_yearmonth_folders' is set to true (checkbox if checked in
  1858. * the administration settings panel), then the time will be used. The format
  1859. * will be year first and then month.
  1860. *
  1861. * If the path couldn't be created, then an error will be returned with the key
  1862. * 'error' containing the error message. The error suggests that the parent
  1863. * directory is not writable by the server.
  1864. *
  1865. * On success, the returned array will have many indices:
  1866. * 'path' - base directory and sub directory or full path to upload directory.
  1867. * 'url' - base url and sub directory or absolute URL to upload directory.
  1868. * 'subdir' - sub directory if uploads use year/month folders option is on.
  1869. * 'basedir' - path without subdir.
  1870. * 'baseurl' - URL path without subdir.
  1871. * 'error' - set to false.
  1872. *
  1873. * @since 2.0.0
  1874. * @uses apply_filters() Calls 'upload_dir' on returned array.
  1875. *
  1876. * @param string $time Optional. Time formatted in 'yyyy/mm'.
  1877. * @return array See above for description.
  1878. */
  1879. function wp_upload_dir( $time = null ) {
  1880. global $switched;
  1881. $siteurl = get_option( 'siteurl' );
  1882. $upload_path = get_option( 'upload_path' );
  1883. $upload_path = trim($upload_path);
  1884. $main_override = is_multisite() && defined( 'MULTISITE' ) && is_main_site();
  1885. if ( empty($upload_path) ) {
  1886. $dir = WP_CONTENT_DIR . '/uploads';
  1887. } else {
  1888. $dir = $upload_path;
  1889. if ( 'wp-content/uploads' == $upload_path ) {
  1890. $dir = WP_CONTENT_DIR . '/uploads';
  1891. } elseif ( 0 !== strpos($dir, ABSPATH) ) {
  1892. // $dir is absolute, $upload_path is (maybe) relative to ABSPATH
  1893. $dir = path_join( ABSPATH, $dir );
  1894. }
  1895. }
  1896. if ( !$url = get_option( 'upload_url_path' ) ) {
  1897. if ( empty($upload_path) || ( 'wp-content/uploads' == $upload_path ) || ( $upload_path == $dir ) )
  1898. $url = WP_CONTENT_URL . '/uploads';
  1899. else
  1900. $url = trailingslashit( $siteurl ) . $upload_path;
  1901. }
  1902. if ( defined('UPLOADS') && !$main_override && ( !isset( $switched ) || $switched === false ) ) {
  1903. $dir = ABSPATH . UPLOADS;
  1904. $url = trailingslashit( $siteurl ) . UPLOADS;
  1905. }
  1906. if ( is_multisite() && !$main_override && ( !isset( $switched ) || $switched === false ) ) {
  1907. if ( defined( 'BLOGUPLOADDIR' ) )
  1908. $dir = untrailingslashit(BLOGUPLOADDIR);
  1909. $url = str_replace( UPLOADS, 'files', $url );
  1910. }
  1911. $bdir = $dir;
  1912. $burl = $url;
  1913. $subdir = '';
  1914. if ( get_option( 'uploads_use_yearmonth_folders' ) ) {
  1915. // Generate the yearly and monthly dirs
  1916. if ( !$time )
  1917. $time = current_time( 'mysql' );
  1918. $y = substr( $time, 0, 4 );
  1919. $m = substr( $time, 5, 2 );
  1920. $subdir = "/$y/$m";
  1921. }
  1922. $dir .= $subdir;
  1923. $url .= $subdir;
  1924. $uploads = apply_filters( 'upload_dir', array( 'path' => $dir, 'url' => $url, 'subdir' => $subdir, 'basedir' => $bdir, 'baseurl' => $burl, 'error' => false ) );
  1925. // Make sure we have an uploads dir
  1926. if ( ! wp_mkdir_p( $uploads['path'] ) ) {
  1927. $message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), $uploads['path'] );
  1928. return array( 'error' => $message );
  1929. }
  1930. return $uploads;
  1931. }
  1932. /**
  1933. * Get a filename that is sanitized and unique for the given directory.
  1934. *
  1935. * If the filename is not unique, then a number will be added to the filename
  1936. * before the extension, and will continue adding numbers until the filename is
  1937. * unique.
  1938. *
  1939. * The callback must accept two parameters, the first one is the directory and
  1940. * the second is the filename. The callback must be a function.
  1941. *
  1942. * @since 2.5
  1943. *
  1944. * @param string $dir
  1945. * @param string $filename
  1946. * @param string $unique_filename_callback Function name, must be a function.
  1947. * @return string New filename, if given wasn't unique.
  1948. */
  1949. function wp_unique_filename( $dir, $filename, $unique_filename_callback = null ) {
  1950. // sanitize the file name before we begin processing
  1951. $filename = sanitize_file_name($filename);
  1952. // separate the filename into a name and extension
  1953. $info = pathinfo($filename);
  1954. $ext = !empty($info['extension']) ? '.' . $info['extension'] : '';
  1955. $name = basename($filename, $ext);
  1956. // edge case: if file is named '.ext', treat as an empty name
  1957. if ( $name === $ext )
  1958. $name = '';
  1959. // Increment the file number until we have a unique file to save in $dir. Use $override['unique_filename_callback'] if supplied.
  1960. if ( $unique_filename_callback && is_callable( $unique_filename_callback ) ) {
  1961. $filename = $unique_filename_callback( $dir, $name );
  1962. } else {
  1963. $number = '';
  1964. // change '.ext' to lower case
  1965. if ( $ext && strtolower($ext) != $ext ) {
  1966. $ext2 = strtolower($ext);
  1967. $filename2 = preg_replace( '|' . preg_quote($ext) . '$|', $ext2, $filename );
  1968. // check for both lower and upper case extension or image sub-sizes may be overwritten
  1969. while ( file_exists($dir . "/$filename") || file_exists($dir . "/$filename2") ) {
  1970. $new_number = $number + 1;
  1971. $filename = str_replace( "$number$ext", "$new_number$ext", $filename );
  1972. $filename2 = str_replace( "$number$ext2", "$new_number$ext2", $filename2 );
  1973. $number = $new_number;
  1974. }
  1975. return $filename2;
  1976. }
  1977. while ( file_exists( $dir . "/$filename" ) ) {
  1978. if ( '' == "$number$ext" )
  1979. $filename = $filename . ++$number . $ext;
  1980. else
  1981. $filename = str_replace( "$number$ext", ++$number . $ext, $filename );
  1982. }
  1983. }
  1984. return $filename;
  1985. }
  1986. /**
  1987. * Create a file in the upload folder with given content.
  1988. *
  1989. * If there is an error, then the key 'error' will exist with the error message.
  1990. * If success, then the key 'file' will have the unique file path, the 'url' key
  1991. * will have the link to the new file. and the 'error' key will be set to false.
  1992. *
  1993. * This function will not move an uploaded file to the upload folder. It will
  1994. * create a new file with the content in $bits parameter. If you move the upload
  1995. * file, read the content of the uploaded file, and then you can give the
  1996. * filename and content to this function, which will add it to the upload
  1997. * folder.
  1998. *
  1999. * The permissions will be set on the new file automatically by this function.
  2000. *
  2001. * @since 2.0.0
  2002. *
  2003. * @param string $name
  2004. * @param null $deprecated Never used. Set to null.
  2005. * @param mixed $bits File content
  2006. * @param string $time Optional. Time formatted in 'yyyy/mm'.
  2007. * @return array
  2008. */
  2009. function wp_upload_bits( $name, $deprecated, $bits, $time = null ) {
  2010. if ( !empty( $deprecated ) )
  2011. _deprecated_argument( __FUNCTION__, '2.0' );
  2012. if ( empty( $name ) )
  2013. return array( 'error' => __( 'Empty filename' ) );
  2014. $wp_filetype = wp_check_filetype( $name );
  2015. if ( !$wp_filetype['ext'] )
  2016. return array( 'error' => __( 'Invalid file type' ) );
  2017. $upload = wp_upload_dir( $time );
  2018. if ( $upload['error'] !== false )
  2019. return $upload;
  2020. $upload_bits_error = apply_filters( 'wp_upload_bits', array( 'name' => $name, 'bits' => $bits, 'time' => $time ) );
  2021. if ( !is_array( $upload_bits_error ) ) {
  2022. $upload[ 'error' ] = $upload_bits_error;
  2023. return $upload;
  2024. }
  2025. $filename = wp_unique_filename( $upload['path'], $name );
  2026. $new_file = $upload['path'] . "/$filename";
  2027. if ( ! wp_mkdir_p( dirname( $new_file ) ) ) {
  2028. $message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), dirname( $new_file ) );
  2029. return array( 'error' => $message );
  2030. }
  2031. $ifp = @ fopen( $new_file, 'wb' );
  2032. if ( ! $ifp )
  2033. return array( 'error' => sprintf( __( 'Could not write file %s' ), $new_file ) );
  2034. @fwrite( $ifp, $bits );
  2035. fclose( $ifp );
  2036. clearstatcache();
  2037. // Set correct file permissions
  2038. $stat = @ stat( dirname( $new_file ) );
  2039. $perms = $stat['mode'] & 0007777;
  2040. $perms = $perms & 0000666;
  2041. @ chmod( $new_file, $perms );
  2042. clearstatcache();
  2043. // Compute the URL
  2044. $url = $upload['url'] . "/$filename";
  2045. return array( 'file' => $new_file, 'url' => $url, 'error' => false );
  2046. }
  2047. /**
  2048. * Retrieve the file type based on the extension name.
  2049. *
  2050. * @package WordPress
  2051. * @since 2.5.0
  2052. * @uses apply_filters() Calls 'ext2type' hook on default supported types.
  2053. *
  2054. * @param string $ext The extension to search.
  2055. * @return string|null The file type, example: audio, video, document, spreadsheet, etc. Null if not found.
  2056. */
  2057. function wp_ext2type( $ext ) {
  2058. $ext2type = apply_filters( 'ext2type', array(
  2059. 'audio' => array( 'aac', 'ac3', 'aif', 'aiff', 'm3a', 'm4a', 'm4b', 'mka', 'mp1', 'mp2', 'mp3', 'ogg', 'oga', 'ram', 'wav', 'wma' ),
  2060. 'video' => array( 'asf', 'avi', 'divx', 'dv', 'flv', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'mpv', 'ogm', 'ogv', 'qt', 'rm', 'vob', 'wmv' ),
  2061. 'document' => array( 'doc', 'docx', 'docm', 'dotm', 'odt', 'pages', 'pdf', 'rtf', 'wp', 'wpd' ),
  2062. 'spreadsheet' => array( 'numbers', 'ods', 'xls', 'xlsx', 'xlsb', 'xlsm' ),
  2063. 'interactive' => array( 'key', 'ppt', 'pptx', 'pptm', 'odp', 'swf' ),
  2064. 'text' => array( 'asc', 'csv', 'tsv', 'txt' ),
  2065. 'archive' => array( 'bz2', 'cab', 'dmg', 'gz', 'rar', 'sea', 'sit', 'sqx', 'tar', 'tgz', 'zip' ),
  2066. 'code' => array( 'css', 'htm', 'html', 'php', 'js' ),
  2067. ));
  2068. foreach ( $ext2type as $type => $exts )
  2069. if ( in_array( $ext, $exts ) )
  2070. return $type;
  2071. }
  2072. /**
  2073. * Retrieve the file type from the file name.
  2074. *
  2075. * You can optionally define the mime array, if needed.
  2076. *
  2077. * @since 2.0.4
  2078. *
  2079. * @param string $filename File name or path.
  2080. * @param array $mimes Optional. Key is the file extension with value as the mime type.
  2081. * @return array Values with extension first and mime type.
  2082. */
  2083. function wp_check_filetype( $filename, $mimes = null ) {
  2084. if ( empty($mimes) )
  2085. $mimes = get_allowed_mime_types();
  2086. $type = false;
  2087. $ext = false;
  2088. foreach ( $mimes as $ext_preg => $mime_match ) {
  2089. $ext_preg = '!\.(' . $ext_preg . ')$!i';
  2090. if ( preg_match( $ext_preg, $filename, $ext_matches ) ) {
  2091. $type = $mime_match;
  2092. $ext = $ext_matches[1];
  2093. break;
  2094. }
  2095. }
  2096. return compact( 'ext', 'type' );
  2097. }
  2098. /**
  2099. * Attempt to determine the real file type of a file.
  2100. * If unable to, the file name extension will be used to determine type.
  2101. *
  2102. * If it's determined that the extension does not match the file's real type,
  2103. * then the "proper_filename" value will be set with a proper filename and extension.
  2104. *
  2105. * Currently this function only supports validating images known to getimagesize().
  2106. *
  2107. * @since 3.0.0
  2108. *
  2109. * @param string $file Full path to the image.
  2110. * @param string $filename The filename of the image (may differ from $file due to $file being in a tmp directory)
  2111. * @param array $mimes Optional. Key is the file extension with value as the mime type.
  2112. * @return array Values for the extension, MIME, and either a corrected filename or false if original $filename is valid
  2113. */
  2114. function wp_check_filetype_and_ext( $file, $filename, $mimes = null ) {
  2115. $proper_filename = false;
  2116. // Do basic extension validation and MIME mapping
  2117. $wp_filetype = wp_check_filetype( $filename, $mimes );
  2118. extract( $wp_filetype );
  2119. // We can't do any further validation without a file to work with
  2120. if ( ! file_exists( $file ) )
  2121. return compact( 'ext', 'type', 'proper_filename' );
  2122. // We're able to validate images using GD
  2123. if ( $type && 0 === strpos( $type, 'image/' ) && function_exists('getimagesize') ) {
  2124. // Attempt to figure out what type of image it actually is
  2125. $imgstats = @getimagesize( $file );
  2126. // If getimagesize() knows what kind of image it really is and if the real MIME doesn't match the claimed MIME
  2127. if ( !empty($imgstats['mime']) && $imgstats['mime'] != $type ) {
  2128. // This is a simplified array of MIMEs that getimagesize() can detect and their extensions
  2129. // You shouldn't need to use this filter, but it's here just in case
  2130. $mime_to_ext = apply_filters( 'getimagesize_mimes_to_exts', array(
  2131. 'image/jpeg' => 'jpg',
  2132. 'image/png' => 'png',
  2133. 'image/gif' => 'gif',
  2134. 'image/bmp' => 'bmp',
  2135. 'image/tiff' => 'tif',
  2136. ) );
  2137. // Replace whatever is after the last period in the filename with the correct extension
  2138. if ( ! empty( $mime_to_ext[ $imgstats['mime'] ] ) ) {
  2139. $filename_parts = explode( '.', $filename );
  2140. array_pop( $filename_parts );
  2141. $filename_parts[] = $mime_to_ext[ $imgstats['mime'] ];
  2142. $new_filename = implode( '.', $filename_parts );
  2143. if ( $new_filename != $filename )
  2144. $proper_filename = $new_filename; // Mark that it changed
  2145. // Redefine the extension / MIME
  2146. $wp_filetype = wp_check_filetype( $new_filename, $mimes );
  2147. extract( $wp_filetype );
  2148. }
  2149. }
  2150. }
  2151. // Let plugins try and validate other types of files
  2152. // Should return an array in the style of array( 'ext' => $ext, 'type' => $type, 'proper_filename' => $proper_filename )
  2153. return apply_filters( 'wp_check_filetype_and_ext', compact( 'ext', 'type', 'proper_filename' ), $file, $filename, $mimes );
  2154. }
  2155. /**
  2156. * Retrieve list of allowed mime types and file extensions.
  2157. *
  2158. * @since 2.8.6
  2159. *
  2160. * @return array Array of mime types keyed by the file extension regex corresponding to those types.
  2161. */
  2162. function get_allowed_mime_types() {
  2163. static $mimes = false;
  2164. if ( !$mimes ) {
  2165. // Accepted MIME types are set here as PCRE unless provided.
  2166. $mimes = apply_filters( 'upload_mimes', array(
  2167. 'jpg|jpeg|jpe' => 'image/jpeg',
  2168. 'gif' => 'image/gif',
  2169. 'png' => 'image/png',
  2170. 'bmp' => 'image/bmp',
  2171. 'tif|tiff' => 'image/tiff',
  2172. 'ico' => 'image/x-icon',
  2173. 'asf|asx|wax|wmv|wmx' => 'video/asf',
  2174. 'avi' => 'video/avi',
  2175. 'divx' => 'video/divx',
  2176. 'flv' => 'video/x-flv',
  2177. 'mov|qt' => 'video/quicktime',
  2178. 'mpeg|mpg|mpe' => 'video/mpeg',
  2179. 'txt|asc|c|cc|h' => 'text/plain',
  2180. 'csv' => 'text/csv',
  2181. 'tsv' => 'text/tab-separated-values',
  2182. 'rtx' => 'text/richtext',
  2183. 'css' => 'text/css',
  2184. 'htm|html' => 'text/html',
  2185. 'mp3|m4a|m4b' => 'audio/mpeg',
  2186. 'mp4|m4v' => 'video/mp4',
  2187. 'ra|ram' => 'audio/x-realaudio',
  2188. 'wav' => 'audio/wav',
  2189. 'ogg|oga' => 'audio/ogg',
  2190. 'ogv' => 'video/ogg',
  2191. 'mid|midi' => 'audio/midi',
  2192. 'wma' => 'audio/wma',
  2193. 'mka' => 'audio/x-matroska',
  2194. 'mkv' => 'video/x-matroska',
  2195. 'rtf' => 'application/rtf',
  2196. 'js' => 'application/javascript',
  2197. 'pdf' => 'application/pdf',
  2198. 'doc|docx' => 'application/msword',
  2199. 'pot|pps|ppt|pptx|ppam|pptm|sldm|ppsm|potm' => 'application/vnd.ms-powerpoint',
  2200. 'wri' => 'application/vnd.ms-write',
  2201. 'xla|xls|xlsx|xlt|xlw|xlam|xlsb|xlsm|xltm' => 'application/vnd.ms-excel',
  2202. 'mdb' => 'application/vnd.ms-access',
  2203. 'mpp' => 'application/vnd.ms-project',
  2204. 'docm|dotm' => 'application/vnd.ms-word',
  2205. 'pptx|sldx|ppsx|potx' => 'application/vnd.openxmlformats-officedocument.presentationml',
  2206. 'xlsx|xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml',
  2207. 'docx|dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml',
  2208. 'onetoc|onetoc2|onetmp|onepkg' => 'application/onenote',
  2209. 'swf' => 'application/x-shockwave-flash',
  2210. 'class' => 'application/java',
  2211. 'tar' => 'application/x-tar',
  2212. 'zip' => 'application/zip',
  2213. 'gz|gzip' => 'application/x-gzip',
  2214. 'exe' => 'application/x-msdownload',
  2215. // openoffice formats
  2216. 'odt' => 'application/vnd.oasis.opendocument.text',
  2217. 'odp' => 'application/vnd.oasis.opendocument.presentation',
  2218. 'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
  2219. 'odg' => 'application/vnd.oasis.opendocument.graphics',
  2220. 'odc' => 'application/vnd.oasis.opendocument.chart',
  2221. 'odb' => 'application/vnd.oasis.opendocument.database',
  2222. 'odf' => 'application/vnd.oasis.opendocument.formula',
  2223. // wordperfect formats
  2224. 'wp|wpd' => 'application/wordperfect',
  2225. ) );
  2226. }
  2227. return $mimes;
  2228. }
  2229. /**
  2230. * Retrieve nonce action "Are you sure" message.
  2231. *
  2232. * The action is split by verb and noun. The action format is as follows:
  2233. * verb-action_extra. The verb is before the first dash and has the format of
  2234. * letters and no spaces and numbers. The noun is after the dash and before the
  2235. * underscore, if an underscore exists. The noun is also only letters.
  2236. *
  2237. * The filter will be called for any action, which is not defined by WordPress.
  2238. * You may use the filter for your plugin to explain nonce actions to the user,
  2239. * when they get the "Are you sure?" message. The filter is in the format of
  2240. * 'explain_nonce_$verb-$noun' with the $verb replaced by the found verb and the
  2241. * $noun replaced by the found noun. The two parameters that are given to the
  2242. * hook are the localized "Are you sure you want to do this?" message with the
  2243. * extra text (the text after the underscore).
  2244. *
  2245. * @package WordPress
  2246. * @subpackage Security
  2247. * @since 2.0.4
  2248. *
  2249. * @param string $action Nonce action.
  2250. * @return string Are you sure message.
  2251. */
  2252. function wp_explain_nonce( $action ) {
  2253. if ( $action !== -1 && preg_match( '/([a-z]+)-([a-z]+)(_(.+))?/', $action, $matches ) ) {
  2254. $verb = $matches[1];
  2255. $noun = $matches[2];
  2256. $trans = array();
  2257. $trans['update']['attachment'] = array( __( 'Your attempt to edit this attachment: &#8220;%s&#8221; has failed.' ), 'get_the_title' );
  2258. $trans['add']['category'] = array( __( 'Your attempt to add this category has failed.' ), false );
  2259. $trans['delete']['category'] = array( __( 'Your attempt to delete this category: &#8220;%s&#8221; has failed.' ), 'get_cat_name' );
  2260. $trans['update']['category'] = array( __( 'Your attempt to edit this category: &#8220;%s&#8221; has failed.' ), 'get_cat_name' );
  2261. $trans['delete']['comment'] = array( __( 'Your attempt to delete this comment: &#8220;%s&#8221; has failed.' ), 'use_id' );
  2262. $trans['unapprove']['comment'] = array( __( 'Your attempt to unapprove this comment: &#8220;%s&#8221; has failed.' ), 'use_id' );
  2263. $trans['approve']['comment'] = array( __( 'Your attempt to approve this comment: &#8220;%s&#8221; has failed.' ), 'use_id' );
  2264. $trans['update']['comment'] = array( __( 'Your attempt to edit this comment: &#8220;%s&#8221; has failed.' ), 'use_id' );
  2265. $trans['bulk']['comments'] = array( __( 'Your attempt to bulk modify comments has failed.' ), false );
  2266. $trans['moderate']['comments'] = array( __( 'Your attempt to moderate comments has failed.' ), false );
  2267. $trans['add']['bookmark'] = array( __( 'Your attempt to add this link has failed.' ), false );
  2268. $trans['delete']['bookmark'] = array( __( 'Your attempt to delete this link: &#8220;%s&#8221; has failed.' ), 'use_id' );
  2269. $trans['update']['bookmark'] = array( __( 'Your attempt to edit this link: &#8220;%s&#8221; has failed.' ), 'use_id' );
  2270. $trans['bulk']['bookmarks'] = array( __( 'Your attempt to bulk modify links has failed.' ), false );
  2271. $trans['add']['page'] = array( __( 'Your attempt to add this page has failed.' ), false );
  2272. $trans['delete']['page'] = array( __( 'Your attempt to delete this page: &#8220;%s&#8221; has failed.' ), 'get_the_title' );
  2273. $trans['update']['page'] = array( __( 'Your attempt to edit this page: &#8220;%s&#8221; has failed.' ), 'get_the_title' );
  2274. $trans['edit']['plugin'] = array( __( 'Your attempt to edit this plugin file: &#8220;%s&#8221; has failed.' ), 'use_id' );
  2275. $trans['activate']['plugin'] = array( __( 'Your attempt to activate this plugin: &#8220;%s&#8221; has failed.' ), 'use_id' );
  2276. $trans['deactivate']['plugin'] = array( __( 'Your attempt to deactivate this plugin: &#8220;%s&#8221; has failed.' ), 'use_id' );
  2277. $trans['upgrade']['plugin'] = array( __( 'Your attempt to upgrade this plugin: &#8220;%s&#8221; has failed.' ), 'use_id' );
  2278. $trans['add']['post'] = array( __( 'Your attempt to add this post has failed.' ), false );
  2279. $trans['delete']['post'] = array( __( 'Your attempt to delete this post: &#8220;%s&#8221; has failed.' ), 'get_the_title' );
  2280. $trans['update']['post'] = array( __( 'Your attempt to edit this post: &#8220;%s&#8221; has failed.' ), 'get_the_title' );
  2281. $trans['add']['user'] = array( __( 'Your attempt to add this user has failed.' ), false );
  2282. $trans['delete']['users'] = array( __( 'Your attempt to delete users has failed.' ), false );
  2283. $trans['bulk']['users'] = array( __( 'Your attempt to bulk modify users has failed.' ), false );
  2284. $trans['update']['user'] = array( __( 'Your attempt to edit this user: &#8220;%s&#8221; has failed.' ), 'get_the_author_meta', 'display_name' );
  2285. $trans['update']['profile'] = array( __( 'Your attempt to modify the profile for: &#8220;%s&#8221; has failed.' ), 'get_the_author_meta', 'display_name' );
  2286. $trans['update']['options'] = array( __( 'Your attempt to edit your settings has failed.' ), false );
  2287. $trans['update']['permalink'] = array( __( 'Your attempt to change your permalink structure to: %s has failed.' ), 'use_id' );
  2288. $trans['edit']['file'] = array( __( 'Your attempt to edit this file: &#8220;%s&#8221; has failed.' ), 'use_id' );
  2289. $trans['edit']['theme'] = array( __( 'Your attempt to edit this theme file: &#8220;%s&#8221; has failed.' ), 'use_id' );
  2290. $trans['switch']['theme'] = array( __( 'Your attempt to switch to this theme: &#8220;%s&#8221; has failed.' ), 'use_id' );
  2291. $trans['log']['out'] = array( sprintf( __( 'You are attempting to log out of %s' ), get_bloginfo( 'sitename' ) ), false );
  2292. if ( isset( $trans[$verb][$noun] ) ) {
  2293. if ( !empty( $trans[$verb][$noun][1] ) ) {
  2294. $lookup = $trans[$verb][$noun][1];
  2295. if ( isset($trans[$verb][$noun][2]) )
  2296. $lookup_value = $trans[$verb][$noun][2];
  2297. $object = $matches[4];
  2298. if ( 'use_id' != $lookup ) {
  2299. if ( isset( $lookup_value ) )
  2300. $object = call_user_func( $lookup, $lookup_value, $object );
  2301. else
  2302. $object = call_user_func( $lookup, $object );
  2303. }
  2304. return sprintf( $trans[$verb][$noun][0], esc_html($object) );
  2305. } else {
  2306. return $trans[$verb][$noun][0];
  2307. }
  2308. }
  2309. return apply_filters( 'explain_nonce_' . $verb . '-' . $noun, __( 'Are you sure you want to do this?' ), isset($matches[4]) ? $matches[4] : '' );
  2310. } else {
  2311. return apply_filters( 'explain_nonce_' . $action, __( 'Are you sure you want to do this?' ) );
  2312. }
  2313. }
  2314. /**
  2315. * Display "Are You Sure" message to confirm the action being taken.
  2316. *
  2317. * If the action has the nonce explain message, then it will be displayed along
  2318. * with the "Are you sure?" message.
  2319. *
  2320. * @package WordPress
  2321. * @subpackage Security
  2322. * @since 2.0.4
  2323. *
  2324. * @param string $action The nonce action.
  2325. */
  2326. function wp_nonce_ays( $action ) {
  2327. $title = __( 'WordPress Failure Notice' );
  2328. $html = esc_html( wp_explain_nonce( $action ) );
  2329. if ( 'log-out' == $action )
  2330. $html .= "</p><p>" . sprintf( __( "Do you really want to <a href='%s'>log out</a>?"), wp_logout_url() );
  2331. elseif ( wp_get_referer() )
  2332. $html .= "</p><p><a href='" . esc_url( remove_query_arg( 'updated', wp_get_referer() ) ) . "'>" . __( 'Please try again.' ) . "</a>";
  2333. wp_die( $html, $title, array('response' => 403) );
  2334. }
  2335. /**
  2336. * Kill WordPress execution and display HTML message with error message.
  2337. *
  2338. * This function complements the die() PHP function. The difference is that
  2339. * HTML will be displayed to the user. It is recommended to use this function
  2340. * only, when the execution should not continue any further. It is not
  2341. * recommended to call this function very often and try to handle as many errors
  2342. * as possible siliently.
  2343. *
  2344. * @since 2.0.4
  2345. *
  2346. * @param string $message Error message.
  2347. * @param string $title Error title.
  2348. * @param string|array $args Optional arguements to control behaviour.
  2349. */
  2350. function wp_die( $message, $title = '', $args = array() ) {
  2351. if ( function_exists( 'apply_filters' ) ) {
  2352. $function = apply_filters( 'wp_die_handler', '_default_wp_die_handler');
  2353. }else {
  2354. $function = '_default_wp_die_handler';
  2355. }
  2356. call_user_func( $function, $message, $title, $args );
  2357. }
  2358. /**
  2359. * Kill WordPress execution and display HTML message with error message.
  2360. *
  2361. * This is the default handler for wp_die if you want a custom one for your
  2362. * site then you can overload using the wp_die_handler filter in wp_die
  2363. *
  2364. * @since 3.0.0
  2365. * @access private
  2366. *
  2367. * @param string $message Error message.
  2368. * @param string $title Error title.
  2369. * @param string|array $args Optional arguements to control behaviour.
  2370. */
  2371. function _default_wp_die_handler( $message, $title = '', $args = array() ) {
  2372. $defaults = array( 'response' => 500 );
  2373. $r = wp_parse_args($args, $defaults);
  2374. $have_gettext = function_exists('__');
  2375. if ( function_exists( 'is_wp_error' ) && is_wp_error( $message ) ) {
  2376. if ( empty( $title ) ) {
  2377. $error_data = $message->get_error_data();
  2378. if ( is_array( $error_data ) && isset( $error_data['title'] ) )
  2379. $title = $error_data['title'];
  2380. }
  2381. $errors = $message->get_error_messages();
  2382. switch ( count( $errors ) ) :
  2383. case 0 :
  2384. $message = '';
  2385. break;
  2386. case 1 :
  2387. $message = "<p>{$errors[0]}</p>";
  2388. break;
  2389. default :
  2390. $message = "<ul>\n\t\t<li>" . join( "</li>\n\t\t<li>", $errors ) . "</li>\n\t</ul>";
  2391. break;
  2392. endswitch;
  2393. } elseif ( is_string( $message ) ) {
  2394. $message = "<p>$message</p>";
  2395. }
  2396. if ( isset( $r['back_link'] ) && $r['back_link'] ) {
  2397. $back_text = $have_gettext? __('&laquo; Back') : '&laquo; Back';
  2398. $message .= "\n<p><a href='javascript:history.back()'>$back_text</p>";
  2399. }
  2400. if ( defined( 'WP_SITEURL' ) && '' != WP_SITEURL )
  2401. $admin_dir = WP_SITEURL . '/wp-admin/';
  2402. elseif ( function_exists( 'get_bloginfo' ) && '' != get_bloginfo( 'wpurl' ) )
  2403. $admin_dir = get_bloginfo( 'wpurl' ) . '/wp-admin/';
  2404. elseif ( strpos( $_SERVER['PHP_SELF'], 'wp-admin' ) !== false )
  2405. $admin_dir = '';
  2406. else
  2407. $admin_dir = 'wp-admin/';
  2408. if ( !function_exists( 'did_action' ) || !did_action( 'admin_head' ) ) :
  2409. if ( !headers_sent() ) {
  2410. status_header( $r['response'] );
  2411. nocache_headers();
  2412. header( 'Content-Type: text/html; charset=utf-8' );
  2413. }
  2414. if ( empty($title) )
  2415. $title = $have_gettext ? __('WordPress &rsaquo; Error') : 'WordPress &rsaquo; Error';
  2416. $text_direction = 'ltr';
  2417. if ( isset($r['text_direction']) && 'rtl' == $r['text_direction'] )
  2418. $text_direction = 'rtl';
  2419. elseif ( function_exists( 'is_rtl' ) && is_rtl() )
  2420. $text_direction = 'rtl';
  2421. ?>
  2422. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2423. <!-- Ticket #11289, IE bug fix: always pad the error page with enough characters such that it is greater than 512 bytes, even after gzip compression abcdefghijklmnopqrstuvwxyz1234567890aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz11223344556677889900abacbcbdcdcededfefegfgfhghgihihjijikjkjlklkmlmlnmnmononpopoqpqprqrqsrsrtstsubcbcdcdedefefgfabcadefbghicjkldmnoepqrfstugvwxhyz1i234j567k890laabmbccnddeoeffpgghqhiirjjksklltmmnunoovppqwqrrxsstytuuzvvw0wxx1yyz2z113223434455666777889890091abc2def3ghi4jkl5mno6pqr7stu8vwx9yz11aab2bcc3dd4ee5ff6gg7hh8ii9j0jk1kl2lmm3nnoo4p5pq6qrr7ss8tt9uuvv0wwx1x2yyzz13aba4cbcb5dcdc6dedfef8egf9gfh0ghg1ihi2hji3jik4jkj5lkl6kml7mln8mnm9ono -->
  2424. <html xmlns="http://www.w3.org/1999/xhtml" <?php if ( function_exists( 'language_attributes' ) ) language_attributes(); ?>>
  2425. <head>
  2426. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  2427. <title><?php echo $title ?></title>
  2428. <link rel="stylesheet" href="<?php echo $admin_dir; ?>css/install.css" type="text/css" />
  2429. <?php
  2430. if ( 'rtl' == $text_direction ) : ?>
  2431. <link rel="stylesheet" href="<?php echo $admin_dir; ?>css/install-rtl.css" type="text/css" />
  2432. <?php endif; ?>
  2433. </head>
  2434. <body id="error-page">
  2435. <?php endif; ?>
  2436. <?php echo $message; ?>
  2437. </body>
  2438. </html>
  2439. <?php
  2440. die();
  2441. }
  2442. /**
  2443. * Retrieve the WordPress home page URL.
  2444. *
  2445. * If the constant named 'WP_HOME' exists, then it willl be used and returned by
  2446. * the function. This can be used to counter the redirection on your local
  2447. * development environment.
  2448. *
  2449. * @access private
  2450. * @package WordPress
  2451. * @since 2.2.0
  2452. *
  2453. * @param string $url URL for the home location
  2454. * @return string Homepage location.
  2455. */
  2456. function _config_wp_home( $url = '' ) {
  2457. if ( defined( 'WP_HOME' ) )
  2458. return WP_HOME;
  2459. return $url;
  2460. }
  2461. /**
  2462. * Retrieve the WordPress site URL.
  2463. *
  2464. * If the constant named 'WP_SITEURL' is defined, then the value in that
  2465. * constant will always be returned. This can be used for debugging a site on
  2466. * your localhost while not having to change the database to your URL.
  2467. *
  2468. * @access private
  2469. * @package WordPress
  2470. * @since 2.2.0
  2471. *
  2472. * @param string $url URL to set the WordPress site location.
  2473. * @return string The WordPress Site URL
  2474. */
  2475. function _config_wp_siteurl( $url = '' ) {
  2476. if ( defined( 'WP_SITEURL' ) )
  2477. return WP_SITEURL;
  2478. return $url;
  2479. }
  2480. /**
  2481. * Set the localized direction for MCE plugin.
  2482. *
  2483. * Will only set the direction to 'rtl', if the WordPress locale has the text
  2484. * direction set to 'rtl'.
  2485. *
  2486. * Fills in the 'directionality', 'plugins', and 'theme_advanced_button1' array
  2487. * keys. These keys are then returned in the $input array.
  2488. *
  2489. * @access private
  2490. * @package WordPress
  2491. * @subpackage MCE
  2492. * @since 2.1.0
  2493. *
  2494. * @param array $input MCE plugin array.
  2495. * @return array Direction set for 'rtl', if needed by locale.
  2496. */
  2497. function _mce_set_direction( $input ) {
  2498. if ( is_rtl() ) {
  2499. $input['directionality'] = 'rtl';
  2500. $input['plugins'] .= ',directionality';
  2501. $input['theme_advanced_buttons1'] .= ',ltr';
  2502. }
  2503. return $input;
  2504. }
  2505. /**
  2506. * Convert smiley code to the icon graphic file equivalent.
  2507. *
  2508. * You can turn off smilies, by going to the write setting screen and unchecking
  2509. * the box, or by setting 'use_smilies' option to false or removing the option.
  2510. *
  2511. * Plugins may override the default smiley list by setting the $wpsmiliestrans
  2512. * to an array, with the key the code the blogger types in and the value the
  2513. * image file.
  2514. *
  2515. * The $wp_smiliessearch global is for the regular expression and is set each
  2516. * time the function is called.
  2517. *
  2518. * The full list of smilies can be found in the function and won't be listed in
  2519. * the description. Probably should create a Codex page for it, so that it is
  2520. * available.
  2521. *
  2522. * @global array $wpsmiliestrans
  2523. * @global array $wp_smiliessearch
  2524. * @since 2.2.0
  2525. */
  2526. function smilies_init() {
  2527. global $wpsmiliestrans, $wp_smiliessearch;
  2528. // don't bother setting up smilies if they are disabled
  2529. if ( !get_option( 'use_smilies' ) )
  2530. return;
  2531. if ( !isset( $wpsmiliestrans ) ) {
  2532. $wpsmiliestrans = array(
  2533. ':mrgreen:' => 'icon_mrgreen.gif',
  2534. ':neutral:' => 'icon_neutral.gif',
  2535. ':twisted:' => 'icon_twisted.gif',
  2536. ':arrow:' => 'icon_arrow.gif',
  2537. ':shock:' => 'icon_eek.gif',
  2538. ':smile:' => 'icon_smile.gif',
  2539. ':???:' => 'icon_confused.gif',
  2540. ':cool:' => 'icon_cool.gif',
  2541. ':evil:' => 'icon_evil.gif',
  2542. ':grin:' => 'icon_biggrin.gif',
  2543. ':idea:' => 'icon_idea.gif',
  2544. ':oops:' => 'icon_redface.gif',
  2545. ':razz:' => 'icon_razz.gif',
  2546. ':roll:' => 'icon_rolleyes.gif',
  2547. ':wink:' => 'icon_wink.gif',
  2548. ':cry:' => 'icon_cry.gif',
  2549. ':eek:' => 'icon_surprised.gif',
  2550. ':lol:' => 'icon_lol.gif',
  2551. ':mad:' => 'icon_mad.gif',
  2552. ':sad:' => 'icon_sad.gif',
  2553. '8-)' => 'icon_cool.gif',
  2554. '8-O' => 'icon_eek.gif',
  2555. ':-(' => 'icon_sad.gif',
  2556. ':-)' => 'icon_smile.gif',
  2557. ':-?' => 'icon_confused.gif',
  2558. ':-D' => 'icon_biggrin.gif',
  2559. ':-P' => 'icon_razz.gif',
  2560. ':-o' => 'icon_surprised.gif',
  2561. ':-x' => 'icon_mad.gif',
  2562. ':-|' => 'icon_neutral.gif',
  2563. ';-)' => 'icon_wink.gif',
  2564. '8)' => 'icon_cool.gif',
  2565. '8O' => 'icon_eek.gif',
  2566. ':(' => 'icon_sad.gif',
  2567. ':)' => 'icon_smile.gif',
  2568. ':?' => 'icon_confused.gif',
  2569. ':D' => 'icon_biggrin.gif',
  2570. ':P' => 'icon_razz.gif',
  2571. ':o' => 'icon_surprised.gif',
  2572. ':x' => 'icon_mad.gif',
  2573. ':|' => 'icon_neutral.gif',
  2574. ';)' => 'icon_wink.gif',
  2575. ':!:' => 'icon_exclaim.gif',
  2576. ':?:' => 'icon_question.gif',
  2577. );
  2578. }
  2579. if (count($wpsmiliestrans) == 0) {
  2580. return;
  2581. }
  2582. /*
  2583. * NOTE: we sort the smilies in reverse key order. This is to make sure
  2584. * we match the longest possible smilie (:???: vs :?) as the regular
  2585. * expression used below is first-match
  2586. */
  2587. krsort($wpsmiliestrans);
  2588. $wp_smiliessearch = '/(?:\s|^)';
  2589. $subchar = '';
  2590. foreach ( (array) $wpsmiliestrans as $smiley => $img ) {
  2591. $firstchar = substr($smiley, 0, 1);
  2592. $rest = substr($smiley, 1);
  2593. // new subpattern?
  2594. if ($firstchar != $subchar) {
  2595. if ($subchar != '') {
  2596. $wp_smiliessearch .= ')|(?:\s|^)';
  2597. }
  2598. $subchar = $firstchar;
  2599. $wp_smiliessearch .= preg_quote($firstchar, '/') . '(?:';
  2600. } else {
  2601. $wp_smiliessearch .= '|';
  2602. }
  2603. $wp_smiliessearch .= preg_quote($rest, '/');
  2604. }
  2605. $wp_smiliessearch .= ')(?:\s|$)/m';
  2606. }
  2607. /**
  2608. * Merge user defined arguments into defaults array.
  2609. *
  2610. * This function is used throughout WordPress to allow for both string or array
  2611. * to be merged into another array.
  2612. *
  2613. * @since 2.2.0
  2614. *
  2615. * @param string|array $args Value to merge with $defaults
  2616. * @param array $defaults Array that serves as the defaults.
  2617. * @return array Merged user defined values with defaults.
  2618. */
  2619. function wp_parse_args( $args, $defaults = '' ) {
  2620. if ( is_object( $args ) )
  2621. $r = get_object_vars( $args );
  2622. elseif ( is_array( $args ) )
  2623. $r =& $args;
  2624. else
  2625. wp_parse_str( $args, $r );
  2626. if ( is_array( $defaults ) )
  2627. return array_merge( $defaults, $r );
  2628. return $r;
  2629. }
  2630. /**
  2631. * Clean up an array, comma- or space-separated list of IDs
  2632. *
  2633. * @since 3.0.0
  2634. *
  2635. * @param array|string $list
  2636. * @return array Sanitized array of IDs
  2637. */
  2638. function wp_parse_id_list( $list ) {
  2639. if ( !is_array($list) )
  2640. $list = preg_split('/[\s,]+/', $list);
  2641. return array_unique(array_map('absint', $list));
  2642. }
  2643. /**
  2644. * Filters a list of objects, based on a set of key => value arguments
  2645. *
  2646. * @since 3.0.0
  2647. *
  2648. * @param array $list An array of objects to filter
  2649. * @param array $args An array of key => value arguments to match against each object
  2650. * @param string $operator The logical operation to perform. 'or' means only one element
  2651. * from the array needs to match; 'and' means all elements must match. The default is 'and'.
  2652. * @param bool|string $field A field from the object to place instead of the entire object
  2653. * @return array A list of objects or object fields
  2654. */
  2655. function wp_filter_object_list( $list, $args = array(), $operator = 'and', $field = false ) {
  2656. if ( !is_array($list) )
  2657. return array();
  2658. if ( empty($args) )
  2659. $args = array();
  2660. if ( empty($args) && !$field )
  2661. return $list; // nothing to do
  2662. $count = count($args);
  2663. $filtered = array();
  2664. foreach ( $list as $key => $obj ) {
  2665. $matched = count(array_intersect_assoc(get_object_vars($obj), $args));
  2666. if ( ('and' == $operator && $matched == $count) || ('or' == $operator && $matched <= $count) ) {
  2667. if ( $field )
  2668. $filtered[] = $obj->$field;
  2669. else
  2670. $filtered[$key] = $obj;
  2671. }
  2672. }
  2673. return $filtered;
  2674. }
  2675. /**
  2676. * Determines if default embed handlers should be loaded.
  2677. *
  2678. * Checks to make sure that the embeds library hasn't already been loaded. If
  2679. * it hasn't, then it will load the embeds library.
  2680. *
  2681. * @since 2.9.0
  2682. */
  2683. function wp_maybe_load_embeds() {
  2684. if ( ! apply_filters('load_default_embeds', true) )
  2685. return;
  2686. require_once( ABSPATH . WPINC . '/default-embeds.php' );
  2687. }
  2688. /**
  2689. * Determines if Widgets library should be loaded.
  2690. *
  2691. * Checks to make sure that the widgets library hasn't already been loaded. If
  2692. * it hasn't, then it will load the widgets library and run an action hook.
  2693. *
  2694. * @since 2.2.0
  2695. * @uses add_action() Calls '_admin_menu' hook with 'wp_widgets_add_menu' value.
  2696. */
  2697. function wp_maybe_load_widgets() {
  2698. if ( ! apply_filters('load_default_widgets', true) )
  2699. return;
  2700. require_once( ABSPATH . WPINC . '/default-widgets.php' );
  2701. add_action( '_admin_menu', 'wp_widgets_add_menu' );
  2702. }
  2703. /**
  2704. * Append the Widgets menu to the themes main menu.
  2705. *
  2706. * @since 2.2.0
  2707. * @uses $submenu The administration submenu list.
  2708. */
  2709. function wp_widgets_add_menu() {
  2710. global $submenu;
  2711. $submenu['themes.php'][7] = array( __( 'Widgets' ), 'edit_theme_options', 'widgets.php' );
  2712. ksort( $submenu['themes.php'], SORT_NUMERIC );
  2713. }
  2714. /**
  2715. * Flush all output buffers for PHP 5.2.
  2716. *
  2717. * Make sure all output buffers are flushed before our singletons our destroyed.
  2718. *
  2719. * @since 2.2.0
  2720. */
  2721. function wp_ob_end_flush_all() {
  2722. $levels = ob_get_level();
  2723. for ($i=0; $i<$levels; $i++)
  2724. ob_end_flush();
  2725. }
  2726. /**
  2727. * Load the correct database class file.
  2728. *
  2729. * This function is used to load the database class file either at runtime or by
  2730. * wp-admin/setup-config.php We must globalise $wpdb to ensure that it is
  2731. * defined globally by the inline code in wp-db.php.
  2732. *
  2733. * @since 2.5.0
  2734. * @global $wpdb WordPress Database Object
  2735. */
  2736. function require_wp_db() {
  2737. global $wpdb;
  2738. if ( file_exists( WP_CONTENT_DIR . '/db.php' ) )
  2739. require_once( WP_CONTENT_DIR . '/db.php' );
  2740. else
  2741. require_once( ABSPATH . WPINC . '/wp-db.php' );
  2742. }
  2743. /**
  2744. * Load custom DB error or display WordPress DB error.
  2745. *
  2746. * If a file exists in the wp-content directory named db-error.php, then it will
  2747. * be loaded instead of displaying the WordPress DB error. If it is not found,
  2748. * then the WordPress DB error will be displayed instead.
  2749. *
  2750. * The WordPress DB error sets the HTTP status header to 500 to try to prevent
  2751. * search engines from caching the message. Custom DB messages should do the
  2752. * same.
  2753. *
  2754. * This function was backported to the the WordPress 2.3.2, but originally was
  2755. * added in WordPress 2.5.0.
  2756. *
  2757. * @since 2.3.2
  2758. * @uses $wpdb
  2759. */
  2760. function dead_db() {
  2761. global $wpdb;
  2762. // Load custom DB error template, if present.
  2763. if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
  2764. require_once( WP_CONTENT_DIR . '/db-error.php' );
  2765. die();
  2766. }
  2767. // If installing or in the admin, provide the verbose message.
  2768. if ( defined('WP_INSTALLING') || defined('WP_ADMIN') )
  2769. wp_die($wpdb->error);
  2770. // Otherwise, be terse.
  2771. status_header( 500 );
  2772. nocache_headers();
  2773. header( 'Content-Type: text/html; charset=utf-8' );
  2774. ?>
  2775. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2776. <html xmlns="http://www.w3.org/1999/xhtml" <?php if ( function_exists( 'language_attributes' ) ) language_attributes(); ?>>
  2777. <head>
  2778. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  2779. <title>Database Error</title>
  2780. </head>
  2781. <body>
  2782. <h1>Error establishing a database connection</h1>
  2783. </body>
  2784. </html>
  2785. <?php
  2786. die();
  2787. }
  2788. /**
  2789. * Converts value to nonnegative integer.
  2790. *
  2791. * @since 2.5.0
  2792. *
  2793. * @param mixed $maybeint Data you wish to have convered to an nonnegative integer
  2794. * @return int An nonnegative integer
  2795. */
  2796. function absint( $maybeint ) {
  2797. return abs( intval( $maybeint ) );
  2798. }
  2799. /**
  2800. * Determines if the blog can be accessed over SSL.
  2801. *
  2802. * Determines if blog can be accessed over SSL by using cURL to access the site
  2803. * using the https in the siteurl. Requires cURL extension to work correctly.
  2804. *
  2805. * @since 2.5.0
  2806. *
  2807. * @param string $url
  2808. * @return bool Whether SSL access is available
  2809. */
  2810. function url_is_accessable_via_ssl($url)
  2811. {
  2812. if (in_array('curl', get_loaded_extensions())) {
  2813. $ssl = preg_replace( '/^http:\/\//', 'https://', $url );
  2814. $ch = curl_init();
  2815. curl_setopt($ch, CURLOPT_URL, $ssl);
  2816. curl_setopt($ch, CURLOPT_FAILONERROR, true);
  2817. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  2818. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  2819. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
  2820. curl_exec($ch);
  2821. $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  2822. curl_close ($ch);
  2823. if ($status == 200 || $status == 401) {
  2824. return true;
  2825. }
  2826. }
  2827. return false;
  2828. }
  2829. /**
  2830. * Secure URL, if available or the given URL.
  2831. *
  2832. * @since 2.5.0
  2833. *
  2834. * @param string $url Complete URL path with transport.
  2835. * @return string Secure or regular URL path.
  2836. */
  2837. function atom_service_url_filter($url)
  2838. {
  2839. if ( url_is_accessable_via_ssl($url) )
  2840. return preg_replace( '/^http:\/\//', 'https://', $url );
  2841. else
  2842. return $url;
  2843. }
  2844. /**
  2845. * Marks a function as deprecated and informs when it has been used.
  2846. *
  2847. * There is a hook deprecated_function_run that will be called that can be used
  2848. * to get the backtrace up to what file and function called the deprecated
  2849. * function.
  2850. *
  2851. * The current behavior is to trigger an user error if WP_DEBUG is true.
  2852. *
  2853. * This function is to be used in every function in depreceated.php
  2854. *
  2855. * @package WordPress
  2856. * @subpackage Debug
  2857. * @since 2.5.0
  2858. * @access private
  2859. *
  2860. * @uses do_action() Calls 'deprecated_function_run' and passes the function name, what to use instead,
  2861. * and the version the function was deprecated in.
  2862. * @uses apply_filters() Calls 'deprecated_function_trigger_error' and expects boolean value of true to do
  2863. * trigger or false to not trigger error.
  2864. *
  2865. * @param string $function The function that was called
  2866. * @param string $version The version of WordPress that deprecated the function
  2867. * @param string $replacement Optional. The function that should have been called
  2868. */
  2869. function _deprecated_function( $function, $version, $replacement=null ) {
  2870. do_action( 'deprecated_function_run', $function, $replacement, $version );
  2871. // Allow plugin to filter the output error trigger
  2872. if ( WP_DEBUG && apply_filters( 'deprecated_function_trigger_error', true ) ) {
  2873. if ( ! is_null($replacement) )
  2874. trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.'), $function, $version, $replacement ) );
  2875. else
  2876. trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.'), $function, $version ) );
  2877. }
  2878. }
  2879. /**
  2880. * Marks a file as deprecated and informs when it has been used.
  2881. *
  2882. * There is a hook deprecated_file_included that will be called that can be used
  2883. * to get the backtrace up to what file and function included the deprecated
  2884. * file.
  2885. *
  2886. * The current behavior is to trigger an user error if WP_DEBUG is true.
  2887. *
  2888. * This function is to be used in every file that is depreceated
  2889. *
  2890. * @package WordPress
  2891. * @subpackage Debug
  2892. * @since 2.5.0
  2893. * @access private
  2894. *
  2895. * @uses do_action() Calls 'deprecated_file_included' and passes the file name, what to use instead,
  2896. * the version in which the file was deprecated, and any message regarding the change.
  2897. * @uses apply_filters() Calls 'deprecated_file_trigger_error' and expects boolean value of true to do
  2898. * trigger or false to not trigger error.
  2899. *
  2900. * @param string $file The file that was included
  2901. * @param string $version The version of WordPress that deprecated the file
  2902. * @param string $replacement Optional. The file that should have been included based on ABSPATH
  2903. * @param string $message Optional. A message regarding the change
  2904. */
  2905. function _deprecated_file( $file, $version, $replacement = null, $message = '' ) {
  2906. do_action( 'deprecated_file_included', $file, $replacement, $version, $message );
  2907. // Allow plugin to filter the output error trigger
  2908. if ( WP_DEBUG && apply_filters( 'deprecated_file_trigger_error', true ) ) {
  2909. $message = empty( $message ) ? '' : ' ' . $message;
  2910. if ( ! is_null( $replacement ) )
  2911. trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.'), $file, $version, $replacement ) . $message );
  2912. else
  2913. trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.'), $file, $version ) . $message );
  2914. }
  2915. }
  2916. /**
  2917. * Marks a function argument as deprecated and informs when it has been used.
  2918. *
  2919. * This function is to be used whenever a deprecated function argument is used.
  2920. * Before this function is called, the argument must be checked for whether it was
  2921. * used by comparing it to its default value or evaluating whether it is empty.
  2922. * For example:
  2923. * <code>
  2924. * if ( !empty($deprecated) )
  2925. * _deprecated_argument( __FUNCTION__, '3.0' );
  2926. * </code>
  2927. *
  2928. * There is a hook deprecated_argument_run that will be called that can be used
  2929. * to get the backtrace up to what file and function used the deprecated
  2930. * argument.
  2931. *
  2932. * The current behavior is to trigger an user error if WP_DEBUG is true.
  2933. *
  2934. * @package WordPress
  2935. * @subpackage Debug
  2936. * @since 3.0.0
  2937. * @access private
  2938. *
  2939. * @uses do_action() Calls 'deprecated_argument_run' and passes the function name, a message on the change,
  2940. * and the version in which the argument was deprecated.
  2941. * @uses apply_filters() Calls 'deprecated_argument_trigger_error' and expects boolean value of true to do
  2942. * trigger or false to not trigger error.
  2943. *
  2944. * @param string $function The function that was called
  2945. * @param string $version The version of WordPress that deprecated the argument used
  2946. * @param string $message Optional. A message regarding the change.
  2947. */
  2948. function _deprecated_argument( $function, $version, $message = null ) {
  2949. do_action( 'deprecated_argument_run', $function, $message, $version );
  2950. // Allow plugin to filter the output error trigger
  2951. if ( WP_DEBUG && apply_filters( 'deprecated_argument_trigger_error', true ) ) {
  2952. if ( ! is_null( $message ) )
  2953. trigger_error( sprintf( __('%1$s was called with an argument that is <strong>deprecated</strong> since version %2$s! %3$s'), $function, $version, $message ) );
  2954. else
  2955. trigger_error( sprintf( __('%1$s was called with an argument that is <strong>deprecated</strong> since version %2$s with no alternative available.'), $function, $version ) );
  2956. }
  2957. }
  2958. /**
  2959. * Is the server running earlier than 1.5.0 version of lighttpd
  2960. *
  2961. * @since 2.5.0
  2962. *
  2963. * @return bool Whether the server is running lighttpd < 1.5.0
  2964. */
  2965. function is_lighttpd_before_150() {
  2966. $server_parts = explode( '/', isset( $_SERVER['SERVER_SOFTWARE'] )? $_SERVER['SERVER_SOFTWARE'] : '' );
  2967. $server_parts[1] = isset( $server_parts[1] )? $server_parts[1] : '';
  2968. return 'lighttpd' == $server_parts[0] && -1 == version_compare( $server_parts[1], '1.5.0' );
  2969. }
  2970. /**
  2971. * Does the specified module exist in the apache config?
  2972. *
  2973. * @since 2.5.0
  2974. *
  2975. * @param string $mod e.g. mod_rewrite
  2976. * @param bool $default The default return value if the module is not found
  2977. * @return bool
  2978. */
  2979. function apache_mod_loaded($mod, $default = false) {
  2980. global $is_apache;
  2981. if ( !$is_apache )
  2982. return false;
  2983. if ( function_exists('apache_get_modules') ) {
  2984. $mods = apache_get_modules();
  2985. if ( in_array($mod, $mods) )
  2986. return true;
  2987. } elseif ( function_exists('phpinfo') ) {
  2988. ob_start();
  2989. phpinfo(8);
  2990. $phpinfo = ob_get_clean();
  2991. if ( false !== strpos($phpinfo, $mod) )
  2992. return true;
  2993. }
  2994. return $default;
  2995. }
  2996. /**
  2997. * File validates against allowed set of defined rules.
  2998. *
  2999. * A return value of '1' means that the $file contains either '..' or './'. A
  3000. * return value of '2' means that the $file contains ':' after the first
  3001. * character. A return value of '3' means that the file is not in the allowed
  3002. * files list.
  3003. *
  3004. * @since 1.2.0
  3005. *
  3006. * @param string $file File path.
  3007. * @param array $allowed_files List of allowed files.
  3008. * @return int 0 means nothing is wrong, greater than 0 means something was wrong.
  3009. */
  3010. function validate_file( $file, $allowed_files = '' ) {
  3011. if ( false !== strpos( $file, '..' ))
  3012. return 1;
  3013. if ( false !== strpos( $file, './' ))
  3014. return 1;
  3015. if (!empty ( $allowed_files ) && (!in_array( $file, $allowed_files ) ) )
  3016. return 3;
  3017. if (':' == substr( $file, 1, 1 ))
  3018. return 2;
  3019. return 0;
  3020. }
  3021. /**
  3022. * Determine if SSL is used.
  3023. *
  3024. * @since 2.6.0
  3025. *
  3026. * @return bool True if SSL, false if not used.
  3027. */
  3028. function is_ssl() {
  3029. if ( isset($_SERVER['HTTPS']) ) {
  3030. if ( 'on' == strtolower($_SERVER['HTTPS']) )
  3031. return true;
  3032. if ( '1' == $_SERVER['HTTPS'] )
  3033. return true;
  3034. } elseif ( isset($_SERVER['SERVER_PORT']) && ( '443' == $_SERVER['SERVER_PORT'] ) ) {
  3035. return true;
  3036. }
  3037. return false;
  3038. }
  3039. /**
  3040. * Whether SSL login should be forced.
  3041. *
  3042. * @since 2.6.0
  3043. *
  3044. * @param string|bool $force Optional.
  3045. * @return bool True if forced, false if not forced.
  3046. */
  3047. function force_ssl_login( $force = null ) {
  3048. static $forced = false;
  3049. if ( !is_null( $force ) ) {
  3050. $old_forced = $forced;
  3051. $forced = $force;
  3052. return $old_forced;
  3053. }
  3054. return $forced;
  3055. }
  3056. /**
  3057. * Whether to force SSL used for the Administration Panels.
  3058. *
  3059. * @since 2.6.0
  3060. *
  3061. * @param string|bool $force
  3062. * @return bool True if forced, false if not forced.
  3063. */
  3064. function force_ssl_admin( $force = null ) {
  3065. static $forced = false;
  3066. if ( !is_null( $force ) ) {
  3067. $old_forced = $forced;
  3068. $forced = $force;
  3069. return $old_forced;
  3070. }
  3071. return $forced;
  3072. }
  3073. /**
  3074. * Guess the URL for the site.
  3075. *
  3076. * Will remove wp-admin links to retrieve only return URLs not in the wp-admin
  3077. * directory.
  3078. *
  3079. * @since 2.6.0
  3080. *
  3081. * @return string
  3082. */
  3083. function wp_guess_url() {
  3084. if ( defined('WP_SITEURL') && '' != WP_SITEURL ) {
  3085. $url = WP_SITEURL;
  3086. } else {
  3087. $schema = is_ssl() ? 'https://' : 'http://';
  3088. $url = preg_replace('|/wp-admin/.*|i', '', $schema . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
  3089. }
  3090. return $url;
  3091. }
  3092. /**
  3093. * Suspend cache invalidation.
  3094. *
  3095. * Turns cache invalidation on and off. Useful during imports where you don't wont to do invalidations
  3096. * every time a post is inserted. Callers must be sure that what they are doing won't lead to an inconsistent
  3097. * cache when invalidation is suspended.
  3098. *
  3099. * @since 2.7.0
  3100. *
  3101. * @param bool $suspend Whether to suspend or enable cache invalidation
  3102. * @return bool The current suspend setting
  3103. */
  3104. function wp_suspend_cache_invalidation($suspend = true) {
  3105. global $_wp_suspend_cache_invalidation;
  3106. $current_suspend = $_wp_suspend_cache_invalidation;
  3107. $_wp_suspend_cache_invalidation = $suspend;
  3108. return $current_suspend;
  3109. }
  3110. /**
  3111. * Retrieve site option value based on name of option.
  3112. *
  3113. * @see get_option()
  3114. * @package WordPress
  3115. * @subpackage Option
  3116. * @since 2.8.0
  3117. *
  3118. * @uses apply_filters() Calls 'pre_site_option_$option' before checking the option.
  3119. * Any value other than false will "short-circuit" the retrieval of the option
  3120. * and return the returned value.
  3121. * @uses apply_filters() Calls 'site_option_$option', after checking the option, with
  3122. * the option value.
  3123. *
  3124. * @param string $option Name of option to retrieve. Expected to not be SQL-escaped.
  3125. * @param mixed $default Optional value to return if option doesn't exist. Default false.
  3126. * @param bool $use_cache Whether to use cache. Multisite only. Default true.
  3127. * @return mixed Value set for the option.
  3128. */
  3129. function get_site_option( $option, $default = false, $use_cache = true ) {
  3130. global $wpdb;
  3131. // Allow plugins to short-circuit site options.
  3132. $pre = apply_filters( 'pre_site_option_' . $option, false );
  3133. if ( false !== $pre )
  3134. return $pre;
  3135. if ( !is_multisite() ) {
  3136. $value = get_option($option, $default);
  3137. } else {
  3138. $cache_key = "{$wpdb->siteid}:$option";
  3139. if ( $use_cache )
  3140. $value = wp_cache_get($cache_key, 'site-options');
  3141. if ( !isset($value) || (false === $value) ) {
  3142. $row = $wpdb->get_row( $wpdb->prepare("SELECT meta_value FROM $wpdb->sitemeta WHERE meta_key = %s AND site_id = %d", $option, $wpdb->siteid ) );
  3143. // Has to be get_row instead of get_var because of funkiness with 0, false, null values
  3144. if ( is_object( $row ) )
  3145. $value = $row->meta_value;
  3146. else
  3147. $value = $default;
  3148. $value = maybe_unserialize( $value );
  3149. wp_cache_set( $cache_key, $value, 'site-options' );
  3150. }
  3151. }
  3152. return apply_filters( 'site_option_' . $option, $value );
  3153. }
  3154. /**
  3155. * Add a new site option.
  3156. *
  3157. * @see add_option()
  3158. * @package WordPress
  3159. * @subpackage Option
  3160. * @since 2.8.0
  3161. *
  3162. * @uses apply_filters() Calls 'pre_add_site_option_$option' hook to allow overwriting the
  3163. * option value to be stored.
  3164. * @uses do_action() Calls 'add_site_option_$option' and 'add_site_option' hooks on success.
  3165. *
  3166. * @param string $option Name of option to add. Expected to not be SQL-escaped.
  3167. * @param mixed $value Optional. Option value, can be anything. Expected to not be SQL-escaped.
  3168. * @return bool False if option was not added and true if option was added.
  3169. */
  3170. function add_site_option( $option, $value ) {
  3171. global $wpdb;
  3172. $value = apply_filters( 'pre_add_site_option_' . $option, $value );
  3173. if ( !is_multisite() ) {
  3174. $result = add_option( $option, $value );
  3175. } else {
  3176. $cache_key = "{$wpdb->siteid}:$option";
  3177. if ( $wpdb->get_row( $wpdb->prepare( "SELECT meta_value FROM $wpdb->sitemeta WHERE meta_key = %s AND site_id = %d", $option, $wpdb->siteid ) ) )
  3178. return update_site_option( $option, $value );
  3179. $value = sanitize_option( $option, $value );
  3180. wp_cache_set( $cache_key, $value, 'site-options' );
  3181. $_value = $value;
  3182. $value = maybe_serialize($value);
  3183. $result = $wpdb->insert( $wpdb->sitemeta, array('site_id' => $wpdb->siteid, 'meta_key' => $option, 'meta_value' => $value ) );
  3184. $value = $_value;
  3185. }
  3186. do_action( "add_site_option_{$option}", $option, $value );
  3187. do_action( "add_site_option", $option, $value );
  3188. return $result;
  3189. }
  3190. /**
  3191. * Removes site option by name.
  3192. *
  3193. * @see delete_option()
  3194. * @package WordPress
  3195. * @subpackage Option
  3196. * @since 2.8.0
  3197. *
  3198. * @uses do_action() Calls 'pre_delete_site_option_$option' hook before option is deleted.
  3199. * @uses do_action() Calls 'delete_site_option' and 'delete_site_option_$option'
  3200. * hooks on success.
  3201. *
  3202. * @param string $option Name of option to remove. Expected to not be SQL-escaped.
  3203. * @return bool True, if succeed. False, if failure.
  3204. */
  3205. function delete_site_option( $option ) {
  3206. global $wpdb;
  3207. // ms_protect_special_option( $option ); @todo
  3208. do_action( 'pre_delete_site_option_' . $option );
  3209. if ( !is_multisite() ) {
  3210. $result = delete_option( $option );
  3211. } else {
  3212. $row = $wpdb->get_row( $wpdb->prepare( "SELECT meta_id FROM {$wpdb->sitemeta} WHERE meta_key = %s AND site_id = %d", $option, $wpdb->siteid ) );
  3213. if ( is_null( $row ) || !$row->meta_id )
  3214. return false;
  3215. $cache_key = "{$wpdb->siteid}:$option";
  3216. wp_cache_delete( $cache_key, 'site-options' );
  3217. $result = $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->sitemeta} WHERE meta_key = %s AND site_id = %d", $option, $wpdb->siteid ) );
  3218. }
  3219. if ( $result ) {
  3220. do_action( "delete_site_option_{$option}", $option );
  3221. do_action( "delete_site_option", $option );
  3222. return true;
  3223. }
  3224. return false;
  3225. }
  3226. /**
  3227. * Update the value of a site option that was already added.
  3228. *
  3229. * @see update_option()
  3230. * @since 2.8.0
  3231. * @package WordPress
  3232. * @subpackage Option
  3233. *
  3234. * @uses apply_filters() Calls 'pre_update_site_option_$option' hook to allow overwriting the
  3235. * option value to be stored.
  3236. * @uses do_action() Calls 'update_site_option_$option' and 'update_site_option' hooks on success.
  3237. *
  3238. * @param string $option Name of option. Expected to not be SQL-escaped.
  3239. * @param mixed $value Option value. Expected to not be SQL-escaped.
  3240. * @return bool False if value was not updated and true if value was updated.
  3241. */
  3242. function update_site_option( $option, $value ) {
  3243. global $wpdb;
  3244. $oldvalue = get_site_option( $option );
  3245. $value = apply_filters( 'pre_update_site_option_' . $option, $value, $oldvalue );
  3246. if ( $value === $oldvalue )
  3247. return false;
  3248. if ( !is_multisite() ) {
  3249. $result = update_option( $option, $value );
  3250. } else {
  3251. $cache_key = "{$wpdb->siteid}:$option";
  3252. if ( $value && !$wpdb->get_row( $wpdb->prepare( "SELECT meta_value FROM $wpdb->sitemeta WHERE meta_key = %s AND site_id = %d", $option, $wpdb->siteid ) ) )
  3253. return add_site_option( $option, $value );
  3254. $value = sanitize_option( $option, $value );
  3255. wp_cache_set( $cache_key, $value, 'site-options' );
  3256. $_value = $value;
  3257. $value = maybe_serialize( $value );
  3258. $result = $wpdb->update( $wpdb->sitemeta, array( 'meta_value' => $value ), array( 'site_id' => $wpdb->siteid, 'meta_key' => $option ) );
  3259. $value = $_value;
  3260. }
  3261. if ( $result ) {
  3262. do_action( "update_site_option_{$option}", $option, $value );
  3263. do_action( "update_site_option", $option, $value );
  3264. return true;
  3265. }
  3266. return false;
  3267. }
  3268. /**
  3269. * Delete a site transient
  3270. *
  3271. * @since 2.9.0
  3272. * @package WordPress
  3273. * @subpackage Transient
  3274. *
  3275. * @uses do_action() Calls 'delete_site_transient_$transient' hook before transient is deleted.
  3276. * @uses do_action() Calls 'deleted_site_transient' hook on success.
  3277. *
  3278. * @param string $transient Transient name. Expected to not be SQL-escaped.
  3279. * @return bool True if successful, false otherwise
  3280. */
  3281. function delete_site_transient( $transient ) {
  3282. global $_wp_using_ext_object_cache;
  3283. do_action( 'delete_site_transient_' . $transient, $transient );
  3284. if ( $_wp_using_ext_object_cache ) {
  3285. $result = wp_cache_delete( $transient, 'site-transient' );
  3286. } else {
  3287. $option_timeout = '_site_transient_timeout_' . $transient;
  3288. $option = '_site_transient_' . $transient;
  3289. $result = delete_site_option( $option );
  3290. if ( $result )
  3291. delete_site_option( $option_timeout );
  3292. }
  3293. if ( $result )
  3294. do_action( 'deleted_site_transient', $transient );
  3295. return $result;
  3296. }
  3297. /**
  3298. * Get the value of a site transient
  3299. *
  3300. * If the transient does not exist or does not have a value, then the return value
  3301. * will be false.
  3302. *
  3303. * @see get_transient()
  3304. * @since 2.9.0
  3305. * @package WordPress
  3306. * @subpackage Transient
  3307. *
  3308. * @uses apply_filters() Calls 'pre_site_transient_$transient' hook before checking the transient.
  3309. * Any value other than false will "short-circuit" the retrieval of the transient
  3310. * and return the returned value.
  3311. * @uses apply_filters() Calls 'site_transient_$option' hook, after checking the transient, with
  3312. * the transient value.
  3313. *
  3314. * @param string $transient Transient name. Expected to not be SQL-escaped.
  3315. * @return mixed Value of transient
  3316. */
  3317. function get_site_transient( $transient ) {
  3318. global $_wp_using_ext_object_cache;
  3319. $pre = apply_filters( 'pre_site_transient_' . $transient, false );
  3320. if ( false !== $pre )
  3321. return $pre;
  3322. if ( $_wp_using_ext_object_cache ) {
  3323. $value = wp_cache_get( $transient, 'site-transient' );
  3324. } else {
  3325. // Core transients that do not have a timeout. Listed here so querying timeouts can be avoided.
  3326. $no_timeout = array('update_core', 'update_plugins', 'update_themes');
  3327. $transient_option = '_site_transient_' . $transient;
  3328. if ( ! in_array( $transient, $no_timeout ) ) {
  3329. $transient_timeout = '_site_transient_timeout_' . $transient;
  3330. $timeout = get_site_option( $transient_timeout );
  3331. if ( false !== $timeout && $timeout < time() ) {
  3332. delete_site_option( $transient_option );
  3333. delete_site_option( $transient_timeout );
  3334. return false;
  3335. }
  3336. }
  3337. $value = get_site_option( $transient_option );
  3338. }
  3339. return apply_filters( 'site_transient_' . $transient, $value );
  3340. }
  3341. /**
  3342. * Set/update the value of a site transient
  3343. *
  3344. * You do not need to serialize values, if the value needs to be serialize, then
  3345. * it will be serialized before it is set.
  3346. *
  3347. * @see set_transient()
  3348. * @since 2.9.0
  3349. * @package WordPress
  3350. * @subpackage Transient
  3351. *
  3352. * @uses apply_filters() Calls 'pre_set_site_transient_$transient' hook to allow overwriting the
  3353. * transient value to be stored.
  3354. * @uses do_action() Calls 'set_site_transient_$transient' and 'setted_site_transient' hooks on success.
  3355. *
  3356. * @param string $transient Transient name. Expected to not be SQL-escaped.
  3357. * @param mixed $value Transient value. Expected to not be SQL-escaped.
  3358. * @param int $expiration Time until expiration in seconds, default 0
  3359. * @return bool False if value was not set and true if value was set.
  3360. */
  3361. function set_site_transient( $transient, $value, $expiration = 0 ) {
  3362. global $_wp_using_ext_object_cache;
  3363. $value = apply_filters( 'pre_set_site_transient_' . $transient, $value );
  3364. if ( $_wp_using_ext_object_cache ) {
  3365. $result = wp_cache_set( $transient, $value, 'site-transient', $expiration );
  3366. } else {
  3367. $transient_timeout = '_site_transient_timeout_' . $transient;
  3368. $transient = '_site_transient_' . $transient;
  3369. if ( false === get_site_option( $transient ) ) {
  3370. if ( $expiration )
  3371. add_site_option( $transient_timeout, time() + $expiration );
  3372. $result = add_site_option( $transient, $value );
  3373. } else {
  3374. if ( $expiration )
  3375. update_site_option( $transient_timeout, time() + $expiration );
  3376. $result = update_site_option( $transient, $value );
  3377. }
  3378. }
  3379. if ( $result ) {
  3380. do_action( 'set_site_transient_' . $transient );
  3381. do_action( 'setted_site_transient', $transient );
  3382. }
  3383. return $result;
  3384. }
  3385. /**
  3386. * is main site
  3387. *
  3388. *
  3389. * @since 3.0.0
  3390. * @package WordPress
  3391. *
  3392. * @param int $blog_id optional blog id to test (default current blog)
  3393. * @return bool True if not multisite or $blog_id is main site
  3394. */
  3395. function is_main_site( $blog_id = '' ) {
  3396. global $current_site, $current_blog;
  3397. if ( !is_multisite() )
  3398. return true;
  3399. if ( !$blog_id )
  3400. $blog_id = $current_blog->blog_id;
  3401. return $blog_id == $current_site->blog_id;
  3402. }
  3403. /**
  3404. * Whether global terms are enabled.
  3405. *
  3406. *
  3407. * @since 3.0.0
  3408. * @package WordPress
  3409. *
  3410. * @return bool True if multisite and global terms enabled
  3411. */
  3412. function global_terms_enabled() {
  3413. if ( ! is_multisite() )
  3414. return false;
  3415. static $global_terms = null;
  3416. if ( is_null( $global_terms ) ) {
  3417. $filter = apply_filters( 'global_terms_enabled', null );
  3418. if ( ! is_null( $filter ) )
  3419. $global_terms = (bool) $filter;
  3420. else
  3421. $global_terms = (bool) get_site_option( 'global_terms_enabled', false );
  3422. }
  3423. return $global_terms;
  3424. }
  3425. /**
  3426. * gmt_offset modification for smart timezone handling
  3427. *
  3428. * Overrides the gmt_offset option if we have a timezone_string available
  3429. *
  3430. * @since 2.8.0
  3431. *
  3432. * @return float|bool
  3433. */
  3434. function wp_timezone_override_offset() {
  3435. if ( !wp_timezone_supported() ) {
  3436. return false;
  3437. }
  3438. if ( !$timezone_string = get_option( 'timezone_string' ) ) {
  3439. return false;
  3440. }
  3441. $timezone_object = timezone_open( $timezone_string );
  3442. $datetime_object = date_create();
  3443. if ( false === $timezone_object || false === $datetime_object ) {
  3444. return false;
  3445. }
  3446. return round( timezone_offset_get( $timezone_object, $datetime_object ) / 3600, 2 );
  3447. }
  3448. /**
  3449. * Check for PHP timezone support
  3450. *
  3451. * @since 2.9.0
  3452. *
  3453. * @return bool
  3454. */
  3455. function wp_timezone_supported() {
  3456. $support = false;
  3457. if (
  3458. function_exists( 'date_create' ) &&
  3459. function_exists( 'date_default_timezone_set' ) &&
  3460. function_exists( 'timezone_identifiers_list' ) &&
  3461. function_exists( 'timezone_open' ) &&
  3462. function_exists( 'timezone_offset_get' )
  3463. ) {
  3464. $support = true;
  3465. }
  3466. return apply_filters( 'timezone_support', $support );
  3467. }
  3468. /**
  3469. * {@internal Missing Short Description}}
  3470. *
  3471. * @since 2.9.0
  3472. *
  3473. * @param unknown_type $a
  3474. * @param unknown_type $b
  3475. * @return int
  3476. */
  3477. function _wp_timezone_choice_usort_callback( $a, $b ) {
  3478. // Don't use translated versions of Etc
  3479. if ( 'Etc' === $a['continent'] && 'Etc' === $b['continent'] ) {
  3480. // Make the order of these more like the old dropdown
  3481. if ( 'GMT+' === substr( $a['city'], 0, 4 ) && 'GMT+' === substr( $b['city'], 0, 4 ) ) {
  3482. return -1 * ( strnatcasecmp( $a['city'], $b['city'] ) );
  3483. }
  3484. if ( 'UTC' === $a['city'] ) {
  3485. if ( 'GMT+' === substr( $b['city'], 0, 4 ) ) {
  3486. return 1;
  3487. }
  3488. return -1;
  3489. }
  3490. if ( 'UTC' === $b['city'] ) {
  3491. if ( 'GMT+' === substr( $a['city'], 0, 4 ) ) {
  3492. return -1;
  3493. }
  3494. return 1;
  3495. }
  3496. return strnatcasecmp( $a['city'], $b['city'] );
  3497. }
  3498. if ( $a['t_continent'] == $b['t_continent'] ) {
  3499. if ( $a['t_city'] == $b['t_city'] ) {
  3500. return strnatcasecmp( $a['t_subcity'], $b['t_subcity'] );
  3501. }
  3502. return strnatcasecmp( $a['t_city'], $b['t_city'] );
  3503. } else {
  3504. // Force Etc to the bottom of the list
  3505. if ( 'Etc' === $a['continent'] ) {
  3506. return 1;
  3507. }
  3508. if ( 'Etc' === $b['continent'] ) {
  3509. return -1;
  3510. }
  3511. return strnatcasecmp( $a['t_continent'], $b['t_continent'] );
  3512. }
  3513. }
  3514. /**
  3515. * Gives a nicely formatted list of timezone strings // temporary! Not in final
  3516. *
  3517. * @since 2.9.0
  3518. *
  3519. * @param string $selected_zone Selected Zone
  3520. * @return string
  3521. */
  3522. function wp_timezone_choice( $selected_zone ) {
  3523. static $mo_loaded = false;
  3524. $continents = array( 'Africa', 'America', 'Antarctica', 'Arctic', 'Asia', 'Atlantic', 'Australia', 'Europe', 'Indian', 'Pacific');
  3525. // Load translations for continents and cities
  3526. if ( !$mo_loaded ) {
  3527. $locale = get_locale();
  3528. $mofile = WP_LANG_DIR . '/continents-cities-' . $locale . '.mo';
  3529. load_textdomain( 'continents-cities', $mofile );
  3530. $mo_loaded = true;
  3531. }
  3532. $zonen = array();
  3533. foreach ( timezone_identifiers_list() as $zone ) {
  3534. $zone = explode( '/', $zone );
  3535. if ( !in_array( $zone[0], $continents ) ) {
  3536. continue;
  3537. }
  3538. // This determines what gets set and translated - we don't translate Etc/* strings here, they are done later
  3539. $exists = array(
  3540. 0 => ( isset( $zone[0] ) && $zone[0] ),
  3541. 1 => ( isset( $zone[1] ) && $zone[1] ),
  3542. 2 => ( isset( $zone[2] ) && $zone[2] ),
  3543. );
  3544. $exists[3] = ( $exists[0] && 'Etc' !== $zone[0] );
  3545. $exists[4] = ( $exists[1] && $exists[3] );
  3546. $exists[5] = ( $exists[2] && $exists[3] );
  3547. $zonen[] = array(
  3548. 'continent' => ( $exists[0] ? $zone[0] : '' ),
  3549. 'city' => ( $exists[1] ? $zone[1] : '' ),
  3550. 'subcity' => ( $exists[2] ? $zone[2] : '' ),
  3551. 't_continent' => ( $exists[3] ? translate( str_replace( '_', ' ', $zone[0] ), 'continents-cities' ) : '' ),
  3552. 't_city' => ( $exists[4] ? translate( str_replace( '_', ' ', $zone[1] ), 'continents-cities' ) : '' ),
  3553. 't_subcity' => ( $exists[5] ? translate( str_replace( '_', ' ', $zone[2] ), 'continents-cities' ) : '' )
  3554. );
  3555. }
  3556. usort( $zonen, '_wp_timezone_choice_usort_callback' );
  3557. $structure = array();
  3558. if ( empty( $selected_zone ) ) {
  3559. $structure[] = '<option selected="selected" value="">' . __( 'Select a city' ) . '</option>';
  3560. }
  3561. foreach ( $zonen as $key => $zone ) {
  3562. // Build value in an array to join later
  3563. $value = array( $zone['continent'] );
  3564. if ( empty( $zone['city'] ) ) {
  3565. // It's at the continent level (generally won't happen)
  3566. $display = $zone['t_continent'];
  3567. } else {
  3568. // It's inside a continent group
  3569. // Continent optgroup
  3570. if ( !isset( $zonen[$key - 1] ) || $zonen[$key - 1]['continent'] !== $zone['continent'] ) {
  3571. $label = $zone['t_continent'];
  3572. $structure[] = '<optgroup label="'. esc_attr( $label ) .'">';
  3573. }
  3574. // Add the city to the value
  3575. $value[] = $zone['city'];
  3576. $display = $zone['t_city'];
  3577. if ( !empty( $zone['subcity'] ) ) {
  3578. // Add the subcity to the value
  3579. $value[] = $zone['subcity'];
  3580. $display .= ' - ' . $zone['t_subcity'];
  3581. }
  3582. }
  3583. // Build the value
  3584. $value = join( '/', $value );
  3585. $selected = '';
  3586. if ( $value === $selected_zone ) {
  3587. $selected = 'selected="selected" ';
  3588. }
  3589. $structure[] = '<option ' . $selected . 'value="' . esc_attr( $value ) . '">' . esc_html( $display ) . "</option>";
  3590. // Close continent optgroup
  3591. if ( !empty( $zone['city'] ) && ( !isset($zonen[$key + 1]) || (isset( $zonen[$key + 1] ) && $zonen[$key + 1]['continent'] !== $zone['continent']) ) ) {
  3592. $structure[] = '</optgroup>';
  3593. }
  3594. }
  3595. // Do UTC
  3596. $structure[] = '<optgroup label="'. esc_attr__( 'UTC' ) .'">';
  3597. $selected = '';
  3598. if ( 'UTC' === $selected_zone )
  3599. $selected = 'selected="selected" ';
  3600. $structure[] = '<option ' . $selected . 'value="' . esc_attr( 'UTC' ) . '">' . __('UTC') . '</option>';
  3601. $structure[] = '</optgroup>';
  3602. // Do manual UTC offsets
  3603. $structure[] = '<optgroup label="'. esc_attr__( 'Manual Offsets' ) .'">';
  3604. $offset_range = array (-12, -11.5, -11, -10.5, -10, -9.5, -9, -8.5, -8, -7.5, -7, -6.5, -6, -5.5, -5, -4.5, -4, -3.5, -3, -2.5, -2, -1.5, -1, -0.5,
  3605. 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 5.75, 6, 6.5, 7, 7.5, 8, 8.5, 8.75, 9, 9.5, 10, 10.5, 11, 11.5, 12, 12.75, 13, 13.75, 14);
  3606. foreach ( $offset_range as $offset ) {
  3607. if ( 0 <= $offset )
  3608. $offset_name = '+' . $offset;
  3609. else
  3610. $offset_name = (string) $offset;
  3611. $offset_value = $offset_name;
  3612. $offset_name = str_replace(array('.25','.5','.75'), array(':15',':30',':45'), $offset_name);
  3613. $offset_name = 'UTC' . $offset_name;
  3614. $offset_value = 'UTC' . $offset_value;
  3615. $selected = '';
  3616. if ( $offset_value === $selected_zone )
  3617. $selected = 'selected="selected" ';
  3618. $structure[] = '<option ' . $selected . 'value="' . esc_attr( $offset_value ) . '">' . esc_html( $offset_name ) . "</option>";
  3619. }
  3620. $structure[] = '</optgroup>';
  3621. return join( "\n", $structure );
  3622. }
  3623. /**
  3624. * Strip close comment and close php tags from file headers used by WP
  3625. * See http://core.trac.wordpress.org/ticket/8497
  3626. *
  3627. * @since 2.8.0
  3628. *
  3629. * @param string $str
  3630. * @return string
  3631. */
  3632. function _cleanup_header_comment($str) {
  3633. return trim(preg_replace("/\s*(?:\*\/|\?>).*/", '', $str));
  3634. }
  3635. /**
  3636. * Permanently deletes posts, pages, attachments, and comments which have been in the trash for EMPTY_TRASH_DAYS.
  3637. *
  3638. * @since 2.9.0
  3639. */
  3640. function wp_scheduled_delete() {
  3641. global $wpdb;
  3642. $delete_timestamp = time() - (60*60*24*EMPTY_TRASH_DAYS);
  3643. $posts_to_delete = $wpdb->get_results($wpdb->prepare("SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wp_trash_meta_time' AND meta_value < '%d'", $delete_timestamp), ARRAY_A);
  3644. foreach ( (array) $posts_to_delete as $post ) {
  3645. $post_id = (int) $post['post_id'];
  3646. if ( !$post_id )
  3647. continue;
  3648. $del_post = get_post($post_id);
  3649. if ( !$del_post || 'trash' != $del_post->post_status ) {
  3650. delete_post_meta($post_id, '_wp_trash_meta_status');
  3651. delete_post_meta($post_id, '_wp_trash_meta_time');
  3652. } else {
  3653. wp_delete_post($post_id);
  3654. }
  3655. }
  3656. $comments_to_delete = $wpdb->get_results($wpdb->prepare("SELECT comment_id FROM $wpdb->commentmeta WHERE meta_key = '_wp_trash_meta_time' AND meta_value < '%d'", $delete_timestamp), ARRAY_A);
  3657. foreach ( (array) $comments_to_delete as $comment ) {
  3658. $comment_id = (int) $comment['comment_id'];
  3659. if ( !$comment_id )
  3660. continue;
  3661. $del_comment = get_comment($comment_id);
  3662. if ( !$del_comment || 'trash' != $del_comment->comment_approved ) {
  3663. delete_comment_meta($comment_id, '_wp_trash_meta_time');
  3664. delete_comment_meta($comment_id, '_wp_trash_meta_status');
  3665. } else {
  3666. wp_delete_comment($comment_id);
  3667. }
  3668. }
  3669. }
  3670. /**
  3671. * Parse the file contents to retrieve its metadata.
  3672. *
  3673. * Searches for metadata for a file, such as a plugin or theme. Each piece of
  3674. * metadata must be on its own line. For a field spanning multple lines, it
  3675. * must not have any newlines or only parts of it will be displayed.
  3676. *
  3677. * Some users have issues with opening large files and manipulating the contents
  3678. * for want is usually the first 1kiB or 2kiB. This function stops pulling in
  3679. * the file contents when it has all of the required data.
  3680. *
  3681. * The first 8kiB of the file will be pulled in and if the file data is not
  3682. * within that first 8kiB, then the author should correct their plugin file
  3683. * and move the data headers to the top.
  3684. *
  3685. * The file is assumed to have permissions to allow for scripts to read
  3686. * the file. This is not checked however and the file is only opened for
  3687. * reading.
  3688. *
  3689. * @since 2.9.0
  3690. *
  3691. * @param string $file Path to the file
  3692. * @param bool $markup If the returned data should have HTML markup applied
  3693. * @param string $context If specified adds filter hook "extra_<$context>_headers"
  3694. */
  3695. function get_file_data( $file, $default_headers, $context = '' ) {
  3696. // We don't need to write to the file, so just open for reading.
  3697. $fp = fopen( $file, 'r' );
  3698. // Pull only the first 8kiB of the file in.
  3699. $file_data = fread( $fp, 8192 );
  3700. // PHP will close file handle, but we are good citizens.
  3701. fclose( $fp );
  3702. if ( $context != '' ) {
  3703. $extra_headers = apply_filters( "extra_$context".'_headers', array() );
  3704. $extra_headers = array_flip( $extra_headers );
  3705. foreach( $extra_headers as $key=>$value ) {
  3706. $extra_headers[$key] = $key;
  3707. }
  3708. $all_headers = array_merge($extra_headers, $default_headers);
  3709. } else {
  3710. $all_headers = $default_headers;
  3711. }
  3712. foreach ( $all_headers as $field => $regex ) {
  3713. preg_match( '/' . preg_quote( $regex, '/' ) . ':(.*)$/mi', $file_data, ${$field});
  3714. if ( !empty( ${$field} ) )
  3715. ${$field} = _cleanup_header_comment( ${$field}[1] );
  3716. else
  3717. ${$field} = '';
  3718. }
  3719. $file_data = compact( array_keys( $all_headers ) );
  3720. return $file_data;
  3721. }
  3722. /*
  3723. * Used internally to tidy up the search terms
  3724. *
  3725. * @access private
  3726. * @since 2.9.0
  3727. *
  3728. * @param string $t
  3729. * @return string
  3730. */
  3731. function _search_terms_tidy($t) {
  3732. return trim($t, "\"'\n\r ");
  3733. }
  3734. /**
  3735. * Returns true
  3736. *
  3737. * Useful for returning true to filters easily
  3738. *
  3739. * @since 3.0.0
  3740. * @see __return_false()
  3741. * @return bool true
  3742. */
  3743. function __return_true() {
  3744. return true;
  3745. }
  3746. /**
  3747. * Returns false
  3748. *
  3749. * Useful for returning false to filters easily
  3750. *
  3751. * @since 3.0.0
  3752. * @see __return_true()
  3753. * @return bool false
  3754. */
  3755. function __return_false() {
  3756. return false;
  3757. }
  3758. /**
  3759. * Returns 0
  3760. *
  3761. * Useful for returning 0 to filters easily
  3762. *
  3763. * @since 3.0.0
  3764. * @see __return_zero()
  3765. * @return int 0
  3766. */
  3767. function __return_zero() {
  3768. return 0;
  3769. }
  3770. /**
  3771. * Returns an empty array
  3772. *
  3773. * Useful for returning an empty array to filters easily
  3774. *
  3775. * @since 3.0.0
  3776. * @see __return_zero()
  3777. * @return array Empty array
  3778. */
  3779. function __return_empty_array() {
  3780. return array();
  3781. }
  3782. /**
  3783. * Send a HTTP header to disable content type sniffing in browsers which support it.
  3784. *
  3785. * @link http://blogs.msdn.com/ie/archive/2008/07/02/ie8-security-part-v-comprehensive-protection.aspx
  3786. * @link http://src.chromium.org/viewvc/chrome?view=rev&revision=6985
  3787. *
  3788. * @since 3.0.0
  3789. * @return none
  3790. */
  3791. function send_nosniff_header() {
  3792. @header( 'X-Content-Type-Options: nosniff' );
  3793. }
  3794. /**
  3795. * Returns a MySQL expression for selecting the week number based on the start_of_week option.
  3796. *
  3797. * @internal
  3798. * @since 3.0.0
  3799. * @param string $column
  3800. * @return string
  3801. */
  3802. function _wp_mysql_week( $column ) {
  3803. switch ( $start_of_week = (int) get_option( 'start_of_week' ) ) {
  3804. default :
  3805. case 0 :
  3806. return "WEEK( $column, 0 )";
  3807. case 1 :
  3808. return "WEEK( $column, 1 )";
  3809. case 2 :
  3810. case 3 :
  3811. case 4 :
  3812. case 5 :
  3813. case 6 :
  3814. return "WEEK( DATE_SUB( $column, INTERVAL $start_of_week DAY ), 0 )";
  3815. }
  3816. }
  3817. ?>