PageRenderTime 144ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-includes/functions.php

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