PageRenderTime 62ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/blog/wp-includes/functions.php

https://bitbucket.org/abtris/phpframeworks
PHP | 3342 lines | 1643 code | 360 blank | 1339 comment | 386 complexity | 180606468fb97fef790e1c2851235bfe MD5 | raw file
Possible License(s): LGPL-2.1, AGPL-1.0
  1. <?php
  2. /**
  3. * Main WordPress API
  4. *
  5. * @package WordPress
  6. */
  7. /**
  8. * Converts MySQL DATETIME field to user specified date format.
  9. *
  10. * If $dateformatstring has 'G' value, then gmmktime() function will be used to
  11. * make the time. If $dateformatstring is set to 'U', then mktime() function
  12. * will be used to make the time.
  13. *
  14. * The $translate will only be used, if it is set to true and it is by default
  15. * and if the $wp_locale object has the month and weekday set.
  16. *
  17. * @since 0.71
  18. *
  19. * @param string $dateformatstring Either 'G', 'U', or php date format.
  20. * @param string $mysqlstring Time from mysql DATETIME field.
  21. * @param bool $translate Optional. Default is true. Will switch format to locale.
  22. * @return string Date formated by $dateformatstring or locale (if available).
  23. */
  24. function mysql2date( $dateformatstring, $mysqlstring, $translate = true ) {
  25. global $wp_locale;
  26. $m = $mysqlstring;
  27. if ( empty( $m ) )
  28. return false;
  29. if( 'G' == $dateformatstring ) {
  30. return strtotime( $m . ' +0000' );
  31. }
  32. $i = strtotime( $m );
  33. if( 'U' == $dateformatstring )
  34. return $i;
  35. if ( $translate)
  36. return date_i18n( $dateformatstring, $i );
  37. else
  38. return date( $dateformatstring, $i );
  39. }
  40. /**
  41. * Retrieve the current time based on specified type.
  42. *
  43. * The 'mysql' type will return the time in the format for MySQL DATETIME field.
  44. * The 'timestamp' type will return the current timestamp.
  45. *
  46. * If $gmt is set to either '1' or 'true', then both types will use GMT time.
  47. * if $gmt is false, the output is adjusted with the GMT offset in the WordPress option.
  48. *
  49. * @since 1.0.0
  50. *
  51. * @param string $type Either 'mysql' or 'timestamp'.
  52. * @param int|bool $gmt Optional. Whether to use GMT timezone. Default is false.
  53. * @return int|string String if $type is 'gmt', int if $type is 'timestamp'.
  54. */
  55. function current_time( $type, $gmt = 0 ) {
  56. switch ( $type ) {
  57. case 'mysql':
  58. return ( $gmt ) ? gmdate( 'Y-m-d H:i:s' ) : gmdate( 'Y-m-d H:i:s', ( time() + ( get_option( 'gmt_offset' ) * 3600 ) ) );
  59. break;
  60. case 'timestamp':
  61. return ( $gmt ) ? time() : time() + ( get_option( 'gmt_offset' ) * 3600 );
  62. break;
  63. }
  64. }
  65. /**
  66. * Retrieve the date in localized format, based on timestamp.
  67. *
  68. * If the locale specifies the locale month and weekday, then the locale will
  69. * take over the format for the date. If it isn't, then the date format string
  70. * will be used instead.
  71. *
  72. * @since 0.71
  73. *
  74. * @param string $dateformatstring Format to display the date.
  75. * @param int $unixtimestamp Optional. Unix timestamp.
  76. * @param bool $gmt Optional, default is false. Whether to convert to GMT for time.
  77. * @return string The date, translated if locale specifies it.
  78. */
  79. function date_i18n( $dateformatstring, $unixtimestamp = false, $gmt = false ) {
  80. global $wp_locale;
  81. $i = $unixtimestamp;
  82. // Sanity check for PHP 5.1.0-
  83. if ( false === $i || intval($i) < 0 ) {
  84. if ( ! $gmt )
  85. $i = current_time( 'timestamp' );
  86. else
  87. $i = time();
  88. // we should not let date() interfere with our
  89. // specially computed timestamp
  90. $gmt = true;
  91. }
  92. // store original value for language with untypical grammars
  93. // see http://core.trac.wordpress.org/ticket/9396
  94. $req_format = $dateformatstring;
  95. $datefunc = $gmt? 'gmdate' : 'date';
  96. if ( ( !empty( $wp_locale->month ) ) && ( !empty( $wp_locale->weekday ) ) ) {
  97. $datemonth = $wp_locale->get_month( $datefunc( 'm', $i ) );
  98. $datemonth_abbrev = $wp_locale->get_month_abbrev( $datemonth );
  99. $dateweekday = $wp_locale->get_weekday( $datefunc( 'w', $i ) );
  100. $dateweekday_abbrev = $wp_locale->get_weekday_abbrev( $dateweekday );
  101. $datemeridiem = $wp_locale->get_meridiem( $datefunc( 'a', $i ) );
  102. $datemeridiem_capital = $wp_locale->get_meridiem( $datefunc( 'A', $i ) );
  103. $dateformatstring = ' '.$dateformatstring;
  104. $dateformatstring = preg_replace( "/([^\\\])D/", "\\1" . backslashit( $dateweekday_abbrev ), $dateformatstring );
  105. $dateformatstring = preg_replace( "/([^\\\])F/", "\\1" . backslashit( $datemonth ), $dateformatstring );
  106. $dateformatstring = preg_replace( "/([^\\\])l/", "\\1" . backslashit( $dateweekday ), $dateformatstring );
  107. $dateformatstring = preg_replace( "/([^\\\])M/", "\\1" . backslashit( $datemonth_abbrev ), $dateformatstring );
  108. $dateformatstring = preg_replace( "/([^\\\])a/", "\\1" . backslashit( $datemeridiem ), $dateformatstring );
  109. $dateformatstring = preg_replace( "/([^\\\])A/", "\\1" . backslashit( $datemeridiem_capital ), $dateformatstring );
  110. $dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 );
  111. }
  112. $j = @$datefunc( $dateformatstring, $i );
  113. // allow plugins to redo this entirely for languages with untypical grammars
  114. $j = apply_filters('date_i18n', $j, $req_format, $i, $gmt);
  115. return $j;
  116. }
  117. /**
  118. * Convert number to format based on the locale.
  119. *
  120. * @since 2.3.0
  121. *
  122. * @param mixed $number The number to convert based on locale.
  123. * @param int $decimals Precision of the number of decimal places.
  124. * @return string Converted number in string format.
  125. */
  126. function number_format_i18n( $number, $decimals = null ) {
  127. global $wp_locale;
  128. // let the user override the precision only
  129. $decimals = ( is_null( $decimals ) ) ? $wp_locale->number_format['decimals'] : intval( $decimals );
  130. $num = number_format( $number, $decimals, $wp_locale->number_format['decimal_point'], $wp_locale->number_format['thousands_sep'] );
  131. // let the user translate digits from latin to localized language
  132. return apply_filters( 'number_format_i18n', $num );
  133. }
  134. /**
  135. * Convert number of bytes largest unit bytes will fit into.
  136. *
  137. * It is easier to read 1kB than 1024 bytes and 1MB than 1048576 bytes. Converts
  138. * number of bytes to human readable number by taking the number of that unit
  139. * that the bytes will go into it. Supports TB value.
  140. *
  141. * Please note that integers in PHP are limited to 32 bits, unless they are on
  142. * 64 bit architecture, then they have 64 bit size. If you need to place the
  143. * larger size then what PHP integer type will hold, then use a string. It will
  144. * be converted to a double, which should always have 64 bit length.
  145. *
  146. * Technically the correct unit names for powers of 1024 are KiB, MiB etc.
  147. * @link http://en.wikipedia.org/wiki/Byte
  148. *
  149. * @since 2.3.0
  150. *
  151. * @param int|string $bytes Number of bytes. Note max integer size for integers.
  152. * @param int $decimals Precision of number of decimal places.
  153. * @return bool|string False on failure. Number string on success.
  154. */
  155. function size_format( $bytes, $decimals = null ) {
  156. $quant = array(
  157. // ========================= Origin ====
  158. 'TB' => 1099511627776, // pow( 1024, 4)
  159. 'GB' => 1073741824, // pow( 1024, 3)
  160. 'MB' => 1048576, // pow( 1024, 2)
  161. 'kB' => 1024, // pow( 1024, 1)
  162. 'B ' => 1, // pow( 1024, 0)
  163. );
  164. foreach ( $quant as $unit => $mag )
  165. if ( doubleval($bytes) >= $mag )
  166. return number_format_i18n( $bytes / $mag, $decimals ) . ' ' . $unit;
  167. return false;
  168. }
  169. /**
  170. * Get the week start and end from the datetime or date string from mysql.
  171. *
  172. * @since 0.71
  173. *
  174. * @param string $mysqlstring Date or datetime field type from mysql.
  175. * @param int $start_of_week Optional. Start of the week as an integer.
  176. * @return array Keys are 'start' and 'end'.
  177. */
  178. function get_weekstartend( $mysqlstring, $start_of_week = '' ) {
  179. $my = substr( $mysqlstring, 0, 4 ); // Mysql string Year
  180. $mm = substr( $mysqlstring, 8, 2 ); // Mysql string Month
  181. $md = substr( $mysqlstring, 5, 2 ); // Mysql string day
  182. $day = mktime( 0, 0, 0, $md, $mm, $my ); // The timestamp for mysqlstring day.
  183. $weekday = date( 'w', $day ); // The day of the week from the timestamp
  184. $i = 86400; // One day
  185. if( !is_numeric($start_of_week) )
  186. $start_of_week = get_option( 'start_of_week' );
  187. if ( $weekday < $start_of_week )
  188. $weekday = 7 - $start_of_week - $weekday;
  189. while ( $weekday > $start_of_week ) {
  190. $weekday = date( 'w', $day );
  191. if ( $weekday < $start_of_week )
  192. $weekday = 7 - $start_of_week - $weekday;
  193. $day -= 86400;
  194. $i = 0;
  195. }
  196. $week['start'] = $day + 86400 - $i;
  197. $week['end'] = $week['start'] + 604799;
  198. return $week;
  199. }
  200. /**
  201. * Unserialize value only if it was serialized.
  202. *
  203. * @since 2.0.0
  204. *
  205. * @param string $original Maybe unserialized original, if is needed.
  206. * @return mixed Unserialized data can be any type.
  207. */
  208. function maybe_unserialize( $original ) {
  209. if ( is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in
  210. return @unserialize( $original );
  211. return $original;
  212. }
  213. /**
  214. * Check value to find if it was serialized.
  215. *
  216. * If $data is not an string, then returned value will always be false.
  217. * Serialized data is always a string.
  218. *
  219. * @since 2.0.5
  220. *
  221. * @param mixed $data Value to check to see if was serialized.
  222. * @return bool False if not serialized and true if it was.
  223. */
  224. function is_serialized( $data ) {
  225. // if it isn't a string, it isn't serialized
  226. if ( !is_string( $data ) )
  227. return false;
  228. $data = trim( $data );
  229. if ( 'N;' == $data )
  230. return true;
  231. if ( !preg_match( '/^([adObis]):/', $data, $badions ) )
  232. return false;
  233. switch ( $badions[1] ) {
  234. case 'a' :
  235. case 'O' :
  236. case 's' :
  237. if ( preg_match( "/^{$badions[1]}:[0-9]+:.*[;}]\$/s", $data ) )
  238. return true;
  239. break;
  240. case 'b' :
  241. case 'i' :
  242. case 'd' :
  243. if ( preg_match( "/^{$badions[1]}:[0-9.E-]+;\$/", $data ) )
  244. return true;
  245. break;
  246. }
  247. return false;
  248. }
  249. /**
  250. * Check whether serialized data is of string type.
  251. *
  252. * @since 2.0.5
  253. *
  254. * @param mixed $data Serialized data
  255. * @return bool False if not a serialized string, true if it is.
  256. */
  257. function is_serialized_string( $data ) {
  258. // if it isn't a string, it isn't a serialized string
  259. if ( !is_string( $data ) )
  260. return false;
  261. $data = trim( $data );
  262. if ( preg_match( '/^s:[0-9]+:.*;$/s', $data ) ) // this should fetch all serialized strings
  263. return true;
  264. return false;
  265. }
  266. /**
  267. * Retrieve option value based on setting name.
  268. *
  269. * If the option does not exist or does not have a value, then the return value
  270. * will be false. This is useful to check whether you need to install an option
  271. * and is commonly used during installation of plugin options and to test
  272. * whether upgrading is required.
  273. *
  274. * You can "short-circuit" the retrieval of the option from the database for
  275. * your plugin or core options that aren't protected. You can do so by hooking
  276. * into the 'pre_option_$option' with the $option being replaced by the option
  277. * name. You should not try to override special options, but you will not be
  278. * prevented from doing so.
  279. *
  280. * There is a second filter called 'option_$option' with the $option being
  281. * replaced with the option name. This gives the value as the only parameter.
  282. *
  283. * If the option was serialized, when the option was added and, or updated, then
  284. * it will be unserialized, when it is returned.
  285. *
  286. * @since 1.5.0
  287. * @package WordPress
  288. * @subpackage Option
  289. * @uses apply_filters() Calls 'pre_option_$optionname' false to allow
  290. * overwriting the option value in a plugin.
  291. * @uses apply_filters() Calls 'option_$optionname' with the option name value.
  292. *
  293. * @param string $setting Name of option to retrieve. Should already be SQL-escaped
  294. * @return mixed Value set for the option.
  295. */
  296. function get_option( $setting, $default = false ) {
  297. global $wpdb;
  298. // Allow plugins to short-circuit options.
  299. $pre = apply_filters( 'pre_option_' . $setting, false );
  300. if ( false !== $pre )
  301. return $pre;
  302. // prevent non-existent options from triggering multiple queries
  303. $notoptions = wp_cache_get( 'notoptions', 'options' );
  304. if ( isset( $notoptions[$setting] ) )
  305. return $default;
  306. $alloptions = wp_load_alloptions();
  307. if ( isset( $alloptions[$setting] ) ) {
  308. $value = $alloptions[$setting];
  309. } else {
  310. $value = wp_cache_get( $setting, 'options' );
  311. if ( false === $value ) {
  312. if ( defined( 'WP_INSTALLING' ) )
  313. $suppress = $wpdb->suppress_errors();
  314. // expected_slashed ($setting)
  315. $row = $wpdb->get_row( "SELECT option_value FROM $wpdb->options WHERE option_name = '$setting' LIMIT 1" );
  316. if ( defined( 'WP_INSTALLING' ) )
  317. $wpdb->suppress_errors($suppress);
  318. if ( is_object( $row) ) { // Has to be get_row instead of get_var because of funkiness with 0, false, null values
  319. $value = $row->option_value;
  320. wp_cache_add( $setting, $value, 'options' );
  321. } else { // option does not exist, so we must cache its non-existence
  322. $notoptions[$setting] = true;
  323. wp_cache_set( 'notoptions', $notoptions, 'options' );
  324. return $default;
  325. }
  326. }
  327. }
  328. // If home is not set use siteurl.
  329. if ( 'home' == $setting && '' == $value )
  330. return get_option( 'siteurl' );
  331. if ( in_array( $setting, array('siteurl', 'home', 'category_base', 'tag_base') ) )
  332. $value = untrailingslashit( $value );
  333. return apply_filters( 'option_' . $setting, maybe_unserialize( $value ) );
  334. }
  335. /**
  336. * Protect WordPress special option from being modified.
  337. *
  338. * Will die if $option is in protected list. Protected options are 'alloptions'
  339. * and 'notoptions' options.
  340. *
  341. * @since 2.2.0
  342. * @package WordPress
  343. * @subpackage Option
  344. *
  345. * @param string $option Option name.
  346. */
  347. function wp_protect_special_option( $option ) {
  348. $protected = array( 'alloptions', 'notoptions' );
  349. if ( in_array( $option, $protected ) )
  350. die( sprintf( __( '%s is a protected WP option and may not be modified' ), esc_html( $option ) ) );
  351. }
  352. /**
  353. * Print option value after sanitizing for forms.
  354. *
  355. * @uses attr Sanitizes value.
  356. * @since 1.5.0
  357. * @package WordPress
  358. * @subpackage Option
  359. *
  360. * @param string $option Option name.
  361. */
  362. function form_option( $option ) {
  363. echo esc_attr(get_option( $option ) );
  364. }
  365. /**
  366. * Retrieve all autoload options or all options, if no autoloaded ones exist.
  367. *
  368. * This is different from wp_load_alloptions() in that this function does not
  369. * cache its results and will retrieve all options from the database every time
  370. *
  371. * it is called.
  372. *
  373. * @since 1.0.0
  374. * @package WordPress
  375. * @subpackage Option
  376. * @uses apply_filters() Calls 'pre_option_$optionname' hook with option value as parameter.
  377. * @uses apply_filters() Calls 'all_options' on options list.
  378. *
  379. * @return array List of all options.
  380. */
  381. function get_alloptions() {
  382. global $wpdb;
  383. $show = $wpdb->hide_errors();
  384. if ( !$options = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options WHERE autoload = 'yes'" ) )
  385. $options = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options" );
  386. $wpdb->show_errors($show);
  387. foreach ( (array) $options as $option ) {
  388. // "When trying to design a foolproof system,
  389. // never underestimate the ingenuity of the fools :)" -- Dougal
  390. if ( in_array( $option->option_name, array( 'siteurl', 'home', 'category_base', 'tag_base' ) ) )
  391. $option->option_value = untrailingslashit( $option->option_value );
  392. $value = maybe_unserialize( $option->option_value );
  393. $all_options->{$option->option_name} = apply_filters( 'pre_option_' . $option->option_name, $value );
  394. }
  395. return apply_filters( 'all_options', $all_options );
  396. }
  397. /**
  398. * Loads and caches all autoloaded options, if available or all options.
  399. *
  400. * This is different from get_alloptions(), in that this function will cache the
  401. * options and will return the cached options when called again.
  402. *
  403. * @since 2.2.0
  404. * @package WordPress
  405. * @subpackage Option
  406. *
  407. * @return array List all options.
  408. */
  409. function wp_load_alloptions() {
  410. global $wpdb;
  411. $alloptions = wp_cache_get( 'alloptions', 'options' );
  412. if ( !$alloptions ) {
  413. $suppress = $wpdb->suppress_errors();
  414. if ( !$alloptions_db = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options WHERE autoload = 'yes'" ) )
  415. $alloptions_db = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options" );
  416. $wpdb->suppress_errors($suppress);
  417. $alloptions = array();
  418. foreach ( (array) $alloptions_db as $o )
  419. $alloptions[$o->option_name] = $o->option_value;
  420. wp_cache_add( 'alloptions', $alloptions, 'options' );
  421. }
  422. return $alloptions;
  423. }
  424. /**
  425. * Update the value of an option that was already added.
  426. *
  427. * You do not need to serialize values, if the value needs to be serialize, then
  428. * it will be serialized before it is inserted into the database. Remember,
  429. * resources can not be serialized or added as an option.
  430. *
  431. * If the option does not exist, then the option will be added with the option
  432. * value, but you will not be able to set whether it is autoloaded. If you want
  433. * to set whether an option autoloaded, then you need to use the add_option().
  434. *
  435. * Before the option is updated, then the filter named
  436. * 'pre_update_option_$option_name', with the $option_name as the $option_name
  437. * parameter value, will be called. The hook should accept two parameters, the
  438. * first is the new value and the second is the old value. Whatever is
  439. * returned will be used as the new value.
  440. *
  441. * After the value has been updated the action named 'update_option_$option_name'
  442. * will be called. This action receives two parameters the first being the old
  443. * value and the second the new value.
  444. *
  445. * @since 1.0.0
  446. * @package WordPress
  447. * @subpackage Option
  448. *
  449. * @param string $option_name Option name. Expected to not be SQL-escaped
  450. * @param mixed $newvalue Option value.
  451. * @return bool False if value was not updated and true if value was updated.
  452. */
  453. function update_option( $option_name, $newvalue ) {
  454. global $wpdb;
  455. wp_protect_special_option( $option_name );
  456. $safe_option_name = $wpdb->escape( $option_name );
  457. $newvalue = sanitize_option( $option_name, $newvalue );
  458. $oldvalue = get_option( $safe_option_name );
  459. $newvalue = apply_filters( 'pre_update_option_' . $option_name, $newvalue, $oldvalue );
  460. // If the new and old values are the same, no need to update.
  461. if ( $newvalue === $oldvalue )
  462. return false;
  463. if ( false === $oldvalue ) {
  464. add_option( $option_name, $newvalue );
  465. return true;
  466. }
  467. $notoptions = wp_cache_get( 'notoptions', 'options' );
  468. if ( is_array( $notoptions ) && isset( $notoptions[$option_name] ) ) {
  469. unset( $notoptions[$option_name] );
  470. wp_cache_set( 'notoptions', $notoptions, 'options' );
  471. }
  472. $_newvalue = $newvalue;
  473. $newvalue = maybe_serialize( $newvalue );
  474. $alloptions = wp_load_alloptions();
  475. if ( isset( $alloptions[$option_name] ) ) {
  476. $alloptions[$option_name] = $newvalue;
  477. wp_cache_set( 'alloptions', $alloptions, 'options' );
  478. } else {
  479. wp_cache_set( $option_name, $newvalue, 'options' );
  480. }
  481. $wpdb->update($wpdb->options, array('option_value' => $newvalue), array('option_name' => $option_name) );
  482. if ( $wpdb->rows_affected == 1 ) {
  483. do_action( "update_option_{$option_name}", $oldvalue, $_newvalue );
  484. return true;
  485. }
  486. return false;
  487. }
  488. /**
  489. * Add a new option.
  490. *
  491. * You do not need to serialize values, if the value needs to be serialize, then
  492. * it will be serialized before it is inserted into the database. Remember,
  493. * resources can not be serialized or added as an option.
  494. *
  495. * You can create options without values and then add values later. Does not
  496. * check whether the option has already been added, but does check that you
  497. * aren't adding a protected WordPress option. Care should be taken to not name
  498. * options, the same as the ones which are protected and to not add options
  499. * that were already added.
  500. *
  501. * The filter named 'add_option_$optionname', with the $optionname being
  502. * replaced with the option's name, will be called. The hook should accept two
  503. * parameters, the first is the option name, and the second is the value.
  504. *
  505. * @package WordPress
  506. * @subpackage Option
  507. * @since 1.0.0
  508. * @link http://alex.vort-x.net/blog/ Thanks Alex Stapleton
  509. *
  510. * @param string $name Option name to add. Expects to NOT be SQL escaped.
  511. * @param mixed $value Optional. Option value, can be anything.
  512. * @param mixed $deprecated Optional. Description. Not used anymore.
  513. * @param bool $autoload Optional. Default is enabled. Whether to load the option when WordPress starts up.
  514. * @return null returns when finished.
  515. */
  516. function add_option( $name, $value = '', $deprecated = '', $autoload = 'yes' ) {
  517. global $wpdb;
  518. wp_protect_special_option( $name );
  519. $safe_name = $wpdb->escape( $name );
  520. $value = sanitize_option( $name, $value );
  521. // Make sure the option doesn't already exist. We can check the 'notoptions' cache before we ask for a db query
  522. $notoptions = wp_cache_get( 'notoptions', 'options' );
  523. if ( !is_array( $notoptions ) || !isset( $notoptions[$name] ) )
  524. if ( false !== get_option( $safe_name ) )
  525. return;
  526. $value = maybe_serialize( $value );
  527. $autoload = ( 'no' === $autoload ) ? 'no' : 'yes';
  528. if ( 'yes' == $autoload ) {
  529. $alloptions = wp_load_alloptions();
  530. $alloptions[$name] = $value;
  531. wp_cache_set( 'alloptions', $alloptions, 'options' );
  532. } else {
  533. wp_cache_set( $name, $value, 'options' );
  534. }
  535. // This option exists now
  536. $notoptions = wp_cache_get( 'notoptions', 'options' ); // yes, again... we need it to be fresh
  537. if ( is_array( $notoptions ) && isset( $notoptions[$name] ) ) {
  538. unset( $notoptions[$name] );
  539. wp_cache_set( 'notoptions', $notoptions, 'options' );
  540. }
  541. $wpdb->insert($wpdb->options, array('option_name' => $name, 'option_value' => $value, 'autoload' => $autoload) );
  542. do_action( "add_option_{$name}", $name, $value );
  543. return;
  544. }
  545. /**
  546. * Removes option by name and prevents removal of protected WordPress options.
  547. *
  548. * @package WordPress
  549. * @subpackage Option
  550. * @since 1.2.0
  551. *
  552. * @param string $name Option name to remove.
  553. * @return bool True, if succeed. False, if failure.
  554. */
  555. function delete_option( $name ) {
  556. global $wpdb;
  557. wp_protect_special_option( $name );
  558. // Get the ID, if no ID then return
  559. // expected_slashed ($name)
  560. $option = $wpdb->get_row( "SELECT option_id, autoload FROM $wpdb->options WHERE option_name = '$name'" );
  561. if ( is_null($option) || !$option->option_id )
  562. return false;
  563. // expected_slashed ($name)
  564. $wpdb->query( "DELETE FROM $wpdb->options WHERE option_name = '$name'" );
  565. if ( 'yes' == $option->autoload ) {
  566. $alloptions = wp_load_alloptions();
  567. if ( isset( $alloptions[$name] ) ) {
  568. unset( $alloptions[$name] );
  569. wp_cache_set( 'alloptions', $alloptions, 'options' );
  570. }
  571. } else {
  572. wp_cache_delete( $name, 'options' );
  573. }
  574. return true;
  575. }
  576. /**
  577. * Delete a transient
  578. *
  579. * @since 2.8.0
  580. * @package WordPress
  581. * @subpackage Transient
  582. *
  583. * @param string $transient Transient name. Expected to not be SQL-escaped
  584. * @return bool true if successful, false otherwise
  585. */
  586. function delete_transient($transient) {
  587. global $_wp_using_ext_object_cache, $wpdb;
  588. if ( $_wp_using_ext_object_cache ) {
  589. return wp_cache_delete($transient, 'transient');
  590. } else {
  591. $transient = '_transient_' . $wpdb->escape($transient);
  592. return delete_option($transient);
  593. }
  594. }
  595. /**
  596. * Get the value of a transient
  597. *
  598. * If the transient does not exist or does not have a value, then the return value
  599. * will be false.
  600. *
  601. * @since 2.8.0
  602. * @package WordPress
  603. * @subpackage Transient
  604. *
  605. * @param string $transient Transient name. Expected to not be SQL-escaped
  606. * @return mixed Value of transient
  607. */
  608. function get_transient($transient) {
  609. global $_wp_using_ext_object_cache, $wpdb;
  610. $pre = apply_filters( 'pre_transient_' . $transient, false );
  611. if ( false !== $pre )
  612. return $pre;
  613. if ( $_wp_using_ext_object_cache ) {
  614. $value = wp_cache_get($transient, 'transient');
  615. } else {
  616. $transient_option = '_transient_' . $wpdb->escape($transient);
  617. // If option is not in alloptions, it is not autoloaded and thus has a timeout
  618. $alloptions = wp_load_alloptions();
  619. if ( !isset( $alloptions[$transient_option] ) ) {
  620. $transient_timeout = '_transient_timeout_' . $wpdb->escape($transient);
  621. if ( get_option($transient_timeout) < time() ) {
  622. delete_option($transient_option);
  623. delete_option($transient_timeout);
  624. return false;
  625. }
  626. }
  627. $value = get_option($transient_option);
  628. }
  629. return apply_filters('transient_' . $transient, $value);
  630. }
  631. /**
  632. * Set/update the value of a transient
  633. *
  634. * You do not need to serialize values, if the value needs to be serialize, then
  635. * it will be serialized before it is set.
  636. *
  637. * @since 2.8.0
  638. * @package WordPress
  639. * @subpackage Transient
  640. *
  641. * @param string $transient Transient name. Expected to not be SQL-escaped
  642. * @param mixed $value Transient value.
  643. * @param int $expiration Time until expiration in seconds, default 0
  644. * @return bool False if value was not set and true if value was set.
  645. */
  646. function set_transient($transient, $value, $expiration = 0) {
  647. global $_wp_using_ext_object_cache, $wpdb;
  648. if ( $_wp_using_ext_object_cache ) {
  649. return wp_cache_set($transient, $value, 'transient', $expiration);
  650. } else {
  651. $transient_timeout = '_transient_timeout_' . $transient;
  652. $transient = '_transient_' . $transient;
  653. $safe_transient = $wpdb->escape($transient);
  654. if ( false === get_option( $safe_transient ) ) {
  655. $autoload = 'yes';
  656. if ( 0 != $expiration ) {
  657. $autoload = 'no';
  658. add_option($transient_timeout, time() + $expiration, '', 'no');
  659. }
  660. return add_option($transient, $value, '', $autoload);
  661. } else {
  662. if ( 0 != $expiration )
  663. update_option($transient_timeout, time() + $expiration);
  664. return update_option($transient, $value);
  665. }
  666. }
  667. }
  668. /**
  669. * Saves and restores user interface settings stored in a cookie.
  670. *
  671. * Checks if the current user-settings cookie is updated and stores it. When no
  672. * cookie exists (different browser used), adds the last saved cookie restoring
  673. * the settings.
  674. *
  675. * @package WordPress
  676. * @subpackage Option
  677. * @since 2.7.0
  678. */
  679. function wp_user_settings() {
  680. if ( ! is_admin() )
  681. return;
  682. if ( defined('DOING_AJAX') )
  683. return;
  684. if ( ! $user = wp_get_current_user() )
  685. return;
  686. $settings = get_user_option( 'user-settings', $user->ID, false );
  687. if ( isset( $_COOKIE['wp-settings-' . $user->ID] ) ) {
  688. $cookie = preg_replace( '/[^A-Za-z0-9=&_]/', '', $_COOKIE['wp-settings-' . $user->ID] );
  689. if ( ! empty( $cookie ) && strpos( $cookie, '=' ) ) {
  690. if ( $cookie == $settings )
  691. return;
  692. $last_time = (int) get_user_option( 'user-settings-time', $user->ID, false );
  693. $saved = isset( $_COOKIE['wp-settings-time-' . $user->ID]) ? preg_replace( '/[^0-9]/', '', $_COOKIE['wp-settings-time-' . $user->ID] ) : 0;
  694. if ( $saved > $last_time ) {
  695. update_user_option( $user->ID, 'user-settings', $cookie, false );
  696. update_user_option( $user->ID, 'user-settings-time', time() - 5, false );
  697. return;
  698. }
  699. }
  700. }
  701. setcookie( 'wp-settings-' . $user->ID, $settings, time() + 31536000, SITECOOKIEPATH );
  702. setcookie( 'wp-settings-time-' . $user->ID, time(), time() + 31536000, SITECOOKIEPATH );
  703. $_COOKIE['wp-settings-' . $user->ID] = $settings;
  704. }
  705. /**
  706. * Retrieve user interface setting value based on setting name.
  707. *
  708. * @package WordPress
  709. * @subpackage Option
  710. * @since 2.7.0
  711. *
  712. * @param string $name The name of the setting.
  713. * @param string $default Optional default value to return when $name is not set.
  714. * @return mixed the last saved user setting or the default value/false if it doesn't exist.
  715. */
  716. function get_user_setting( $name, $default = false ) {
  717. $all = get_all_user_settings();
  718. return isset($all[$name]) ? $all[$name] : $default;
  719. }
  720. /**
  721. * Add or update user interface setting.
  722. *
  723. * Both $name and $value can contain only ASCII letters, numbers and underscores.
  724. * This function has to be used before any output has started as it calls setcookie().
  725. *
  726. * @package WordPress
  727. * @subpackage Option
  728. * @since 2.8.0
  729. *
  730. * @param string $name The name of the setting.
  731. * @param string $value The value for the setting.
  732. * @return bool true if set successfully/false if not.
  733. */
  734. function set_user_setting( $name, $value ) {
  735. if ( headers_sent() )
  736. return false;
  737. $all = get_all_user_settings();
  738. $name = preg_replace( '/[^A-Za-z0-9_]+/', '', $name );
  739. if ( empty($name) )
  740. return false;
  741. $all[$name] = $value;
  742. return wp_set_all_user_settings($all);
  743. }
  744. /**
  745. * Delete user interface settings.
  746. *
  747. * Deleting settings would reset them to the defaults.
  748. * This function has to be used before any output has started as it calls setcookie().
  749. *
  750. * @package WordPress
  751. * @subpackage Option
  752. * @since 2.7.0
  753. *
  754. * @param mixed $names The name or array of names of the setting to be deleted.
  755. * @return bool true if deleted successfully/false if not.
  756. */
  757. function delete_user_setting( $names ) {
  758. if ( headers_sent() )
  759. return false;
  760. $all = get_all_user_settings();
  761. $names = (array) $names;
  762. foreach ( $names as $name ) {
  763. if ( isset($all[$name]) ) {
  764. unset($all[$name]);
  765. $deleted = true;
  766. }
  767. }
  768. if ( isset($deleted) )
  769. return wp_set_all_user_settings($all);
  770. return false;
  771. }
  772. /**
  773. * Retrieve all user interface settings.
  774. *
  775. * @package WordPress
  776. * @subpackage Option
  777. * @since 2.7.0
  778. *
  779. * @return array the last saved user settings or empty array.
  780. */
  781. function get_all_user_settings() {
  782. global $_updated_user_settings;
  783. if ( ! $user = wp_get_current_user() )
  784. return array();
  785. if ( isset($_updated_user_settings) && is_array($_updated_user_settings) )
  786. return $_updated_user_settings;
  787. $all = array();
  788. if ( isset($_COOKIE['wp-settings-' . $user->ID]) ) {
  789. $cookie = preg_replace( '/[^A-Za-z0-9=&_]/', '', $_COOKIE['wp-settings-' . $user->ID] );
  790. if ( $cookie && strpos($cookie, '=') ) // the '=' cannot be 1st char
  791. parse_str($cookie, $all);
  792. } else {
  793. $option = get_user_option('user-settings', $user->ID);
  794. if ( $option && is_string($option) )
  795. parse_str( $option, $all );
  796. }
  797. return $all;
  798. }
  799. /**
  800. * Private. Set all user interface settings.
  801. *
  802. * @package WordPress
  803. * @subpackage Option
  804. * @since 2.8.0
  805. *
  806. */
  807. function wp_set_all_user_settings($all) {
  808. global $_updated_user_settings;
  809. if ( ! $user = wp_get_current_user() )
  810. return false;
  811. $_updated_user_settings = $all;
  812. $settings = '';
  813. foreach ( $all as $k => $v ) {
  814. $v = preg_replace( '/[^A-Za-z0-9_]+/', '', $v );
  815. $settings .= $k . '=' . $v . '&';
  816. }
  817. $settings = rtrim($settings, '&');
  818. update_user_option( $user->ID, 'user-settings', $settings, false );
  819. update_user_option( $user->ID, 'user-settings-time', time(), false );
  820. return true;
  821. }
  822. /**
  823. * Delete the user settings of the current user.
  824. *
  825. * @package WordPress
  826. * @subpackage Option
  827. * @since 2.7.0
  828. */
  829. function delete_all_user_settings() {
  830. if ( ! $user = wp_get_current_user() )
  831. return;
  832. update_user_option( $user->ID, 'user-settings', '', false );
  833. setcookie('wp-settings-' . $user->ID, ' ', time() - 31536000, SITECOOKIEPATH);
  834. }
  835. /**
  836. * Serialize data, if needed.
  837. *
  838. * @since 2.0.5
  839. *
  840. * @param mixed $data Data that might be serialized.
  841. * @return mixed A scalar data
  842. */
  843. function maybe_serialize( $data ) {
  844. if ( is_array( $data ) || is_object( $data ) )
  845. return serialize( $data );
  846. if ( is_serialized( $data ) )
  847. return serialize( $data );
  848. return $data;
  849. }
  850. /**
  851. * Strip HTML and put links at the bottom of stripped content.
  852. *
  853. * Searches for all of the links, strips them out of the content, and places
  854. * them at the bottom of the content with numbers.
  855. *
  856. * @since 0.71
  857. *
  858. * @param string $content Content to get links
  859. * @return string HTML stripped out of content with links at the bottom.
  860. */
  861. function make_url_footnote( $content ) {
  862. preg_match_all( '/<a(.+?)href=\"(.+?)\"(.*?)>(.+?)<\/a>/', $content, $matches );
  863. $links_summary = "\n";
  864. for ( $i=0; $i<count($matches[0]); $i++ ) {
  865. $link_match = $matches[0][$i];
  866. $link_number = '['.($i+1).']';
  867. $link_url = $matches[2][$i];
  868. $link_text = $matches[4][$i];
  869. $content = str_replace( $link_match, $link_text . ' ' . $link_number, $content );
  870. $link_url = ( ( strtolower( substr( $link_url, 0, 7 ) ) != 'http://' ) && ( strtolower( substr( $link_url, 0, 8 ) ) != 'https://' ) ) ? get_option( 'home' ) . $link_url : $link_url;
  871. $links_summary .= "\n" . $link_number . ' ' . $link_url;
  872. }
  873. $content = strip_tags( $content );
  874. $content .= $links_summary;
  875. return $content;
  876. }
  877. /**
  878. * Retrieve post title from XMLRPC XML.
  879. *
  880. * If the title element is not part of the XML, then the default post title from
  881. * the $post_default_title will be used instead.
  882. *
  883. * @package WordPress
  884. * @subpackage XMLRPC
  885. * @since 0.71
  886. *
  887. * @global string $post_default_title Default XMLRPC post title.
  888. *
  889. * @param string $content XMLRPC XML Request content
  890. * @return string Post title
  891. */
  892. function xmlrpc_getposttitle( $content ) {
  893. global $post_default_title;
  894. if ( preg_match( '/<title>(.+?)<\/title>/is', $content, $matchtitle ) ) {
  895. $post_title = $matchtitle[1];
  896. } else {
  897. $post_title = $post_default_title;
  898. }
  899. return $post_title;
  900. }
  901. /**
  902. * Retrieve the post category or categories from XMLRPC XML.
  903. *
  904. * If the category element is not found, then the default post category will be
  905. * used. The return type then would be what $post_default_category. If the
  906. * category is found, then it will always be an array.
  907. *
  908. * @package WordPress
  909. * @subpackage XMLRPC
  910. * @since 0.71
  911. *
  912. * @global string $post_default_category Default XMLRPC post category.
  913. *
  914. * @param string $content XMLRPC XML Request content
  915. * @return string|array List of categories or category name.
  916. */
  917. function xmlrpc_getpostcategory( $content ) {
  918. global $post_default_category;
  919. if ( preg_match( '/<category>(.+?)<\/category>/is', $content, $matchcat ) ) {
  920. $post_category = trim( $matchcat[1], ',' );
  921. $post_category = explode( ',', $post_category );
  922. } else {
  923. $post_category = $post_default_category;
  924. }
  925. return $post_category;
  926. }
  927. /**
  928. * XMLRPC XML content without title and category elements.
  929. *
  930. * @package WordPress
  931. * @subpackage XMLRPC
  932. * @since 0.71
  933. *
  934. * @param string $content XMLRPC XML Request content
  935. * @return string XMLRPC XML Request content without title and category elements.
  936. */
  937. function xmlrpc_removepostdata( $content ) {
  938. $content = preg_replace( '/<title>(.+?)<\/title>/si', '', $content );
  939. $content = preg_replace( '/<category>(.+?)<\/category>/si', '', $content );
  940. $content = trim( $content );
  941. return $content;
  942. }
  943. /**
  944. * Open the file handle for debugging.
  945. *
  946. * This function is used for XMLRPC feature, but it is general purpose enough
  947. * to be used in anywhere.
  948. *
  949. * @see fopen() for mode options.
  950. * @package WordPress
  951. * @subpackage Debug
  952. * @since 0.71
  953. * @uses $debug Used for whether debugging is enabled.
  954. *
  955. * @param string $filename File path to debug file.
  956. * @param string $mode Same as fopen() mode parameter.
  957. * @return bool|resource File handle. False on failure.
  958. */
  959. function debug_fopen( $filename, $mode ) {
  960. global $debug;
  961. if ( 1 == $debug ) {
  962. $fp = fopen( $filename, $mode );
  963. return $fp;
  964. } else {
  965. return false;
  966. }
  967. }
  968. /**
  969. * Write contents to the file used for debugging.
  970. *
  971. * Technically, this can be used to write to any file handle when the global
  972. * $debug is set to 1 or true.
  973. *
  974. * @package WordPress
  975. * @subpackage Debug
  976. * @since 0.71
  977. * @uses $debug Used for whether debugging is enabled.
  978. *
  979. * @param resource $fp File handle for debugging file.
  980. * @param string $string Content to write to debug file.
  981. */
  982. function debug_fwrite( $fp, $string ) {
  983. global $debug;
  984. if ( 1 == $debug )
  985. fwrite( $fp, $string );
  986. }
  987. /**
  988. * Close the debugging file handle.
  989. *
  990. * Technically, this can be used to close any file handle when the global $debug
  991. * is set to 1 or true.
  992. *
  993. * @package WordPress
  994. * @subpackage Debug
  995. * @since 0.71
  996. * @uses $debug Used for whether debugging is enabled.
  997. *
  998. * @param resource $fp Debug File handle.
  999. */
  1000. function debug_fclose( $fp ) {
  1001. global $debug;
  1002. if ( 1 == $debug )
  1003. fclose( $fp );
  1004. }
  1005. /**
  1006. * Check content for video and audio links to add as enclosures.
  1007. *
  1008. * Will not add enclosures that have already been added and will
  1009. * remove enclosures that are no longer in the post. This is called as
  1010. * pingbacks and trackbacks.
  1011. *
  1012. * @package WordPress
  1013. * @since 1.5.0
  1014. *
  1015. * @uses $wpdb
  1016. *
  1017. * @param string $content Post Content
  1018. * @param int $post_ID Post ID
  1019. */
  1020. function do_enclose( $content, $post_ID ) {
  1021. global $wpdb;
  1022. include_once( ABSPATH . WPINC . '/class-IXR.php' );
  1023. $log = debug_fopen( ABSPATH . 'enclosures.log', 'a' );
  1024. $post_links = array();
  1025. debug_fwrite( $log, 'BEGIN ' . date( 'YmdHis', time() ) . "\n" );
  1026. $pung = get_enclosed( $post_ID );
  1027. $ltrs = '\w';
  1028. $gunk = '/#~:.?+=&%@!\-';
  1029. $punc = '.:?\-';
  1030. $any = $ltrs . $gunk . $punc;
  1031. preg_match_all( "{\b http : [$any] +? (?= [$punc] * [^$any] | $)}x", $content, $post_links_temp );
  1032. debug_fwrite( $log, 'Post contents:' );
  1033. debug_fwrite( $log, $content . "\n" );
  1034. foreach ( $pung as $link_test ) {
  1035. if ( !in_array( $link_test, $post_links_temp[0] ) ) { // link no longer in post
  1036. $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE (%s)", $post_ID, $link_test . '%') );
  1037. }
  1038. }
  1039. foreach ( (array) $post_links_temp[0] as $link_test ) {
  1040. if ( !in_array( $link_test, $pung ) ) { // If we haven't pung it already
  1041. $test = parse_url( $link_test );
  1042. if ( isset( $test['query'] ) )
  1043. $post_links[] = $link_test;
  1044. elseif ( $test['path'] != '/' && $test['path'] != '' )
  1045. $post_links[] = $link_test;
  1046. }
  1047. }
  1048. foreach ( (array) $post_links as $url ) {
  1049. if ( $url != '' && !$wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE (%s)", $post_ID, $url . '%' ) ) ) {
  1050. if ( $headers = wp_get_http_headers( $url) ) {
  1051. $len = (int) $headers['content-length'];
  1052. $type = $headers['content-type'];
  1053. $allowed_types = array( 'video', 'audio' );
  1054. if ( in_array( substr( $type, 0, strpos( $type, "/" ) ), $allowed_types ) ) {
  1055. $meta_value = "$url\n$len\n$type\n";
  1056. $wpdb->insert($wpdb->postmeta, array('post_id' => $post_ID, 'meta_key' => 'enclosure', 'meta_value' => $meta_value) );
  1057. }
  1058. }
  1059. }
  1060. }
  1061. }
  1062. /**
  1063. * Perform a HTTP HEAD or GET request.
  1064. *
  1065. * If $file_path is a writable filename, this will do a GET request and write
  1066. * the file to that path.
  1067. *
  1068. * @since 2.5.0
  1069. *
  1070. * @param string $url URL to fetch.
  1071. * @param string|bool $file_path Optional. File path to write request to.
  1072. * @param bool $deprecated Deprecated. Not used.
  1073. * @return bool|string False on failure and string of headers if HEAD request.
  1074. */
  1075. function wp_get_http( $url, $file_path = false, $deprecated = false ) {
  1076. @set_time_limit( 60 );
  1077. $options = array();
  1078. $options['redirection'] = 5;
  1079. if ( false == $file_path )
  1080. $options['method'] = 'HEAD';
  1081. else
  1082. $options['method'] = 'GET';
  1083. $response = wp_remote_request($url, $options);
  1084. if ( is_wp_error( $response ) )
  1085. return false;
  1086. $headers = wp_remote_retrieve_headers( $response );
  1087. $headers['response'] = $response['response']['code'];
  1088. if ( false == $file_path )
  1089. return $headers;
  1090. // GET request - write it to the supplied filename
  1091. $out_fp = fopen($file_path, 'w');
  1092. if ( !$out_fp )
  1093. return $headers;
  1094. fwrite( $out_fp, $response['body']);
  1095. fclose($out_fp);
  1096. return $headers;
  1097. }
  1098. /**
  1099. * Retrieve HTTP Headers from URL.
  1100. *
  1101. * @since 1.5.1
  1102. *
  1103. * @param string $url
  1104. * @param bool $deprecated Not Used.
  1105. * @return bool|string False on failure, headers on success.
  1106. */
  1107. function wp_get_http_headers( $url, $deprecated = false ) {
  1108. $response = wp_remote_head( $url );
  1109. if ( is_wp_error( $response ) )
  1110. return false;
  1111. return wp_remote_retrieve_headers( $response );
  1112. }
  1113. /**
  1114. * Whether today is a new day.
  1115. *
  1116. * @since 0.71
  1117. * @uses $day Today
  1118. * @uses $previousday Previous day
  1119. *
  1120. * @return int 1 when new day, 0 if not a new day.
  1121. */
  1122. function is_new_day() {
  1123. global $day, $previousday;
  1124. if ( $day != $previousday )
  1125. return 1;
  1126. else
  1127. return 0;
  1128. }
  1129. /**
  1130. * Build URL query based on an associative and, or indexed array.
  1131. *
  1132. * This is a convenient function for easily building url queries. It sets the
  1133. * separator to '&' and uses _http_build_query() function.
  1134. *
  1135. * @see _http_build_query() Used to build the query
  1136. * @link http://us2.php.net/manual/en/function.http-build-query.php more on what
  1137. * http_build_query() does.
  1138. *
  1139. * @since 2.3.0
  1140. *
  1141. * @param array $data URL-encode key/value pairs.
  1142. * @return string URL encoded string
  1143. */
  1144. function build_query( $data ) {
  1145. return _http_build_query( $data, null, '&', '', false );
  1146. }
  1147. /**
  1148. * Retrieve a modified URL query string.
  1149. *
  1150. * You can rebuild the URL and append a new query variable to the URL query by
  1151. * using this function. You can also retrieve the full URL with query data.
  1152. *
  1153. * Adding a single key & value or an associative array. Setting a key value to
  1154. * emptystring removes the key. Omitting oldquery_or_uri uses the $_SERVER
  1155. * value.
  1156. *
  1157. * @since 1.5.0
  1158. *
  1159. * @param mixed $param1 Either newkey or an associative_array
  1160. * @param mixed $param2 Either newvalue or oldquery or uri
  1161. * @param mixed $param3 Optional. Old query or uri
  1162. * @return string New URL query string.
  1163. */
  1164. function add_query_arg() {
  1165. $ret = '';
  1166. if ( is_array( func_get_arg(0) ) ) {
  1167. if ( @func_num_args() < 2 || false === @func_get_arg( 1 ) )
  1168. $uri = $_SERVER['REQUEST_URI'];
  1169. else
  1170. $uri = @func_get_arg( 1 );
  1171. } else {
  1172. if ( @func_num_args() < 3 || false === @func_get_arg( 2 ) )
  1173. $uri = $_SERVER['REQUEST_URI'];
  1174. else
  1175. $uri = @func_get_arg( 2 );
  1176. }
  1177. if ( $frag = strstr( $uri, '#' ) )
  1178. $uri = substr( $uri, 0, -strlen( $frag ) );
  1179. else
  1180. $frag = '';
  1181. if ( preg_match( '|^https?://|i', $uri, $matches ) ) {
  1182. $protocol = $matches[0];
  1183. $uri = substr( $uri, strlen( $protocol ) );
  1184. } else {
  1185. $protocol = '';
  1186. }
  1187. if ( strpos( $uri, '?' ) !== false ) {
  1188. $parts = explode( '?', $uri, 2 );
  1189. if ( 1 == count( $parts ) ) {
  1190. $base = '?';
  1191. $query = $parts[0];
  1192. } else {
  1193. $base = $parts[0] . '?';
  1194. $query = $parts[1];
  1195. }
  1196. } elseif ( !empty( $protocol ) || strpos( $uri, '=' ) === false ) {
  1197. $base = $uri . '?';
  1198. $query = '';
  1199. } else {
  1200. $base = '';
  1201. $query = $uri;
  1202. }
  1203. wp_parse_str( $query, $qs );
  1204. $qs = urlencode_deep( $qs ); // this re-URL-encodes things that were already in the query string
  1205. if ( is_array( func_get_arg( 0 ) ) ) {
  1206. $kayvees = func_get_arg( 0 );
  1207. $qs = array_merge( $qs, $kayvees );
  1208. } else {
  1209. $qs[func_get_arg( 0 )] = func_get_arg( 1 );
  1210. }
  1211. foreach ( (array) $qs as $k => $v ) {
  1212. if ( $v === false )
  1213. unset( $qs[$k] );
  1214. }
  1215. $ret = build_query( $qs );
  1216. $ret = trim( $ret, '?' );
  1217. $ret = preg_replace( '#=(&|$)#', '$1', $ret );
  1218. $ret = $protocol . $base . $ret . $frag;
  1219. $ret = rtrim( $ret, '?' );
  1220. return $ret;
  1221. }
  1222. /**
  1223. * Removes an item or list from the query string.
  1224. *
  1225. * @since 1.5.0
  1226. *
  1227. * @param string|array $key Query key or keys to remove.
  1228. * @param bool $query When false uses the $_SERVER value.
  1229. * @return string New URL query string.
  1230. */
  1231. function remove_query_arg( $key, $query=false ) {
  1232. if ( is_array( $key ) ) { // removing multiple keys
  1233. foreach ( $key as $k )
  1234. $query = add_query_arg( $k, false, $query );
  1235. return $query;
  1236. }
  1237. return add_query_arg( $key, false, $query );
  1238. }
  1239. /**
  1240. * Walks the array while sanitizing the contents.
  1241. *
  1242. * @uses $wpdb Used to sanitize values
  1243. * @since 0.71
  1244. *
  1245. * @param array $array Array to used to walk while sanitizing contents.
  1246. * @return array Sanitized $array.
  1247. */
  1248. function add_magic_quotes( $array ) {
  1249. global $wpdb;
  1250. foreach ( (array) $array as $k => $v ) {
  1251. if ( is_array( $v ) ) {
  1252. $array[$k] = add_magic_quotes( $v );
  1253. } else {
  1254. $array[$k] = $wpdb->escape( $v );
  1255. }
  1256. }
  1257. return $array;
  1258. }
  1259. /**
  1260. * HTTP request for URI to retrieve content.
  1261. *
  1262. * @since 1.5.1
  1263. * @uses wp_remote_get()
  1264. *
  1265. * @param string $uri URI/URL of web page to retrieve.
  1266. * @return bool|string HTTP content. False on failure.
  1267. */
  1268. function wp_remote_fopen( $uri ) {
  1269. $parsed_url = @parse_url( $uri );
  1270. if ( !$parsed_url || !is_array( $parsed_url ) )
  1271. return false;
  1272. $options = array();
  1273. $options['timeout'] = 10;
  1274. $response = wp_remote_get( $uri, $options );
  1275. if ( is_wp_error( $response ) )
  1276. return false;
  1277. return $response['body'];
  1278. }
  1279. /**
  1280. * Setup the WordPress query.
  1281. *
  1282. * @since 2.0.0
  1283. *
  1284. * @param string $query_vars Default WP_Query arguments.
  1285. */
  1286. function wp( $query_vars = '' ) {
  1287. global $wp, $wp_query, $wp_the_query;
  1288. $wp->main( $query_vars );
  1289. if( !isset($wp_the_query) )
  1290. $wp_the_query = $wp_query;
  1291. }
  1292. /**
  1293. * Retrieve the description for the HTTP status.
  1294. *
  1295. * @since 2.3.0
  1296. *
  1297. * @param int $code HTTP status code.
  1298. * @return string Empty string if not found, or description if found.
  1299. */
  1300. function get_status_header_desc( $code ) {
  1301. global $wp_header_to_desc;
  1302. $code = absint( $code );
  1303. if ( !isset( $wp_header_to_desc ) ) {
  1304. $wp_header_to_desc = array(
  1305. 100 => 'Continue',
  1306. 101 => 'Switching Protocols',
  1307. 102 => 'Processing',
  1308. 200 => 'OK',
  1309. 201 => 'Created',
  1310. 202 => 'Accepted',
  1311. 203 => 'Non-Authoritative Information',
  1312. 204 => 'No Content',
  1313. 205 => 'Reset Content',
  1314. 206 => 'Partial Content',
  1315. 207 => 'Multi-Status',
  1316. 226 => 'IM Used',
  1317. 300 => 'Multiple Choices',
  1318. 301 => 'Moved Permanently',
  1319. 302 => 'Found',
  1320. 303 => 'See Other',
  1321. 304 => 'Not Modified',
  1322. 305 => 'Use Proxy',
  1323. 306 => 'Reserved',
  1324. 307 => 'Temporary Redirect',
  1325. 400 => 'Bad Request',
  1326. 401 => 'Unauthorized',
  1327. 402 => 'Payment Required',
  1328. 403 => 'Forbidden',
  1329. 404 => 'Not Found',
  1330. 405 => 'Method Not Allowed',
  1331. 406 => 'Not Acceptable',
  1332. 407 => 'Proxy Authentication Required',
  1333. 408 => 'Request Timeout',
  1334. 409 => 'Conflict',
  1335. 410 => 'Gone',
  1336. 411 => 'Length Required',
  1337. 412 => 'Precondition Failed',
  1338. 413 => 'Request Entity Too Large',
  1339. 414 => 'Request-URI Too Long',
  1340. 415 => 'Unsupported Media Type',
  1341. 416 => 'Requested Range Not Satisfiable',
  1342. 417 => 'Expectation Failed',
  1343. 422 => 'Unprocessable Entity',
  1344. 423 => 'Locked',
  1345. 424 => 'Failed Dependency',
  1346. 426 => 'Upgrade Required',
  1347. 500 => 'Internal Server Error',
  1348. 501 => 'Not Implemented',
  1349. 502 => 'Bad Gateway',
  1350. 503 => 'Service Unavailable',
  1351. 504 => 'Gateway Timeout',
  1352. 505 => 'HTTP Version Not Supported',
  1353. 506 => 'Variant Also Negotiates',
  1354. 507 => 'Insufficient Storage',
  1355. 510 => 'Not Extended'
  1356. );
  1357. }
  1358. if ( isset( $wp_header_to_desc[$code] ) )
  1359. return $wp_header_to_desc[$code];
  1360. else
  1361. return '';
  1362. }
  1363. /**
  1364. * Set HTTP status header.
  1365. *
  1366. * @since 2.0.0
  1367. * @uses apply_filters() Calls 'status_header' on status header string, HTTP
  1368. * HTTP code, HTTP code description, and protocol string as separate
  1369. * parameters.
  1370. *
  1371. * @param int $header HTTP status code
  1372. * @return null Does not return anything.
  1373. */
  1374. function status_header( $header ) {
  1375. $text = get_status_header_desc( $header );
  1376. if ( empty( $text ) )
  1377. return false;
  1378. $protocol = $_SERVER["SERVER_PROTOCOL"];
  1379. if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol )
  1380. $protocol = 'HTTP/1.0';
  1381. $status_header = "$protocol $header $text";
  1382. if ( function_exists( 'apply_filters' ) )
  1383. $status_header = apply_filters( 'status_header', $status_header, $header, $text, $protocol );
  1384. return @header( $status_header, true, $header );
  1385. }
  1386. /**
  1387. * Gets the header information to prevent caching.
  1388. *
  1389. * The several different headers cover the different ways cache prevention is handled
  1390. * by different browsers
  1391. *
  1392. * @since 2.8
  1393. *
  1394. * @uses apply_filters()
  1395. * @return array The associative array of header names and field values.
  1396. */
  1397. function wp_get_nocache_headers() {
  1398. $headers = array(
  1399. 'Expires' => 'Wed, 11 Jan 1984 05:00:00 GMT',
  1400. 'Last-Modified' => gmdate( 'D, d M Y H:i:s' ) . ' GMT',
  1401. 'Cache-Control' => 'no-cache, must-revalidate, max-age=0',
  1402. 'Pragma' => 'no-cache',
  1403. );
  1404. if ( function_exists('apply_filters') ) {
  1405. $headers = apply_filters('nocache_headers', $headers);
  1406. }
  1407. return $headers;
  1408. }
  1409. /**
  1410. * Sets the headers to prevent caching for the different browsers.
  1411. *
  1412. * Different browsers support different nocache headers, so several headers must
  1413. * be sent so that all of them get the point that no caching should occur.
  1414. *
  1415. * @since 2.0.0
  1416. * @uses wp_get_nocache_headers()
  1417. */
  1418. function nocache_headers() {
  1419. $headers = wp_get_nocache_headers();
  1420. foreach( (array) $headers as $name => $field_value )
  1421. @header("{$name}: {$field_value}");
  1422. }
  1423. /**
  1424. * Set the headers for caching for 10 days with JavaScript content type.
  1425. *
  1426. * @since 2.1.0
  1427. */
  1428. function cache_javascript_headers() {
  1429. $expiresOffset = 864000; // 10 days
  1430. header( "Content-Type: text/javascript; charset=" . get_bloginfo( 'charset' ) );
  1431. header( "Vary: Accept-Encoding" ); // Handle proxies
  1432. header( "Expires: " . gmdate( "D, d M Y H:i:s", time() + $expiresOffset ) . " GMT" );
  1433. }
  1434. /**
  1435. * Retrieve the number of database queries during the WordPress execution.
  1436. *
  1437. * @since 2.0.0
  1438. *
  1439. * @return int Number of database queries
  1440. */
  1441. function get_num_queries() {
  1442. global $wpdb;
  1443. return $wpdb->num_queries;
  1444. }
  1445. /**
  1446. * Whether input is yes or no. Must be 'y' to be true.
  1447. *
  1448. * @since 1.0.0
  1449. *
  1450. * @param string $yn Character string containing either 'y' or 'n'
  1451. * @return bool True if yes, false on anything else
  1452. */
  1453. function bool_from_yn( $yn ) {
  1454. return ( strtolower( $yn ) == 'y' );
  1455. }
  1456. /**
  1457. * Loads the feed template from the use of an action hook.
  1458. *
  1459. * If the feed action does not have a hook, then the function will die with a
  1460. * message telling the visitor that the feed is not valid.
  1461. *
  1462. * It is better to only have one hook for each feed.
  1463. *
  1464. * @since 2.1.0
  1465. * @uses $wp_query Used to tell if the use a comment feed.
  1466. * @uses do_action() Calls 'do_feed_$feed' hook, if a hook exists for the feed.
  1467. */
  1468. function do_feed() {
  1469. global $wp_query;
  1470. $feed = get_query_var( 'feed' );
  1471. // Remove the pad, if present.
  1472. $feed = preg_replace( '/^_+/', '', $feed );
  1473. if ( $feed == '' || $feed == 'feed' )
  1474. $feed = get_default_feed();
  1475. $hook = 'do_feed_' . $feed;
  1476. if ( !has_action($hook) ) {
  1477. $message = sprintf( __( 'ERROR: %s is not a valid feed template' ), esc_html($feed));
  1478. wp_die($message);
  1479. }
  1480. do_action( $hook, $wp_query->is_comment_feed );
  1481. }
  1482. /**
  1483. * Load the RDF RSS 0.91 Feed template.
  1484. *
  1485. * @since 2.1.0
  1486. */
  1487. function do_feed_rdf() {
  1488. load_template( ABSPATH . WPINC . '/feed-rdf.php' );
  1489. }
  1490. /**
  1491. * Load the RSS 1.0 Feed Template
  1492. *
  1493. * @since 2.1.0
  1494. */
  1495. function do_feed_rss() {
  1496. load_template( ABSPATH . WPINC . '/feed-rss.php' );
  1497. }
  1498. /**
  1499. * Load either the RSS2 comment feed or the RSS2 posts feed.
  1500. *
  1501. * @since 2.1.0
  1502. *
  1503. * @param bool $for_comments True for the comment feed, false for normal feed.
  1504. */
  1505. function do_feed_rss2( $for_comments ) {
  1506. if ( $for_comments )
  1507. load_template( ABSPATH . WPINC . '/feed-rss2-comments.php' );
  1508. else
  1509. load_template( ABSPATH . WPINC . '/feed-rss2.php' );
  1510. }
  1511. /**
  1512. * Load either Atom comment feed or Atom posts feed.
  1513. *
  1514. * @since 2.1.0
  1515. *
  1516. * @param bool $for_comments True for the comment feed, false for normal feed.
  1517. */
  1518. function do_feed_atom( $for_comments ) {
  1519. if ($for_comments)
  1520. load_template( ABSPATH . WPINC . '/feed-atom-comments.php');
  1521. else
  1522. load_template( ABSPATH . WPINC . '/feed-atom.php' );
  1523. }
  1524. /**
  1525. * Display the robot.txt file content.
  1526. *
  1527. * The echo content should be with usage of the permalinks or for creating the
  1528. * robot.txt file.
  1529. *
  1530. * @since 2.1.0
  1531. * @uses do_action() Calls 'do_robotstxt' hook for displaying robot.txt rules.
  1532. */
  1533. function do_robots() {
  1534. header( 'Content-Type: text/plain; charset=utf-8' );
  1535. do_action( 'do_robotstxt' );
  1536. if ( '0' == get_option( 'blog_public' ) ) {
  1537. echo "User-agent: *\n";
  1538. echo "Disallow: /\n";
  1539. } else {
  1540. echo "User-agent: *\n";
  1541. echo "Disallow:\n";
  1542. }
  1543. }
  1544. /**
  1545. * Test whether blog is already installed.
  1546. *
  1547. * The cache will be checked first. If you have a cache plugin, which saves the
  1548. * cache values, then this will work. If you use the default WordPress cache,
  1549. * and the database goes away, then you might have problems.
  1550. *
  1551. * Checks for the option siteurl for whether WordPress is installed.
  1552. *
  1553. * @since 2.1.0
  1554. * @uses $wpdb
  1555. *
  1556. * @return bool Whether blog is already installed.
  1557. */
  1558. function is_blog_installed() {
  1559. global $wpdb;
  1560. // Check cache first. If options table goes away and we have true cached, oh well.
  1561. if ( wp_cache_get( 'is_blog_installed' ) )
  1562. return true;
  1563. $suppress = $wpdb->suppress_errors();
  1564. $alloptions = wp_load_alloptions();
  1565. // If siteurl is not set to autoload, check it specifically
  1566. if ( !isset( $alloptions['siteurl'] ) )
  1567. $installed = $wpdb->get_var( "SELECT option_value FROM $wpdb->options WHERE option_name = 'siteurl'" );
  1568. else
  1569. $installed = $alloptions['siteurl'];
  1570. $wpdb->suppress_errors( $suppress );
  1571. $installed = !empty( $installed );
  1572. wp_cache_set( 'is_blog_installed', $installed );
  1573. return $installed;
  1574. }
  1575. /**
  1576. * Retrieve URL with nonce added to URL query.
  1577. *
  1578. * @package WordPress
  1579. * @subpackage Security
  1580. * @since 2.0.4
  1581. *
  1582. * @param string $actionurl URL to add nonce action
  1583. * @param string $action Optional. Nonce action name
  1584. * @return string URL with nonce action added.
  1585. */
  1586. function wp_nonce_url( $actionurl, $action = -1 ) {
  1587. $actionurl = str_replace( '&amp;', '&', $actionurl );
  1588. return esc_html( add_query_arg( '_wpnonce', wp_create_nonce( $action ), $actionurl ) );
  1589. }
  1590. /**
  1591. * Retrieve or display nonce hidden field for forms.
  1592. *
  1593. * The nonce field is used to validate that the contents of the form came from
  1594. * the location on the current site and not somewhere else. The nonce does not
  1595. * offer absolute protection, but should protect against most cases. It is very
  1596. * important to use nonce field in forms.
  1597. *
  1598. * If you set $echo to true and set $referer to true, then you will need to
  1599. * retrieve the {@link wp_referer_field() wp referer field}. If you have the
  1600. * $referer set to true and are echoing the nonce field, it will also echo the
  1601. * referer field.
  1602. *
  1603. * The $action and $name are optional, but if you want to have better security,
  1604. * it is strongly suggested to set those two parameters. It is easier to just
  1605. * call the function without any parameters, because validation of the nonce
  1606. * doesn't require any parameters, but since crackers know what the default is
  1607. * it won't be difficult for them to find a way around your nonce and cause
  1608. * damage.
  1609. *
  1610. * The input name will be whatever $name value you gave. The input value will be
  1611. * the nonce creation value.
  1612. *
  1613. * @package WordPress
  1614. * @subpackage Security
  1615. * @since 2.0.4
  1616. *
  1617. * @param string $action Optional. Action name.
  1618. * @param string $name Optional. Nonce name.
  1619. * @param bool $referer Optional, default true. Whether to set the referer field for validation.
  1620. * @param bool $echo Optional, default true. Whether to display or return hidden form field.
  1621. * @return string Nonce field.
  1622. */
  1623. function wp_nonce_field( $action = -1, $name = "_wpnonce", $referer = true , $echo = true ) {
  1624. $name = esc_attr( $name );
  1625. $nonce_field = '<input type="hidden" id="' . $name . '" name="' . $name . '" value="' . wp_create_nonce( $action ) . '" />';
  1626. if ( $echo )
  1627. echo $nonce_field;
  1628. if ( $referer )
  1629. wp_referer_field( $echo, 'previous' );
  1630. return $nonce_field;
  1631. }
  1632. /**
  1633. * Retrieve or display referer hidden field for forms.
  1634. *
  1635. * The referer link is the current Request URI from the server super global. The
  1636. * input name is '_wp_http_referer', in case you wanted to check manually.
  1637. *
  1638. * @package WordPress
  1639. * @subpackage Security
  1640. * @since 2.0.4
  1641. *
  1642. * @param bool $echo Whether to echo or return the referer field.
  1643. * @return string Referer field.
  1644. */
  1645. function wp_referer_field( $echo = true) {
  1646. $ref = esc_attr( $_SERVER['REQUEST_URI'] );
  1647. $referer_field = '<input type="hidden" name="_wp_http_referer" value="'. $ref . '" />';
  1648. if ( $echo )
  1649. echo $referer_field;
  1650. return $referer_field;
  1651. }
  1652. /**
  1653. * Retrieve or display original referer hidden field for forms.
  1654. *
  1655. * The input name is '_wp_original_http_referer' and will be either the same
  1656. * value of {@link wp_referer_field()}, if that was posted already or it will
  1657. * be the current page, if it doesn't exist.
  1658. *
  1659. * @package WordPress
  1660. * @subpackage Security
  1661. * @since 2.0.4
  1662. *
  1663. * @param bool $echo Whether to echo the original http referer
  1664. * @param string $jump_back_to Optional, default is 'current'. Can be 'previous' or page you want to jump back to.
  1665. * @return string Original referer field.
  1666. */
  1667. function wp_original_referer_field( $echo = true, $jump_back_to = 'current' ) {
  1668. $jump_back_to = ( 'previous' == $jump_back_to ) ? wp_get_referer() : $_SERVER['REQUEST_URI'];
  1669. $ref = ( wp_get_original_referer() ) ? wp_get_original_referer() : $jump_back_to;
  1670. $orig_referer_field = '<input type="hidden" name="_wp_original_http_referer" value="' . esc_attr( stripslashes( $ref ) ) . '" />';
  1671. if ( $echo )
  1672. echo $orig_referer_field;
  1673. return $orig_referer_field;
  1674. }
  1675. /**
  1676. * Retrieve referer from '_wp_http_referer', HTTP referer, or current page respectively.
  1677. *
  1678. * @package WordPress
  1679. * @subpackage Security
  1680. * @since 2.0.4
  1681. *
  1682. * @return string|bool False on failure. Referer URL on success.
  1683. */
  1684. function wp_get_referer() {
  1685. $ref = '';
  1686. if ( ! empty( $_REQUEST['_wp_http_referer'] ) )
  1687. $ref = $_REQUEST['_wp_http_referer'];
  1688. else if ( ! empty( $_SERVER['HTTP_REFERER'] ) )
  1689. $ref = $_SERVER['HTTP_REFERER'];
  1690. if ( $ref !== $_SERVER['REQUEST_URI'] )
  1691. return $ref;
  1692. return false;
  1693. }
  1694. /**
  1695. * Retrieve original referer that was posted, if it exists.
  1696. *
  1697. * @package WordPress
  1698. * @subpackage Security
  1699. * @since 2.0.4
  1700. *
  1701. * @return string|bool False if no original referer or original referer if set.
  1702. */
  1703. function wp_get_original_referer() {
  1704. if ( !empty( $_REQUEST['_wp_original_http_referer'] ) )
  1705. return $_REQUEST['_wp_original_http_referer'];
  1706. return false;
  1707. }
  1708. /**
  1709. * Recursive directory creation based on full path.
  1710. *
  1711. * Will attempt to set permissions on folders.
  1712. *
  1713. * @since 2.0.1
  1714. *
  1715. * @param string $target Full path to attempt to create.
  1716. * @return bool Whether the path was created or not. True if path already exists.
  1717. */
  1718. function wp_mkdir_p( $target ) {
  1719. // from php.net/mkdir user contributed notes
  1720. $target = str_replace( '//', '/', $target );
  1721. if ( file_exists( $target ) )
  1722. return @is_dir( $target );
  1723. // Attempting to create the directory may clutter up our display.
  1724. if ( @mkdir( $target ) ) {
  1725. $stat = @stat( dirname( $target ) );
  1726. $dir_perms = $stat['mode'] & 0007777; // Get the permission bits.
  1727. @chmod( $target, $dir_perms );
  1728. return true;
  1729. } elseif ( is_dir( dirname( $target ) ) ) {
  1730. return false;
  1731. }
  1732. // If the above failed, attempt to create the parent node, then try again.
  1733. if ( ( $target != '/' ) && ( wp_mkdir_p( dirname( $target ) ) ) )
  1734. return wp_mkdir_p( $target );
  1735. return false;
  1736. }
  1737. /**
  1738. * Test if a give filesystem path is absolute ('/foo/bar', 'c:\windows').
  1739. *
  1740. * @since 2.5.0
  1741. *
  1742. * @param string $path File path
  1743. * @return bool True if path is absolute, false is not absolute.
  1744. */
  1745. function path_is_absolute( $path ) {
  1746. // this is definitive if true but fails if $path does not exist or contains a symbolic link
  1747. if ( realpath($path) == $path )
  1748. return true;
  1749. if ( strlen($path) == 0 || $path{0} == '.' )
  1750. return false;
  1751. // windows allows absolute paths like this
  1752. if ( preg_match('#^[a-zA-Z]:\\\\#', $path) )
  1753. return true;
  1754. // a path starting with / or \ is absolute; anything else is relative
  1755. return (bool) preg_match('#^[/\\\\]#', $path);
  1756. }
  1757. /**
  1758. * Join two filesystem paths together (e.g. 'give me $path relative to $base').
  1759. *
  1760. * If the $path is absolute, then it the full path is returned.
  1761. *
  1762. * @since 2.5.0
  1763. *
  1764. * @param string $base
  1765. * @param string $path
  1766. * @return string The path with the base or absolute path.
  1767. */
  1768. function path_join( $base, $path ) {
  1769. if ( path_is_absolute($path) )
  1770. return $path;
  1771. return rtrim($base, '/') . '/' . ltrim($path, '/');
  1772. }
  1773. /**
  1774. * Get an array containing the current upload directory's path and url.
  1775. *
  1776. * Checks the 'upload_path' option, which should be from the web root folder,
  1777. * and if it isn't empty it will be used. If it is empty, then the path will be
  1778. * 'WP_CONTENT_DIR/uploads'. If the 'UPLOADS' constant is defined, then it will
  1779. * override the 'upload_path' option and 'WP_CONTENT_DIR/uploads' path.
  1780. *
  1781. * The upload URL path is set either by the 'upload_url_path' option or by using
  1782. * the 'WP_CONTENT_URL' constant and appending '/uploads' to the path.
  1783. *
  1784. * If the 'uploads_use_yearmonth_folders' is set to true (checkbox if checked in
  1785. * the administration settings panel), then the time will be used. The format
  1786. * will be year first and then month.
  1787. *
  1788. * If the path couldn't be created, then an error will be returned with the key
  1789. * 'error' containing the error message. The error suggests that the parent
  1790. * directory is not writable by the server.
  1791. *
  1792. * On success, the returned array will have many indices:
  1793. * 'path' - base directory and sub directory or full path to upload directory.
  1794. * 'url' - base url and sub directory or absolute URL to upload directory.
  1795. * 'subdir' - sub directory if uploads use year/month folders option is on.
  1796. * 'basedir' - path without subdir.
  1797. * 'baseurl' - URL path without subdir.
  1798. * 'error' - set to false.
  1799. *
  1800. * @since 2.0.0
  1801. * @uses apply_filters() Calls 'upload_dir' on returned array.
  1802. *
  1803. * @param string $time Optional. Time formatted in 'yyyy/mm'.
  1804. * @return array See above for description.
  1805. */
  1806. function wp_upload_dir( $time = null ) {
  1807. $siteurl = get_option( 'siteurl' );
  1808. $upload_path = get_option( 'upload_path' );
  1809. $upload_path = trim($upload_path);
  1810. if ( empty($upload_path) )
  1811. $dir = WP_CONTENT_DIR . '/uploads';
  1812. else
  1813. $dir = $upload_path;
  1814. // $dir is absolute, $path is (maybe) relative to ABSPATH
  1815. $dir = path_join( ABSPATH, $dir );
  1816. if ( !$url = get_option( 'upload_url_path' ) ) {
  1817. if ( empty($upload_path) or ( $upload_path == $dir ) )
  1818. $url = WP_CONTENT_URL . '/uploads';
  1819. else
  1820. $url = trailingslashit( $siteurl ) . $upload_path;
  1821. }
  1822. if ( defined('UPLOADS') ) {
  1823. $dir = ABSPATH . UPLOADS;
  1824. $url = trailingslashit( $siteurl ) . UPLOADS;
  1825. }
  1826. $bdir = $dir;
  1827. $burl = $url;
  1828. $subdir = '';
  1829. if ( get_option( 'uploads_use_yearmonth_folders' ) ) {
  1830. // Generate the yearly and monthly dirs
  1831. if ( !$time )
  1832. $time = current_time( 'mysql' );
  1833. $y = substr( $time, 0, 4 );
  1834. $m = substr( $time, 5, 2 );
  1835. $subdir = "/$y/$m";
  1836. }
  1837. $dir .= $subdir;
  1838. $url .= $subdir;
  1839. $uploads = apply_filters( 'upload_dir', array( 'path' => $dir, 'url' => $url, 'subdir' => $subdir, 'basedir' => $bdir, 'baseurl' => $burl, 'error' => false ) );
  1840. // Make sure we have an uploads dir
  1841. if ( ! wp_mkdir_p( $uploads['path'] ) ) {
  1842. $message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), $uploads['path'] );
  1843. return array( 'error' => $message );
  1844. }
  1845. return $uploads;
  1846. }
  1847. /**
  1848. * Get a filename that is sanitized and unique for the given directory.
  1849. *
  1850. * If the filename is not unique, then a number will be added to the filename
  1851. * before the extension, and will continue adding numbers until the filename is
  1852. * unique.
  1853. *
  1854. * The callback must accept two parameters, the first one is the directory and
  1855. * the second is the filename. The callback must be a function.
  1856. *
  1857. * @since 2.5
  1858. *
  1859. * @param string $dir
  1860. * @param string $filename
  1861. * @param string $unique_filename_callback Function name, must be a function.
  1862. * @return string New filename, if given wasn't unique.
  1863. */
  1864. function wp_unique_filename( $dir, $filename, $unique_filename_callback = null ) {
  1865. // sanitize the file name before we begin processing
  1866. $filename = sanitize_file_name($filename);
  1867. // separate the filename into a name and extension
  1868. $info = pathinfo($filename);
  1869. $ext = !empty($info['extension']) ? $info['extension'] : '';
  1870. $name = basename($filename, ".{$ext}");
  1871. // edge case: if file is named '.ext', treat as an empty name
  1872. if( $name === ".$ext" )
  1873. $name = '';
  1874. // Increment the file number until we have a unique file to save in $dir. Use $override['unique_filename_callback'] if supplied.
  1875. if ( $unique_filename_callback && function_exists( $unique_filename_callback ) ) {
  1876. $filename = $unique_filename_callback( $dir, $name );
  1877. } else {
  1878. $number = '';
  1879. if ( !empty( $ext ) )
  1880. $ext = ".$ext";
  1881. while ( file_exists( $dir . "/$filename" ) ) {
  1882. if ( '' == "$number$ext" )
  1883. $filename = $filename . ++$number . $ext;
  1884. else
  1885. $filename = str_replace( "$number$ext", ++$number . $ext, $filename );
  1886. }
  1887. }
  1888. return $filename;
  1889. }
  1890. /**
  1891. * Create a file in the upload folder with given content.
  1892. *
  1893. * If there is an error, then the key 'error' will exist with the error message.
  1894. * If success, then the key 'file' will have the unique file path, the 'url' key
  1895. * will have the link to the new file. and the 'error' key will be set to false.
  1896. *
  1897. * This function will not move an uploaded file to the upload folder. It will
  1898. * create a new file with the content in $bits parameter. If you move the upload
  1899. * file, read the content of the uploaded file, and then you can give the
  1900. * filename and content to this function, which will add it to the upload
  1901. * folder.
  1902. *
  1903. * The permissions will be set on the new file automatically by this function.
  1904. *
  1905. * @since 2.0.0
  1906. *
  1907. * @param string $name
  1908. * @param null $deprecated Not used. Set to null.
  1909. * @param mixed $bits File content
  1910. * @param string $time Optional. Time formatted in 'yyyy/mm'.
  1911. * @return array
  1912. */
  1913. function wp_upload_bits( $name, $deprecated, $bits, $time = null ) {
  1914. if ( empty( $name ) )
  1915. return array( 'error' => __( 'Empty filename' ) );
  1916. $wp_filetype = wp_check_filetype( $name );
  1917. if ( !$wp_filetype['ext'] )
  1918. return array( 'error' => __( 'Invalid file type' ) );
  1919. $upload = wp_upload_dir( $time );
  1920. if ( $upload['error'] !== false )
  1921. return $upload;
  1922. $filename = wp_unique_filename( $upload['path'], $name );
  1923. $new_file = $upload['path'] . "/$filename";
  1924. if ( ! wp_mkdir_p( dirname( $new_file ) ) ) {
  1925. $message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), dirname( $new_file ) );
  1926. return array( 'error' => $message );
  1927. }
  1928. $ifp = @ fopen( $new_file, 'wb' );
  1929. if ( ! $ifp )
  1930. return array( 'error' => sprintf( __( 'Could not write file %s' ), $new_file ) );
  1931. @fwrite( $ifp, $bits );
  1932. fclose( $ifp );
  1933. // Set correct file permissions
  1934. $stat = @ stat( dirname( $new_file ) );
  1935. $perms = $stat['mode'] & 0007777;
  1936. $perms = $perms & 0000666;
  1937. @ chmod( $new_file, $perms );
  1938. // Compute the URL
  1939. $url = $upload['url'] . "/$filename";
  1940. return array( 'file' => $new_file, 'url' => $url, 'error' => false );
  1941. }
  1942. /**
  1943. * Retrieve the file type based on the extension name.
  1944. *
  1945. * @package WordPress
  1946. * @since 2.5.0
  1947. * @uses apply_filters() Calls 'ext2type' hook on default supported types.
  1948. *
  1949. * @param string $ext The extension to search.
  1950. * @return string|null The file type, example: audio, video, document, spreadsheet, etc. Null if not found.
  1951. */
  1952. function wp_ext2type( $ext ) {
  1953. $ext2type = apply_filters('ext2type', array(
  1954. 'audio' => array('aac','ac3','aif','aiff','mp1','mp2','mp3','m3a','m4a','m4b','ogg','ram','wav','wma'),
  1955. 'video' => array('asf','avi','divx','dv','mov','mpg','mpeg','mp4','mpv','ogm','qt','rm','vob','wmv', 'm4v'),
  1956. 'document' => array('doc','docx','pages','odt','rtf','pdf'),
  1957. 'spreadsheet' => array('xls','xlsx','numbers','ods'),
  1958. 'interactive' => array('ppt','pptx','key','odp','swf'),
  1959. 'text' => array('txt'),
  1960. 'archive' => array('tar','bz2','gz','cab','dmg','rar','sea','sit','sqx','zip'),
  1961. 'code' => array('css','html','php','js'),
  1962. ));
  1963. foreach ( $ext2type as $type => $exts )
  1964. if ( in_array($ext, $exts) )
  1965. return $type;
  1966. }
  1967. /**
  1968. * Retrieve the file type from the file name.
  1969. *
  1970. * You can optionally define the mime array, if needed.
  1971. *
  1972. * @since 2.0.4
  1973. *
  1974. * @param string $filename File name or path.
  1975. * @param array $mimes Optional. Key is the file extension with value as the mime type.
  1976. * @return array Values with extension first and mime type.
  1977. */
  1978. function wp_check_filetype( $filename, $mimes = null ) {
  1979. // Accepted MIME types are set here as PCRE unless provided.
  1980. $mimes = ( is_array( $mimes ) ) ? $mimes : apply_filters( 'upload_mimes', array(
  1981. 'jpg|jpeg|jpe' => 'image/jpeg',
  1982. 'gif' => 'image/gif',
  1983. 'png' => 'image/png',
  1984. 'bmp' => 'image/bmp',
  1985. 'tif|tiff' => 'image/tiff',
  1986. 'ico' => 'image/x-icon',
  1987. 'asf|asx|wax|wmv|wmx' => 'video/asf',
  1988. 'avi' => 'video/avi',
  1989. 'divx' => 'video/divx',
  1990. 'mov|qt' => 'video/quicktime',
  1991. 'mpeg|mpg|mpe' => 'video/mpeg',
  1992. 'txt|c|cc|h' => 'text/plain',
  1993. 'rtx' => 'text/richtext',
  1994. 'css' => 'text/css',
  1995. 'htm|html' => 'text/html',
  1996. 'mp3|m4a' => 'audio/mpeg',
  1997. 'mp4|m4v' => 'video/mp4',
  1998. 'ra|ram' => 'audio/x-realaudio',
  1999. 'wav' => 'audio/wav',
  2000. 'ogg' => 'audio/ogg',
  2001. 'mid|midi' => 'audio/midi',
  2002. 'wma' => 'audio/wma',
  2003. 'rtf' => 'application/rtf',
  2004. 'js' => 'application/javascript',
  2005. 'pdf' => 'application/pdf',
  2006. 'doc|docx' => 'application/msword',
  2007. 'pot|pps|ppt|pptx' => 'application/vnd.ms-powerpoint',
  2008. 'wri' => 'application/vnd.ms-write',
  2009. 'xla|xls|xlsx|xlt|xlw' => 'application/vnd.ms-excel',
  2010. 'mdb' => 'application/vnd.ms-access',
  2011. 'mpp' => 'application/vnd.ms-project',
  2012. 'swf' => 'application/x-shockwave-flash',
  2013. 'class' => 'application/java',
  2014. 'tar' => 'application/x-tar',
  2015. 'zip' => 'application/zip',
  2016. 'gz|gzip' => 'application/x-gzip',
  2017. 'exe' => 'application/x-msdownload',
  2018. // openoffice formats
  2019. 'odt' => 'application/vnd.oasis.opendocument.text',
  2020. 'odp' => 'application/vnd.oasis.opendocument.presentation',
  2021. 'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
  2022. 'odg' => 'application/vnd.oasis.opendocument.graphics',
  2023. 'odc' => 'application/vnd.oasis.opendocument.chart',
  2024. 'odb' => 'application/vnd.oasis.opendocument.database',
  2025. 'odf' => 'application/vnd.oasis.opendocument.formula',
  2026. )
  2027. );
  2028. $type = false;
  2029. $ext = false;
  2030. foreach ( $mimes as $ext_preg => $mime_match ) {
  2031. $ext_preg = '!\.(' . $ext_preg . ')$!i';
  2032. if ( preg_match( $ext_preg, $filename, $ext_matches ) ) {
  2033. $type = $mime_match;
  2034. $ext = $ext_matches[1];
  2035. break;
  2036. }
  2037. }
  2038. return compact( 'ext', 'type' );
  2039. }
  2040. /**
  2041. * Retrieve nonce action "Are you sure" message.
  2042. *
  2043. * The action is split by verb and noun. The action format is as follows:
  2044. * verb-action_extra. The verb is before the first dash and has the format of
  2045. * letters and no spaces and numbers. The noun is after the dash and before the
  2046. * underscore, if an underscore exists. The noun is also only letters.
  2047. *
  2048. * The filter will be called for any action, which is not defined by WordPress.
  2049. * You may use the filter for your plugin to explain nonce actions to the user,
  2050. * when they get the "Are you sure?" message. The filter is in the format of
  2051. * 'explain_nonce_$verb-$noun' with the $verb replaced by the found verb and the
  2052. * $noun replaced by the found noun. The two parameters that are given to the
  2053. * hook are the localized "Are you sure you want to do this?" message with the
  2054. * extra text (the text after the underscore).
  2055. *
  2056. * @package WordPress
  2057. * @subpackage Security
  2058. * @since 2.0.4
  2059. *
  2060. * @param string $action Nonce action.
  2061. * @return string Are you sure message.
  2062. */
  2063. function wp_explain_nonce( $action ) {
  2064. if ( $action !== -1 && preg_match( '/([a-z]+)-([a-z]+)(_(.+))?/', $action, $matches ) ) {
  2065. $verb = $matches[1];
  2066. $noun = $matches[2];
  2067. $trans = array();
  2068. $trans['update']['attachment'] = array( __( 'Your attempt to edit this attachment: &#8220;%s&#8221; has failed.' ), 'get_the_title' );
  2069. $trans['add']['category'] = array( __( 'Your attempt to add this category has failed.' ), false );
  2070. $trans['delete']['category'] = array( __( 'Your attempt to delete this category: &#8220;%s&#8221; has failed.' ), 'get_cat_name' );
  2071. $trans['update']['category'] = array( __( 'Your attempt to edit this category: &#8220;%s&#8221; has failed.' ), 'get_cat_name' );
  2072. $trans['delete']['comment'] = array( __( 'Your attempt to delete this comment: &#8220;%s&#8221; has failed.' ), 'use_id' );
  2073. $trans['unapprove']['comment'] = array( __( 'Your attempt to unapprove this comment: &#8220;%s&#8221; has failed.' ), 'use_id' );
  2074. $trans['approve']['comment'] = array( __( 'Your attempt to approve this comment: &#8220;%s&#8221; has failed.' ), 'use_id' );
  2075. $trans['update']['comment'] = array( __( 'Your attempt to edit this comment: &#8220;%s&#8221; has failed.' ), 'use_id' );
  2076. $trans['bulk']['comments'] = array( __( 'Your attempt to bulk modify comments has failed.' ), false );
  2077. $trans['moderate']['comments'] = array( __( 'Your attempt to moderate comments has failed.' ), false );
  2078. $trans['add']['bookmark'] = array( __( 'Your attempt to add this link has failed.' ), false );
  2079. $trans['delete']['bookmark'] = array( __( 'Your attempt to delete this link: &#8220;%s&#8221; has failed.' ), 'use_id' );
  2080. $trans['update']['bookmark'] = array( __( 'Your attempt to edit this link: &#8220;%s&#8221; has failed.' ), 'use_id' );
  2081. $trans['bulk']['bookmarks'] = array( __( 'Your attempt to bulk modify links has failed.' ), false );
  2082. $trans['add']['page'] = array( __( 'Your attempt to add this page has failed.' ), false );
  2083. $trans['delete']['page'] = array( __( 'Your attempt to delete this page: &#8220;%s&#8221; has failed.' ), 'get_the_title' );
  2084. $trans['update']['page'] = array( __( 'Your attempt to edit this page: &#8220;%s&#8221; has failed.' ), 'get_the_title' );
  2085. $trans['edit']['plugin'] = array( __( 'Your attempt to edit this plugin file: &#8220;%s&#8221; has failed.' ), 'use_id' );
  2086. $trans['activate']['plugin'] = array( __( 'Your attempt to activate this plugin: &#8220;%s&#8221; has failed.' ), 'use_id' );
  2087. $trans['deactivate']['plugin'] = array( __( 'Your attempt to deactivate this plugin: &#8220;%s&#8221; has failed.' ), 'use_id' );
  2088. $trans['upgrade']['plugin'] = array( __( 'Your attempt to upgrade this plugin: &#8220;%s&#8221; has failed.' ), 'use_id' );
  2089. $trans['add']['post'] = array( __( 'Your attempt to add this post has failed.' ), false );
  2090. $trans['delete']['post'] = array( __( 'Your attempt to delete this post: &#8220;%s&#8221; has failed.' ), 'get_the_title' );
  2091. $trans['update']['post'] = array( __( 'Your attempt to edit this post: &#8220;%s&#8221; has failed.' ), 'get_the_title' );
  2092. $trans['add']['user'] = array( __( 'Your attempt to add this user has failed.' ), false );
  2093. $trans['delete']['users'] = array( __( 'Your attempt to delete users has failed.' ), false );
  2094. $trans['bulk']['users'] = array( __( 'Your attempt to bulk modify users has failed.' ), false );
  2095. $trans['update']['user'] = array( __( 'Your attempt to edit this user: &#8220;%s&#8221; has failed.' ), 'get_the_author_meta', 'display_name' );
  2096. $trans['update']['profile'] = array( __( 'Your attempt to modify the profile for: &#8220;%s&#8221; has failed.' ), 'get_the_author_meta', 'display_name' );
  2097. $trans['update']['options'] = array( __( 'Your attempt to edit your settings has failed.' ), false );
  2098. $trans['update']['permalink'] = array( __( 'Your attempt to change your permalink structure to: %s has failed.' ), 'use_id' );
  2099. $trans['edit']['file'] = array( __( 'Your attempt to edit this file: &#8220;%s&#8221; has failed.' ), 'use_id' );
  2100. $trans['edit']['theme'] = array( __( 'Your attempt to edit this theme file: &#8220;%s&#8221; has failed.' ), 'use_id' );
  2101. $trans['switch']['theme'] = array( __( 'Your attempt to switch to this theme: &#8220;%s&#8221; has failed.' ), 'use_id' );
  2102. $trans['log']['out'] = array( sprintf( __( 'You are attempting to log out of %s' ), get_bloginfo( 'sitename' ) ), false );
  2103. if ( isset( $trans[$verb][$noun] ) ) {
  2104. if ( !empty( $trans[$verb][$noun][1] ) ) {
  2105. $lookup = $trans[$verb][$noun][1];
  2106. if ( isset($trans[$verb][$noun][2]) )
  2107. $lookup_value = $trans[$verb][$noun][2];
  2108. $object = $matches[4];
  2109. if ( 'use_id' != $lookup ) {
  2110. if ( isset( $lookup_value ) )
  2111. $object = call_user_func( $lookup, $lookup_value, $object );
  2112. else
  2113. $object = call_user_func( $lookup, $object );
  2114. }
  2115. return sprintf( $trans[$verb][$noun][0], esc_html($object) );
  2116. } else {
  2117. return $trans[$verb][$noun][0];
  2118. }
  2119. }
  2120. return apply_filters( 'explain_nonce_' . $verb . '-' . $noun, __( 'Are you sure you want to do this?' ), $matches[4] );
  2121. } else {
  2122. return apply_filters( 'explain_nonce_' . $action, __( 'Are you sure you want to do this?' ) );
  2123. }
  2124. }
  2125. /**
  2126. * Display "Are You Sure" message to confirm the action being taken.
  2127. *
  2128. * If the action has the nonce explain message, then it will be displayed along
  2129. * with the "Are you sure?" message.
  2130. *
  2131. * @package WordPress
  2132. * @subpackage Security
  2133. * @since 2.0.4
  2134. *
  2135. * @param string $action The nonce action.
  2136. */
  2137. function wp_nonce_ays( $action ) {
  2138. $title = __( 'WordPress Failure Notice' );
  2139. $html = esc_html( wp_explain_nonce( $action ) );
  2140. if ( wp_get_referer() )
  2141. $html .= "</p><p><a href='" . esc_url( remove_query_arg( 'updated', wp_get_referer() ) ) . "'>" . __( 'Please try again.' ) . "</a>";
  2142. elseif ( 'log-out' == $action )
  2143. $html .= "</p><p>" . sprintf( __( "Do you really want to <a href='%s'>log out</a>?"), wp_logout_url() );
  2144. wp_die( $html, $title);
  2145. }
  2146. /**
  2147. * Kill WordPress execution and display HTML message with error message.
  2148. *
  2149. * Call this function complements the die() PHP function. The difference is that
  2150. * HTML will be displayed to the user. It is recommended to use this function
  2151. * only, when the execution should not continue any further. It is not
  2152. * recommended to call this function very often and try to handle as many errors
  2153. * as possible siliently.
  2154. *
  2155. * @since 2.0.4
  2156. *
  2157. * @param string $message Error message.
  2158. * @param string $title Error title.
  2159. * @param string|array $args Optional arguements to control behaviour.
  2160. */
  2161. function wp_die( $message, $title = '', $args = array() ) {
  2162. global $wp_locale;
  2163. $defaults = array( 'response' => 500 );
  2164. $r = wp_parse_args($args, $defaults);
  2165. $have_gettext = function_exists('__');
  2166. if ( function_exists( 'is_wp_error' ) && is_wp_error( $message ) ) {
  2167. if ( empty( $title ) ) {
  2168. $error_data = $message->get_error_data();
  2169. if ( is_array( $error_data ) && isset( $error_data['title'] ) )
  2170. $title = $error_data['title'];
  2171. }
  2172. $errors = $message->get_error_messages();
  2173. switch ( count( $errors ) ) :
  2174. case 0 :
  2175. $message = '';
  2176. break;
  2177. case 1 :
  2178. $message = "<p>{$errors[0]}</p>";
  2179. break;
  2180. default :
  2181. $message = "<ul>\n\t\t<li>" . join( "</li>\n\t\t<li>", $errors ) . "</li>\n\t</ul>";
  2182. break;
  2183. endswitch;
  2184. } elseif ( is_string( $message ) ) {
  2185. $message = "<p>$message</p>";
  2186. }
  2187. if ( isset( $r['back_link'] ) && $r['back_link'] ) {
  2188. $back_text = $have_gettext? __('&laquo; Back') : '&laquo; Back';
  2189. $message .= "\n<p><a href='javascript:history.back()'>$back_text</p>";
  2190. }
  2191. if ( defined( 'WP_SITEURL' ) && '' != WP_SITEURL )
  2192. $admin_dir = WP_SITEURL . '/wp-admin/';
  2193. elseif ( function_exists( 'get_bloginfo' ) && '' != get_bloginfo( 'wpurl' ) )
  2194. $admin_dir = get_bloginfo( 'wpurl' ) . '/wp-admin/';
  2195. elseif ( strpos( $_SERVER['PHP_SELF'], 'wp-admin' ) !== false )
  2196. $admin_dir = '';
  2197. else
  2198. $admin_dir = 'wp-admin/';
  2199. if ( !function_exists( 'did_action' ) || !did_action( 'admin_head' ) ) :
  2200. if( !headers_sent() ){
  2201. status_header( $r['response'] );
  2202. nocache_headers();
  2203. header( 'Content-Type: text/html; charset=utf-8' );
  2204. }
  2205. if ( empty($title) ) {
  2206. $title = $have_gettext? __('WordPress &rsaquo; Error') : 'WordPress &rsaquo; Error';
  2207. }
  2208. $text_direction = 'ltr';
  2209. if ( isset($r['text_direction']) && $r['text_direction'] == 'rtl' ) $text_direction = 'rtl';
  2210. if ( ( $wp_locale ) && ( 'rtl' == $wp_locale->text_direction ) ) $text_direction = 'rtl';
  2211. ?>
  2212. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2213. <html xmlns="http://www.w3.org/1999/xhtml" <?php if ( function_exists( 'language_attributes' ) ) language_attributes(); ?>>
  2214. <head>
  2215. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  2216. <title><?php echo $title ?></title>
  2217. <link rel="stylesheet" href="<?php echo $admin_dir; ?>css/install.css" type="text/css" />
  2218. <?php
  2219. if ( 'rtl' == $text_direction ) : ?>
  2220. <link rel="stylesheet" href="<?php echo $admin_dir; ?>css/install-rtl.css" type="text/css" />
  2221. <?php endif; ?>
  2222. </head>
  2223. <body id="error-page">
  2224. <?php endif; ?>
  2225. <?php echo $message; ?>
  2226. </body>
  2227. <!-- Ticket #8942, IE bug fix: always pad the error page with enough characters such that it is greater than 512 bytes, even after gzip compression abcdefghijklmnopqrstuvwxyz1234567890aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz11223344556677889900abacbcbdcdcededfefegfgfhghgihihjijikjkjlklkmlmlnmnmononpopoqpqprqrqsrsrtstsubcbcdcdedefefgfabcadefbghicjkldmnoepqrfstugvwxhyz1i234j567k890laabmbccnddeoeffpgghqhiirjjksklltmmnunoovppqwqrrxsstytuuzvvw0wxx1yyz2z113223434455666777889890091abc2def3ghi4jkl5mno6pqr7stu8vwx9yz11aab2bcc3dd4ee5ff6gg7hh8ii9j0jk1kl2lmm3nnoo4p5pq6qrr7ss8tt9uuvv0wwx1x2yyzz13aba4cbcb5dcdc6dedfef8egf9gfh0ghg1ihi2hji3jik4jkj5lkl6kml7mln8mnm9ono -->
  2228. </html>
  2229. <?php
  2230. die();
  2231. }
  2232. /**
  2233. * Retrieve the WordPress home page URL.
  2234. *
  2235. * If the constant named 'WP_HOME' exists, then it willl be used and returned by
  2236. * the function. This can be used to counter the redirection on your local
  2237. * development environment.
  2238. *
  2239. * @access private
  2240. * @package WordPress
  2241. * @since 2.2.0
  2242. *
  2243. * @param string $url URL for the home location
  2244. * @return string Homepage location.
  2245. */
  2246. function _config_wp_home( $url = '' ) {
  2247. if ( defined( 'WP_HOME' ) )
  2248. return WP_HOME;
  2249. return $url;
  2250. }
  2251. /**
  2252. * Retrieve the WordPress site URL.
  2253. *
  2254. * If the constant named 'WP_SITEURL' is defined, then the value in that
  2255. * constant will always be returned. This can be used for debugging a site on
  2256. * your localhost while not having to change the database to your URL.
  2257. *
  2258. * @access private
  2259. * @package WordPress
  2260. * @since 2.2.0
  2261. *
  2262. * @param string $url URL to set the WordPress site location.
  2263. * @return string The WordPress Site URL
  2264. */
  2265. function _config_wp_siteurl( $url = '' ) {
  2266. if ( defined( 'WP_SITEURL' ) )
  2267. return WP_SITEURL;
  2268. return $url;
  2269. }
  2270. /**
  2271. * Set the localized direction for MCE plugin.
  2272. *
  2273. * Will only set the direction to 'rtl', if the WordPress locale has the text
  2274. * direction set to 'rtl'.
  2275. *
  2276. * Fills in the 'directionality', 'plugins', and 'theme_advanced_button1' array
  2277. * keys. These keys are then returned in the $input array.
  2278. *
  2279. * @access private
  2280. * @package WordPress
  2281. * @subpackage MCE
  2282. * @since 2.1.0
  2283. *
  2284. * @param array $input MCE plugin array.
  2285. * @return array Direction set for 'rtl', if needed by locale.
  2286. */
  2287. function _mce_set_direction( $input ) {
  2288. global $wp_locale;
  2289. if ( 'rtl' == $wp_locale->text_direction ) {
  2290. $input['directionality'] = 'rtl';
  2291. $input['plugins'] .= ',directionality';
  2292. $input['theme_advanced_buttons1'] .= ',ltr';
  2293. }
  2294. return $input;
  2295. }
  2296. /**
  2297. * Convert smiley code to the icon graphic file equivalent.
  2298. *
  2299. * You can turn off smilies, by going to the write setting screen and unchecking
  2300. * the box, or by setting 'use_smilies' option to false or removing the option.
  2301. *
  2302. * Plugins may override the default smiley list by setting the $wpsmiliestrans
  2303. * to an array, with the key the code the blogger types in and the value the
  2304. * image file.
  2305. *
  2306. * The $wp_smiliessearch global is for the regular expression and is set each
  2307. * time the function is called.
  2308. *
  2309. * The full list of smilies can be found in the function and won't be listed in
  2310. * the description. Probably should create a Codex page for it, so that it is
  2311. * available.
  2312. *
  2313. * @global array $wpsmiliestrans
  2314. * @global array $wp_smiliessearch
  2315. * @since 2.2.0
  2316. */
  2317. function smilies_init() {
  2318. global $wpsmiliestrans, $wp_smiliessearch;
  2319. // don't bother setting up smilies if they are disabled
  2320. if ( !get_option( 'use_smilies' ) )
  2321. return;
  2322. if ( !isset( $wpsmiliestrans ) ) {
  2323. $wpsmiliestrans = array(
  2324. ':mrgreen:' => 'icon_mrgreen.gif',
  2325. ':neutral:' => 'icon_neutral.gif',
  2326. ':twisted:' => 'icon_twisted.gif',
  2327. ':arrow:' => 'icon_arrow.gif',
  2328. ':shock:' => 'icon_eek.gif',
  2329. ':smile:' => 'icon_smile.gif',
  2330. ':???:' => 'icon_confused.gif',
  2331. ':cool:' => 'icon_cool.gif',
  2332. ':evil:' => 'icon_evil.gif',
  2333. ':grin:' => 'icon_biggrin.gif',
  2334. ':idea:' => 'icon_idea.gif',
  2335. ':oops:' => 'icon_redface.gif',
  2336. ':razz:' => 'icon_razz.gif',
  2337. ':roll:' => 'icon_rolleyes.gif',
  2338. ':wink:' => 'icon_wink.gif',
  2339. ':cry:' => 'icon_cry.gif',
  2340. ':eek:' => 'icon_surprised.gif',
  2341. ':lol:' => 'icon_lol.gif',
  2342. ':mad:' => 'icon_mad.gif',
  2343. ':sad:' => 'icon_sad.gif',
  2344. '8-)' => 'icon_cool.gif',
  2345. '8-O' => 'icon_eek.gif',
  2346. ':-(' => 'icon_sad.gif',
  2347. ':-)' => 'icon_smile.gif',
  2348. ':-?' => 'icon_confused.gif',
  2349. ':-D' => 'icon_biggrin.gif',
  2350. ':-P' => 'icon_razz.gif',
  2351. ':-o' => 'icon_surprised.gif',
  2352. ':-x' => 'icon_mad.gif',
  2353. ':-|' => 'icon_neutral.gif',
  2354. ';-)' => 'icon_wink.gif',
  2355. '8)' => 'icon_cool.gif',
  2356. '8O' => 'icon_eek.gif',
  2357. ':(' => 'icon_sad.gif',
  2358. ':)' => 'icon_smile.gif',
  2359. ':?' => 'icon_confused.gif',
  2360. ':D' => 'icon_biggrin.gif',
  2361. ':P' => 'icon_razz.gif',
  2362. ':o' => 'icon_surprised.gif',
  2363. ':x' => 'icon_mad.gif',
  2364. ':|' => 'icon_neutral.gif',
  2365. ';)' => 'icon_wink.gif',
  2366. ':!:' => 'icon_exclaim.gif',
  2367. ':?:' => 'icon_question.gif',
  2368. );
  2369. }
  2370. if (count($wpsmiliestrans) == 0) {
  2371. return;
  2372. }
  2373. /*
  2374. * NOTE: we sort the smilies in reverse key order. This is to make sure
  2375. * we match the longest possible smilie (:???: vs :?) as the regular
  2376. * expression used below is first-match
  2377. */
  2378. krsort($wpsmiliestrans);
  2379. $wp_smiliessearch = '/(?:\s|^)';
  2380. $subchar = '';
  2381. foreach ( (array) $wpsmiliestrans as $smiley => $img ) {
  2382. $firstchar = substr($smiley, 0, 1);
  2383. $rest = substr($smiley, 1);
  2384. // new subpattern?
  2385. if ($firstchar != $subchar) {
  2386. if ($subchar != '') {
  2387. $wp_smiliessearch .= ')|(?:\s|^)';
  2388. }
  2389. $subchar = $firstchar;
  2390. $wp_smiliessearch .= preg_quote($firstchar, '/') . '(?:';
  2391. } else {
  2392. $wp_smiliessearch .= '|';
  2393. }
  2394. $wp_smiliessearch .= preg_quote($rest, '/');
  2395. }
  2396. $wp_smiliessearch .= ')(?:\s|$)/m';
  2397. }
  2398. /**
  2399. * Merge user defined arguments into defaults array.
  2400. *
  2401. * This function is used throughout WordPress to allow for both string or array
  2402. * to be merged into another array.
  2403. *
  2404. * @since 2.2.0
  2405. *
  2406. * @param string|array $args Value to merge with $defaults
  2407. * @param array $defaults Array that serves as the defaults.
  2408. * @return array Merged user defined values with defaults.
  2409. */
  2410. function wp_parse_args( $args, $defaults = '' ) {
  2411. if ( is_object( $args ) )
  2412. $r = get_object_vars( $args );
  2413. elseif ( is_array( $args ) )
  2414. $r =& $args;
  2415. else
  2416. wp_parse_str( $args, $r );
  2417. if ( is_array( $defaults ) )
  2418. return array_merge( $defaults, $r );
  2419. return $r;
  2420. }
  2421. /**
  2422. * Determines if Widgets library should be loaded.
  2423. *
  2424. * Checks to make sure that the widgets library hasn't already been loaded. If
  2425. * it hasn't, then it will load the widgets library and run an action hook.
  2426. *
  2427. * @since 2.2.0
  2428. * @uses add_action() Calls '_admin_menu' hook with 'wp_widgets_add_menu' value.
  2429. */
  2430. function wp_maybe_load_widgets() {
  2431. if ( ! apply_filters('load_default_widgets', true) )
  2432. return;
  2433. require_once( ABSPATH . WPINC . '/default-widgets.php' );
  2434. add_action( '_admin_menu', 'wp_widgets_add_menu' );
  2435. }
  2436. /**
  2437. * Append the Widgets menu to the themes main menu.
  2438. *
  2439. * @since 2.2.0
  2440. * @uses $submenu The administration submenu list.
  2441. */
  2442. function wp_widgets_add_menu() {
  2443. global $submenu;
  2444. $submenu['themes.php'][7] = array( __( 'Widgets' ), 'switch_themes', 'widgets.php' );
  2445. ksort( $submenu['themes.php'], SORT_NUMERIC );
  2446. }
  2447. /**
  2448. * Flush all output buffers for PHP 5.2.
  2449. *
  2450. * Make sure all output buffers are flushed before our singletons our destroyed.
  2451. *
  2452. * @since 2.2.0
  2453. */
  2454. function wp_ob_end_flush_all() {
  2455. $levels = ob_get_level();
  2456. for ($i=0; $i<$levels; $i++)
  2457. ob_end_flush();
  2458. }
  2459. /**
  2460. * Load the correct database class file.
  2461. *
  2462. * This function is used to load the database class file either at runtime or by
  2463. * wp-admin/setup-config.php We must globalise $wpdb to ensure that it is
  2464. * defined globally by the inline code in wp-db.php.
  2465. *
  2466. * @since 2.5.0
  2467. * @global $wpdb WordPress Database Object
  2468. */
  2469. function require_wp_db() {
  2470. global $wpdb;
  2471. if ( file_exists( WP_CONTENT_DIR . '/db.php' ) )
  2472. require_once( WP_CONTENT_DIR . '/db.php' );
  2473. else
  2474. require_once( ABSPATH . WPINC . '/wp-db.php' );
  2475. }
  2476. /**
  2477. * Load custom DB error or display WordPress DB error.
  2478. *
  2479. * If a file exists in the wp-content directory named db-error.php, then it will
  2480. * be loaded instead of displaying the WordPress DB error. If it is not found,
  2481. * then the WordPress DB error will be displayed instead.
  2482. *
  2483. * The WordPress DB error sets the HTTP status header to 500 to try to prevent
  2484. * search engines from caching the message. Custom DB messages should do the
  2485. * same.
  2486. *
  2487. * This function was backported to the the WordPress 2.3.2, but originally was
  2488. * added in WordPress 2.5.0.
  2489. *
  2490. * @since 2.3.2
  2491. * @uses $wpdb
  2492. */
  2493. function dead_db() {
  2494. global $wpdb;
  2495. // Load custom DB error template, if present.
  2496. if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
  2497. require_once( WP_CONTENT_DIR . '/db-error.php' );
  2498. die();
  2499. }
  2500. // If installing or in the admin, provide the verbose message.
  2501. if ( defined('WP_INSTALLING') || defined('WP_ADMIN') )
  2502. wp_die($wpdb->error);
  2503. // Otherwise, be terse.
  2504. status_header( 500 );
  2505. nocache_headers();
  2506. header( 'Content-Type: text/html; charset=utf-8' );
  2507. ?>
  2508. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2509. <html xmlns="http://www.w3.org/1999/xhtml" <?php if ( function_exists( 'language_attributes' ) ) language_attributes(); ?>>
  2510. <head>
  2511. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  2512. <title>Database Error</title>
  2513. </head>
  2514. <body>
  2515. <h1>Error establishing a database connection</h1>
  2516. </body>
  2517. </html>
  2518. <?php
  2519. die();
  2520. }
  2521. /**
  2522. * Converts value to nonnegative integer.
  2523. *
  2524. * @since 2.5.0
  2525. *
  2526. * @param mixed $maybeint Data you wish to have convered to an nonnegative integer
  2527. * @return int An nonnegative integer
  2528. */
  2529. function absint( $maybeint ) {
  2530. return abs( intval( $maybeint ) );
  2531. }
  2532. /**
  2533. * Determines if the blog can be accessed over SSL.
  2534. *
  2535. * Determines if blog can be accessed over SSL by using cURL to access the site
  2536. * using the https in the siteurl. Requires cURL extension to work correctly.
  2537. *
  2538. * @since 2.5.0
  2539. *
  2540. * @return bool Whether or not SSL access is available
  2541. */
  2542. function url_is_accessable_via_ssl($url)
  2543. {
  2544. if (in_array('curl', get_loaded_extensions())) {
  2545. $ssl = preg_replace( '/^http:\/\//', 'https://', $url );
  2546. $ch = curl_init();
  2547. curl_setopt($ch, CURLOPT_URL, $ssl);
  2548. curl_setopt($ch, CURLOPT_FAILONERROR, true);
  2549. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  2550. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  2551. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
  2552. curl_exec($ch);
  2553. $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  2554. curl_close ($ch);
  2555. if ($status == 200 || $status == 401) {
  2556. return true;
  2557. }
  2558. }
  2559. return false;
  2560. }
  2561. /**
  2562. * Secure URL, if available or the given URL.
  2563. *
  2564. * @since 2.5.0
  2565. *
  2566. * @param string $url Complete URL path with transport.
  2567. * @return string Secure or regular URL path.
  2568. */
  2569. function atom_service_url_filter($url)
  2570. {
  2571. if ( url_is_accessable_via_ssl($url) )
  2572. return preg_replace( '/^http:\/\//', 'https://', $url );
  2573. else
  2574. return $url;
  2575. }
  2576. /**
  2577. * Marks a function as deprecated and informs when it has been used.
  2578. *
  2579. * There is a hook deprecated_function_run that will be called that can be used
  2580. * to get the backtrace up to what file and function called the deprecated
  2581. * function.
  2582. *
  2583. * The current behavior is to trigger an user error if WP_DEBUG is defined and
  2584. * is true.
  2585. *
  2586. * This function is to be used in every function in depreceated.php
  2587. *
  2588. * @package WordPress
  2589. * @package Debug
  2590. * @since 2.5.0
  2591. * @access private
  2592. *
  2593. * @uses do_action() Calls 'deprecated_function_run' and passes the function name and what to use instead.
  2594. * @uses apply_filters() Calls 'deprecated_function_trigger_error' and expects boolean value of true to do trigger or false to not trigger error.
  2595. *
  2596. * @param string $function The function that was called
  2597. * @param string $version The version of WordPress that deprecated the function
  2598. * @param string $replacement Optional. The function that should have been called
  2599. */
  2600. function _deprecated_function($function, $version, $replacement=null) {
  2601. do_action('deprecated_function_run', $function, $replacement);
  2602. // Allow plugin to filter the output error trigger
  2603. if( defined('WP_DEBUG') && ( true === WP_DEBUG ) && apply_filters( 'deprecated_function_trigger_error', true )) {
  2604. if( !is_null($replacement) )
  2605. trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.'), $function, $version, $replacement ) );
  2606. else
  2607. trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.'), $function, $version ) );
  2608. }
  2609. }
  2610. /**
  2611. * Marks a file as deprecated and informs when it has been used.
  2612. *
  2613. * There is a hook deprecated_file_included that will be called that can be used
  2614. * to get the backtrace up to what file and function included the deprecated
  2615. * file.
  2616. *
  2617. * The current behavior is to trigger an user error if WP_DEBUG is defined and
  2618. * is true.
  2619. *
  2620. * This function is to be used in every file that is depreceated
  2621. *
  2622. * @package WordPress
  2623. * @package Debug
  2624. * @since 2.5.0
  2625. * @access private
  2626. *
  2627. * @uses do_action() Calls 'deprecated_file_included' and passes the file name and what to use instead.
  2628. * @uses apply_filters() Calls 'deprecated_file_trigger_error' and expects boolean value of true to do trigger or false to not trigger error.
  2629. *
  2630. * @param string $file The file that was included
  2631. * @param string $version The version of WordPress that deprecated the function
  2632. * @param string $replacement Optional. The function that should have been called
  2633. */
  2634. function _deprecated_file($file, $version, $replacement=null) {
  2635. do_action('deprecated_file_included', $file, $replacement);
  2636. // Allow plugin to filter the output error trigger
  2637. if( defined('WP_DEBUG') && ( true === WP_DEBUG ) && apply_filters( 'deprecated_file_trigger_error', true )) {
  2638. if( !is_null($replacement) )
  2639. trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.'), $file, $version, $replacement ) );
  2640. else
  2641. trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.'), $file, $version ) );
  2642. }
  2643. }
  2644. /**
  2645. * Is the server running earlier than 1.5.0 version of lighttpd
  2646. *
  2647. * @since 2.5.0
  2648. *
  2649. * @return bool Whether the server is running lighttpd < 1.5.0
  2650. */
  2651. function is_lighttpd_before_150() {
  2652. $server_parts = explode( '/', isset( $_SERVER['SERVER_SOFTWARE'] )? $_SERVER['SERVER_SOFTWARE'] : '' );
  2653. $server_parts[1] = isset( $server_parts[1] )? $server_parts[1] : '';
  2654. return 'lighttpd' == $server_parts[0] && -1 == version_compare( $server_parts[1], '1.5.0' );
  2655. }
  2656. /**
  2657. * Does the specified module exist in the apache config?
  2658. *
  2659. * @since 2.5.0
  2660. *
  2661. * @param string $mod e.g. mod_rewrite
  2662. * @param bool $default The default return value if the module is not found
  2663. * @return bool
  2664. */
  2665. function apache_mod_loaded($mod, $default = false) {
  2666. global $is_apache;
  2667. if ( !$is_apache )
  2668. return false;
  2669. if ( function_exists('apache_get_modules') ) {
  2670. $mods = apache_get_modules();
  2671. if ( in_array($mod, $mods) )
  2672. return true;
  2673. } elseif ( function_exists('phpinfo') ) {
  2674. ob_start();
  2675. phpinfo(8);
  2676. $phpinfo = ob_get_clean();
  2677. if ( false !== strpos($phpinfo, $mod) )
  2678. return true;
  2679. }
  2680. return $default;
  2681. }
  2682. /**
  2683. * File validates against allowed set of defined rules.
  2684. *
  2685. * A return value of '1' means that the $file contains either '..' or './'. A
  2686. * return value of '2' means that the $file contains ':' after the first
  2687. * character. A return value of '3' means that the file is not in the allowed
  2688. * files list.
  2689. *
  2690. * @since 1.2.0
  2691. *
  2692. * @param string $file File path.
  2693. * @param array $allowed_files List of allowed files.
  2694. * @return int 0 means nothing is wrong, greater than 0 means something was wrong.
  2695. */
  2696. function validate_file( $file, $allowed_files = '' ) {
  2697. if ( false !== strpos( $file, '..' ))
  2698. return 1;
  2699. if ( false !== strpos( $file, './' ))
  2700. return 1;
  2701. if (':' == substr( $file, 1, 1 ))
  2702. return 2;
  2703. if (!empty ( $allowed_files ) && (!in_array( $file, $allowed_files ) ) )
  2704. return 3;
  2705. return 0;
  2706. }
  2707. /**
  2708. * Determine if SSL is used.
  2709. *
  2710. * @since 2.6.0
  2711. *
  2712. * @return bool True if SSL, false if not used.
  2713. */
  2714. function is_ssl() {
  2715. if ( isset($_SERVER['HTTPS']) ) {
  2716. if ( 'on' == strtolower($_SERVER['HTTPS']) )
  2717. return true;
  2718. if ( '1' == $_SERVER['HTTPS'] )
  2719. return true;
  2720. } elseif ( isset($_SERVER['SERVER_PORT']) && ( '443' == $_SERVER['SERVER_PORT'] ) ) {
  2721. return true;
  2722. }
  2723. return false;
  2724. }
  2725. /**
  2726. * Whether SSL login should be forced.
  2727. *
  2728. * @since 2.6.0
  2729. *
  2730. * @param string|bool $force Optional.
  2731. * @return bool True if forced, false if not forced.
  2732. */
  2733. function force_ssl_login($force = '') {
  2734. static $forced;
  2735. if ( '' != $force ) {
  2736. $old_forced = $forced;
  2737. $forced = $force;
  2738. return $old_forced;
  2739. }
  2740. return $forced;
  2741. }
  2742. /**
  2743. * Whether to force SSL used for the Administration Panels.
  2744. *
  2745. * @since 2.6.0
  2746. *
  2747. * @param string|bool $force
  2748. * @return bool True if forced, false if not forced.
  2749. */
  2750. function force_ssl_admin($force = '') {
  2751. static $forced;
  2752. if ( '' != $force ) {
  2753. $old_forced = $forced;
  2754. $forced = $force;
  2755. return $old_forced;
  2756. }
  2757. return $forced;
  2758. }
  2759. /**
  2760. * Guess the URL for the site.
  2761. *
  2762. * Will remove wp-admin links to retrieve only return URLs not in the wp-admin
  2763. * directory.
  2764. *
  2765. * @since 2.6.0
  2766. *
  2767. * @return string
  2768. */
  2769. function wp_guess_url() {
  2770. if ( defined('WP_SITEURL') && '' != WP_SITEURL ) {
  2771. $url = WP_SITEURL;
  2772. } else {
  2773. $schema = ( isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ) ? 'https://' : 'http://';
  2774. $url = preg_replace('|/wp-admin/.*|i', '', $schema . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
  2775. }
  2776. return $url;
  2777. }
  2778. /**
  2779. * Suspend cache invalidation.
  2780. *
  2781. * Turns cache invalidation on and off. Useful during imports where you don't wont to do invalidations
  2782. * every time a post is inserted. Callers must be sure that what they are doing won't lead to an inconsistent
  2783. * cache when invalidation is suspended.
  2784. *
  2785. * @since 2.7.0
  2786. *
  2787. * @param bool $suspend Whether to suspend or enable cache invalidation
  2788. * @return bool The current suspend setting
  2789. */
  2790. function wp_suspend_cache_invalidation($suspend = true) {
  2791. global $_wp_suspend_cache_invalidation;
  2792. $current_suspend = $_wp_suspend_cache_invalidation;
  2793. $_wp_suspend_cache_invalidation = $suspend;
  2794. return $current_suspend;
  2795. }
  2796. function get_site_option( $key, $default = false, $use_cache = true ) {
  2797. return get_option($key, $default);
  2798. }
  2799. // expects $key, $value not to be SQL escaped
  2800. function add_site_option( $key, $value ) {
  2801. return add_option($key, $value);
  2802. }
  2803. // expects $key, $value not to be SQL escaped
  2804. function update_site_option( $key, $value ) {
  2805. return update_option($key, $value);
  2806. }
  2807. /**
  2808. * gmt_offset modification for smart timezone handling
  2809. *
  2810. * Overrides the gmt_offset option if we have a timezone_string available
  2811. */
  2812. function wp_timezone_override_offset() {
  2813. if ( !wp_timezone_supported() ) {
  2814. return false;
  2815. }
  2816. if ( !$timezone_string = get_option( 'timezone_string' ) ) {
  2817. return false;
  2818. }
  2819. @date_default_timezone_set( $timezone_string );
  2820. $timezone_object = timezone_open( $timezone_string );
  2821. $datetime_object = date_create();
  2822. if ( false === $timezone_object || false === $datetime_object ) {
  2823. return false;
  2824. }
  2825. return round( timezone_offset_get( $timezone_object, $datetime_object ) / 3600, 2 );
  2826. }
  2827. /**
  2828. * Check for PHP timezone support
  2829. */
  2830. function wp_timezone_supported() {
  2831. $support = false;
  2832. if (
  2833. function_exists( 'date_default_timezone_set' ) &&
  2834. function_exists( 'timezone_identifiers_list' ) &&
  2835. function_exists( 'timezone_open' ) &&
  2836. function_exists( 'timezone_offset_get' )
  2837. ) {
  2838. $support = true;
  2839. }
  2840. return apply_filters( 'timezone_support', $support );
  2841. }
  2842. function _wp_timezone_choice_usort_callback( $a, $b ) {
  2843. // Don't use translated versions of Etc
  2844. if ( 'Etc' === $a['continent'] && 'Etc' === $b['continent'] ) {
  2845. // Make the order of these more like the old dropdown
  2846. if ( 'GMT+' === substr( $a['city'], 0, 4 ) && 'GMT+' === substr( $b['city'], 0, 4 ) ) {
  2847. return -1 * ( strnatcasecmp( $a['city'], $b['city'] ) );
  2848. }
  2849. if ( 'UTC' === $a['city'] ) {
  2850. if ( 'GMT+' === substr( $b['city'], 0, 4 ) ) {
  2851. return 1;
  2852. }
  2853. return -1;
  2854. }
  2855. if ( 'UTC' === $b['city'] ) {
  2856. if ( 'GMT+' === substr( $a['city'], 0, 4 ) ) {
  2857. return -1;
  2858. }
  2859. return 1;
  2860. }
  2861. return strnatcasecmp( $a['city'], $b['city'] );
  2862. }
  2863. if ( $a['t_continent'] == $b['t_continent'] ) {
  2864. if ( $a['t_city'] == $b['t_city'] ) {
  2865. return strnatcasecmp( $a['t_subcity'], $b['t_subcity'] );
  2866. }
  2867. return strnatcasecmp( $a['t_city'], $b['t_city'] );
  2868. } else {
  2869. // Force Etc to the bottom of the list
  2870. if ( 'Etc' === $a['continent'] ) {
  2871. return 1;
  2872. }
  2873. if ( 'Etc' === $b['continent'] ) {
  2874. return -1;
  2875. }
  2876. return strnatcasecmp( $a['t_continent'], $b['t_continent'] );
  2877. }
  2878. }
  2879. /**
  2880. * Gives a nicely formatted list of timezone strings // temporary! Not in final
  2881. *
  2882. * @param $selected_zone string Selected Zone
  2883. *
  2884. */
  2885. function wp_timezone_choice( $selected_zone ) {
  2886. static $mo_loaded = false;
  2887. $continents = array( 'Africa', 'America', 'Antarctica', 'Arctic', 'Asia', 'Atlantic', 'Australia', 'Europe', 'Indian', 'Pacific', 'Etc' );
  2888. // Load translations for continents and cities
  2889. if ( !$mo_loaded ) {
  2890. $locale = get_locale();
  2891. $mofile = WP_LANG_DIR . '/continents-cities-' . $locale . '.mo';
  2892. load_textdomain( 'continents-cities', $mofile );
  2893. $mo_loaded = true;
  2894. }
  2895. $zonen = array();
  2896. foreach ( timezone_identifiers_list() as $zone ) {
  2897. $zone = explode( '/', $zone );
  2898. if ( !in_array( $zone[0], $continents ) ) {
  2899. continue;
  2900. }
  2901. if ( 'Etc' === $zone[0] && in_array( $zone[1], array( 'UCT', 'GMT', 'GMT0', 'GMT+0', 'GMT-0', 'Greenwich', 'Universal', 'Zulu' ) ) ) {
  2902. continue;
  2903. }
  2904. // This determines what gets set and translated - we don't translate Etc/* strings here, they are done later
  2905. $exists = array(
  2906. 0 => ( isset( $zone[0] ) && $zone[0] ) ? true : false,
  2907. 1 => ( isset( $zone[1] ) && $zone[1] ) ? true : false,
  2908. 2 => ( isset( $zone[2] ) && $zone[2] ) ? true : false
  2909. );
  2910. $exists[3] = ( $exists[0] && 'Etc' !== $zone[0] ) ? true : false;
  2911. $exists[4] = ( $exists[1] && $exists[3] ) ? true : false;
  2912. $exists[5] = ( $exists[2] && $exists[3] ) ? true : false;
  2913. $zonen[] = array(
  2914. 'continent' => ( $exists[0] ? $zone[0] : '' ),
  2915. 'city' => ( $exists[1] ? $zone[1] : '' ),
  2916. 'subcity' => ( $exists[2] ? $zone[2] : '' ),
  2917. 't_continent' => ( $exists[3] ? translate( str_replace( '_', ' ', $zone[0] ), 'continents-cities' ) : '' ),
  2918. 't_city' => ( $exists[4] ? translate( str_replace( '_', ' ', $zone[1] ), 'continents-cities' ) : '' ),
  2919. 't_subcity' => ( $exists[5] ? translate( str_replace( '_', ' ', $zone[2] ), 'continents-cities' ) : '' )
  2920. );
  2921. }
  2922. usort( $zonen, '_wp_timezone_choice_usort_callback' );
  2923. $structure = array();
  2924. if ( empty( $selected_zone ) ) {
  2925. $structure[] = '<option selected="selected" value="">' . __( 'Select a city' ) . '</option>';
  2926. }
  2927. foreach ( $zonen as $key => $zone ) {
  2928. // Build value in an array to join later
  2929. $value = array( $zone['continent'] );
  2930. if ( empty( $zone['city'] ) ) {
  2931. // It's at the continent level (generally won't happen)
  2932. $display = $zone['t_continent'];
  2933. } else {
  2934. // It's inside a continent group
  2935. // Continent optgroup
  2936. if ( !isset( $zonen[$key - 1] ) || $zonen[$key - 1]['continent'] !== $zone['continent'] ) {
  2937. $label = ( 'Etc' === $zone['continent'] ) ? __( 'Manual offsets' ) : $zone['t_continent'];
  2938. $structure[] = '<optgroup label="'. esc_attr( $label ) .'">';
  2939. }
  2940. // Add the city to the value
  2941. $value[] = $zone['city'];
  2942. if ( 'Etc' === $zone['continent'] ) {
  2943. if ( 'UTC' === $zone['city'] ) {
  2944. $display = '';
  2945. } else {
  2946. $display = str_replace( 'GMT', '', $zone['city'] );
  2947. $display = strtr( $display, '+-', '-+' ) . ':00';
  2948. }
  2949. $display = sprintf( __( 'UTC %s' ), $display );
  2950. } else {
  2951. $display = $zone['t_city'];
  2952. if ( !empty( $zone['subcity'] ) ) {
  2953. // Add the subcity to the value
  2954. $value[] = $zone['subcity'];
  2955. $display .= ' - ' . $zone['t_subcity'];
  2956. }
  2957. }
  2958. }
  2959. // Build the value
  2960. $value = join( '/', $value );
  2961. $selected = '';
  2962. if ( $value === $selected_zone ) {
  2963. $selected = 'selected="selected" ';
  2964. }
  2965. $structure[] = '<option ' . $selected . 'value="' . esc_attr( $value ) . '">' . esc_html( $display ) . "</option>";
  2966. // Close continent optgroup
  2967. if ( !empty( $zone['city'] ) && ( !isset($zonen[$key + 1]) || (isset( $zonen[$key + 1] ) && $zonen[$key + 1]['continent'] !== $zone['continent']) ) ) {
  2968. $structure[] = '</optgroup>';
  2969. }
  2970. }
  2971. return join( "\n", $structure );
  2972. }
  2973. /**
  2974. * Strip close comment and close php tags from file headers used by WP
  2975. * See http://core.trac.wordpress.org/ticket/8497
  2976. *
  2977. * @since 2.8
  2978. **/
  2979. function _cleanup_header_comment($str) {
  2980. return trim(preg_replace("/\s*(?:\*\/|\?>).*/", '', $str));
  2981. }
  2982. ?>