PageRenderTime 58ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 2ms

/wp-includes/functions.php

http://github.com/wordpress/wordpress
PHP | 7608 lines | 3958 code | 684 blank | 2966 comment | 667 complexity | 864ae3860c8ac08e4923a3ed0e802023 MD5 | raw file
Possible License(s): 0BSD

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. require ABSPATH . WPINC . '/option.php';
  8. /**
  9. * Convert given MySQL date string into a different format.
  10. *
  11. * `$format` should be a PHP date format string.
  12. * 'U' and 'G' formats will return a sum of timestamp with timezone offset.
  13. * `$date` is expected to be local time in MySQL format (`Y-m-d H:i:s`).
  14. *
  15. * Historically UTC time could be passed to the function to produce Unix timestamp.
  16. *
  17. * If `$translate` is true then the given date and format string will
  18. * be passed to `wp_date()` for translation.
  19. *
  20. * @since 0.71
  21. *
  22. * @param string $format Format of the date to return.
  23. * @param string $date Date string to convert.
  24. * @param bool $translate Whether the return date should be translated. Default true.
  25. * @return string|int|false Formatted date string or sum of Unix timestamp and timezone offset.
  26. * False on failure.
  27. */
  28. function mysql2date( $format, $date, $translate = true ) {
  29. if ( empty( $date ) ) {
  30. return false;
  31. }
  32. $datetime = date_create( $date, wp_timezone() );
  33. if ( false === $datetime ) {
  34. return false;
  35. }
  36. // Returns a sum of timestamp with timezone offset. Ideally should never be used.
  37. if ( 'G' === $format || 'U' === $format ) {
  38. return $datetime->getTimestamp() + $datetime->getOffset();
  39. }
  40. if ( $translate ) {
  41. return wp_date( $format, $datetime->getTimestamp() );
  42. }
  43. return $datetime->format( $format );
  44. }
  45. /**
  46. * Retrieves the current time based on specified type.
  47. *
  48. * The 'mysql' type will return the time in the format for MySQL DATETIME field.
  49. * The 'timestamp' type will return the current timestamp or a sum of timestamp
  50. * and timezone offset, depending on `$gmt`.
  51. * Other strings will be interpreted as PHP date formats (e.g. 'Y-m-d').
  52. *
  53. * If $gmt is set to either '1' or 'true', then both types will use GMT time.
  54. * if $gmt is false, the output is adjusted with the GMT offset in the WordPress option.
  55. *
  56. * @since 1.0.0
  57. *
  58. * @param string $type Type of time to retrieve. Accepts 'mysql', 'timestamp',
  59. * or PHP date format string (e.g. 'Y-m-d').
  60. * @param int|bool $gmt Optional. Whether to use GMT timezone. Default false.
  61. * @return int|string Integer if $type is 'timestamp', string otherwise.
  62. */
  63. function current_time( $type, $gmt = 0 ) {
  64. // Don't use non-GMT timestamp, unless you know the difference and really need to.
  65. if ( 'timestamp' === $type || 'U' === $type ) {
  66. return $gmt ? time() : time() + (int) ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
  67. }
  68. if ( 'mysql' === $type ) {
  69. $type = 'Y-m-d H:i:s';
  70. }
  71. $timezone = $gmt ? new DateTimeZone( 'UTC' ) : wp_timezone();
  72. $datetime = new DateTime( 'now', $timezone );
  73. return $datetime->format( $type );
  74. }
  75. /**
  76. * Retrieves the current time as an object with the timezone from settings.
  77. *
  78. * @since 5.3.0
  79. *
  80. * @return DateTimeImmutable Date and time object.
  81. */
  82. function current_datetime() {
  83. return new DateTimeImmutable( 'now', wp_timezone() );
  84. }
  85. /**
  86. * Retrieves the timezone from site settings as a string.
  87. *
  88. * Uses the `timezone_string` option to get a proper timezone if available,
  89. * otherwise falls back to an offset.
  90. *
  91. * @since 5.3.0
  92. *
  93. * @return string PHP timezone string or a ±HH:MM offset.
  94. */
  95. function wp_timezone_string() {
  96. $timezone_string = get_option( 'timezone_string' );
  97. if ( $timezone_string ) {
  98. return $timezone_string;
  99. }
  100. $offset = (float) get_option( 'gmt_offset' );
  101. $hours = (int) $offset;
  102. $minutes = ( $offset - $hours );
  103. $sign = ( $offset < 0 ) ? '-' : '+';
  104. $abs_hour = abs( $hours );
  105. $abs_mins = abs( $minutes * 60 );
  106. $tz_offset = sprintf( '%s%02d:%02d', $sign, $abs_hour, $abs_mins );
  107. return $tz_offset;
  108. }
  109. /**
  110. * Retrieves the timezone from site settings as a `DateTimeZone` object.
  111. *
  112. * Timezone can be based on a PHP timezone string or a ±HH:MM offset.
  113. *
  114. * @since 5.3.0
  115. *
  116. * @return DateTimeZone Timezone object.
  117. */
  118. function wp_timezone() {
  119. return new DateTimeZone( wp_timezone_string() );
  120. }
  121. /**
  122. * Retrieves the date in localized format, based on a sum of Unix timestamp and
  123. * timezone offset in seconds.
  124. *
  125. * If the locale specifies the locale month and weekday, then the locale will
  126. * take over the format for the date. If it isn't, then the date format string
  127. * will be used instead.
  128. *
  129. * Note that due to the way WP typically generates a sum of timestamp and offset
  130. * with `strtotime()`, it implies offset added at a _current_ time, not at the time
  131. * the timestamp represents. Storing such timestamps or calculating them differently
  132. * will lead to invalid output.
  133. *
  134. * @since 0.71
  135. * @since 5.3.0 Converted into a wrapper for wp_date().
  136. *
  137. * @global WP_Locale $wp_locale WordPress date and time locale object.
  138. *
  139. * @param string $format Format to display the date.
  140. * @param int|bool $timestamp_with_offset Optional. A sum of Unix timestamp and timezone offset
  141. * in seconds. Default false.
  142. * @param bool $gmt Optional. Whether to use GMT timezone. Only applies
  143. * if timestamp is not provided. Default false.
  144. * @return string The date, translated if locale specifies it.
  145. */
  146. function date_i18n( $format, $timestamp_with_offset = false, $gmt = false ) {
  147. $timestamp = $timestamp_with_offset;
  148. // If timestamp is omitted it should be current time (summed with offset, unless `$gmt` is true).
  149. if ( ! is_numeric( $timestamp ) ) {
  150. $timestamp = current_time( 'timestamp', $gmt );
  151. }
  152. /*
  153. * This is a legacy implementation quirk that the returned timestamp is also with offset.
  154. * Ideally this function should never be used to produce a timestamp.
  155. */
  156. if ( 'U' === $format ) {
  157. $date = $timestamp;
  158. } elseif ( $gmt && false === $timestamp_with_offset ) { // Current time in UTC.
  159. $date = wp_date( $format, null, new DateTimeZone( 'UTC' ) );
  160. } elseif ( false === $timestamp_with_offset ) { // Current time in site's timezone.
  161. $date = wp_date( $format );
  162. } else {
  163. /*
  164. * Timestamp with offset is typically produced by a UTC `strtotime()` call on an input without timezone.
  165. * This is the best attempt to reverse that operation into a local time to use.
  166. */
  167. $local_time = gmdate( 'Y-m-d H:i:s', $timestamp );
  168. $timezone = wp_timezone();
  169. $datetime = date_create( $local_time, $timezone );
  170. $date = wp_date( $format, $datetime->getTimestamp(), $timezone );
  171. }
  172. /**
  173. * Filters the date formatted based on the locale.
  174. *
  175. * @since 2.8.0
  176. *
  177. * @param string $date Formatted date string.
  178. * @param string $format Format to display the date.
  179. * @param int $timestamp A sum of Unix timestamp and timezone offset in seconds.
  180. * Might be without offset if input omitted timestamp but requested GMT.
  181. * @param bool $gmt Whether to use GMT timezone. Only applies if timestamp was not provided.
  182. * Default false.
  183. */
  184. $date = apply_filters( 'date_i18n', $date, $format, $timestamp, $gmt );
  185. return $date;
  186. }
  187. /**
  188. * Retrieves the date, in localized format.
  189. *
  190. * This is a newer function, intended to replace `date_i18n()` without legacy quirks in it.
  191. *
  192. * Note that, unlike `date_i18n()`, this function accepts a true Unix timestamp, not summed
  193. * with timezone offset.
  194. *
  195. * @since 5.3.0
  196. *
  197. * @param string $format PHP date format.
  198. * @param int $timestamp Optional. Unix timestamp. Defaults to current time.
  199. * @param DateTimeZone $timezone Optional. Timezone to output result in. Defaults to timezone
  200. * from site settings.
  201. * @return string|false The date, translated if locale specifies it. False on invalid timestamp input.
  202. */
  203. function wp_date( $format, $timestamp = null, $timezone = null ) {
  204. global $wp_locale;
  205. if ( null === $timestamp ) {
  206. $timestamp = time();
  207. } elseif ( ! is_numeric( $timestamp ) ) {
  208. return false;
  209. }
  210. if ( ! $timezone ) {
  211. $timezone = wp_timezone();
  212. }
  213. $datetime = date_create( '@' . $timestamp );
  214. $datetime->setTimezone( $timezone );
  215. if ( empty( $wp_locale->month ) || empty( $wp_locale->weekday ) ) {
  216. $date = $datetime->format( $format );
  217. } else {
  218. // We need to unpack shorthand `r` format because it has parts that might be localized.
  219. $format = preg_replace( '/(?<!\\\\)r/', DATE_RFC2822, $format );
  220. $new_format = '';
  221. $format_length = strlen( $format );
  222. $month = $wp_locale->get_month( $datetime->format( 'm' ) );
  223. $weekday = $wp_locale->get_weekday( $datetime->format( 'w' ) );
  224. for ( $i = 0; $i < $format_length; $i ++ ) {
  225. switch ( $format[ $i ] ) {
  226. case 'D':
  227. $new_format .= addcslashes( $wp_locale->get_weekday_abbrev( $weekday ), '\\A..Za..z' );
  228. break;
  229. case 'F':
  230. $new_format .= addcslashes( $month, '\\A..Za..z' );
  231. break;
  232. case 'l':
  233. $new_format .= addcslashes( $weekday, '\\A..Za..z' );
  234. break;
  235. case 'M':
  236. $new_format .= addcslashes( $wp_locale->get_month_abbrev( $month ), '\\A..Za..z' );
  237. break;
  238. case 'a':
  239. $new_format .= addcslashes( $wp_locale->get_meridiem( $datetime->format( 'a' ) ), '\\A..Za..z' );
  240. break;
  241. case 'A':
  242. $new_format .= addcslashes( $wp_locale->get_meridiem( $datetime->format( 'A' ) ), '\\A..Za..z' );
  243. break;
  244. case '\\':
  245. $new_format .= $format[ $i ];
  246. // If character follows a slash, we add it without translating.
  247. if ( $i < $format_length ) {
  248. $new_format .= $format[ ++$i ];
  249. }
  250. break;
  251. default:
  252. $new_format .= $format[ $i ];
  253. break;
  254. }
  255. }
  256. $date = $datetime->format( $new_format );
  257. $date = wp_maybe_decline_date( $date, $format );
  258. }
  259. /**
  260. * Filters the date formatted based on the locale.
  261. *
  262. * @since 5.3.0
  263. *
  264. * @param string $date Formatted date string.
  265. * @param string $format Format to display the date.
  266. * @param int $timestamp Unix timestamp.
  267. * @param DateTimeZone $timezone Timezone.
  268. *
  269. */
  270. $date = apply_filters( 'wp_date', $date, $format, $timestamp, $timezone );
  271. return $date;
  272. }
  273. /**
  274. * Determines if the date should be declined.
  275. *
  276. * If the locale specifies that month names require a genitive case in certain
  277. * formats (like 'j F Y'), the month name will be replaced with a correct form.
  278. *
  279. * @since 4.4.0
  280. * @since 5.4.0 The `$format` parameter was added.
  281. *
  282. * @global WP_Locale $wp_locale WordPress date and time locale object.
  283. *
  284. * @param string $date Formatted date string.
  285. * @param string $format Optional. Date format to check. Default empty string.
  286. * @return string The date, declined if locale specifies it.
  287. */
  288. function wp_maybe_decline_date( $date, $format = '' ) {
  289. global $wp_locale;
  290. // i18n functions are not available in SHORTINIT mode.
  291. if ( ! function_exists( '_x' ) ) {
  292. return $date;
  293. }
  294. /*
  295. * translators: If months in your language require a genitive case,
  296. * translate this to 'on'. Do not translate into your own language.
  297. */
  298. if ( 'on' === _x( 'off', 'decline months names: on or off' ) ) {
  299. $months = $wp_locale->month;
  300. $months_genitive = $wp_locale->month_genitive;
  301. /*
  302. * Match a format like 'j F Y' or 'j. F' (day of the month, followed by month name)
  303. * and decline the month.
  304. */
  305. if ( $format ) {
  306. $decline = preg_match( '#[dj]\.? F#', $format );
  307. } else {
  308. // If the format is not passed, try to guess it from the date string.
  309. $decline = preg_match( '#\b\d{1,2}\.? [^\d ]+\b#u', $date );
  310. }
  311. if ( $decline ) {
  312. foreach ( $months as $key => $month ) {
  313. $months[ $key ] = '# ' . preg_quote( $month, '#' ) . '\b#u';
  314. }
  315. foreach ( $months_genitive as $key => $month ) {
  316. $months_genitive[ $key ] = ' ' . $month;
  317. }
  318. $date = preg_replace( $months, $months_genitive, $date );
  319. }
  320. /*
  321. * Match a format like 'F jS' or 'F j' (month name, followed by day with an optional ordinal suffix)
  322. * and change it to declined 'j F'.
  323. */
  324. if ( $format ) {
  325. $decline = preg_match( '#F [dj]#', $format );
  326. } else {
  327. // If the format is not passed, try to guess it from the date string.
  328. $decline = preg_match( '#\b[^\d ]+ \d{1,2}(st|nd|rd|th)?\b#u', trim( $date ) );
  329. }
  330. if ( $decline ) {
  331. foreach ( $months as $key => $month ) {
  332. $months[ $key ] = '#\b' . preg_quote( $month, '#' ) . ' (\d{1,2})(st|nd|rd|th)?([-–]\d{1,2})?(st|nd|rd|th)?\b#u';
  333. }
  334. foreach ( $months_genitive as $key => $month ) {
  335. $months_genitive[ $key ] = '$1$3 ' . $month;
  336. }
  337. $date = preg_replace( $months, $months_genitive, $date );
  338. }
  339. }
  340. // Used for locale-specific rules.
  341. $locale = get_locale();
  342. if ( 'ca' === $locale ) {
  343. // " de abril| de agost| de octubre..." -> " d'abril| d'agost| d'octubre..."
  344. $date = preg_replace( '# de ([ao])#i', " d'\\1", $date );
  345. }
  346. return $date;
  347. }
  348. /**
  349. * Convert float number to format based on the locale.
  350. *
  351. * @since 2.3.0
  352. *
  353. * @global WP_Locale $wp_locale WordPress date and time locale object.
  354. *
  355. * @param float $number The number to convert based on locale.
  356. * @param int $decimals Optional. Precision of the number of decimal places. Default 0.
  357. * @return string Converted number in string format.
  358. */
  359. function number_format_i18n( $number, $decimals = 0 ) {
  360. global $wp_locale;
  361. if ( isset( $wp_locale ) ) {
  362. $formatted = number_format( $number, absint( $decimals ), $wp_locale->number_format['decimal_point'], $wp_locale->number_format['thousands_sep'] );
  363. } else {
  364. $formatted = number_format( $number, absint( $decimals ) );
  365. }
  366. /**
  367. * Filters the number formatted based on the locale.
  368. *
  369. * @since 2.8.0
  370. * @since 4.9.0 The `$number` and `$decimals` parameters were added.
  371. *
  372. * @param string $formatted Converted number in string format.
  373. * @param float $number The number to convert based on locale.
  374. * @param int $decimals Precision of the number of decimal places.
  375. */
  376. return apply_filters( 'number_format_i18n', $formatted, $number, $decimals );
  377. }
  378. /**
  379. * Convert number of bytes largest unit bytes will fit into.
  380. *
  381. * It is easier to read 1 KB than 1024 bytes and 1 MB than 1048576 bytes. Converts
  382. * number of bytes to human readable number by taking the number of that unit
  383. * that the bytes will go into it. Supports TB value.
  384. *
  385. * Please note that integers in PHP are limited to 32 bits, unless they are on
  386. * 64 bit architecture, then they have 64 bit size. If you need to place the
  387. * larger size then what PHP integer type will hold, then use a string. It will
  388. * be converted to a double, which should always have 64 bit length.
  389. *
  390. * Technically the correct unit names for powers of 1024 are KiB, MiB etc.
  391. *
  392. * @since 2.3.0
  393. *
  394. * @param int|string $bytes Number of bytes. Note max integer size for integers.
  395. * @param int $decimals Optional. Precision of number of decimal places. Default 0.
  396. * @return string|false False on failure. Number string on success.
  397. */
  398. function size_format( $bytes, $decimals = 0 ) {
  399. $quant = array(
  400. 'TB' => TB_IN_BYTES,
  401. 'GB' => GB_IN_BYTES,
  402. 'MB' => MB_IN_BYTES,
  403. 'KB' => KB_IN_BYTES,
  404. 'B' => 1,
  405. );
  406. if ( 0 === $bytes ) {
  407. return number_format_i18n( 0, $decimals ) . ' B';
  408. }
  409. foreach ( $quant as $unit => $mag ) {
  410. if ( doubleval( $bytes ) >= $mag ) {
  411. return number_format_i18n( $bytes / $mag, $decimals ) . ' ' . $unit;
  412. }
  413. }
  414. return false;
  415. }
  416. /**
  417. * Convert a duration to human readable format.
  418. *
  419. * @since 5.1.0
  420. *
  421. * @param string $duration Duration will be in string format (HH:ii:ss) OR (ii:ss),
  422. * with a possible prepended negative sign (-).
  423. * @return string|false A human readable duration string, false on failure.
  424. */
  425. function human_readable_duration( $duration = '' ) {
  426. if ( ( empty( $duration ) || ! is_string( $duration ) ) ) {
  427. return false;
  428. }
  429. $duration = trim( $duration );
  430. // Remove prepended negative sign.
  431. if ( '-' === substr( $duration, 0, 1 ) ) {
  432. $duration = substr( $duration, 1 );
  433. }
  434. // Extract duration parts.
  435. $duration_parts = array_reverse( explode( ':', $duration ) );
  436. $duration_count = count( $duration_parts );
  437. $hour = null;
  438. $minute = null;
  439. $second = null;
  440. if ( 3 === $duration_count ) {
  441. // Validate HH:ii:ss duration format.
  442. if ( ! ( (bool) preg_match( '/^([0-9]+):([0-5]?[0-9]):([0-5]?[0-9])$/', $duration ) ) ) {
  443. return false;
  444. }
  445. // Three parts: hours, minutes & seconds.
  446. list( $second, $minute, $hour ) = $duration_parts;
  447. } elseif ( 2 === $duration_count ) {
  448. // Validate ii:ss duration format.
  449. if ( ! ( (bool) preg_match( '/^([0-5]?[0-9]):([0-5]?[0-9])$/', $duration ) ) ) {
  450. return false;
  451. }
  452. // Two parts: minutes & seconds.
  453. list( $second, $minute ) = $duration_parts;
  454. } else {
  455. return false;
  456. }
  457. $human_readable_duration = array();
  458. // Add the hour part to the string.
  459. if ( is_numeric( $hour ) ) {
  460. /* translators: %s: Time duration in hour or hours. */
  461. $human_readable_duration[] = sprintf( _n( '%s hour', '%s hours', $hour ), (int) $hour );
  462. }
  463. // Add the minute part to the string.
  464. if ( is_numeric( $minute ) ) {
  465. /* translators: %s: Time duration in minute or minutes. */
  466. $human_readable_duration[] = sprintf( _n( '%s minute', '%s minutes', $minute ), (int) $minute );
  467. }
  468. // Add the second part to the string.
  469. if ( is_numeric( $second ) ) {
  470. /* translators: %s: Time duration in second or seconds. */
  471. $human_readable_duration[] = sprintf( _n( '%s second', '%s seconds', $second ), (int) $second );
  472. }
  473. return implode( ', ', $human_readable_duration );
  474. }
  475. /**
  476. * Get the week start and end from the datetime or date string from MySQL.
  477. *
  478. * @since 0.71
  479. *
  480. * @param string $mysqlstring Date or datetime field type from MySQL.
  481. * @param int|string $start_of_week Optional. Start of the week as an integer. Default empty string.
  482. * @return array Keys are 'start' and 'end'.
  483. */
  484. function get_weekstartend( $mysqlstring, $start_of_week = '' ) {
  485. // MySQL string year.
  486. $my = substr( $mysqlstring, 0, 4 );
  487. // MySQL string month.
  488. $mm = substr( $mysqlstring, 8, 2 );
  489. // MySQL string day.
  490. $md = substr( $mysqlstring, 5, 2 );
  491. // The timestamp for MySQL string day.
  492. $day = mktime( 0, 0, 0, $md, $mm, $my );
  493. // The day of the week from the timestamp.
  494. $weekday = gmdate( 'w', $day );
  495. if ( ! is_numeric( $start_of_week ) ) {
  496. $start_of_week = get_option( 'start_of_week' );
  497. }
  498. if ( $weekday < $start_of_week ) {
  499. $weekday += 7;
  500. }
  501. // The most recent week start day on or before $day.
  502. $start = $day - DAY_IN_SECONDS * ( $weekday - $start_of_week );
  503. // $start + 1 week - 1 second.
  504. $end = $start + WEEK_IN_SECONDS - 1;
  505. return compact( 'start', 'end' );
  506. }
  507. /**
  508. * Serialize data, if needed.
  509. *
  510. * @since 2.0.5
  511. *
  512. * @param string|array|object $data Data that might be serialized.
  513. * @return mixed A scalar data.
  514. */
  515. function maybe_serialize( $data ) {
  516. if ( is_array( $data ) || is_object( $data ) ) {
  517. return serialize( $data );
  518. }
  519. /*
  520. * Double serialization is required for backward compatibility.
  521. * See https://core.trac.wordpress.org/ticket/12930
  522. * Also the world will end. See WP 3.6.1.
  523. */
  524. if ( is_serialized( $data, false ) ) {
  525. return serialize( $data );
  526. }
  527. return $data;
  528. }
  529. /**
  530. * Unserialize data only if it was serialized.
  531. *
  532. * @since 2.0.0
  533. *
  534. * @param string $data Data that might be unserialized.
  535. * @return mixed Unserialized data can be any type.
  536. */
  537. function maybe_unserialize( $data ) {
  538. if ( is_serialized( $data ) ) { // Don't attempt to unserialize data that wasn't serialized going in.
  539. return @unserialize( trim( $data ) );
  540. }
  541. return $data;
  542. }
  543. /**
  544. * Check value to find if it was serialized.
  545. *
  546. * If $data is not an string, then returned value will always be false.
  547. * Serialized data is always a string.
  548. *
  549. * @since 2.0.5
  550. *
  551. * @param string $data Value to check to see if was serialized.
  552. * @param bool $strict Optional. Whether to be strict about the end of the string. Default true.
  553. * @return bool False if not serialized and true if it was.
  554. */
  555. function is_serialized( $data, $strict = true ) {
  556. // If it isn't a string, it isn't serialized.
  557. if ( ! is_string( $data ) ) {
  558. return false;
  559. }
  560. $data = trim( $data );
  561. if ( 'N;' == $data ) {
  562. return true;
  563. }
  564. if ( strlen( $data ) < 4 ) {
  565. return false;
  566. }
  567. if ( ':' !== $data[1] ) {
  568. return false;
  569. }
  570. if ( $strict ) {
  571. $lastc = substr( $data, -1 );
  572. if ( ';' !== $lastc && '}' !== $lastc ) {
  573. return false;
  574. }
  575. } else {
  576. $semicolon = strpos( $data, ';' );
  577. $brace = strpos( $data, '}' );
  578. // Either ; or } must exist.
  579. if ( false === $semicolon && false === $brace ) {
  580. return false;
  581. }
  582. // But neither must be in the first X characters.
  583. if ( false !== $semicolon && $semicolon < 3 ) {
  584. return false;
  585. }
  586. if ( false !== $brace && $brace < 4 ) {
  587. return false;
  588. }
  589. }
  590. $token = $data[0];
  591. switch ( $token ) {
  592. case 's':
  593. if ( $strict ) {
  594. if ( '"' !== substr( $data, -2, 1 ) ) {
  595. return false;
  596. }
  597. } elseif ( false === strpos( $data, '"' ) ) {
  598. return false;
  599. }
  600. // Or else fall through.
  601. case 'a':
  602. case 'O':
  603. return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
  604. case 'b':
  605. case 'i':
  606. case 'd':
  607. $end = $strict ? '$' : '';
  608. return (bool) preg_match( "/^{$token}:[0-9.E+-]+;$end/", $data );
  609. }
  610. return false;
  611. }
  612. /**
  613. * Check whether serialized data is of string type.
  614. *
  615. * @since 2.0.5
  616. *
  617. * @param string $data Serialized data.
  618. * @return bool False if not a serialized string, true if it is.
  619. */
  620. function is_serialized_string( $data ) {
  621. // if it isn't a string, it isn't a serialized string.
  622. if ( ! is_string( $data ) ) {
  623. return false;
  624. }
  625. $data = trim( $data );
  626. if ( strlen( $data ) < 4 ) {
  627. return false;
  628. } elseif ( ':' !== $data[1] ) {
  629. return false;
  630. } elseif ( ';' !== substr( $data, -1 ) ) {
  631. return false;
  632. } elseif ( 's' !== $data[0] ) {
  633. return false;
  634. } elseif ( '"' !== substr( $data, -2, 1 ) ) {
  635. return false;
  636. } else {
  637. return true;
  638. }
  639. }
  640. /**
  641. * Retrieve post title from XMLRPC XML.
  642. *
  643. * If the title element is not part of the XML, then the default post title from
  644. * the $post_default_title will be used instead.
  645. *
  646. * @since 0.71
  647. *
  648. * @global string $post_default_title Default XML-RPC post title.
  649. *
  650. * @param string $content XMLRPC XML Request content
  651. * @return string Post title
  652. */
  653. function xmlrpc_getposttitle( $content ) {
  654. global $post_default_title;
  655. if ( preg_match( '/<title>(.+?)<\/title>/is', $content, $matchtitle ) ) {
  656. $post_title = $matchtitle[1];
  657. } else {
  658. $post_title = $post_default_title;
  659. }
  660. return $post_title;
  661. }
  662. /**
  663. * Retrieve the post category or categories from XMLRPC XML.
  664. *
  665. * If the category element is not found, then the default post category will be
  666. * used. The return type then would be what $post_default_category. If the
  667. * category is found, then it will always be an array.
  668. *
  669. * @since 0.71
  670. *
  671. * @global string $post_default_category Default XML-RPC post category.
  672. *
  673. * @param string $content XMLRPC XML Request content
  674. * @return string|array List of categories or category name.
  675. */
  676. function xmlrpc_getpostcategory( $content ) {
  677. global $post_default_category;
  678. if ( preg_match( '/<category>(.+?)<\/category>/is', $content, $matchcat ) ) {
  679. $post_category = trim( $matchcat[1], ',' );
  680. $post_category = explode( ',', $post_category );
  681. } else {
  682. $post_category = $post_default_category;
  683. }
  684. return $post_category;
  685. }
  686. /**
  687. * XMLRPC XML content without title and category elements.
  688. *
  689. * @since 0.71
  690. *
  691. * @param string $content XML-RPC XML Request content.
  692. * @return string XMLRPC XML Request content without title and category elements.
  693. */
  694. function xmlrpc_removepostdata( $content ) {
  695. $content = preg_replace( '/<title>(.+?)<\/title>/si', '', $content );
  696. $content = preg_replace( '/<category>(.+?)<\/category>/si', '', $content );
  697. $content = trim( $content );
  698. return $content;
  699. }
  700. /**
  701. * Use RegEx to extract URLs from arbitrary content.
  702. *
  703. * @since 3.7.0
  704. *
  705. * @param string $content Content to extract URLs from.
  706. * @return string[] Array of URLs found in passed string.
  707. */
  708. function wp_extract_urls( $content ) {
  709. preg_match_all(
  710. "#([\"']?)("
  711. . '(?:([\w-]+:)?//?)'
  712. . '[^\s()<>]+'
  713. . '[.]'
  714. . '(?:'
  715. . '\([\w\d]+\)|'
  716. . '(?:'
  717. . "[^`!()\[\]{};:'\".,<>«»“”‘’\s]|"
  718. . '(?:[:]\d+)?/?'
  719. . ')+'
  720. . ')'
  721. . ")\\1#",
  722. $content,
  723. $post_links
  724. );
  725. $post_links = array_unique( array_map( 'html_entity_decode', $post_links[2] ) );
  726. return array_values( $post_links );
  727. }
  728. /**
  729. * Check content for video and audio links to add as enclosures.
  730. *
  731. * Will not add enclosures that have already been added and will
  732. * remove enclosures that are no longer in the post. This is called as
  733. * pingbacks and trackbacks.
  734. *
  735. * @since 1.5.0
  736. * @since 5.3.0 The `$content` parameter was made optional, and the `$post` parameter was
  737. * updated to accept a post ID or a WP_Post object.
  738. *
  739. * @global wpdb $wpdb WordPress database abstraction object.
  740. *
  741. * @param string $content Post content. If `null`, the `post_content` field from `$post` is used.
  742. * @param int|WP_Post $post Post ID or post object.
  743. * @return null|bool Returns false if post is not found.
  744. */
  745. function do_enclose( $content = null, $post ) {
  746. global $wpdb;
  747. // @todo Tidy this code and make the debug code optional.
  748. include_once ABSPATH . WPINC . '/class-IXR.php';
  749. $post = get_post( $post );
  750. if ( ! $post ) {
  751. return false;
  752. }
  753. if ( null === $content ) {
  754. $content = $post->post_content;
  755. }
  756. $post_links = array();
  757. $pung = get_enclosed( $post->ID );
  758. $post_links_temp = wp_extract_urls( $content );
  759. foreach ( $pung as $link_test ) {
  760. // Link is no longer in post.
  761. if ( ! in_array( $link_test, $post_links_temp, true ) ) {
  762. $mids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE %s", $post->ID, $wpdb->esc_like( $link_test ) . '%' ) );
  763. foreach ( $mids as $mid ) {
  764. delete_metadata_by_mid( 'post', $mid );
  765. }
  766. }
  767. }
  768. foreach ( (array) $post_links_temp as $link_test ) {
  769. // If we haven't pung it already.
  770. if ( ! in_array( $link_test, $pung, true ) ) {
  771. $test = parse_url( $link_test );
  772. if ( false === $test ) {
  773. continue;
  774. }
  775. if ( isset( $test['query'] ) ) {
  776. $post_links[] = $link_test;
  777. } elseif ( isset( $test['path'] ) && ( '/' !== $test['path'] ) && ( '' !== $test['path'] ) ) {
  778. $post_links[] = $link_test;
  779. }
  780. }
  781. }
  782. /**
  783. * Filters the list of enclosure links before querying the database.
  784. *
  785. * Allows for the addition and/or removal of potential enclosures to save
  786. * to postmeta before checking the database for existing enclosures.
  787. *
  788. * @since 4.4.0
  789. *
  790. * @param string[] $post_links An array of enclosure links.
  791. * @param int $post_ID Post ID.
  792. */
  793. $post_links = apply_filters( 'enclosure_links', $post_links, $post->ID );
  794. foreach ( (array) $post_links as $url ) {
  795. 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, $wpdb->esc_like( $url ) . '%' ) ) ) {
  796. $headers = wp_get_http_headers( $url );
  797. if ( $headers ) {
  798. $len = isset( $headers['content-length'] ) ? (int) $headers['content-length'] : 0;
  799. $type = isset( $headers['content-type'] ) ? $headers['content-type'] : '';
  800. $allowed_types = array( 'video', 'audio' );
  801. // Check to see if we can figure out the mime type from the extension.
  802. $url_parts = parse_url( $url );
  803. if ( false !== $url_parts ) {
  804. $extension = pathinfo( $url_parts['path'], PATHINFO_EXTENSION );
  805. if ( ! empty( $extension ) ) {
  806. foreach ( wp_get_mime_types() as $exts => $mime ) {
  807. if ( preg_match( '!^(' . $exts . ')$!i', $extension ) ) {
  808. $type = $mime;
  809. break;
  810. }
  811. }
  812. }
  813. }
  814. if ( in_array( substr( $type, 0, strpos( $type, '/' ) ), $allowed_types, true ) ) {
  815. add_post_meta( $post->ID, 'enclosure', "$url\n$len\n$mime\n" );
  816. }
  817. }
  818. }
  819. }
  820. }
  821. /**
  822. * Retrieve HTTP Headers from URL.
  823. *
  824. * @since 1.5.1
  825. *
  826. * @param string $url URL to retrieve HTTP headers from.
  827. * @param bool $deprecated Not Used.
  828. * @return bool|string False on failure, headers on success.
  829. */
  830. function wp_get_http_headers( $url, $deprecated = false ) {
  831. if ( ! empty( $deprecated ) ) {
  832. _deprecated_argument( __FUNCTION__, '2.7.0' );
  833. }
  834. $response = wp_safe_remote_head( $url );
  835. if ( is_wp_error( $response ) ) {
  836. return false;
  837. }
  838. return wp_remote_retrieve_headers( $response );
  839. }
  840. /**
  841. * Determines whether the publish date of the current post in the loop is different
  842. * from the publish date of the previous post in the loop.
  843. *
  844. * For more information on this and similar theme functions, check out
  845. * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
  846. * Conditional Tags} article in the Theme Developer Handbook.
  847. *
  848. * @since 0.71
  849. *
  850. * @global string $currentday The day of the current post in the loop.
  851. * @global string $previousday The day of the previous post in the loop.
  852. *
  853. * @return int 1 when new day, 0 if not a new day.
  854. */
  855. function is_new_day() {
  856. global $currentday, $previousday;
  857. if ( $currentday !== $previousday ) {
  858. return 1;
  859. } else {
  860. return 0;
  861. }
  862. }
  863. /**
  864. * Build URL query based on an associative and, or indexed array.
  865. *
  866. * This is a convenient function for easily building url queries. It sets the
  867. * separator to '&' and uses _http_build_query() function.
  868. *
  869. * @since 2.3.0
  870. *
  871. * @see _http_build_query() Used to build the query
  872. * @link https://www.php.net/manual/en/function.http-build-query.php for more on what
  873. * http_build_query() does.
  874. *
  875. * @param array $data URL-encode key/value pairs.
  876. * @return string URL-encoded string.
  877. */
  878. function build_query( $data ) {
  879. return _http_build_query( $data, null, '&', '', false );
  880. }
  881. /**
  882. * From php.net (modified by Mark Jaquith to behave like the native PHP5 function).
  883. *
  884. * @since 3.2.0
  885. * @access private
  886. *
  887. * @see https://www.php.net/manual/en/function.http-build-query.php
  888. *
  889. * @param array|object $data An array or object of data. Converted to array.
  890. * @param string $prefix Optional. Numeric index. If set, start parameter numbering with it.
  891. * Default null.
  892. * @param string $sep Optional. Argument separator; defaults to 'arg_separator.output'.
  893. * Default null.
  894. * @param string $key Optional. Used to prefix key name. Default empty.
  895. * @param bool $urlencode Optional. Whether to use urlencode() in the result. Default true.
  896. *
  897. * @return string The query string.
  898. */
  899. function _http_build_query( $data, $prefix = null, $sep = null, $key = '', $urlencode = true ) {
  900. $ret = array();
  901. foreach ( (array) $data as $k => $v ) {
  902. if ( $urlencode ) {
  903. $k = urlencode( $k );
  904. }
  905. if ( is_int( $k ) && null != $prefix ) {
  906. $k = $prefix . $k;
  907. }
  908. if ( ! empty( $key ) ) {
  909. $k = $key . '%5B' . $k . '%5D';
  910. }
  911. if ( null === $v ) {
  912. continue;
  913. } elseif ( false === $v ) {
  914. $v = '0';
  915. }
  916. if ( is_array( $v ) || is_object( $v ) ) {
  917. array_push( $ret, _http_build_query( $v, '', $sep, $k, $urlencode ) );
  918. } elseif ( $urlencode ) {
  919. array_push( $ret, $k . '=' . urlencode( $v ) );
  920. } else {
  921. array_push( $ret, $k . '=' . $v );
  922. }
  923. }
  924. if ( null === $sep ) {
  925. $sep = ini_get( 'arg_separator.output' );
  926. }
  927. return implode( $sep, $ret );
  928. }
  929. /**
  930. * Retrieves a modified URL query string.
  931. *
  932. * You can rebuild the URL and append query variables to the URL query by using this function.
  933. * There are two ways to use this function; either a single key and value, or an associative array.
  934. *
  935. * Using a single key and value:
  936. *
  937. * add_query_arg( 'key', 'value', 'http://example.com' );
  938. *
  939. * Using an associative array:
  940. *
  941. * add_query_arg( array(
  942. * 'key1' => 'value1',
  943. * 'key2' => 'value2',
  944. * ), 'http://example.com' );
  945. *
  946. * Omitting the URL from either use results in the current URL being used
  947. * (the value of `$_SERVER['REQUEST_URI']`).
  948. *
  949. * Values are expected to be encoded appropriately with urlencode() or rawurlencode().
  950. *
  951. * Setting any query variable's value to boolean false removes the key (see remove_query_arg()).
  952. *
  953. * Important: The return value of add_query_arg() is not escaped by default. Output should be
  954. * late-escaped with esc_url() or similar to help prevent vulnerability to cross-site scripting
  955. * (XSS) attacks.
  956. *
  957. * @since 1.5.0
  958. * @since 5.3.0 Formalized the existing and already documented parameters
  959. * by adding `...$args` to the function signature.
  960. *
  961. * @param string|array $key Either a query variable key, or an associative array of query variables.
  962. * @param string $value Optional. Either a query variable value, or a URL to act upon.
  963. * @param string $url Optional. A URL to act upon.
  964. * @return string New URL query string (unescaped).
  965. */
  966. function add_query_arg( ...$args ) {
  967. if ( is_array( $args[0] ) ) {
  968. if ( count( $args ) < 2 || false === $args[1] ) {
  969. $uri = $_SERVER['REQUEST_URI'];
  970. } else {
  971. $uri = $args[1];
  972. }
  973. } else {
  974. if ( count( $args ) < 3 || false === $args[2] ) {
  975. $uri = $_SERVER['REQUEST_URI'];
  976. } else {
  977. $uri = $args[2];
  978. }
  979. }
  980. $frag = strstr( $uri, '#' );
  981. if ( $frag ) {
  982. $uri = substr( $uri, 0, -strlen( $frag ) );
  983. } else {
  984. $frag = '';
  985. }
  986. if ( 0 === stripos( $uri, 'http://' ) ) {
  987. $protocol = 'http://';
  988. $uri = substr( $uri, 7 );
  989. } elseif ( 0 === stripos( $uri, 'https://' ) ) {
  990. $protocol = 'https://';
  991. $uri = substr( $uri, 8 );
  992. } else {
  993. $protocol = '';
  994. }
  995. if ( strpos( $uri, '?' ) !== false ) {
  996. list( $base, $query ) = explode( '?', $uri, 2 );
  997. $base .= '?';
  998. } elseif ( $protocol || strpos( $uri, '=' ) === false ) {
  999. $base = $uri . '?';
  1000. $query = '';
  1001. } else {
  1002. $base = '';
  1003. $query = $uri;
  1004. }
  1005. wp_parse_str( $query, $qs );
  1006. $qs = urlencode_deep( $qs ); // This re-URL-encodes things that were already in the query string.
  1007. if ( is_array( $args[0] ) ) {
  1008. foreach ( $args[0] as $k => $v ) {
  1009. $qs[ $k ] = $v;
  1010. }
  1011. } else {
  1012. $qs[ $args[0] ] = $args[1];
  1013. }
  1014. foreach ( $qs as $k => $v ) {
  1015. if ( false === $v ) {
  1016. unset( $qs[ $k ] );
  1017. }
  1018. }
  1019. $ret = build_query( $qs );
  1020. $ret = trim( $ret, '?' );
  1021. $ret = preg_replace( '#=(&|$)#', '$1', $ret );
  1022. $ret = $protocol . $base . $ret . $frag;
  1023. $ret = rtrim( $ret, '?' );
  1024. return $ret;
  1025. }
  1026. /**
  1027. * Removes an item or items from a query string.
  1028. *
  1029. * @since 1.5.0
  1030. *
  1031. * @param string|array $key Query key or keys to remove.
  1032. * @param bool|string $query Optional. When false uses the current URL. Default false.
  1033. * @return string New URL query string.
  1034. */
  1035. function remove_query_arg( $key, $query = false ) {
  1036. if ( is_array( $key ) ) { // Removing multiple keys.
  1037. foreach ( $key as $k ) {
  1038. $query = add_query_arg( $k, false, $query );
  1039. }
  1040. return $query;
  1041. }
  1042. return add_query_arg( $key, false, $query );
  1043. }
  1044. /**
  1045. * Returns an array of single-use query variable names that can be removed from a URL.
  1046. *
  1047. * @since 4.4.0
  1048. *
  1049. * @return string[] An array of parameters to remove from the URL.
  1050. */
  1051. function wp_removable_query_args() {
  1052. $removable_query_args = array(
  1053. 'activate',
  1054. 'activated',
  1055. 'approved',
  1056. 'deactivate',
  1057. 'deleted',
  1058. 'disabled',
  1059. 'doing_wp_cron',
  1060. 'enabled',
  1061. 'error',
  1062. 'hotkeys_highlight_first',
  1063. 'hotkeys_highlight_last',
  1064. 'locked',
  1065. 'message',
  1066. 'same',
  1067. 'saved',
  1068. 'settings-updated',
  1069. 'skipped',
  1070. 'spammed',
  1071. 'trashed',
  1072. 'unspammed',
  1073. 'untrashed',
  1074. 'update',
  1075. 'updated',
  1076. 'wp-post-new-reload',
  1077. );
  1078. /**
  1079. * Filters the list of query variables to remove.
  1080. *
  1081. * @since 4.2.0
  1082. *
  1083. * @param string[] $removable_query_args An array of query variables to remove from a URL.
  1084. */
  1085. return apply_filters( 'removable_query_args', $removable_query_args );
  1086. }
  1087. /**
  1088. * Walks the array while sanitizing the contents.
  1089. *
  1090. * @since 0.71
  1091. *
  1092. * @param array $array Array to walk while sanitizing contents.
  1093. * @return array Sanitized $array.
  1094. */
  1095. function add_magic_quotes( $array ) {
  1096. foreach ( (array) $array as $k => $v ) {
  1097. if ( is_array( $v ) ) {
  1098. $array[ $k ] = add_magic_quotes( $v );
  1099. } else {
  1100. $array[ $k ] = addslashes( $v );
  1101. }
  1102. }
  1103. return $array;
  1104. }
  1105. /**
  1106. * HTTP request for URI to retrieve content.
  1107. *
  1108. * @since 1.5.1
  1109. *
  1110. * @see wp_safe_remote_get()
  1111. *
  1112. * @param string $uri URI/URL of web page to retrieve.
  1113. * @return string|false HTTP content. False on failure.
  1114. */
  1115. function wp_remote_fopen( $uri ) {
  1116. $parsed_url = parse_url( $uri );
  1117. if ( ! $parsed_url || ! is_array( $parsed_url ) ) {
  1118. return false;
  1119. }
  1120. $options = array();
  1121. $options['timeout'] = 10;
  1122. $response = wp_safe_remote_get( $uri, $options );
  1123. if ( is_wp_error( $response ) ) {
  1124. return false;
  1125. }
  1126. return wp_remote_retrieve_body( $response );
  1127. }
  1128. /**
  1129. * Set up the WordPress query.
  1130. *
  1131. * @since 2.0.0
  1132. *
  1133. * @global WP $wp Current WordPress environment instance.
  1134. * @global WP_Query $wp_query WordPress Query object.
  1135. * @global WP_Query $wp_the_query Copy of the WordPress Query object.
  1136. *
  1137. * @param string|array $query_vars Default WP_Query arguments.
  1138. */
  1139. function wp( $query_vars = '' ) {
  1140. global $wp, $wp_query, $wp_the_query;
  1141. $wp->main( $query_vars );
  1142. if ( ! isset( $wp_the_query ) ) {
  1143. $wp_the_query = $wp_query;
  1144. }
  1145. }
  1146. /**
  1147. * Retrieve the description for the HTTP status.
  1148. *
  1149. * @since 2.3.0
  1150. * @since 3.9.0 Added status codes 418, 428, 429, 431, and 511.
  1151. * @since 4.5.0 Added status codes 308, 421, and 451.
  1152. * @since 5.1.0 Added status code 103.
  1153. *
  1154. * @global array $wp_header_to_desc
  1155. *
  1156. * @param int $code HTTP status code.
  1157. * @return string Status description if found, an empty string otherwise.
  1158. */
  1159. function get_status_header_desc( $code ) {
  1160. global $wp_header_to_desc;
  1161. $code = absint( $code );
  1162. if ( ! isset( $wp_header_to_desc ) ) {
  1163. $wp_header_to_desc = array(
  1164. 100 => 'Continue',
  1165. 101 => 'Switching Protocols',
  1166. 102 => 'Processing',
  1167. 103 => 'Early Hints',
  1168. 200 => 'OK',
  1169. 201 => 'Created',
  1170. 202 => 'Accepted',
  1171. 203 => 'Non-Authoritative Information',
  1172. 204 => 'No Content',
  1173. 205 => 'Reset Content',
  1174. 206 => 'Partial Content',
  1175. 207 => 'Multi-Status',
  1176. 226 => 'IM Used',
  1177. 300 => 'Multiple Choices',
  1178. 301 => 'Moved Permanently',
  1179. 302 => 'Found',
  1180. 303 => 'See Other',
  1181. 304 => 'Not Modified',
  1182. 305 => 'Use Proxy',
  1183. 306 => 'Reserved',
  1184. 307 => 'Temporary Redirect',
  1185. 308 => 'Permanent Redirect',
  1186. 400 => 'Bad Request',
  1187. 401 => 'Unauthorized',
  1188. 402 => 'Payment Required',
  1189. 403 => 'Forbidden',
  1190. 404 => 'Not Found',
  1191. 405 => 'Method Not Allowed',
  1192. 406 => 'Not Acceptable',
  1193. 407 => 'Proxy Authentication Required',
  1194. 408 => 'Request Timeout',
  1195. 409 => 'Conflict',
  1196. 410 => 'Gone',
  1197. 411 => 'Length Required',
  1198. 412 => 'Precondition Failed',
  1199. 413 => 'Request Entity Too Large',
  1200. 414 => 'Request-URI Too Long',
  1201. 415 => 'Unsupported Media Type',
  1202. 416 => 'Requested Range Not Satisfiable',
  1203. 417 => 'Expectation Failed',
  1204. 418 => 'I\'m a teapot',
  1205. 421 => 'Misdirected Request',
  1206. 422 => 'Unprocessable Entity',
  1207. 423 => 'Locked',
  1208. 424 => 'Failed Dependency',
  1209. 426 => 'Upgrade Required',
  1210. 428 => 'Precondition Required',
  1211. 429 => 'Too Many Requests',
  1212. 431 => 'Request Header Fields Too Large',
  1213. 451 => 'Unavailable For Legal Reasons',
  1214. 500 => 'Internal Server Error',
  1215. 501 => 'Not Implemented',
  1216. 502 => 'Bad Gateway',
  1217. 503 => 'Service Unavailable',
  1218. 504 => 'Gateway Timeout',
  1219. 505 => 'HTTP Version Not Supported',
  1220. 506 => 'Variant Also Negotiates',
  1221. 507 => 'Insufficient Storage',
  1222. 510 => 'Not Extended',
  1223. 511 => 'Network Authentication Required',
  1224. );
  1225. }
  1226. if ( isset( $wp_header_to_desc[ $code ] ) ) {
  1227. return $wp_header_to_desc[ $code ];
  1228. } else {
  1229. return '';
  1230. }
  1231. }
  1232. /**
  1233. * Set HTTP status header.
  1234. *
  1235. * @since 2.0.0
  1236. * @since 4.4.0 Added the `$description` parameter.
  1237. *
  1238. * @see get_status_header_desc()
  1239. *
  1240. * @param int $code HTTP status code.
  1241. * @param string $description Optional. A custom description for the HTTP status.
  1242. */
  1243. function status_header( $code, $description = '' ) {
  1244. if ( ! $description ) {
  1245. $description = get_status_header_desc( $code );
  1246. }
  1247. if ( empty( $description ) ) {
  1248. return;
  1249. }
  1250. $protocol = wp_get_server_protocol();
  1251. $status_header = "$protocol $code $description";
  1252. if ( function_exists( 'apply_filters' ) ) {
  1253. /**
  1254. * Filters an HTTP status header.
  1255. *
  1256. * @since 2.2.0
  1257. *
  1258. * @param string $status_header HTTP status header.
  1259. * @param int $code HTTP status code.
  1260. * @param string $description Description for the status code.
  1261. * @param string $protocol Server protocol.
  1262. */
  1263. $status_header = apply_filters( 'status_header', $status_header, $code, $description, $protocol );
  1264. }
  1265. if ( ! headers_sent() ) {
  1266. header( $status_header, true, $code );
  1267. }
  1268. }
  1269. /**
  1270. * Get the header information to prevent caching.
  1271. *
  1272. * The several different headers cover the different ways cache prevention
  1273. * is handled by different browsers
  1274. *
  1275. * @since 2.8.0
  1276. *
  1277. * @return array The associative array of header names and field values.
  1278. */
  1279. function wp_get_nocache_headers() {
  1280. $headers = array(
  1281. 'Expires' => 'Wed, 11 Jan 1984 05:00:00 GMT',
  1282. 'Cache-Control' => 'no-cache, must-revalidate, max-age=0',
  1283. );
  1284. if ( function_exists( 'apply_filters' ) ) {
  1285. /**
  1286. * Filters the cache-controlling headers.
  1287. *
  1288. * @since 2.8.0
  1289. *
  1290. * @see wp_get_nocache_headers()
  1291. *
  1292. * @param array $headers {
  1293. * Header names and field values.
  1294. *
  1295. * @type string $Expires Expires header.
  1296. * @type string $Cache-Control Cache-Control header.
  1297. * }
  1298. */
  1299. $headers = (array) apply_filters( 'nocache_headers', $headers );
  1300. }
  1301. $headers['Last-Modified'] = false;
  1302. return $headers;
  1303. }
  1304. /**
  1305. * Set the headers to prevent caching for the different browsers.
  1306. *
  1307. * Different browsers support different nocache headers, so several
  1308. * headers must be sent so that all of them get the point that no
  1309. * caching should occur.
  1310. *
  1311. * @since 2.0.0
  1312. *
  1313. * @see wp_get_nocache_headers()
  1314. */
  1315. function nocache_headers() {
  1316. if ( headers_sent() ) {
  1317. return;
  1318. }
  1319. $headers = wp_get_nocache_headers();
  1320. unset( $headers['Last-Modified'] );
  1321. header_remove( 'Last-Modified' );
  1322. foreach ( $headers as $name => $field_value ) {
  1323. header( "{$name}: {$field_value}" );
  1324. }
  1325. }
  1326. /**
  1327. * Set the headers for caching for 10 days with JavaScript content type.
  1328. *
  1329. * @since 2.1.0
  1330. */
  1331. function cache_javascript_headers() {
  1332. $expiresOffset = 10 * DAY_IN_SECONDS;
  1333. header( 'Content-Type: text/javascript; charset=' . get_bloginfo( 'charset' ) );
  1334. header( 'Vary: Accept-Encoding' ); // Handle proxies.
  1335. header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', time() + $expiresOffset ) . ' GMT' );
  1336. }
  1337. /**
  1338. * Retrieve the number of database queries during the WordPress execution.
  1339. *
  1340. * @since 2.0.0
  1341. *
  1342. * @global wpdb $wpdb WordPress database abstraction object.
  1343. *
  1344. * @return int Number of database queries.
  1345. */
  1346. function get_num_queries() {
  1347. global $wpdb;
  1348. return $wpdb->num_queries;
  1349. }
  1350. /**
  1351. * Whether input is yes or no.
  1352. *
  1353. * Must be 'y' to be true.
  1354. *
  1355. * @since 1.0.0
  1356. *
  1357. * @param string $yn Character string containing either 'y' (yes) or 'n' (no).
  1358. * @return bool True if yes, false on anything else.
  1359. */
  1360. function bool_from_yn( $yn ) {
  1361. return ( strtolower( $yn ) == 'y' );
  1362. }
  1363. /**
  1364. * Load the feed template from the use of an action hook.
  1365. *
  1366. * If the feed action does not have a hook, then the function will die with a
  1367. * message telling the visitor that the feed is not valid.
  1368. *
  1369. * It is better to only have one hook for each feed.
  1370. *
  1371. * @since 2.1.0
  1372. *
  1373. * @global WP_Query $wp_query WordPress Query object.
  1374. */
  1375. function do_feed() {
  1376. global $wp_query;
  1377. $feed = get_query_var( 'feed' );
  1378. // Remove the pad, if present.
  1379. $feed = preg_replace( '/^_+/', '', $feed );
  1380. if ( '' == $feed || 'feed' === $feed ) {
  1381. $feed = get_default_feed();
  1382. }
  1383. if ( ! has_action( "do_feed_{$feed}" ) ) {
  1384. wp_die( __( 'Error: This is not a valid feed template.' ), '', array( 'response' => 404 ) );
  1385. }
  1386. /**
  1387. * Fires once the given feed is loaded.
  1388. *
  1389. * The dynamic portion of the hook name, `$feed`, refers to the feed template name.
  1390. * Possible values include: 'rdf', 'rss', 'rss2', and 'atom'.
  1391. *
  1392. * @since 2.1.0
  1393. * @since 4.4.0 The `$feed` parameter was added.
  1394. *
  1395. * @param bool $is_comment_feed Whether the feed is a comment feed.
  1396. * @param string $feed The feed name.
  1397. */
  1398. do_action( "do_feed_{$feed}", $wp_query->is_comment_feed, $feed );
  1399. }
  1400. /**
  1401. * Load the RDF RSS 0.91 Feed template.
  1402. *
  1403. * @since 2.1.0
  1404. *
  1405. * @see load_template()
  1406. */
  1407. function do_feed_rdf() {
  1408. load_template( ABSPATH . WPINC . '/feed-rdf.php' );
  1409. }
  1410. /**
  1411. * Load the RSS 1.0 Feed Template.
  1412. *
  1413. * @since 2.1.0
  1414. *
  1415. * @see load_template()
  1416. */
  1417. function do_feed_rss() {
  1418. load_template( ABSPATH . WPINC . '/feed-rss.php' );
  1419. }
  1420. /**
  1421. * Load either the RSS2 comment feed or the RSS2 posts feed.
  1422. *
  1423. * @since 2.1.0
  1424. *
  1425. * @see load_template()
  1426. *
  1427. * @param bool $for_comments True for the comment feed, false for normal feed.
  1428. */
  1429. function do_feed_rss2( $for_comments ) {
  1430. if ( $for_comments ) {
  1431. load_template( ABSPATH . WPINC . '/feed-rss2-comments.php' );
  1432. } else {
  1433. load_template( ABSPATH . WPINC . '/feed-rss2.php' );
  1434. }
  1435. }
  1436. /**
  1437. * Load either Atom comment feed or Atom posts feed.
  1438. *
  1439. * @since 2.1.0
  1440. *
  1441. * @see load_template()
  1442. *
  1443. * @param bool $for_comments True for the comment feed, false for normal feed.
  1444. */
  1445. function do_feed_atom( $for_comments ) {
  1446. if ( $for_comments ) {
  1447. load_template( ABSPATH . WPINC . '/feed-atom-comments.php' );
  1448. } else {
  1449. load_template( ABSPATH . WPINC . '/feed-atom.php' );
  1450. }
  1451. }
  1452. /**
  1453. * Displays the default robots.txt file content.
  1454. *
  1455. * @since 2.1.0
  1456. * @since 5.3.0 Remove the "Disallow: /" output if search engine visiblity is
  1457. * discouraged in favor of robots meta HTML tag in wp_no_robots().
  1458. */
  1459. function do_robots() {
  1460. header( 'Content-Type: text/plain; charset=utf-8' );
  1461. /**
  1462. * Fires when displaying the robots.txt file.
  1463. *
  1464. * @since 2.1.0
  1465. */
  1466. do_action( 'do_robotstxt' );
  1467. $output = "User-agent: *\n";
  1468. $public = get_option( 'blog_public' );
  1469. $site_url = parse_url( site_url() );
  1470. $path = ( ! empty( $site_url['path'] ) ) ? $site_url['path'] : '';
  1471. $output .= "Disallow: $path/wp-admin/\n";
  1472. $output .= "Allow: $path/wp-admin/admin-ajax.php\n";
  1473. /**
  1474. * Filters the robots.txt output.
  1475. *
  1476. * @since 3.0.0
  1477. *
  1478. * @param string $output The robots.txt output.
  1479. * @param bool $public Whether the site is considered "public".
  1480. */
  1481. echo apply_filters( 'robots_txt', $output, $public );
  1482. }
  1483. /**
  1484. * Display the favicon.ico file content.
  1485. *
  1486. * @since 5.4.0
  1487. */
  1488. function do_favicon() {
  1489. /**
  1490. * Fires when serving the favicon.ico file.
  1491. *
  1492. * @since 5.4.0
  1493. */
  1494. do_action( 'do_faviconico' );
  1495. wp_redirect( get_site_icon_url( 32, admin_url( 'images/w-logo-blue.png' ) ) );
  1496. exit;
  1497. }
  1498. /**
  1499. * Determines whether WordPress is already installed.
  1500. *
  1501. * The cache will be checked first. If you have a cache plugin, which saves
  1502. * the cache values, then this will work. If you use the default WordPress
  1503. * cache, and the database goes away, then you might have problems.
  1504. *
  1505. * Checks for the 'siteurl' option for whether WordPress is installed.
  1506. *
  1507. * For more information on this and similar theme functions, check out
  1508. * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
  1509. * Conditional Tags} article in the Theme Developer Handbook.
  1510. *
  1511. * @since 2.1.0
  1512. *
  1513. * @global wpdb $wpdb WordPress database abstraction object.
  1514. *
  1515. * @return bool Whether the site is already installed.
  1516. */
  1517. function is_blog_installed() {
  1518. global $wpdb;
  1519. /*
  1520. * Check cache first. If options table goes away and we have true
  1521. * cached, oh well.
  1522. */
  1523. if ( wp_cache_get( 'is_blog_installed' ) ) {
  1524. return true;
  1525. }
  1526. $suppress = $wpdb->suppress_errors();
  1527. if ( ! wp_installing() ) {
  1528. $alloptions = wp_load_alloptions();
  1529. }
  1530. // If siteurl is not set to autoload, check it specifically.
  1531. if ( ! isset( $alloptions['siteurl'] ) ) {
  1532. $installed = $wpdb->get_var( "SELECT option_value FROM $wpdb->options WHERE option_name = 'siteurl'" );
  1533. } else {
  1534. $installed = $alloptions['siteurl'];
  1535. }
  1536. $wpdb->suppress_errors( $suppress );
  1537. $installed = ! empty( $installed );
  1538. wp_cache_set( 'is_blog_installed', $installed );
  1539. if ( $installed ) {
  1540. return true;
  1541. }
  1542. // If visiting repair.php, return true and let it take over.
  1543. if ( defined( 'WP_REPAIRING' ) ) {
  1544. return true;
  1545. }
  1546. $suppress = $wpdb->suppress_errors();
  1547. /*
  1548. * Loop over the WP tables. If none exist, then scratch installation is allowed.
  1549. * If one or more exist, suggest table repair since we got here because the
  1550. * options table could not be accessed.
  1551. */
  1552. $wp_tables = $wpdb->tables();
  1553. foreach ( $wp_tables as $table ) {
  1554. // The existence of custom user tables shouldn't suggest an insane state or prevent a clean installation.
  1555. if ( defined( 'CUSTOM_USER_TABLE' ) && CUSTOM_USER_TABLE == $table ) {
  1556. continue;
  1557. }
  1558. if ( defined( 'CUSTOM_USER_META_TABLE' ) && CUSTOM_USER_META_TABLE == $table ) {
  1559. continue;
  1560. }
  1561. if ( ! $wpdb->get_results( "DESCRIBE $table;" ) ) {
  1562. continue;
  1563. }
  1564. // One or more tables exist. We are insane.
  1565. wp_load_translations_early();
  1566. // Die with a DB error.
  1567. $wpdb->error = sprintf(
  1568. /* translators: %s: Database repair URL. */
  1569. __( 'One or more database tables are unavailable. The database may need to be <a href="%s">repaired</a>.' ),
  1570. 'maint/repair.php?referrer=is_blog_installed'
  1571. );
  1572. dead_db();
  1573. }
  1574. $wpdb->suppress_errors( $suppress );
  1575. wp_cache_set( 'is_blog_installed', false );
  1576. return false;
  1577. }
  1578. /**
  1579. * Retrieve URL with nonce added to URL query.
  1580. *
  1581. * @since 2.0.4
  1582. *
  1583. * @param string $actionurl URL to add nonce action.
  1584. * @param int|string $action Optional. Nonce action name. Default -1.
  1585. * @param string $name Optional. Nonce name. Default '_wpnonce'.
  1586. * @return string Escaped URL with nonce action added.
  1587. */
  1588. function wp_nonce_url( $actionurl, $action = -1, $name = '_wpnonce' ) {
  1589. $a

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