PageRenderTime 71ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/functions.php

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