PageRenderTime 40ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/msw/dev/wp-includes/functions.php

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