PageRenderTime 76ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/functions.php

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