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

/blog/wp-includes/functions.php

https://bitbucket.org/abtris/phpframeworks
PHP | 3342 lines | 1643 code | 360 blank | 1339 comment | 386 complexity | 180606468fb97fef790e1c2851235bfe MD5 | raw file
Possible License(s): LGPL-2.1, AGPL-1.0

Large files files are truncated, but you can click here to view the full 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. // store original value for language with untypical grammars
  93. // see http://core.trac.wordpress.org/ticket/9396
  94. $req_format = $dateformatstring;
  95. $datefunc = $gmt? 'gmdate' : 'date';
  96. if ( ( !empty( $wp_locale->month ) ) && ( !empty( $wp_locale->weekday ) ) ) {
  97. $datemonth = $wp_locale->get_month( $datefunc( 'm', $i ) );
  98. $datemonth_abbrev = $wp_locale->get_month_abbrev( $datemonth );
  99. $dateweekday = $wp_locale->get_weekday( $datefunc( 'w', $i ) );
  100. $dateweekday_abbrev = $wp_locale->get_weekday_abbrev( $dateweekday );
  101. $datemeridiem = $wp_locale->get_meridiem( $datefunc( 'a', $i ) );
  102. $datemeridiem_capital = $wp_locale->get_meridiem( $datefunc( 'A', $i ) );
  103. $dateformatstring = ' '.$dateformatstring;
  104. $dateformatstring = preg_replace( "/([^\\\])D/", "\\1" . backslashit( $dateweekday_abbrev ), $dateformatstring );
  105. $dateformatstring = preg_replace( "/([^\\\])F/", "\\1" . backslashit( $datemonth ), $dateformatstring );
  106. $dateformatstring = preg_replace( "/([^\\\])l/", "\\1" . backslashit( $dateweekday ), $dateformatstring );
  107. $dateformatstring = preg_replace( "/([^\\\])M/", "\\1" . backslashit( $datemonth_abbrev ), $dateformatstring );
  108. $dateformatstring = preg_replace( "/([^\\\])a/", "\\1" . backslashit( $datemeridiem ), $dateformatstring );
  109. $dateformatstring = preg_replace( "/([^\\\])A/", "\\1" . backslashit( $datemeridiem_capital ), $dateformatstring );
  110. $dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 );
  111. }
  112. $j = @$datefunc( $dateformatstring, $i );
  113. // allow plugins to redo this entirely for languages with untypical grammars
  114. $j = apply_filters('date_i18n', $j, $req_format, $i, $gmt);
  115. return $j;
  116. }
  117. /**
  118. * Convert number to format based on the locale.
  119. *
  120. * @since 2.3.0
  121. *
  122. * @param mixed $number The number to convert based on locale.
  123. * @param int $decimals Precision of the number of decimal places.
  124. * @return string Converted number in string format.
  125. */
  126. function number_format_i18n( $number, $decimals = null ) {
  127. global $wp_locale;
  128. // let the user override the precision only
  129. $decimals = ( is_null( $decimals ) ) ? $wp_locale->number_format['decimals'] : intval( $decimals );
  130. $num = number_format( $number, $decimals, $wp_locale->number_format['decimal_point'], $wp_locale->number_format['thousands_sep'] );
  131. // let the user translate digits from latin to localized language
  132. return apply_filters( 'number_format_i18n', $num );
  133. }
  134. /**
  135. * Convert number of bytes largest unit bytes will fit into.
  136. *
  137. * It is easier to read 1kB than 1024 bytes and 1MB than 1048576 bytes. Converts
  138. * number of bytes to human readable number by taking the number of that unit
  139. * that the bytes will go into it. Supports TB value.
  140. *
  141. * Please note that integers in PHP are limited to 32 bits, unless they are on
  142. * 64 bit architecture, then they have 64 bit size. If you need to place the
  143. * larger size then what PHP integer type will hold, then use a string. It will
  144. * be converted to a double, which should always have 64 bit length.
  145. *
  146. * Technically the correct unit names for powers of 1024 are KiB, MiB etc.
  147. * @link http://en.wikipedia.org/wiki/Byte
  148. *
  149. * @since 2.3.0
  150. *
  151. * @param int|string $bytes Number of bytes. Note max integer size for integers.
  152. * @param int $decimals Precision of number of decimal places.
  153. * @return bool|string False on failure. Number string on success.
  154. */
  155. function size_format( $bytes, $decimals = null ) {
  156. $quant = array(
  157. // ========================= Origin ====
  158. 'TB' => 1099511627776, // pow( 1024, 4)
  159. 'GB' => 1073741824, // pow( 1024, 3)
  160. 'MB' => 1048576, // pow( 1024, 2)
  161. 'kB' => 1024, // pow( 1024, 1)
  162. 'B ' => 1, // pow( 1024, 0)
  163. );
  164. foreach ( $quant as $unit => $mag )
  165. if ( doubleval($bytes) >= $mag )
  166. return number_format_i18n( $bytes / $mag, $decimals ) . ' ' . $unit;
  167. return false;
  168. }
  169. /**
  170. * Get the week start and end from the datetime or date string from mysql.
  171. *
  172. * @since 0.71
  173. *
  174. * @param string $mysqlstring Date or datetime field type from mysql.
  175. * @param int $start_of_week Optional. Start of the week as an integer.
  176. * @return array Keys are 'start' and 'end'.
  177. */
  178. function get_weekstartend( $mysqlstring, $start_of_week = '' ) {
  179. $my = substr( $mysqlstring, 0, 4 ); // Mysql string Year
  180. $mm = substr( $mysqlstring, 8, 2 ); // Mysql string Month
  181. $md = substr( $mysqlstring, 5, 2 ); // Mysql string day
  182. $day = mktime( 0, 0, 0, $md, $mm, $my ); // The timestamp for mysqlstring day.
  183. $weekday = date( 'w', $day ); // The day of the week from the timestamp
  184. $i = 86400; // One day
  185. if( !is_numeric($start_of_week) )
  186. $start_of_week = get_option( 'start_of_week' );
  187. if ( $weekday < $start_of_week )
  188. $weekday = 7 - $start_of_week - $weekday;
  189. while ( $weekday > $start_of_week ) {
  190. $weekday = date( 'w', $day );
  191. if ( $weekday < $start_of_week )
  192. $weekday = 7 - $start_of_week - $weekday;
  193. $day -= 86400;
  194. $i = 0;
  195. }
  196. $week['start'] = $day + 86400 - $i;
  197. $week['end'] = $week['start'] + 604799;
  198. return $week;
  199. }
  200. /**
  201. * Unserialize value only if it was serialized.
  202. *
  203. * @since 2.0.0
  204. *
  205. * @param string $original Maybe unserialized original, if is needed.
  206. * @return mixed Unserialized data can be any type.
  207. */
  208. function maybe_unserialize( $original ) {
  209. if ( is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in
  210. return @unserialize( $original );
  211. return $original;
  212. }
  213. /**
  214. * Check value to find if it was serialized.
  215. *
  216. * If $data is not an string, then returned value will always be false.
  217. * Serialized data is always a string.
  218. *
  219. * @since 2.0.5
  220. *
  221. * @param mixed $data Value to check to see if was serialized.
  222. * @return bool False if not serialized and true if it was.
  223. */
  224. function is_serialized( $data ) {
  225. // if it isn't a string, it isn't serialized
  226. if ( !is_string( $data ) )
  227. return false;
  228. $data = trim( $data );
  229. if ( 'N;' == $data )
  230. return true;
  231. if ( !preg_match( '/^([adObis]):/', $data, $badions ) )
  232. return false;
  233. switch ( $badions[1] ) {
  234. case 'a' :
  235. case 'O' :
  236. case 's' :
  237. if ( preg_match( "/^{$badions[1]}:[0-9]+:.*[;}]\$/s", $data ) )
  238. return true;
  239. break;
  240. case 'b' :
  241. case 'i' :
  242. case 'd' :
  243. if ( preg_match( "/^{$badions[1]}:[0-9.E-]+;\$/", $data ) )
  244. return true;
  245. break;
  246. }
  247. return false;
  248. }
  249. /**
  250. * Check whether serialized data is of string type.
  251. *
  252. * @since 2.0.5
  253. *
  254. * @param mixed $data Serialized data
  255. * @return bool False if not a serialized string, true if it is.
  256. */
  257. function is_serialized_string( $data ) {
  258. // if it isn't a string, it isn't a serialized string
  259. if ( !is_string( $data ) )
  260. return false;
  261. $data = trim( $data );
  262. if ( preg_match( '/^s:[0-9]+:.*;$/s', $data ) ) // this should fetch all serialized strings
  263. return true;
  264. return false;
  265. }
  266. /**
  267. * Retrieve option value based on setting name.
  268. *
  269. * If the option does not exist or does not have a value, then the return value
  270. * will be false. This is useful to check whether you need to install an option
  271. * and is commonly used during installation of plugin options and to test
  272. * whether upgrading is required.
  273. *
  274. * You can "short-circuit" the retrieval of the option from the database for
  275. * your plugin or core options that aren't protected. You can do so by hooking
  276. * into the 'pre_option_$option' with the $option being replaced by the option
  277. * name. You should not try to override special options, but you will not be
  278. * prevented from doing so.
  279. *
  280. * There is a second filter called 'option_$option' with the $option being
  281. * replaced with the option name. This gives the value as the only parameter.
  282. *
  283. * If the option was serialized, when the option was added and, or updated, then
  284. * it will be unserialized, when it is returned.
  285. *
  286. * @since 1.5.0
  287. * @package WordPress
  288. * @subpackage Option
  289. * @uses apply_filters() Calls 'pre_option_$optionname' false to allow
  290. * overwriting the option value in a plugin.
  291. * @uses apply_filters() Calls 'option_$optionname' with the option name value.
  292. *
  293. * @param string $setting Name of option to retrieve. Should already be SQL-escaped
  294. * @return mixed Value set for the option.
  295. */
  296. function get_option( $setting, $default = false ) {
  297. global $wpdb;
  298. // Allow plugins to short-circuit options.
  299. $pre = apply_filters( 'pre_option_' . $setting, false );
  300. if ( false !== $pre )
  301. return $pre;
  302. // prevent non-existent options from triggering multiple queries
  303. $notoptions = wp_cache_get( 'notoptions', 'options' );
  304. if ( isset( $notoptions[$setting] ) )
  305. return $default;
  306. $alloptions = wp_load_alloptions();
  307. if ( isset( $alloptions[$setting] ) ) {
  308. $value = $alloptions[$setting];
  309. } else {
  310. $value = wp_cache_get( $setting, 'options' );
  311. if ( false === $value ) {
  312. if ( defined( 'WP_INSTALLING' ) )
  313. $suppress = $wpdb->suppress_errors();
  314. // expected_slashed ($setting)
  315. $row = $wpdb->get_row( "SELECT option_value FROM $wpdb->options WHERE option_name = '$setting' LIMIT 1" );
  316. if ( defined( 'WP_INSTALLING' ) )
  317. $wpdb->suppress_errors($suppress);
  318. if ( is_object( $row) ) { // Has to be get_row instead of get_var because of funkiness with 0, false, null values
  319. $value = $row->option_value;
  320. wp_cache_add( $setting, $value, 'options' );
  321. } else { // option does not exist, so we must cache its non-existence
  322. $notoptions[$setting] = true;
  323. wp_cache_set( 'notoptions', $notoptions, 'options' );
  324. return $default;
  325. }
  326. }
  327. }
  328. // If home is not set use siteurl.
  329. if ( 'home' == $setting && '' == $value )
  330. return get_option( 'siteurl' );
  331. if ( in_array( $setting, array('siteurl', 'home', 'category_base', 'tag_base') ) )
  332. $value = untrailingslashit( $value );
  333. return apply_filters( 'option_' . $setting, maybe_unserialize( $value ) );
  334. }
  335. /**
  336. * Protect WordPress special option from being modified.
  337. *
  338. * Will die if $option is in protected list. Protected options are 'alloptions'
  339. * and 'notoptions' options.
  340. *
  341. * @since 2.2.0
  342. * @package WordPress
  343. * @subpackage Option
  344. *
  345. * @param string $option Option name.
  346. */
  347. function wp_protect_special_option( $option ) {
  348. $protected = array( 'alloptions', 'notoptions' );
  349. if ( in_array( $option, $protected ) )
  350. die( sprintf( __( '%s is a protected WP option and may not be modified' ), esc_html( $option ) ) );
  351. }
  352. /**
  353. * Print option value after sanitizing for forms.
  354. *
  355. * @uses attr Sanitizes value.
  356. * @since 1.5.0
  357. * @package WordPress
  358. * @subpackage Option
  359. *
  360. * @param string $option Option name.
  361. */
  362. function form_option( $option ) {
  363. echo esc_attr(get_option( $option ) );
  364. }
  365. /**
  366. * Retrieve all autoload options or all options, if no autoloaded ones exist.
  367. *
  368. * This is different from wp_load_alloptions() in that this function does not
  369. * cache its results and will retrieve all options from the database every time
  370. *
  371. * it is called.
  372. *
  373. * @since 1.0.0
  374. * @package WordPress
  375. * @subpackage Option
  376. * @uses apply_filters() Calls 'pre_option_$optionname' hook with option value as parameter.
  377. * @uses apply_filters() Calls 'all_options' on options list.
  378. *
  379. * @return array List of all options.
  380. */
  381. function get_alloptions() {
  382. global $wpdb;
  383. $show = $wpdb->hide_errors();
  384. if ( !$options = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options WHERE autoload = 'yes'" ) )
  385. $options = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options" );
  386. $wpdb->show_errors($show);
  387. foreach ( (array) $options as $option ) {
  388. // "When trying to design a foolproof system,
  389. // never underestimate the ingenuity of the fools :)" -- Dougal
  390. if ( in_array( $option->option_name, array( 'siteurl', 'home', 'category_base', 'tag_base' ) ) )
  391. $option->option_value = untrailingslashit( $option->option_value );
  392. $value = maybe_unserialize( $option->option_value );
  393. $all_options->{$option->option_name} = apply_filters( 'pre_option_' . $option->option_name, $value );
  394. }
  395. return apply_filters( 'all_options', $all_options );
  396. }
  397. /**
  398. * Loads and caches all autoloaded options, if available or all options.
  399. *
  400. * This is different from get_alloptions(), in that this function will cache the
  401. * options and will return the cached options when called again.
  402. *
  403. * @since 2.2.0
  404. * @package WordPress
  405. * @subpackage Option
  406. *
  407. * @return array List all options.
  408. */
  409. function wp_load_alloptions() {
  410. global $wpdb;
  411. $alloptions = wp_cache_get( 'alloptions', 'options' );
  412. if ( !$alloptions ) {
  413. $suppress = $wpdb->suppress_errors();
  414. if ( !$alloptions_db = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options WHERE autoload = 'yes'" ) )
  415. $alloptions_db = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options" );
  416. $wpdb->suppress_errors($suppress);
  417. $alloptions = array();
  418. foreach ( (array) $alloptions_db as $o )
  419. $alloptions[$o->option_name] = $o->option_value;
  420. wp_cache_add( 'alloptions', $alloptions, 'options' );
  421. }
  422. return $alloptions;
  423. }
  424. /**
  425. * Update the value of an option that was already added.
  426. *
  427. * You do not need to serialize values, if the value needs to be serialize, then
  428. * it will be serialized before it is inserted into the database. Remember,
  429. * resources can not be serialized or added as an option.
  430. *
  431. * If the option does not exist, then the option will be added with the option
  432. * value, but you will not be able to set whether it is autoloaded. If you want
  433. * to set whether an option autoloaded, then you need to use the add_option().
  434. *
  435. * Before the option is updated, then the filter named
  436. * 'pre_update_option_$option_name', with the $option_name as the $option_name
  437. * parameter value, will be called. The hook should accept two parameters, the
  438. * first is the new value and the second is the old value. Whatever is
  439. * returned will be used as the new value.
  440. *
  441. * After the value has been updated the action named 'update_option_$option_name'
  442. * will be called. This action receives two parameters the first being the old
  443. * value and the second the new value.
  444. *
  445. * @since 1.0.0
  446. * @package WordPress
  447. * @subpackage Option
  448. *
  449. * @param string $option_name Option name. Expected to not be SQL-escaped
  450. * @param mixed $newvalue Option value.
  451. * @return bool False if value was not updated and true if value was updated.
  452. */
  453. function update_option( $option_name, $newvalue ) {
  454. global $wpdb;
  455. wp_protect_special_option( $option_name );
  456. $safe_option_name = $wpdb->escape( $option_name );
  457. $newvalue = sanitize_option( $option_name, $newvalue );
  458. $oldvalue = get_option( $safe_option_name );
  459. $newvalue = apply_filters( 'pre_update_option_' . $option_name, $newvalue, $oldvalue );
  460. // If the new and old values are the same, no need to update.
  461. if ( $newvalue === $oldvalue )
  462. return false;
  463. if ( false === $oldvalue ) {
  464. add_option( $option_name, $newvalue );
  465. return true;
  466. }
  467. $notoptions = wp_cache_get( 'notoptions', 'options' );
  468. if ( is_array( $notoptions ) && isset( $notoptions[$option_name] ) ) {
  469. unset( $notoptions[$option_name] );
  470. wp_cache_set( 'notoptions', $notoptions, 'options' );
  471. }
  472. $_newvalue = $newvalue;
  473. $newvalue = maybe_serialize( $newvalue );
  474. $alloptions = wp_load_alloptions();
  475. if ( isset( $alloptions[$option_name] ) ) {
  476. $alloptions[$option_name] = $newvalue;
  477. wp_cache_set( 'alloptions', $alloptions, 'options' );
  478. } else {
  479. wp_cache_set( $option_name, $newvalue, 'options' );
  480. }
  481. $wpdb->update($wpdb->options, array('option_value' => $newvalue), array('option_name' => $option_name) );
  482. if ( $wpdb->rows_affected == 1 ) {
  483. do_action( "update_option_{$option_name}", $oldvalue, $_newvalue );
  484. return true;
  485. }
  486. return false;
  487. }
  488. /**
  489. * Add a new option.
  490. *
  491. * You do not need to serialize values, if the value needs to be serialize, then
  492. * it will be serialized before it is inserted into the database. Remember,
  493. * resources can not be serialized or added as an option.
  494. *
  495. * You can create options without values and then add values later. Does not
  496. * check whether the option has already been added, but does check that you
  497. * aren't adding a protected WordPress option. Care should be taken to not name
  498. * options, the same as the ones which are protected and to not add options
  499. * that were already added.
  500. *
  501. * The filter named 'add_option_$optionname', with the $optionname being
  502. * replaced with the option's name, will be called. The hook should accept two
  503. * parameters, the first is the option name, and the second is the value.
  504. *
  505. * @package WordPress
  506. * @subpackage Option
  507. * @since 1.0.0
  508. * @link http://alex.vort-x.net/blog/ Thanks Alex Stapleton
  509. *
  510. * @param string $name Option name to add. Expects to NOT be SQL escaped.
  511. * @param mixed $value Optional. Option value, can be anything.
  512. * @param mixed $deprecated Optional. Description. Not used anymore.
  513. * @param bool $autoload Optional. Default is enabled. Whether to load the option when WordPress starts up.
  514. * @return null returns when finished.
  515. */
  516. function add_option( $name, $value = '', $deprecated = '', $autoload = 'yes' ) {
  517. global $wpdb;
  518. wp_protect_special_option( $name );
  519. $safe_name = $wpdb->escape( $name );
  520. $value = sanitize_option( $name, $value );
  521. // Make sure the option doesn't already exist. We can check the 'notoptions' cache before we ask for a db query
  522. $notoptions = wp_cache_get( 'notoptions', 'options' );
  523. if ( !is_array( $notoptions ) || !isset( $notoptions[$name] ) )
  524. if ( false !== get_option( $safe_name ) )
  525. return;
  526. $value = maybe_serialize( $value );
  527. $autoload = ( 'no' === $autoload ) ? 'no' : 'yes';
  528. if ( 'yes' == $autoload ) {
  529. $alloptions = wp_load_alloptions();
  530. $alloptions[$name] = $value;
  531. wp_cache_set( 'alloptions', $alloptions, 'options' );
  532. } else {
  533. wp_cache_set( $name, $value, 'options' );
  534. }
  535. // This option exists now
  536. $notoptions = wp_cache_get( 'notoptions', 'options' ); // yes, again... we need it to be fresh
  537. if ( is_array( $notoptions ) && isset( $notoptions[$name] ) ) {
  538. unset( $notoptions[$name] );
  539. wp_cache_set( 'notoptions', $notoptions, 'options' );
  540. }
  541. $wpdb->insert($wpdb->options, array('option_name' => $name, 'option_value' => $value, 'autoload' => $autoload) );
  542. do_action( "add_option_{$name}", $name, $value );
  543. return;
  544. }
  545. /**
  546. * Removes option by name and prevents removal of protected WordPress options.
  547. *
  548. * @package WordPress
  549. * @subpackage Option
  550. * @since 1.2.0
  551. *
  552. * @param string $name Option name to remove.
  553. * @return bool True, if succeed. False, if failure.
  554. */
  555. function delete_option( $name ) {
  556. global $wpdb;
  557. wp_protect_special_option( $name );
  558. // Get the ID, if no ID then return
  559. // expected_slashed ($name)
  560. $option = $wpdb->get_row( "SELECT option_id, autoload FROM $wpdb->options WHERE option_name = '$name'" );
  561. if ( is_null($option) || !$option->option_id )
  562. return false;
  563. // expected_slashed ($name)
  564. $wpdb->query( "DELETE FROM $wpdb->options WHERE option_name = '$name'" );
  565. if ( 'yes' == $option->autoload ) {
  566. $alloptions = wp_load_alloptions();
  567. if ( isset( $alloptions[$name] ) ) {
  568. unset( $alloptions[$name] );
  569. wp_cache_set( 'alloptions', $alloptions, 'options' );
  570. }
  571. } else {
  572. wp_cache_delete( $name, 'options' );
  573. }
  574. return true;
  575. }
  576. /**
  577. * Delete a transient
  578. *
  579. * @since 2.8.0
  580. * @package WordPress
  581. * @subpackage Transient
  582. *
  583. * @param string $transient Transient name. Expected to not be SQL-escaped
  584. * @return bool true if successful, false otherwise
  585. */
  586. function delete_transient($transient) {
  587. global $_wp_using_ext_object_cache, $wpdb;
  588. if ( $_wp_using_ext_object_cache ) {
  589. return wp_cache_delete($transient, 'transient');
  590. } else {
  591. $transient = '_transient_' . $wpdb->escape($transient);
  592. return delete_option($transient);
  593. }
  594. }
  595. /**
  596. * Get the value of a transient
  597. *
  598. * If the transient does not exist or does not have a value, then the return value
  599. * will be false.
  600. *
  601. * @since 2.8.0
  602. * @package WordPress
  603. * @subpackage Transient
  604. *
  605. * @param string $transient Transient name. Expected to not be SQL-escaped
  606. * @return mixed Value of transient
  607. */
  608. function get_transient($transient) {
  609. global $_wp_using_ext_object_cache, $wpdb;
  610. $pre = apply_filters( 'pre_transient_' . $transient, false );
  611. if ( false !== $pre )
  612. return $pre;
  613. if ( $_wp_using_ext_object_cache ) {
  614. $value = wp_cache_get($transient, 'transient');
  615. } else {
  616. $transient_option = '_transient_' . $wpdb->escape($transient);
  617. // If option is not in alloptions, it is not autoloaded and thus has a timeout
  618. $alloptions = wp_load_alloptions();
  619. if ( !isset( $alloptions[$transient_option] ) ) {
  620. $transient_timeout = '_transient_timeout_' . $wpdb->escape($transient);
  621. if ( get_option($transient_timeout) < time() ) {
  622. delete_option($transient_option);
  623. delete_option($transient_timeout);
  624. return false;
  625. }
  626. }
  627. $value = get_option($transient_option);
  628. }
  629. return apply_filters('transient_' . $transient, $value);
  630. }
  631. /**
  632. * Set/update the value of a transient
  633. *
  634. * You do not need to serialize values, if the value needs to be serialize, then
  635. * it will be serialized before it is set.
  636. *
  637. * @since 2.8.0
  638. * @package WordPress
  639. * @subpackage Transient
  640. *
  641. * @param string $transient Transient name. Expected to not be SQL-escaped
  642. * @param mixed $value Transient value.
  643. * @param int $expiration Time until expiration in seconds, default 0
  644. * @return bool False if value was not set and true if value was set.
  645. */
  646. function set_transient($transient, $value, $expiration = 0) {
  647. global $_wp_using_ext_object_cache, $wpdb;
  648. if ( $_wp_using_ext_object_cache ) {
  649. return wp_cache_set($transient, $value, 'transient', $expiration);
  650. } else {
  651. $transient_timeout = '_transient_timeout_' . $transient;
  652. $transient = '_transient_' . $transient;
  653. $safe_transient = $wpdb->escape($transient);
  654. if ( false === get_option( $safe_transient ) ) {
  655. $autoload = 'yes';
  656. if ( 0 != $expiration ) {
  657. $autoload = 'no';
  658. add_option($transient_timeout, time() + $expiration, '', 'no');
  659. }
  660. return add_option($transient, $value, '', $autoload);
  661. } else {
  662. if ( 0 != $expiration )
  663. update_option($transient_timeout, time() + $expiration);
  664. return update_option($transient, $value);
  665. }
  666. }
  667. }
  668. /**
  669. * Saves and restores user interface settings stored in a cookie.
  670. *
  671. * Checks if the current user-settings cookie is updated and stores it. When no
  672. * cookie exists (different browser used), adds the last saved cookie restoring
  673. * the settings.
  674. *
  675. * @package WordPress
  676. * @subpackage Option
  677. * @since 2.7.0
  678. */
  679. function wp_user_settings() {
  680. if ( ! is_admin() )
  681. return;
  682. if ( defined('DOING_AJAX') )
  683. return;
  684. if ( ! $user = wp_get_current_user() )
  685. return;
  686. $settings = get_user_option( 'user-settings', $user->ID, false );
  687. if ( isset( $_COOKIE['wp-settings-' . $user->ID] ) ) {
  688. $cookie = preg_replace( '/[^A-Za-z0-9=&_]/', '', $_COOKIE['wp-settings-' . $user->ID] );
  689. if ( ! empty( $cookie ) && strpos( $cookie, '=' ) ) {
  690. if ( $cookie == $settings )
  691. return;
  692. $last_time = (int) get_user_option( 'user-settings-time', $user->ID, false );
  693. $saved = isset( $_COOKIE['wp-settings-time-' . $user->ID]) ? preg_replace( '/[^0-9]/', '', $_COOKIE['wp-settings-time-' . $user->ID] ) : 0;
  694. if ( $saved > $last_time ) {
  695. update_user_option( $user->ID, 'user-settings', $cookie, false );
  696. update_user_option( $user->ID, 'user-settings-time', time() - 5, false );
  697. return;
  698. }
  699. }
  700. }
  701. setcookie( 'wp-settings-' . $user->ID, $settings, time() + 31536000, SITECOOKIEPATH );
  702. setcookie( 'wp-settings-time-' . $user->ID, time(), time() + 31536000, SITECOOKIEPATH );
  703. $_COOKIE['wp-settings-' . $user->ID] = $settings;
  704. }
  705. /**
  706. * Retrieve user interface setting value based on setting name.
  707. *
  708. * @package WordPress
  709. * @subpackage Option
  710. * @since 2.7.0
  711. *
  712. * @param string $name The name of the setting.
  713. * @param string $default Optional default value to return when $name is not set.
  714. * @return mixed the last saved user setting or the default value/false if it doesn't exist.
  715. */
  716. function get_user_setting( $name, $default = false ) {
  717. $all = get_all_user_settings();
  718. return isset($all[$name]) ? $all[$name] : $default;
  719. }
  720. /**
  721. * Add or update user interface setting.
  722. *
  723. * Both $name and $value can contain only ASCII letters, numbers and underscores.
  724. * This function has to be used before any output has started as it calls setcookie().
  725. *
  726. * @package WordPress
  727. * @subpackage Option
  728. * @since 2.8.0
  729. *
  730. * @param string $name The name of the setting.
  731. * @param string $value The value for the setting.
  732. * @return bool true if set successfully/false if not.
  733. */
  734. function set_user_setting( $name, $value ) {
  735. if ( headers_sent() )
  736. return false;
  737. $all = get_all_user_settings();
  738. $name = preg_replace( '/[^A-Za-z0-9_]+/', '', $name );
  739. if ( empty($name) )
  740. return false;
  741. $all[$name] = $value;
  742. return wp_set_all_user_settings($all);
  743. }
  744. /**
  745. * Delete user interface settings.
  746. *
  747. * Deleting settings would reset them to the defaults.
  748. * This function has to be used before any output has started as it calls setcookie().
  749. *
  750. * @package WordPress
  751. * @subpackage Option
  752. * @since 2.7.0
  753. *
  754. * @param mixed $names The name or array of names of the setting to be deleted.
  755. * @return bool true if deleted successfully/false if not.
  756. */
  757. function delete_user_setting( $names ) {
  758. if ( headers_sent() )
  759. return false;
  760. $all = get_all_user_settings();
  761. $names = (array) $names;
  762. foreach ( $names as $name ) {
  763. if ( isset($all[$name]) ) {
  764. unset($all[$name]);
  765. $deleted = true;
  766. }
  767. }
  768. if ( isset($deleted) )
  769. return wp_set_all_user_settings($all);
  770. return false;
  771. }
  772. /**
  773. * Retrieve all user interface settings.
  774. *
  775. * @package WordPress
  776. * @subpackage Option
  777. * @since 2.7.0
  778. *
  779. * @return array the last saved user settings or empty array.
  780. */
  781. function get_all_user_settings() {
  782. global $_updated_user_settings;
  783. if ( ! $user = wp_get_current_user() )
  784. return array();
  785. if ( isset($_updated_user_settings) && is_array($_updated_user_settings) )
  786. return $_updated_user_settings;
  787. $all = array();
  788. if ( isset($_COOKIE['wp-settings-' . $user->ID]) ) {
  789. $cookie = preg_replace( '/[^A-Za-z0-9=&_]/', '', $_COOKIE['wp-settings-' . $user->ID] );
  790. if ( $cookie && strpos($cookie, '=') ) // the '=' cannot be 1st char
  791. parse_str($cookie, $all);
  792. } else {
  793. $option = get_user_option('user-settings', $user->ID);
  794. if ( $option && is_string($option) )
  795. parse_str( $option, $all );
  796. }
  797. return $all;
  798. }
  799. /**
  800. * Private. Set all user interface settings.
  801. *
  802. * @package WordPress
  803. * @subpackage Option
  804. * @since 2.8.0
  805. *
  806. */
  807. function wp_set_all_user_settings($all) {
  808. global $_updated_user_settings;
  809. if ( ! $user = wp_get_current_user() )
  810. return false;
  811. $_updated_user_settings = $all;
  812. $settings = '';
  813. foreach ( $all as $k => $v ) {
  814. $v = preg_replace( '/[^A-Za-z0-9_]+/', '', $v );
  815. $settings .= $k . '=' . $v . '&';
  816. }
  817. $settings = rtrim($settings, '&');
  818. update_user_option( $user->ID, 'user-settings', $settings, false );
  819. update_user_option( $user->ID, 'user-settings-time', time(), false );
  820. return true;
  821. }
  822. /**
  823. * Delete the user settings of the current user.
  824. *
  825. * @package WordPress
  826. * @subpackage Option
  827. * @since 2.7.0
  828. */
  829. function delete_all_user_settings() {
  830. if ( ! $user = wp_get_current_user() )
  831. return;
  832. update_user_option( $user->ID, 'user-settings', '', false );
  833. setcookie('wp-settings-' . $user->ID, ' ', time() - 31536000, SITECOOKIEPATH);
  834. }
  835. /**
  836. * Serialize data, if needed.
  837. *
  838. * @since 2.0.5
  839. *
  840. * @param mixed $data Data that might be serialized.
  841. * @return mixed A scalar data
  842. */
  843. function maybe_serialize( $data ) {
  844. if ( is_array( $data ) || is_object( $data ) )
  845. return serialize( $data );
  846. if ( is_serialized( $data ) )
  847. return serialize( $data );
  848. return $data;
  849. }
  850. /**
  851. * Strip HTML and put links at the bottom of stripped content.
  852. *
  853. * Searches for all of the links, strips them out of the content, and places
  854. * them at the bottom of the content with numbers.
  855. *
  856. * @since 0.71
  857. *
  858. * @param string $content Content to get links
  859. * @return string HTML stripped out of content with links at the bottom.
  860. */
  861. function make_url_footnote( $content ) {
  862. preg_match_all( '/<a(.+?)href=\"(.+?)\"(.*?)>(.+?)<\/a>/', $content, $matches );
  863. $links_summary = "\n";
  864. for ( $i=0; $i<count($matches[0]); $i++ ) {
  865. $link_match = $matches[0][$i];
  866. $link_number = '['.($i+1).']';
  867. $link_url = $matches[2][$i];
  868. $link_text = $matches[4][$i];
  869. $content = str_replace( $link_match, $link_text . ' ' . $link_number, $content );
  870. $link_url = ( ( strtolower( substr( $link_url, 0, 7 ) ) != 'http://' ) && ( strtolower( substr( $link_url, 0, 8 ) ) != 'https://' ) ) ? get_option( 'home' ) . $link_url : $link_url;
  871. $links_summary .= "\n" . $link_number . ' ' . $link_url;
  872. }
  873. $content = strip_tags( $content );
  874. $content .= $links_summary;
  875. return $content;
  876. }
  877. /**
  878. * Retrieve post title from XMLRPC XML.
  879. *
  880. * If the title element is not part of the XML, then the default post title from
  881. * the $post_default_title will be used instead.
  882. *
  883. * @package WordPress
  884. * @subpackage XMLRPC
  885. * @since 0.71
  886. *
  887. * @global string $post_default_title Default XMLRPC post title.
  888. *
  889. * @param string $content XMLRPC XML Request content
  890. * @return string Post title
  891. */
  892. function xmlrpc_getposttitle( $content ) {
  893. global $post_default_title;
  894. if ( preg_match( '/<title>(.+?)<\/title>/is', $content, $matchtitle ) ) {
  895. $post_title = $matchtitle[1];
  896. } else {
  897. $post_title = $post_default_title;
  898. }
  899. return $post_title;
  900. }
  901. /**
  902. * Retrieve the post category or categories from XMLRPC XML.
  903. *
  904. * If the category element is not found, then the default post category will be
  905. * used. The return type then would be what $post_default_category. If the
  906. * category is found, then it will always be an array.
  907. *
  908. * @package WordPress
  909. * @subpackage XMLRPC
  910. * @since 0.71
  911. *
  912. * @global string $post_default_category Default XMLRPC post category.
  913. *
  914. * @param string $content XMLRPC XML Request content
  915. * @return string|array List of categories or category name.
  916. */
  917. function xmlrpc_getpostcategory( $content ) {
  918. global $post_default_category;
  919. if ( preg_match( '/<category>(.+?)<\/category>/is', $content, $matchcat ) ) {
  920. $post_category = trim( $matchcat[1], ',' );
  921. $post_category = explode( ',', $post_category );
  922. } else {
  923. $post_category = $post_default_category;
  924. }
  925. return $post_category;
  926. }
  927. /**
  928. * XMLRPC XML content without title and category elements.
  929. *
  930. * @package WordPress
  931. * @subpackage XMLRPC
  932. * @since 0.71
  933. *
  934. * @param string $content XMLRPC XML Request content
  935. * @return string XMLRPC XML Request content without title and category elements.
  936. */
  937. function xmlrpc_removepostdata( $content ) {
  938. $content = preg_replace( '/<title>(.+?)<\/title>/si', '', $content );
  939. $content = preg_replace( '/<category>(.+?)<\/category>/si', '', $content );
  940. $content = trim( $content );
  941. return $content;
  942. }
  943. /**
  944. * Open the file handle for debugging.
  945. *
  946. * This function is used for XMLRPC feature, but it is general purpose enough
  947. * to be used in anywhere.
  948. *
  949. * @see fopen() for mode options.
  950. * @package WordPress
  951. * @subpackage Debug
  952. * @since 0.71
  953. * @uses $debug Used for whether debugging is enabled.
  954. *
  955. * @param string $filename File path to debug file.
  956. * @param string $mode Same as fopen() mode parameter.
  957. * @return bool|resource File handle. False on failure.
  958. */
  959. function debug_fopen( $filename, $mode ) {
  960. global $debug;
  961. if ( 1 == $debug ) {
  962. $fp = fopen( $filename, $mode );
  963. return $fp;
  964. } else {
  965. return false;
  966. }
  967. }
  968. /**
  969. * Write contents to the file used for debugging.
  970. *
  971. * Technically, this can be used to write to any file handle when the global
  972. * $debug is set to 1 or true.
  973. *
  974. * @package WordPress
  975. * @subpackage Debug
  976. * @since 0.71
  977. * @uses $debug Used for whether debugging is enabled.
  978. *
  979. * @param resource $fp File handle for debugging file.
  980. * @param string $string Content to write to debug file.
  981. */
  982. function debug_fwrite( $fp, $string ) {
  983. global $debug;
  984. if ( 1 == $debug )
  985. fwrite( $fp, $string );
  986. }
  987. /**
  988. * Close the debugging file handle.
  989. *
  990. * Technically, this can be used to close any file handle when the global $debug
  991. * is set to 1 or true.
  992. *
  993. * @package WordPress
  994. * @subpackage Debug
  995. * @since 0.71
  996. * @uses $debug Used for whether debugging is enabled.
  997. *
  998. * @param resource $fp Debug File handle.
  999. */
  1000. function debug_fclose( $fp ) {
  1001. global $debug;
  1002. if ( 1 == $debug )
  1003. fclose( $fp );
  1004. }
  1005. /**
  1006. * Check content for video and audio links to add as enclosures.
  1007. *
  1008. * Will not add enclosures that have already been added and will
  1009. * remove enclosures that are no longer in the post. This is called as
  1010. * pingbacks and trackbacks.
  1011. *
  1012. * @package WordPress
  1013. * @since 1.5.0
  1014. *
  1015. * @uses $wpdb
  1016. *
  1017. * @param string $content Post Content
  1018. * @param int $post_ID Post ID
  1019. */
  1020. function do_enclose( $content, $post_ID ) {
  1021. global $wpdb;
  1022. include_once( ABSPATH . WPINC . '/class-IXR.php' );
  1023. $log = debug_fopen( ABSPATH . 'enclosures.log', 'a' );
  1024. $post_links = array();
  1025. debug_fwrite( $log, 'BEGIN ' . date( 'YmdHis', time() ) . "\n" );
  1026. $pung = get_enclosed( $post_ID );
  1027. $ltrs = '\w';
  1028. $gunk = '/#~:.?+=&%@!\-';
  1029. $punc = '.:?\-';
  1030. $any = $ltrs . $gunk . $punc;
  1031. preg_match_all( "{\b http : [$any] +? (?= [$punc] * [^$any] | $)}x", $content, $post_links_temp );
  1032. debug_fwrite( $log, 'Post contents:' );
  1033. debug_fwrite( $log, $content . "\n" );
  1034. foreach ( $pung as $link_test ) {
  1035. if ( !in_array( $link_test, $post_links_temp[0] ) ) { // link no longer in post
  1036. $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE (%s)", $post_ID, $link_test . '%') );
  1037. }
  1038. }
  1039. foreach ( (array) $post_links_temp[0] as $link_test ) {
  1040. if ( !in_array( $link_test, $pung ) ) { // If we haven't pung it already
  1041. $test = parse_url( $link_test );
  1042. if ( isset( $test['query'] ) )
  1043. $post_links[] = $link_test;
  1044. elseif ( $test['path'] != '/' && $test['path'] != '' )
  1045. $post_links[] = $link_test;
  1046. }
  1047. }
  1048. foreach ( (array) $post_links as $url ) {
  1049. if ( $url != '' && !$wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE (%s)", $post_ID, $url . '%' ) ) ) {
  1050. if ( $headers = wp_get_http_headers( $url) ) {
  1051. $len = (int) $headers['content-length'];
  1052. $type = $headers['content-type'];
  1053. $allowed_types = array( 'video', 'audio' );
  1054. if ( in_array( substr( $type, 0, strpos( $type, "/" ) ), $allowed_types ) ) {
  1055. $meta_value = "$url\n$len\n$type\n";
  1056. $wpdb->insert($wpdb->postmeta, array('post_id' => $post_ID, 'meta_key' => 'enclosure', 'meta_value' => $meta_value) );
  1057. }
  1058. }
  1059. }
  1060. }
  1061. }
  1062. /**
  1063. * Perform a HTTP HEAD or GET request.
  1064. *
  1065. * If $file_path is a writable filename, this will do a GET request and write
  1066. * the file to that path.
  1067. *
  1068. * @since 2.5.0
  1069. *
  1070. * @param string $url URL to fetch.
  1071. * @param string|bool $file_path Optional. File path to write request to.
  1072. * @param bool $deprecated Deprecated. Not used.
  1073. * @return bool|string False on failure and string of headers if HEAD request.
  1074. */
  1075. function wp_get_http( $url, $file_path = false, $deprecated = false ) {
  1076. @set_time_limit( 60 );
  1077. $options = array();
  1078. $options['redirection'] = 5;
  1079. if ( false == $file_path )
  1080. $options['method'] = 'HEAD';
  1081. else
  1082. $options['method'] = 'GET';
  1083. $response = wp_remote_request($url, $options);
  1084. if ( is_wp_error( $response ) )
  1085. return false;
  1086. $headers = wp_remote_retrieve_headers( $response );
  1087. $headers['response'] = $response['response']['code'];
  1088. if ( false == $file_path )
  1089. return $headers;
  1090. // GET request - write it to the supplied filename
  1091. $out_fp = fopen($file_path, 'w');
  1092. if ( !$out_fp )
  1093. return $headers;
  1094. fwrite( $out_fp, $response['body']);
  1095. fclose($out_fp);
  1096. return $headers;
  1097. }
  1098. /**
  1099. * Retrieve HTTP Headers from URL.
  1100. *
  1101. * @since 1.5.1
  1102. *
  1103. * @param string $url
  1104. * @param bool $deprecated Not Used.
  1105. * @return bool|string False on failure, headers on success.
  1106. */
  1107. function wp_get_http_headers( $url, $deprecated = false ) {
  1108. $response = wp_remote_head( $url );
  1109. if ( is_wp_error( $response ) )
  1110. return false;
  1111. return wp_remote_retrieve_headers( $response );
  1112. }
  1113. /**
  1114. * Whether today is a new day.
  1115. *
  1116. * @since 0.71
  1117. * @uses $day Today
  1118. * @uses $previousday Previous day
  1119. *
  1120. * @return int 1 when new day, 0 if not a new day.
  1121. */
  1122. function is_new_day() {
  1123. global $day, $previousday;
  1124. if ( $day != $previousday )
  1125. return 1;
  1126. else
  1127. return 0;
  1128. }
  1129. /**
  1130. * Build URL query based on an associative and, or indexed array.
  1131. *
  1132. * This is a convenient function for easily building url queries. It sets the
  1133. * separator to '&' and uses _http_build_query() function.
  1134. *
  1135. * @see _http_build_query() Used to build the query
  1136. * @link http://us2.php.net/manual/en/function.http-build-query.php more on what
  1137. * http_build_query() does.
  1138. *
  1139. * @since 2.3.0
  1140. *
  1141. * @param array $data URL-encode key/value pairs.
  1142. * @return string URL encoded string
  1143. */
  1144. function build_query( $data ) {
  1145. return _http_build_query( $data, null, '&', '', false );
  1146. }
  1147. /**
  1148. * Retrieve a modified URL query string.
  1149. *
  1150. * You can rebuild the URL and append a new query variable to the URL query by
  1151. * using this function. You can also retrieve the full URL with query data.
  1152. *
  1153. * Adding a single key & value or an associative array. Setting a key value to
  1154. * emptystring removes the key. Omitting oldquery_or_uri uses the $_SERVER
  1155. * value.
  1156. *
  1157. * @since 1.5.0
  1158. *
  1159. * @param mixed $param1 Either newkey or an associative_array
  1160. * @param mixed $param2 Either newvalue or oldquery or uri
  1161. * @param mixed $param3 Optional. Old query or uri
  1162. * @return string New URL query string.
  1163. */
  1164. function add_query_arg() {
  1165. $ret = '';
  1166. if ( is_array( func_get_arg(0) ) ) {
  1167. if ( @func_num_args() < 2 || false === @func_get_arg( 1 ) )
  1168. $uri = $_SERVER['REQUEST_URI'];
  1169. else
  1170. $uri = @func_get_arg( 1 );
  1171. } else {
  1172. if ( @func_num_args() < 3 || false === @func_get_arg( 2 ) )
  1173. $uri = $_SERVER['REQUEST_URI'];
  1174. else
  1175. $uri = @func_get_arg( 2 );
  1176. }
  1177. if ( $frag = strstr( $uri, '#' ) )
  1178. $uri = substr( $uri, 0, -strlen( $frag ) );
  1179. else
  1180. $frag = '';
  1181. if ( preg_match( '|^https?://|i', $uri, $matches ) ) {
  1182. $protocol = $matches[0];
  1183. $uri = substr( $uri, strlen( $protocol ) );
  1184. } else {
  1185. $protocol = '';
  1186. }
  1187. if ( strpos( $uri, '?' ) !== false ) {
  1188. $parts = explode( '?', $uri, 2 );
  1189. if ( 1 == count( $parts ) ) {
  1190. $base = '?';
  1191. $query = $parts[0];
  1192. } else {
  1193. $base = $parts[0] . '?';
  1194. $query = $parts[1];
  1195. }
  1196. } elseif ( !empty( $protocol ) || strpos( $uri, '=' ) === false ) {
  1197. $base = $uri . '?';
  1198. $query = '';
  1199. } else {
  1200. $base = '';
  1201. $query = $uri;
  1202. }
  1203. wp_parse_str( $query, $qs );
  1204. $qs = urlencode_deep( $qs ); // this re-URL-encodes things that were already in the query string
  1205. if ( is_array( func_get_arg( 0 ) ) ) {
  1206. $kayvees = func_get_arg( 0 );
  1207. $qs = array_merge( $qs, $kayvees );
  1208. } else {
  1209. $qs[func_get_arg( 0 )] = func_get_arg( 1 );
  1210. }
  1211. foreach ( (array) $qs as $k => $v ) {
  1212. if ( $v === false )
  1213. unset( $qs[$k] );
  1214. }
  1215. $ret = build_query( $qs );
  1216. $ret = trim( $ret, '?' );
  1217. $ret = preg_replace( '#=(&|$)#', '$1', $ret );
  1218. $ret = $protocol . $base . $ret . $frag;
  1219. $ret = rtrim( $ret, '?' );
  1220. return $ret;
  1221. }
  1222. /**
  1223. * Removes an item or list from the query string.
  1224. *
  1225. * @since 1.5.0
  1226. *
  1227. * @param string|array $key Query key or keys to remove.
  1228. * @param bool $query When false uses the $_SERVER value.
  1229. * @return string New URL query string.
  1230. */
  1231. function remove_query_arg( $key, $query=false ) {
  1232. if ( is_array( $key ) ) { // removing multiple keys
  1233. foreach ( $key as $k )
  1234. $query = add_query_arg( $k, false, $query );
  1235. return $query;
  1236. }
  1237. return add_query_arg( $key, false, $query );
  1238. }
  1239. /**
  1240. * Walks the array while sanitizing the contents.
  1241. *
  1242. * @uses $wpdb Used to sanitize values
  1243. * @since 0.71
  1244. *
  1245. * @param array $array Array to used to walk while sanitizing contents.
  1246. * @return array Sanitized $array.
  1247. */
  1248. function add_magic_quotes( $array ) {
  1249. global $wpdb;
  1250. foreach ( (array) $array as $k => $v ) {
  1251. if ( is_array( $v ) ) {
  1252. $array[$k] = add_magic_quotes( $v );
  1253. } else {
  1254. $array[$k] = $wpdb->escape( $v );
  1255. }
  1256. }
  1257. return $array;
  1258. }
  1259. /**
  1260. * HTTP request for URI to retrieve content.
  1261. *
  1262. * @since 1.5.1
  1263. * @uses wp_remote_get()
  1264. *
  1265. * @param string $uri URI/URL of web page to retrieve.
  1266. * @return bool|string HTTP content. False on failure.
  1267. */
  1268. function wp_remote_fopen( $uri ) {
  1269. $parsed_url = @parse_url( $uri );
  1270. if ( !$parsed_url || !is_array( $parsed_url ) )
  1271. return false;
  1272. $options = array();
  1273. $options['timeout'] = 10;
  1274. $response = wp_remote_get( $uri, $options );
  1275. if ( is_wp_error( $response ) )
  1276. return false;
  1277. return $response['body'];
  1278. }
  1279. /**
  1280. * Setup the WordPress query.
  1281. *
  1282. * @since 2.0.0
  1283. *
  1284. * @param string $query_vars Default WP_Query arguments.
  1285. */
  1286. function wp( $query_vars = '' ) {
  1287. global $wp, $wp_query, $wp_the_query;
  1288. $wp->main( $query_vars );
  1289. if( !isset($wp_the_query) )
  1290. $wp_the_query = $wp_query;
  1291. }
  1292. /**
  1293. * Retrieve the description for the HTTP status.
  1294. *
  1295. * @since 2.3.0
  1296. *
  1297. * @param int $code HTTP status code.
  1298. * @return string Empty string if not found, or description if found.
  1299. */
  1300. function get_status_header_desc( $code ) {
  1301. global $wp_header_to_desc;
  1302. $code = absint( $code );
  1303. if ( !isset( $wp_header_to_desc ) ) {
  1304. $wp_header_to_desc = array(
  1305. 100 => 'Continue',
  1306. 101 => 'Switching Protocols',
  1307. 102 => 'Processing',
  1308. 200 => 'OK',
  1309. 201 => 'Created',
  1310. 202 => 'Accepted',
  1311. 203 => 'Non-Authoritative Information',
  1312. 204 => 'No Content',
  1313. 205 => 'Reset Content',
  1314. 206 => 'Partial Content',
  1315. 207 => 'Multi-Status',
  1316. 226 => 'IM Used',
  1317. 300 => 'Multiple Choices',
  1318. 301 => 'Moved Permanently',
  1319. 302 => 'Found',
  1320. 303 => 'See Other',
  1321. 304 => 'Not Modified',
  1322. 305 => 'Use Proxy',
  1323. 306 => 'Reserved',
  1324. 307 => 'Temporary Redirect',
  1325. 400 => 'Bad Request',
  1326. 401 => 'Unauthorized',
  1327. 402 => 'Payment Required',
  1328. 403 => 'Forbidden',
  1329. 404 => 'Not Found',
  1330. 405 => 'Method Not Allowed',
  1331. 406 => 'Not Acceptable',
  1332. 407 => 'Proxy Authentication Required',
  1333. 408 => 'Request Timeout',
  1334. 409 => 'Conflict',
  1335. 410 => 'Gone',
  1336. 411 => 'Length Required',
  1337. 412 => 'Precondition Failed',
  1338. 413 => 'Request Entity Too Large',
  1339. 414 => 'Request-URI Too Long',
  1340. 415 => 'Unsupported Media Type',
  1341. 416 => 'Requested Range Not Satisfiable',
  1342. 417 => 'Expectation Failed',
  1343. 422 => 'Unprocessable Entity',
  1344. 423 => 'Locked',
  1345. 424 => 'Failed Dependency',
  1346. 426 => 'Upgrade Required',
  1347. 500 => 'Internal Server Error',
  1348. 501 => 'Not Implemented',
  1349. 502 => 'Bad Gateway',
  1350. 503 => 'Service Unavailable',
  1351. 504 => 'Gateway Timeout',
  1352. 505 => 'HTTP Version Not Supported',
  1353. 506 => 'Variant Also Negotiates',
  1354. 507 => 'Insufficient Storage',
  1355. 510 => 'Not Extended'
  1356. );
  1357. }
  1358. if ( isset( $wp_header_to_desc[$code] ) )
  1359. return $wp_header_to_desc[$code];
  1360. else
  1361. return '';
  1362. }
  1363. /**
  1364. * Set HTTP status header.
  1365. *
  1366. * @since 2.0.0
  1367. * @uses apply_filters() Calls 'status_header' on status header string, HTTP
  1368. * HTTP code, HTTP code description, and protocol string as separate
  1369. * parameters.
  1370. *
  1371. * @param int $header HTTP status code
  1372. * @return null Does not return anything.
  1373. */
  1374. function status_header( $header ) {
  1375. $text = get_status_header_desc( $header );
  1376. if ( empty( $text ) )
  1377. return false;
  1378. $protocol = $_SERVER["SERVER_PROTOCOL"];
  1379. if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol )
  1380. $protocol = 'HTTP/1.0';
  1381. $status_header = "$protocol $header $text";
  1382. if ( function_exists( 'apply_filters' ) )
  1383. $status_header = apply_filters( 'status_header', $status_header, $header, $text, $protocol );
  1384. return @header( $status_header, true, $header );
  1385. }
  1386. /**
  1387. * Gets the header information to prevent caching.
  1388. *
  1389. * The several different headers cover the different ways cache prevention is handled
  1390. * by different browsers
  1391. *
  1392. * @since 2.8
  1393. *
  1394. * @uses apply_filters()
  1395. * @return array The associative array of header names and field values.
  1396. */
  1397. function wp_get_nocache_headers() {
  1398. $headers = array(
  1399. 'Expires' => 'Wed, 11 Jan 1984 05:00:00 GMT',
  1400. 'Last-Modified' => gmdate( 'D, d M Y H:i:s' ) . ' GMT',
  1401. 'Cache-Control' => 'no-cache, must-revalidate, max-age=0',
  1402. 'Pragma' => 'no-cache',
  1403. );
  1404. if ( function_exists('apply_filters') ) {
  1405. $headers = apply_filters('nocache_headers', $headers);
  1406. }
  1407. return $headers;
  1408. }
  1409. /**
  1410. * Sets the headers to prevent caching for the different browsers.
  1411. *
  1412. * Different browsers support different nocache headers, so several headers must
  1413. * be sent so that all of them get the point that no caching should occur.
  1414. *
  1415. * @since 2.0.0
  1416. * @uses wp_get_nocache_headers()
  1417. */
  1418. function nocache_headers() {
  1419. $headers = wp_get_nocache_headers();
  1420. foreach( (array) $headers as $name => $field_value )
  1421. @header("{$name}: {$field_value}");
  1422. }
  1423. /**
  1424. * Set the headers for caching for 10 days with JavaScript content type.
  1425. *
  1426. * @since 2.1.0
  1427. */
  1428. function cache_javascript_headers() {
  1429. $expiresOffset = 864000; // 10 days
  1430. header( "Content-Type: text/javascript; charset=" . get_bloginfo( 'charset' ) );
  1431. header( "Vary: Accept-Encoding" ); // Handle proxies
  1432. header( "Expires: " . gmdate( "D, d M Y H:i:s", time() + $expiresOffset ) . " GMT" );
  1433. }
  1434. /**
  1435. * Retrieve the number of database queries during the WordPress execution.
  1436. *
  1437. * @since 2.0.0
  1438. *
  1439. * @return int Number of database queries
  1440. */
  1441. function get_num_queries() {
  1442. global $wpdb;
  1443. return $wpdb->num_queries;
  1444. }
  1445. /**
  1446. * Whether input is yes or no. Must be 'y' to be true.
  1447. *
  1448. * @since 1.0.0
  1449. *
  1450. * @param string $yn Character string containing either 'y' or 'n'
  1451. * @return bool True if yes, false on anything else
  1452. */
  1453. function bool_from_yn( $yn ) {
  1454. return ( strtolower( $yn ) == 'y' );
  1455. }
  1456. /**
  1457. * Loads the feed template from the use of an action hook.
  1458. *
  1459. * If the feed action does not have a hook, then the function will die with a
  1460. * message telling the visitor that the feed is not valid.
  1461. *
  1462. * It is better to only have one hook for each feed.
  1463. *
  1464. * @since 2.1.0
  1465. * @uses $wp_query Used to tell if the use a comment feed.
  1466. * @uses do_action() Calls 'do_feed_$feed' hook, if a hook exists for the feed.
  1467. */
  1468. function do_feed() {
  1469. global $wp_query;
  1470. $feed = get_query_var( 'feed' );
  1471. // Remove the pad, if present.
  1472. $feed = preg_replace( '/^_+/', '', $feed );
  1473. if ( $feed == '' || $feed == 'feed' )
  1474. $feed = get_default_feed();
  1475. $hook = 'do_feed_' . $feed;
  1476. if ( !has_action($hook) ) {
  1477. $message = sprintf( __( 'ERROR: %s is not a valid feed template' ), esc_html($feed));
  1478. wp_die($message);
  1479. }
  1480. do_action( $hook, $wp_query->is_comment_feed );
  1481. }
  1482. /**
  1483. * Load the RDF RSS 0.91 Feed template.
  1484. *
  1485. * @since 2.1.0
  1486. */
  1487. function do_feed_rdf() {
  1488. load_template( ABSPATH . WPINC . '/feed-rdf.php' );
  1489. }
  1490. /**
  1491. * Load the RSS 1.0 Feed Template
  1492. *
  1493. * @since 2.1.0
  1494. */
  1495. function do_feed_rss() {
  1496. load_template( ABSPATH . WPINC . '/feed-rss.php' );
  1497. }
  1498. /**
  1499. * Load either the RSS2 comment feed or the RSS2 posts feed.
  1500. *
  1501. * @since 2.1.0
  1502. *
  1503. * @param bool $for_comments True for the comment feed, false for normal feed.
  1504. */
  1505. function do_feed_rss2( $for_comments ) {
  1506. if ( $for_comments )
  1507. load_template( ABSPATH . WPINC . '/feed-r…

Large files files are truncated, but you can click here to view the full file