PageRenderTime 47ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/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
  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. $actionurl = str_replace( '&amp;', '&', $actionurl );
  1590. return esc_html( add_query_arg( $name, wp_create_nonce( $action ), $actionurl ) );
  1591. }
  1592. /**
  1593. * Retrieve or display nonce hidden field for forms.
  1594. *
  1595. * The nonce field is used to validate that the contents of the form came from
  1596. * the location on the current site and not somewhere else. The nonce does not
  1597. * offer absolute protection, but should protect against most cases. It is very
  1598. * important to use nonce field in forms.
  1599. *
  1600. * The $action and $name are optional, but if you want to have better security,
  1601. * it is strongly suggested to set those two parameters. It is easier to just
  1602. * call the function without any parameters, because validation of the nonce
  1603. * doesn't require any parameters, but since crackers know what the default is
  1604. * it won't be difficult for them to find a way around your nonce and cause
  1605. * damage.
  1606. *
  1607. * The input name will be whatever $name value you gave. The input value will be
  1608. * the nonce creation value.
  1609. *
  1610. * @since 2.0.4
  1611. *
  1612. * @param int|string $action Optional. Action name. Default -1.
  1613. * @param string $name Optional. Nonce name. Default '_wpnonce'.
  1614. * @param bool $referer Optional. Whether to set the referer field for validation. Default true.
  1615. * @param bool $echo Optional. Whether to display or return hidden form field. Default true.
  1616. * @return string Nonce field HTML markup.
  1617. */
  1618. function wp_nonce_field( $action = -1, $name = '_wpnonce', $referer = true, $echo = true ) {
  1619. $name = esc_attr( $name );
  1620. $nonce_field = '<input type="hidden" id="' . $name . '" name="' . $name . '" value="' . wp_create_nonce( $action ) . '" />';
  1621. if ( $referer ) {
  1622. $nonce_field .= wp_referer_field( false );
  1623. }
  1624. if ( $echo ) {
  1625. echo $nonce_field;
  1626. }
  1627. return $nonce_field;
  1628. }
  1629. /**
  1630. * Retrieve or display referer hidden field for forms.
  1631. *
  1632. * The referer link is the current Request URI from the server super global. The
  1633. * input name is '_wp_http_referer', in case you wanted to check manually.
  1634. *
  1635. * @since 2.0.4
  1636. *
  1637. * @param bool $echo Optional. Whether to echo or return the referer field. Default true.
  1638. * @return string Referer field HTML markup.
  1639. */
  1640. function wp_referer_field( $echo = true ) {
  1641. $referer_field = '<input type="hidden" name="_wp_http_referer" value="' . esc_attr( wp_unslash( $_SERVER['REQUEST_URI'] ) ) . '" />';
  1642. if ( $echo ) {
  1643. echo $referer_field;
  1644. }
  1645. return $referer_field;
  1646. }
  1647. /**
  1648. * Retrieve or display original referer hidden field for forms.
  1649. *
  1650. * The input name is '_wp_original_http_referer' and will be either the same
  1651. * value of wp_referer_field(), if that was posted already or it will be the
  1652. * current page, if it doesn't exist.
  1653. *
  1654. * @since 2.0.4
  1655. *
  1656. * @param bool $echo Optional. Whether to echo the original http referer. Default true.
  1657. * @param string $jump_back_to Optional. Can be 'previous' or page you want to jump back to.
  1658. * Default 'current'.
  1659. * @return string Original referer field.
  1660. */
  1661. function wp_original_referer_field( $echo = true, $jump_back_to = 'current' ) {
  1662. $ref = wp_get_original_referer();
  1663. if ( ! $ref ) {
  1664. $ref = 'previous' == $jump_back_to ? wp_get_referer() : wp_unslash( $_SERVER['REQUEST_URI'] );
  1665. }
  1666. $orig_referer_field = '<input type="hidden" name="_wp_original_http_referer" value="' . esc_attr( $ref ) . '" />';
  1667. if ( $echo ) {
  1668. echo $orig_referer_field;
  1669. }
  1670. return $orig_referer_field;
  1671. }
  1672. /**
  1673. * Retrieve referer from '_wp_http_referer' or HTTP referer.
  1674. *
  1675. * If it's the same as the current request URL, will return false.
  1676. *
  1677. * @since 2.0.4
  1678. *
  1679. * @return string|false Referer URL on success, false on failure.
  1680. */
  1681. function wp_get_referer() {
  1682. if ( ! function_exists( 'wp_validate_redirect' ) ) {
  1683. return false;
  1684. }
  1685. $ref = wp_get_raw_referer();
  1686. if ( $ref && wp_unslash( $_SERVER['REQUEST_URI'] ) !== $ref && home_url() . wp_unslash( $_SERVER['REQUEST_URI'] ) !== $ref ) {
  1687. return wp_validate_redirect( $ref, false );
  1688. }
  1689. return false;
  1690. }
  1691. /**
  1692. * Retrieves unvalidated referer from '_wp_http_referer' or HTTP referer.
  1693. *
  1694. * Do not use for redirects, use wp_get_referer() instead.
  1695. *
  1696. * @since 4.5.0
  1697. *
  1698. * @return string|false Referer URL on success, false on failure.
  1699. */
  1700. function wp_get_raw_referer() {
  1701. if ( ! empty( $_REQUEST['_wp_http_referer'] ) ) {
  1702. return wp_unslash( $_REQUEST['_wp_http_referer'] );
  1703. } elseif ( ! empty( $_SERVER['HTTP_REFERER'] ) ) {
  1704. return wp_unslash( $_SERVER['HTTP_REFERER'] );
  1705. }
  1706. return false;
  1707. }
  1708. /**
  1709. * Retrieve original referer that was posted, if it exists.
  1710. *
  1711. * @since 2.0.4
  1712. *
  1713. * @return string|false False if no original referer or original referer if set.
  1714. */
  1715. function wp_get_original_referer() {
  1716. if ( ! empty( $_REQUEST['_wp_original_http_referer'] ) && function_exists( 'wp_validate_redirect' ) ) {
  1717. return wp_validate_redirect( wp_unslash( $_REQUEST['_wp_original_http_referer'] ), false );
  1718. }
  1719. return false;
  1720. }
  1721. /**
  1722. * Recursive directory creation based on full path.
  1723. *
  1724. * Will attempt to set permissions on folders.
  1725. *
  1726. * @since 2.0.1
  1727. *
  1728. * @param string $target Full path to attempt to create.
  1729. * @return bool Whether the path was created. True if path already exists.
  1730. */
  1731. function wp_mkdir_p( $target ) {
  1732. $wrapper = null;
  1733. // Strip the protocol.
  1734. if ( wp_is_stream( $target ) ) {
  1735. list( $wrapper, $target ) = explode( '://', $target, 2 );
  1736. }
  1737. // From php.net/mkdir user contributed notes.
  1738. $target = str_replace( '//', '/', $target );
  1739. // Put the wrapper back on the target.
  1740. if ( null !== $wrapper ) {
  1741. $target = $wrapper . '://' . $target;
  1742. }
  1743. /*
  1744. * Safe mode fails with a trailing slash under certain PHP versions.
  1745. * Use rtrim() instead of untrailingslashit to avoid formatting.php dependency.
  1746. */
  1747. $target = rtrim( $target, '/' );
  1748. if ( empty( $target ) ) {
  1749. $target = '/';
  1750. }
  1751. if ( file_exists( $target ) ) {
  1752. return @is_dir( $target );
  1753. }
  1754. // Do not allow path traversals.
  1755. if ( false !== strpos( $target, '../' ) || false !== strpos( $target, '..' . DIRECTORY_SEPARATOR ) ) {
  1756. return false;
  1757. }
  1758. // We need to find the permissions of the parent folder that exists and inherit that.
  1759. $target_parent = dirname( $target );
  1760. while ( '.' != $target_parent && ! is_dir( $target_parent ) && dirname( $target_parent ) !== $target_parent ) {
  1761. $target_parent = dirname( $target_parent );
  1762. }
  1763. // Get the permission bits.
  1764. $stat = @stat( $target_parent );
  1765. if ( $stat ) {
  1766. $dir_perms = $stat['mode'] & 0007777;
  1767. } else {
  1768. $dir_perms = 0777;
  1769. }
  1770. if ( @mkdir( $target, $dir_perms, true ) ) {
  1771. /*
  1772. * If a umask is set that modifies $dir_perms, we'll have to re-set
  1773. * the $dir_perms correctly with chmod()
  1774. */
  1775. if ( ( $dir_perms & ~umask() ) != $dir_perms ) {
  1776. $folder_parts = explode( '/', substr( $target, strlen( $target_parent ) + 1 ) );
  1777. for ( $i = 1, $c = count( $folder_parts ); $i <= $c; $i++ ) {
  1778. chmod( $target_parent . '/' . implode( '/', array_slice( $folder_parts, 0, $i ) ), $dir_perms );
  1779. }
  1780. }
  1781. return true;
  1782. }
  1783. return false;
  1784. }
  1785. /**
  1786. * Test if a given filesystem path is absolute.
  1787. *
  1788. * For example, '/foo/bar', or 'c:\windows'.
  1789. *
  1790. * @since 2.5.0
  1791. *
  1792. * @param string $path File path.
  1793. * @return bool True if path is absolute, false is not absolute.
  1794. */
  1795. function path_is_absolute( $path ) {
  1796. /*
  1797. * Check to see if the path is a stream and check to see if its an actual
  1798. * path or file as realpath() does not support stream wrappers.
  1799. */
  1800. if ( wp_is_stream( $path ) && ( is_dir( $path ) || is_file( $path ) ) ) {
  1801. return true;
  1802. }
  1803. /*
  1804. * This is definitive if true but fails if $path does not exist or contains
  1805. * a symbolic link.
  1806. */
  1807. if ( realpath( $path ) == $path ) {
  1808. return true;
  1809. }
  1810. if ( strlen( $path ) == 0 || '.' === $path[0] ) {
  1811. return false;
  1812. }
  1813. // Windows allows absolute paths like this.
  1814. if ( preg_match( '#^[a-zA-Z]:\\\\#', $path ) ) {
  1815. return true;
  1816. }
  1817. // A path starting with / or \ is absolute; anything else is relative.
  1818. return ( '/' === $path[0] || '\\' === $path[0] );
  1819. }
  1820. /**
  1821. * Join two filesystem paths together.
  1822. *
  1823. * For example, 'give me $path relative to $base'. If the $path is absolute,
  1824. * then it the full path is returned.
  1825. *
  1826. * @since 2.5.0
  1827. *
  1828. * @param string $base Base path.
  1829. * @param string $path Path relative to $base.
  1830. * @return string The path with the base or absolute path.
  1831. */
  1832. function path_join( $base, $path ) {
  1833. if ( path_is_absolute( $path ) ) {
  1834. return $path;
  1835. }
  1836. return rtrim( $base, '/' ) . '/' . ltrim( $path, '/' );
  1837. }
  1838. /**
  1839. * Normalize a filesystem path.
  1840. *
  1841. * On windows systems, replaces backslashes with forward slashes
  1842. * and forces upper-case drive letters.
  1843. * Allows for two leading slashes for Windows network shares, but
  1844. * ensures that all other duplicate slashes are reduced to a single.
  1845. *
  1846. * @since 3.9.0
  1847. * @since 4.4.0 Ensures upper-case drive letters on Windows systems.
  1848. * @since 4.5.0 Allows for Windows network shares.
  1849. * @since 4.9.7 Allows for PHP file wrappers.
  1850. *
  1851. * @param string $path Path to normalize.
  1852. * @return string Normalized path.
  1853. */
  1854. function wp_normalize_path( $path ) {
  1855. $wrapper = '';
  1856. if ( wp_is_stream( $path ) ) {
  1857. list( $wrapper, $path ) = explode( '://', $path, 2 );
  1858. $wrapper .= '://';
  1859. }
  1860. // Standardise all paths to use '/'.
  1861. $path = str_replace( '\\', '/', $path );
  1862. // Replace multiple slashes down to a singular, allowing for network shares having two slashes.
  1863. $path = preg_replace( '|(?<=.)/+|', '/', $path );
  1864. // Windows paths should uppercase the drive letter.
  1865. if ( ':' === substr( $path, 1, 1 ) ) {
  1866. $path = ucfirst( $path );
  1867. }
  1868. return $wrapper . $path;
  1869. }
  1870. /**
  1871. * Determine a writable directory for temporary files.
  1872. *
  1873. * Function's preference is the return value of sys_get_temp_dir(),
  1874. * followed by your PHP temporary upload directory, followed by WP_CONTENT_DIR,
  1875. * before finally defaulting to /tmp/
  1876. *
  1877. * In the event that this function does not find a writable location,
  1878. * It may be overridden by the WP_TEMP_DIR constant in your wp-config.php file.
  1879. *
  1880. * @since 2.5.0
  1881. *
  1882. * @staticvar string $temp
  1883. *
  1884. * @return string Writable temporary directory.
  1885. */
  1886. function get_temp_dir() {
  1887. static $temp = '';
  1888. if ( defined( 'WP_TEMP_DIR' ) ) {
  1889. return trailingslashit( WP_TEMP_DIR );
  1890. }
  1891. if ( $temp ) {
  1892. return trailingslashit( $temp );
  1893. }
  1894. if ( function_exists( 'sys_get_temp_dir' ) ) {
  1895. $temp = sys_get_temp_dir();
  1896. if ( @is_dir( $temp ) && wp_is_writable( $temp ) ) {
  1897. return trailingslashit( $temp );
  1898. }
  1899. }
  1900. $temp = ini_get( 'upload_tmp_dir' );
  1901. if ( @is_dir( $temp ) && wp_is_writable( $temp ) ) {
  1902. return trailingslashit( $temp );
  1903. }
  1904. $temp = WP_CONTENT_DIR . '/';
  1905. if ( is_dir( $temp ) && wp_is_writable( $temp ) ) {
  1906. return $temp;
  1907. }
  1908. return '/tmp/';
  1909. }
  1910. /**
  1911. * Determine if a directory is writable.
  1912. *
  1913. * This function is used to work around certain ACL issues in PHP primarily
  1914. * affecting Windows Servers.
  1915. *
  1916. * @since 3.6.0
  1917. *
  1918. * @see win_is_writable()
  1919. *
  1920. * @param string $path Path to check for write-ability.
  1921. * @return bool Whether the path is writable.
  1922. */
  1923. function wp_is_writable( $path ) {
  1924. if ( 'WIN' === strtoupper( substr( PHP_OS, 0, 3 ) ) ) {
  1925. return win_is_writable( $path );
  1926. } else {
  1927. return @is_writable( $path );
  1928. }
  1929. }
  1930. /**
  1931. * Workaround for Windows bug in is_writable() function
  1932. *
  1933. * PHP has issues with Windows ACL's for determine if a
  1934. * directory is writable or not, this works around them by
  1935. * checking the ability to open files rather than relying
  1936. * upon PHP to interprate the OS ACL.
  1937. *
  1938. * @since 2.8.0
  1939. *
  1940. * @see https://bugs.php.net/bug.php?id=27609
  1941. * @see https://bugs.php.net/bug.php?id=30931
  1942. *
  1943. * @param string $path Windows path to check for write-ability.
  1944. * @return bool Whether the path is writable.
  1945. */
  1946. function win_is_writable( $path ) {
  1947. if ( '/' === $path[ strlen( $path ) - 1 ] ) {
  1948. // If it looks like a directory, check a random file within the directory.
  1949. return win_is_writable( $path . uniqid( mt_rand() ) . '.tmp' );
  1950. } elseif ( is_dir( $path ) ) {
  1951. // If it's a directory (and not a file), check a random file within the directory.
  1952. return win_is_writable( $path . '/' . uniqid( mt_rand() ) . '.tmp' );
  1953. }
  1954. // Check tmp file for read/write capabilities.
  1955. $should_delete_tmp_file = ! file_exists( $path );
  1956. $f = @fopen( $path, 'a' );
  1957. if ( false === $f ) {
  1958. return false;
  1959. }
  1960. fclose( $f );
  1961. if ( $should_delete_tmp_file ) {
  1962. unlink( $path );
  1963. }
  1964. return true;
  1965. }
  1966. /**
  1967. * Retrieves uploads directory information.
  1968. *
  1969. * Same as wp_upload_dir() but "light weight" as it doesn't attempt to create the uploads directory.
  1970. * Intended for use in themes, when only 'basedir' and 'baseurl' are needed, generally in all cases
  1971. * when not uploading files.
  1972. *
  1973. * @since 4.5.0
  1974. *
  1975. * @see wp_upload_dir()
  1976. *
  1977. * @return array See wp_upload_dir() for description.
  1978. */
  1979. function wp_get_upload_dir() {
  1980. return wp_upload_dir( null, false );
  1981. }
  1982. /**
  1983. * Returns an array containing the current upload directory's path and URL.
  1984. *
  1985. * Checks the 'upload_path' option, which should be from the web root folder,
  1986. * and if it isn't empty it will be used. If it is empty, then the path will be
  1987. * 'WP_CONTENT_DIR/uploads'. If the 'UPLOADS' constant is defined, then it will
  1988. * override the 'upload_path' option and 'WP_CONTENT_DIR/uploads' path.
  1989. *
  1990. * The upload URL path is set either by the 'upload_url_path' option or by using
  1991. * the 'WP_CONTENT_URL' constant and appending '/uploads' to the path.
  1992. *
  1993. * If the 'uploads_use_yearmonth_folders' is set to true (checkbox if checked in
  1994. * the administration settings panel), then the time will be used. The format
  1995. * will be year first and then month.
  1996. *
  1997. * If the path couldn't be created, then an error will be returned with the key
  1998. * 'error' containing the error message. The error suggests that the parent
  1999. * directory is not writable by the server.
  2000. *
  2001. * @since 2.0.0
  2002. * @uses _wp_upload_dir()
  2003. *
  2004. * @staticvar array $cache
  2005. * @staticvar array $tested_paths
  2006. *
  2007. * @param string $time Optional. Time formatted in 'yyyy/mm'. Default null.
  2008. * @param bool $create_dir Optional. Whether to check and create the uploads directory.
  2009. * Default true for backward compatibility.
  2010. * @param bool $refresh_cache Optional. Whether to refresh the cache. Default false.
  2011. * @return array {
  2012. * Array of information about the upload directory.
  2013. *
  2014. * @type string $path Base directory and subdirectory or full path to upload directory.
  2015. * @type string $url Base URL and subdirectory or absolute URL to upload directory.
  2016. * @type string $subdir Subdirectory if uploads use year/month folders option is on.
  2017. * @type string $basedir Path without subdir.
  2018. * @type string $baseurl URL path without subdir.
  2019. * @type string|false $error False or error message.
  2020. * }
  2021. */
  2022. function wp_upload_dir( $time = null, $create_dir = true, $refresh_cache = false ) {
  2023. static $cache = array(), $tested_paths = array();
  2024. $key = sprintf( '%d-%s', get_current_blog_id(), (string) $time );
  2025. if ( $refresh_cache || empty( $cache[ $key ] ) ) {
  2026. $cache[ $key ] = _wp_upload_dir( $time );
  2027. }
  2028. /**
  2029. * Filters the uploads directory data.
  2030. *
  2031. * @since 2.0.0
  2032. *
  2033. * @param array $uploads {
  2034. * Array of information about the upload directory.
  2035. *
  2036. * @type string $path Base directory and subdirectory or full path to upload directory.
  2037. * @type string $url Base URL and subdirectory or absolute URL to upload directory.
  2038. * @type string $subdir Subdirectory if uploads use year/month folders option is on.
  2039. * @type string $basedir Path without subdir.
  2040. * @type string $baseurl URL path without subdir.
  2041. * @type string|false $error False or error message.
  2042. * }
  2043. */
  2044. $uploads = apply_filters( 'upload_dir', $cache[ $key ] );
  2045. if ( $create_dir ) {
  2046. $path = $uploads['path'];
  2047. if ( array_key_exists( $path, $tested_paths ) ) {
  2048. $uploads['error'] = $tested_paths[ $path ];
  2049. } else {
  2050. if ( ! wp_mkdir_p( $path ) ) {
  2051. if ( 0 === strpos( $uploads['basedir'], ABSPATH ) ) {
  2052. $error_path = str_replace( ABSPATH, '', $uploads['basedir'] ) . $uploads['subdir'];
  2053. } else {
  2054. $error_path = wp_basename( $uploads['basedir'] ) . $uploads['subdir'];
  2055. }
  2056. $uploads['error'] = sprintf(
  2057. /* translators: %s: Directory path. */
  2058. __( 'Unable to create directory %s. Is its parent directory writable by the server?' ),
  2059. esc_html( $error_path )
  2060. );
  2061. }
  2062. $tested_paths[ $path ] = $uploads['error'];
  2063. }
  2064. }
  2065. return $uploads;
  2066. }
  2067. /**
  2068. * A non-filtered, non-cached version of wp_upload_dir() that doesn't check the path.
  2069. *
  2070. * @since 4.5.0
  2071. * @access private
  2072. *
  2073. * @param string $time Optional. Time formatted in 'yyyy/mm'. Default null.
  2074. * @return array See wp_upload_dir()
  2075. */
  2076. function _wp_upload_dir( $time = null ) {
  2077. $siteurl = get_option( 'siteurl' );
  2078. $upload_path = trim( get_option( 'upload_path' ) );
  2079. if ( empty( $upload_path ) || 'wp-content/uploads' == $upload_path ) {
  2080. $dir = WP_CONTENT_DIR . '/uploads';
  2081. } elseif ( 0 !== strpos( $upload_path, ABSPATH ) ) {
  2082. // $dir is absolute, $upload_path is (maybe) relative to ABSPATH.
  2083. $dir = path_join( ABSPATH, $upload_path );
  2084. } else {
  2085. $dir = $upload_path;
  2086. }
  2087. $url = get_option( 'upload_url_path' );
  2088. if ( ! $url ) {
  2089. if ( empty( $upload_path ) || ( 'wp-content/uploads' == $upload_path ) || ( $upload_path == $dir ) ) {
  2090. $url = WP_CONTENT_URL . '/uploads';
  2091. } else {
  2092. $url = trailingslashit( $siteurl ) . $upload_path;
  2093. }
  2094. }
  2095. /*
  2096. * Honor the value of UPLOADS. This happens as long as ms-files rewriting is disabled.
  2097. * We also sometimes obey UPLOADS when rewriting is enabled -- see the next block.
  2098. */
  2099. if ( defined( 'UPLOADS' ) && ! ( is_multisite() && get_site_option( 'ms_files_rewriting' ) ) ) {
  2100. $dir = ABSPATH . UPLOADS;
  2101. $url = trailingslashit( $siteurl ) . UPLOADS;
  2102. }
  2103. // If multisite (and if not the main site in a post-MU network).
  2104. if ( is_multisite() && ! ( is_main_network() && is_main_site() && defined( 'MULTISITE' ) ) ) {
  2105. if ( ! get_site_option( 'ms_files_rewriting' ) ) {
  2106. /*
  2107. * If ms-files rewriting is disabled (networks created post-3.5), it is fairly
  2108. * straightforward: Append sites/%d if we're not on the main site (for post-MU
  2109. * networks). (The extra directory prevents a four-digit ID from conflicting with
  2110. * a year-based directory for the main site. But if a MU-era network has disabled
  2111. * ms-files rewriting manually, they don't need the extra directory, as they never
  2112. * had wp-content/uploads for the main site.)
  2113. */
  2114. if ( defined( 'MULTISITE' ) ) {
  2115. $ms_dir = '/sites/' . get_current_blog_id();
  2116. } else {
  2117. $ms_dir = '/' . get_current_blog_id();
  2118. }
  2119. $dir .= $ms_dir;
  2120. $url .= $ms_dir;
  2121. } elseif ( defined( 'UPLOADS' ) && ! ms_is_switched() ) {
  2122. /*
  2123. * Handle the old-form ms-files.php rewriting if the network still has that enabled.
  2124. * When ms-files rewriting is enabled, then we only listen to UPLOADS when:
  2125. * 1) We are not on the main site in a post-MU network, as wp-content/uploads is used
  2126. * there, and
  2127. * 2) We are not switched, as ms_upload_constants() hardcodes these constants to reflect
  2128. * the original blog ID.
  2129. *
  2130. * Rather than UPLOADS, we actually use BLOGUPLOADDIR if it is set, as it is absolute.
  2131. * (And it will be set, see ms_upload_constants().) Otherwise, UPLOADS can be used, as
  2132. * as it is relative to ABSPATH. For the final piece: when UPLOADS is used with ms-files
  2133. * rewriting in multisite, the resulting URL is /files. (#WP22702 for background.)
  2134. */
  2135. if ( defined( 'BLOGUPLOADDIR' ) ) {
  2136. $dir = untrailingslashit( BLOGUPLOADDIR );
  2137. } else {
  2138. $dir = ABSPATH . UPLOADS;
  2139. }
  2140. $url = trailingslashit( $siteurl ) . 'files';
  2141. }
  2142. }
  2143. $basedir = $dir;
  2144. $baseurl = $url;
  2145. $subdir = '';
  2146. if ( get_option( 'uploads_use_yearmonth_folders' ) ) {
  2147. // Generate the yearly and monthly directories.
  2148. if ( ! $time ) {
  2149. $time = current_time( 'mysql' );
  2150. }
  2151. $y = substr( $time, 0, 4 );
  2152. $m = substr( $time, 5, 2 );
  2153. $subdir = "/$y/$m";
  2154. }
  2155. $dir .= $subdir;
  2156. $url .= $subdir;
  2157. return array(
  2158. 'path' => $dir,
  2159. 'url' => $url,
  2160. 'subdir' => $subdir,
  2161. 'basedir' => $basedir,
  2162. 'baseurl' => $baseurl,
  2163. 'error' => false,
  2164. );
  2165. }
  2166. /**
  2167. * Get a filename that is sanitized and unique for the given directory.
  2168. *
  2169. * If the filename is not unique, then a number will be added to the filename
  2170. * before the extension, and will continue adding numbers until the filename is
  2171. * unique.
  2172. *
  2173. * The callback is passed three parameters, the first one is the directory, the
  2174. * second is the filename, and the third is the extension.
  2175. *
  2176. * @since 2.5.0
  2177. *
  2178. * @param string $dir Directory.
  2179. * @param string $filename File name.
  2180. * @param callable $unique_filename_callback Callback. Default null.
  2181. * @return string New filename, if given wasn't unique.
  2182. */
  2183. function wp_unique_filename( $dir, $filename, $unique_filename_callback = null ) {
  2184. // Sanitize the file name before we begin processing.
  2185. $filename = sanitize_file_name( $filename );
  2186. $ext2 = null;
  2187. // Separate the filename into a name and extension.
  2188. $ext = pathinfo( $filename, PATHINFO_EXTENSION );
  2189. $name = pathinfo( $filename, PATHINFO_BASENAME );
  2190. if ( $ext ) {
  2191. $ext = '.' . $ext;
  2192. }
  2193. // Edge case: if file is named '.ext', treat as an empty name.
  2194. if ( $name === $ext ) {
  2195. $name = '';
  2196. }
  2197. /*
  2198. * Increment the file number until we have a unique file to save in $dir.
  2199. * Use callback if supplied.
  2200. */
  2201. if ( $unique_filename_callback && is_callable( $unique_filename_callback ) ) {
  2202. $filename = call_user_func( $unique_filename_callback, $dir, $name, $ext );
  2203. } else {
  2204. $number = '';
  2205. $fname = pathinfo( $filename, PATHINFO_FILENAME );
  2206. // Always append a number to file names that can potentially match image sub-size file names.
  2207. if ( $fname && preg_match( '/-(?:\d+x\d+|scaled|rotated)$/', $fname ) ) {
  2208. $number = 1;
  2209. // At this point the file name may not be unique. This is tested below and the $number is incremented.
  2210. $filename = str_replace( "{$fname}{$ext}", "{$fname}-{$number}{$ext}", $filename );
  2211. }
  2212. // Change '.ext' to lower case.
  2213. if ( $ext && strtolower( $ext ) != $ext ) {
  2214. $ext2 = strtolower( $ext );
  2215. $filename2 = preg_replace( '|' . preg_quote( $ext ) . '$|', $ext2, $filename );
  2216. // Check for both lower and upper case extension or image sub-sizes may be overwritten.
  2217. while ( file_exists( $dir . "/{$filename}" ) || file_exists( $dir . "/{$filename2}" ) ) {
  2218. $new_number = (int) $number + 1;
  2219. $filename = str_replace( array( "-{$number}{$ext}", "{$number}{$ext}" ), "-{$new_number}{$ext}", $filename );
  2220. $filename2 = str_replace( array( "-{$number}{$ext2}", "{$number}{$ext2}" ), "-{$new_number}{$ext2}", $filename2 );
  2221. $number = $new_number;
  2222. }
  2223. $filename = $filename2;
  2224. } else {
  2225. while ( file_exists( $dir . "/{$filename}" ) ) {
  2226. $new_number = (int) $number + 1;
  2227. if ( '' === "{$number}{$ext}" ) {
  2228. $filename = "{$filename}-{$new_number}";
  2229. } else {
  2230. $filename = str_replace( array( "-{$number}{$ext}", "{$number}{$ext}" ), "-{$new_number}{$ext}", $filename );
  2231. }
  2232. $number = $new_number;
  2233. }
  2234. }
  2235. // Prevent collisions with existing file names that contain dimension-like strings
  2236. // (whether they are subsizes or originals uploaded prior to #42437).
  2237. $upload_dir = wp_get_upload_dir();
  2238. // The (resized) image files would have name and extension, and will be in the uploads dir.
  2239. if ( $name && $ext && @is_dir( $dir ) && false !== strpos( $dir, $upload_dir['basedir'] ) ) {
  2240. // List of all files and directories contained in $dir.
  2241. $files = @scandir( $dir );
  2242. if ( ! empty( $files ) ) {
  2243. // Remove "dot" dirs.
  2244. $files = array_diff( $files, array( '.', '..' ) );
  2245. }
  2246. if ( ! empty( $files ) ) {
  2247. // The extension case may have changed above.
  2248. $new_ext = ! empty( $ext2 ) ? $ext2 : $ext;
  2249. // Ensure this never goes into infinite loop
  2250. // as it uses pathinfo() and regex in the check, but string replacement for the changes.
  2251. $count = count( $files );
  2252. $i = 0;
  2253. while ( $i <= $count && _wp_check_existing_file_names( $filename, $files ) ) {
  2254. $new_number = (int) $number + 1;
  2255. $filename = str_replace( array( "-{$number}{$new_ext}", "{$number}{$new_ext}" ), "-{$new_number}{$new_ext}", $filename );
  2256. $number = $new_number;
  2257. $i++;
  2258. }
  2259. }
  2260. }
  2261. }
  2262. /**
  2263. * Filters the result when generating a unique file name.
  2264. *
  2265. * @since 4.5.0
  2266. *
  2267. * @param string $filename Unique file name.
  2268. * @param string $ext File extension, eg. ".png".
  2269. * @param string $dir Directory path.
  2270. * @param callable|null $unique_filename_callback Callback function that generates the unique file name.
  2271. */
  2272. return apply_filters( 'wp_unique_filename', $filename, $ext, $dir, $unique_filename_callback );
  2273. }
  2274. /**
  2275. * Helper function to check if a file name could match an existing image sub-size file name.
  2276. *
  2277. * @since 5.3.1
  2278. * @access private
  2279. *
  2280. * @param string $filename The file name to check.
  2281. * $param array $files An array of existing files in the directory.
  2282. * $return bool True if the tested file name could match an existing file, false otherwise.
  2283. */
  2284. function _wp_check_existing_file_names( $filename, $files ) {
  2285. $fname = pathinfo( $filename, PATHINFO_FILENAME );
  2286. $ext = pathinfo( $filename, PATHINFO_EXTENSION );
  2287. // Edge case, file names like `.ext`.
  2288. if ( empty( $fname ) ) {
  2289. return false;
  2290. }
  2291. if ( $ext ) {
  2292. $ext = ".$ext";
  2293. }
  2294. $regex = '/^' . preg_quote( $fname ) . '-(?:\d+x\d+|scaled|rotated)' . preg_quote( $ext ) . '$/i';
  2295. foreach ( $files as $file ) {
  2296. if ( preg_match( $regex, $file ) ) {
  2297. return true;
  2298. }
  2299. }
  2300. return false;
  2301. }
  2302. /**
  2303. * Create a file in the upload folder with given content.
  2304. *
  2305. * If there is an error, then the key 'error' will exist with the error message.
  2306. * If success, then the key 'file' will have the unique file path, the 'url' key
  2307. * will have the link to the new file. and the 'error' key will be set to false.
  2308. *
  2309. * This function will not move an uploaded file to the upload folder. It will
  2310. * create a new file with the content in $bits parameter. If you move the upload
  2311. * file, read the content of the uploaded file, and then you can give the
  2312. * filename and content to this function, which will add it to the upload
  2313. * folder.
  2314. *
  2315. * The permissions will be set on the new file automatically by this function.
  2316. *
  2317. * @since 2.0.0
  2318. *
  2319. * @param string $name Filename.
  2320. * @param null|string $deprecated Never used. Set to null.
  2321. * @param string $bits File content
  2322. * @param string $time Optional. Time formatted in 'yyyy/mm'. Default null.
  2323. * @return array {
  2324. * Information about the newly-uploaded file.
  2325. *
  2326. * @type string $file Filename of the newly-uploaded file.
  2327. * @type string $url URL of the uploaded file.
  2328. * @type string $type File type.
  2329. * @type string|false $error Error message, if there has been an error.
  2330. * }
  2331. */
  2332. function wp_upload_bits( $name, $deprecated, $bits, $time = null ) {
  2333. if ( ! empty( $deprecated ) ) {
  2334. _deprecated_argument( __FUNCTION__, '2.0.0' );
  2335. }
  2336. if ( empty( $name ) ) {
  2337. return array( 'error' => __( 'Empty filename' ) );
  2338. }
  2339. $wp_filetype = wp_check_filetype( $name );
  2340. if ( ! $wp_filetype['ext'] && ! current_user_can( 'unfiltered_upload' ) ) {
  2341. return array( 'error' => __( 'Sorry, this file type is not permitted for security reasons.' ) );
  2342. }
  2343. $upload = wp_upload_dir( $time );
  2344. if ( false !== $upload['error'] ) {
  2345. return $upload;
  2346. }
  2347. /**
  2348. * Filters whether to treat the upload bits as an error.
  2349. *
  2350. * Returning a non-array from the filter will effectively short-circuit preparing the upload
  2351. * bits, returning that value instead. An error message should be returned as a string.
  2352. *
  2353. * @since 3.0.0
  2354. *
  2355. * @param array|string $upload_bits_error An array of upload bits data, or error message to return.
  2356. */
  2357. $upload_bits_error = apply_filters(
  2358. 'wp_upload_bits',
  2359. array(
  2360. 'name' => $name,
  2361. 'bits' => $bits,
  2362. 'time' => $time,
  2363. )
  2364. );
  2365. if ( ! is_array( $upload_bits_error ) ) {
  2366. $upload['error'] = $upload_bits_error;
  2367. return $upload;
  2368. }
  2369. $filename = wp_unique_filename( $upload['path'], $name );
  2370. $new_file = $upload['path'] . "/$filename";
  2371. if ( ! wp_mkdir_p( dirname( $new_file ) ) ) {
  2372. if ( 0 === strpos( $upload['basedir'], ABSPATH ) ) {
  2373. $error_path = str_replace( ABSPATH, '', $upload['basedir'] ) . $upload['subdir'];
  2374. } else {
  2375. $error_path = wp_basename( $upload['basedir'] ) . $upload['subdir'];
  2376. }
  2377. $message = sprintf(
  2378. /* translators: %s: Directory path. */
  2379. __( 'Unable to create directory %s. Is its parent directory writable by the server?' ),
  2380. $error_path
  2381. );
  2382. return array( 'error' => $message );
  2383. }
  2384. $ifp = @fopen( $new_file, 'wb' );
  2385. if ( ! $ifp ) {
  2386. return array(
  2387. /* translators: %s: File name. */
  2388. 'error' => sprintf( __( 'Could not write file %s' ), $new_file ),
  2389. );
  2390. }
  2391. fwrite( $ifp, $bits );
  2392. fclose( $ifp );
  2393. clearstatcache();
  2394. // Set correct file permissions.
  2395. $stat = @ stat( dirname( $new_file ) );
  2396. $perms = $stat['mode'] & 0007777;
  2397. $perms = $perms & 0000666;
  2398. chmod( $new_file, $perms );
  2399. clearstatcache();
  2400. // Compute the URL.
  2401. $url = $upload['url'] . "/$filename";
  2402. /** This filter is documented in wp-admin/includes/file.php */
  2403. return apply_filters(
  2404. 'wp_handle_upload',
  2405. array(
  2406. 'file' => $new_file,
  2407. 'url' => $url,
  2408. 'type' => $wp_filetype['type'],
  2409. 'error' => false,
  2410. ),
  2411. 'sideload'
  2412. );
  2413. }
  2414. /**
  2415. * Retrieve the file type based on the extension name.
  2416. *
  2417. * @since 2.5.0
  2418. *
  2419. * @param string $ext The extension to search.
  2420. * @return string|void The file type, example: audio, video, document, spreadsheet, etc.
  2421. */
  2422. function wp_ext2type( $ext ) {
  2423. $ext = strtolower( $ext );
  2424. $ext2type = wp_get_ext_types();
  2425. foreach ( $ext2type as $type => $exts ) {
  2426. if ( in_array( $ext, $exts, true ) ) {
  2427. return $type;
  2428. }
  2429. }
  2430. }
  2431. /**
  2432. * Retrieve the file type from the file name.
  2433. *
  2434. * You can optionally define the mime array, if needed.
  2435. *
  2436. * @since 2.0.4
  2437. *
  2438. * @param string $filename File name or path.
  2439. * @param string[] $mimes Optional. Array of mime types keyed by their file extension regex.
  2440. * @return array {
  2441. * Values for the extension and mime type.
  2442. *
  2443. * @type string|false $ext File extension, or false if the file doesn't match a mime type.
  2444. * @type string|false $type File mime type, or false if the file doesn't match a mime type.
  2445. * }
  2446. */
  2447. function wp_check_filetype( $filename, $mimes = null ) {
  2448. if ( empty( $mimes ) ) {
  2449. $mimes = get_allowed_mime_types();
  2450. }
  2451. $type = false;
  2452. $ext = false;
  2453. foreach ( $mimes as $ext_preg => $mime_match ) {
  2454. $ext_preg = '!\.(' . $ext_preg . ')$!i';
  2455. if ( preg_match( $ext_preg, $filename, $ext_matches ) ) {
  2456. $type = $mime_match;
  2457. $ext = $ext_matches[1];
  2458. break;
  2459. }
  2460. }
  2461. return compact( 'ext', 'type' );
  2462. }
  2463. /**
  2464. * Attempt to determine the real file type of a file.
  2465. *
  2466. * If unable to, the file name extension will be used to determine type.
  2467. *
  2468. * If it's determined that the extension does not match the file's real type,
  2469. * then the "proper_filename" value will be set with a proper filename and extension.
  2470. *
  2471. * Currently this function only supports renaming images validated via wp_get_image_mime().
  2472. *
  2473. * @since 3.0.0
  2474. *
  2475. * @param string $file Full path to the file.
  2476. * @param string $filename The name of the file (may differ from $file due to $file being
  2477. * in a tmp directory).
  2478. * @param string[] $mimes Optional. Array of mime types keyed by their file extension regex.
  2479. * @return array {
  2480. * Values for the extension, mime type, and corrected filename.
  2481. *
  2482. * @type string|false $ext File extension, or false if the file doesn't match a mime type.
  2483. * @type string|false $type File mime type, or false if the file doesn't match a mime type.
  2484. * @type string|false $proper_filename File name with its correct extension, or false if it cannot be determined.
  2485. * }
  2486. */
  2487. function wp_check_filetype_and_ext( $file, $filename, $mimes = null ) {
  2488. $proper_filename = false;
  2489. // Do basic extension validation and MIME mapping.
  2490. $wp_filetype = wp_check_filetype( $filename, $mimes );
  2491. $ext = $wp_filetype['ext'];
  2492. $type = $wp_filetype['type'];
  2493. // We can't do any further validation without a file to work with.
  2494. if ( ! file_exists( $file ) ) {
  2495. return compact( 'ext', 'type', 'proper_filename' );
  2496. }
  2497. $real_mime = false;
  2498. // Validate image types.
  2499. if ( $type && 0 === strpos( $type, 'image/' ) ) {
  2500. // Attempt to figure out what type of image it actually is.
  2501. $real_mime = wp_get_image_mime( $file );
  2502. if ( $real_mime && $real_mime != $type ) {
  2503. /**
  2504. * Filters the list mapping image mime types to their respective extensions.
  2505. *
  2506. * @since 3.0.0
  2507. *
  2508. * @param array $mime_to_ext Array of image mime types and their matching extensions.
  2509. */
  2510. $mime_to_ext = apply_filters(
  2511. 'getimagesize_mimes_to_exts',
  2512. array(
  2513. 'image/jpeg' => 'jpg',
  2514. 'image/png' => 'png',
  2515. 'image/gif' => 'gif',
  2516. 'image/bmp' => 'bmp',
  2517. 'image/tiff' => 'tif',
  2518. )
  2519. );
  2520. // Replace whatever is after the last period in the filename with the correct extension.
  2521. if ( ! empty( $mime_to_ext[ $real_mime ] ) ) {
  2522. $filename_parts = explode( '.', $filename );
  2523. array_pop( $filename_parts );
  2524. $filename_parts[] = $mime_to_ext[ $real_mime ];
  2525. $new_filename = implode( '.', $filename_parts );
  2526. if ( $new_filename != $filename ) {
  2527. $proper_filename = $new_filename; // Mark that it changed.
  2528. }
  2529. // Redefine the extension / MIME.
  2530. $wp_filetype = wp_check_filetype( $new_filename, $mimes );
  2531. $ext = $wp_filetype['ext'];
  2532. $type = $wp_filetype['type'];
  2533. } else {
  2534. // Reset $real_mime and try validating again.
  2535. $real_mime = false;
  2536. }
  2537. }
  2538. }
  2539. // Validate files that didn't get validated during previous checks.
  2540. if ( $type && ! $real_mime && extension_loaded( 'fileinfo' ) ) {
  2541. $finfo = finfo_open( FILEINFO_MIME_TYPE );
  2542. $real_mime = finfo_file( $finfo, $file );
  2543. finfo_close( $finfo );
  2544. // fileinfo often misidentifies obscure files as one of these types.
  2545. $nonspecific_types = array(
  2546. 'application/octet-stream',
  2547. 'application/encrypted',
  2548. 'application/CDFV2-encrypted',
  2549. 'application/zip',
  2550. );
  2551. /*
  2552. * If $real_mime doesn't match the content type we're expecting from the file's extension,
  2553. * we need to do some additional vetting. Media types and those listed in $nonspecific_types are
  2554. * allowed some leeway, but anything else must exactly match the real content type.
  2555. */
  2556. if ( in_array( $real_mime, $nonspecific_types, true ) ) {
  2557. // File is a non-specific binary type. That's ok if it's a type that generally tends to be binary.
  2558. if ( ! in_array( substr( $type, 0, strcspn( $type, '/' ) ), array( 'application', 'video', 'audio' ), true ) ) {
  2559. $type = false;
  2560. $ext = false;
  2561. }
  2562. } elseif ( 0 === strpos( $real_mime, 'video/' ) || 0 === strpos( $real_mime, 'audio/' ) ) {
  2563. /*
  2564. * For these types, only the major type must match the real value.
  2565. * This means that common mismatches are forgiven: application/vnd.apple.numbers is often misidentified as application/zip,
  2566. * and some media files are commonly named with the wrong extension (.mov instead of .mp4)
  2567. */
  2568. if ( substr( $real_mime, 0, strcspn( $real_mime, '/' ) ) !== substr( $type, 0, strcspn( $type, '/' ) ) ) {
  2569. $type = false;
  2570. $ext = false;
  2571. }
  2572. } elseif ( 'text/plain' === $real_mime ) {
  2573. // A few common file types are occasionally detected as text/plain; allow those.
  2574. if ( ! in_array(
  2575. $type,
  2576. array(
  2577. 'text/plain',
  2578. 'text/csv',
  2579. 'text/richtext',
  2580. 'text/tsv',
  2581. 'text/vtt',
  2582. ),
  2583. true
  2584. )
  2585. ) {
  2586. $type = false;
  2587. $ext = false;
  2588. }
  2589. } elseif ( 'text/rtf' === $real_mime ) {
  2590. // Special casing for RTF files.
  2591. if ( ! in_array(
  2592. $type,
  2593. array(
  2594. 'text/rtf',
  2595. 'text/plain',
  2596. 'application/rtf',
  2597. ),
  2598. true
  2599. )
  2600. ) {
  2601. $type = false;
  2602. $ext = false;
  2603. }
  2604. } else {
  2605. if ( $type !== $real_mime ) {
  2606. /*
  2607. * Everything else including image/* and application/*:
  2608. * If the real content type doesn't match the file extension, assume it's dangerous.
  2609. */
  2610. $type = false;
  2611. $ext = false;
  2612. }
  2613. }
  2614. }
  2615. // The mime type must be allowed.
  2616. if ( $type ) {
  2617. $allowed = get_allowed_mime_types();
  2618. if ( ! in_array( $type, $allowed, true ) ) {
  2619. $type = false;
  2620. $ext = false;
  2621. }
  2622. }
  2623. /**
  2624. * Filters the "real" file type of the given file.
  2625. *
  2626. * @since 3.0.0
  2627. * @since 5.1.0 The $real_mime parameter was added.
  2628. *
  2629. * @param array $wp_check_filetype_and_ext {
  2630. * Values for the extension, mime type, and corrected filename.
  2631. *
  2632. * @type string|false $ext File extension, or false if the file doesn't match a mime type.
  2633. * @type string|false $type File mime type, or false if the file doesn't match a mime type.
  2634. * @type string|false $proper_filename File name with its correct extension, or false if it cannot be determined.
  2635. * }
  2636. * @param string $file Full path to the file.
  2637. * @param string $filename The name of the file (may differ from $file due to
  2638. * $file being in a tmp directory).
  2639. * @param string[] $mimes Array of mime types keyed by their file extension regex.
  2640. * @param string|bool $real_mime The actual mime type or false if the type cannot be determined.
  2641. */
  2642. return apply_filters( 'wp_check_filetype_and_ext', compact( 'ext', 'type', 'proper_filename' ), $file, $filename, $mimes, $real_mime );
  2643. }
  2644. /**
  2645. * Returns the real mime type of an image file.
  2646. *
  2647. * This depends on exif_imagetype() or getimagesize() to determine real mime types.
  2648. *
  2649. * @since 4.7.1
  2650. *
  2651. * @param string $file Full path to the file.
  2652. * @return string|false The actual mime type or false if the type cannot be determined.
  2653. */
  2654. function wp_get_image_mime( $file ) {
  2655. /*
  2656. * Use exif_imagetype() to check the mimetype if available or fall back to
  2657. * getimagesize() if exif isn't avaialbe. If either function throws an Exception
  2658. * we assume the file could not be validated.
  2659. */
  2660. try {
  2661. if ( is_callable( 'exif_imagetype' ) ) {
  2662. $imagetype = exif_imagetype( $file );
  2663. $mime = ( $imagetype ) ? image_type_to_mime_type( $imagetype ) : false;
  2664. } elseif ( function_exists( 'getimagesize' ) ) {
  2665. $imagesize = @getimagesize( $file );
  2666. $mime = ( isset( $imagesize['mime'] ) ) ? $imagesize['mime'] : false;
  2667. } else {
  2668. $mime = false;
  2669. }
  2670. } catch ( Exception $e ) {
  2671. $mime = false;
  2672. }
  2673. return $mime;
  2674. }
  2675. /**
  2676. * Retrieve list of mime types and file extensions.
  2677. *
  2678. * @since 3.5.0
  2679. * @since 4.2.0 Support was added for GIMP (.xcf) files.
  2680. * @since 4.9.2 Support was added for Flac (.flac) files.
  2681. * @since 4.9.6 Support was added for AAC (.aac) files.
  2682. *
  2683. * @return string[] Array of mime types keyed by the file extension regex corresponding to those types.
  2684. */
  2685. function wp_get_mime_types() {
  2686. /**
  2687. * Filters the list of mime types and file extensions.
  2688. *
  2689. * This filter should be used to add, not remove, mime types. To remove
  2690. * mime types, use the {@see 'upload_mimes'} filter.
  2691. *
  2692. * @since 3.5.0
  2693. *
  2694. * @param string[] $wp_get_mime_types Mime types keyed by the file extension regex
  2695. * corresponding to those types.
  2696. */
  2697. return apply_filters(
  2698. 'mime_types',
  2699. array(
  2700. // Image formats.
  2701. 'jpg|jpeg|jpe' => 'image/jpeg',
  2702. 'gif' => 'image/gif',
  2703. 'png' => 'image/png',
  2704. 'bmp' => 'image/bmp',
  2705. 'tiff|tif' => 'image/tiff',
  2706. 'ico' => 'image/x-icon',
  2707. // Video formats.
  2708. 'asf|asx' => 'video/x-ms-asf',
  2709. 'wmv' => 'video/x-ms-wmv',
  2710. 'wmx' => 'video/x-ms-wmx',
  2711. 'wm' => 'video/x-ms-wm',
  2712. 'avi' => 'video/avi',
  2713. 'divx' => 'video/divx',
  2714. 'flv' => 'video/x-flv',
  2715. 'mov|qt' => 'video/quicktime',
  2716. 'mpeg|mpg|mpe' => 'video/mpeg',
  2717. 'mp4|m4v' => 'video/mp4',
  2718. 'ogv' => 'video/ogg',
  2719. 'webm' => 'video/webm',
  2720. 'mkv' => 'video/x-matroska',
  2721. '3gp|3gpp' => 'video/3gpp', // Can also be audio.
  2722. '3g2|3gp2' => 'video/3gpp2', // Can also be audio.
  2723. // Text formats.
  2724. 'txt|asc|c|cc|h|srt' => 'text/plain',
  2725. 'csv' => 'text/csv',
  2726. 'tsv' => 'text/tab-separated-values',
  2727. 'ics' => 'text/calendar',
  2728. 'rtx' => 'text/richtext',
  2729. 'css' => 'text/css',
  2730. 'htm|html' => 'text/html',
  2731. 'vtt' => 'text/vtt',
  2732. 'dfxp' => 'application/ttaf+xml',
  2733. // Audio formats.
  2734. 'mp3|m4a|m4b' => 'audio/mpeg',
  2735. 'aac' => 'audio/aac',
  2736. 'ra|ram' => 'audio/x-realaudio',
  2737. 'wav' => 'audio/wav',
  2738. 'ogg|oga' => 'audio/ogg',
  2739. 'flac' => 'audio/flac',
  2740. 'mid|midi' => 'audio/midi',
  2741. 'wma' => 'audio/x-ms-wma',
  2742. 'wax' => 'audio/x-ms-wax',
  2743. 'mka' => 'audio/x-matroska',
  2744. // Misc application formats.
  2745. 'rtf' => 'application/rtf',
  2746. 'js' => 'application/javascript',
  2747. 'pdf' => 'application/pdf',
  2748. 'swf' => 'application/x-shockwave-flash',
  2749. 'class' => 'application/java',
  2750. 'tar' => 'application/x-tar',
  2751. 'zip' => 'application/zip',
  2752. 'gz|gzip' => 'application/x-gzip',
  2753. 'rar' => 'application/rar',
  2754. '7z' => 'application/x-7z-compressed',
  2755. 'exe' => 'application/x-msdownload',
  2756. 'psd' => 'application/octet-stream',
  2757. 'xcf' => 'application/octet-stream',
  2758. // MS Office formats.
  2759. 'doc' => 'application/msword',
  2760. 'pot|pps|ppt' => 'application/vnd.ms-powerpoint',
  2761. 'wri' => 'application/vnd.ms-write',
  2762. 'xla|xls|xlt|xlw' => 'application/vnd.ms-excel',
  2763. 'mdb' => 'application/vnd.ms-access',
  2764. 'mpp' => 'application/vnd.ms-project',
  2765. 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  2766. 'docm' => 'application/vnd.ms-word.document.macroEnabled.12',
  2767. 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
  2768. 'dotm' => 'application/vnd.ms-word.template.macroEnabled.12',
  2769. 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  2770. 'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12',
  2771. 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
  2772. 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
  2773. 'xltm' => 'application/vnd.ms-excel.template.macroEnabled.12',
  2774. 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
  2775. 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  2776. 'pptm' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12',
  2777. 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
  2778. 'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12',
  2779. 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
  2780. 'potm' => 'application/vnd.ms-powerpoint.template.macroEnabled.12',
  2781. 'ppam' => 'application/vnd.ms-powerpoint.addin.macroEnabled.12',
  2782. 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
  2783. 'sldm' => 'application/vnd.ms-powerpoint.slide.macroEnabled.12',
  2784. 'onetoc|onetoc2|onetmp|onepkg' => 'application/onenote',
  2785. 'oxps' => 'application/oxps',
  2786. 'xps' => 'application/vnd.ms-xpsdocument',
  2787. // OpenOffice formats.
  2788. 'odt' => 'application/vnd.oasis.opendocument.text',
  2789. 'odp' => 'application/vnd.oasis.opendocument.presentation',
  2790. 'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
  2791. 'odg' => 'application/vnd.oasis.opendocument.graphics',
  2792. 'odc' => 'application/vnd.oasis.opendocument.chart',
  2793. 'odb' => 'application/vnd.oasis.opendocument.database',
  2794. 'odf' => 'application/vnd.oasis.opendocument.formula',
  2795. // WordPerfect formats.
  2796. 'wp|wpd' => 'application/wordperfect',
  2797. // iWork formats.
  2798. 'key' => 'application/vnd.apple.keynote',
  2799. 'numbers' => 'application/vnd.apple.numbers',
  2800. 'pages' => 'application/vnd.apple.pages',
  2801. )
  2802. );
  2803. }
  2804. /**
  2805. * Retrieves the list of common file extensions and their types.
  2806. *
  2807. * @since 4.6.0
  2808. *
  2809. * @return array[] Multi-dimensional array of file extensions types keyed by the type of file.
  2810. */
  2811. function wp_get_ext_types() {
  2812. /**
  2813. * Filters file type based on the extension name.
  2814. *
  2815. * @since 2.5.0
  2816. *
  2817. * @see wp_ext2type()
  2818. *
  2819. * @param array[] $ext2type Multi-dimensional array of file extensions types keyed by the type of file.
  2820. */
  2821. return apply_filters(
  2822. 'ext2type',
  2823. array(
  2824. 'image' => array( 'jpg', 'jpeg', 'jpe', 'gif', 'png', 'bmp', 'tif', 'tiff', 'ico' ),
  2825. 'audio' => array( 'aac', 'ac3', 'aif', 'aiff', 'flac', 'm3a', 'm4a', 'm4b', 'mka', 'mp1', 'mp2', 'mp3', 'ogg', 'oga', 'ram', 'wav', 'wma' ),
  2826. 'video' => array( '3g2', '3gp', '3gpp', 'asf', 'avi', 'divx', 'dv', 'flv', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'mpv', 'ogm', 'ogv', 'qt', 'rm', 'vob', 'wmv' ),
  2827. 'document' => array( 'doc', 'docx', 'docm', 'dotm', 'odt', 'pages', 'pdf', 'xps', 'oxps', 'rtf', 'wp', 'wpd', 'psd', 'xcf' ),
  2828. 'spreadsheet' => array( 'numbers', 'ods', 'xls', 'xlsx', 'xlsm', 'xlsb' ),
  2829. 'interactive' => array( 'swf', 'key', 'ppt', 'pptx', 'pptm', 'pps', 'ppsx', 'ppsm', 'sldx', 'sldm', 'odp' ),
  2830. 'text' => array( 'asc', 'csv', 'tsv', 'txt' ),
  2831. 'archive' => array( 'bz2', 'cab', 'dmg', 'gz', 'rar', 'sea', 'sit', 'sqx', 'tar', 'tgz', 'zip', '7z' ),
  2832. 'code' => array( 'css', 'htm', 'html', 'php', 'js' ),
  2833. )
  2834. );
  2835. }
  2836. /**
  2837. * Retrieve list of allowed mime types and file extensions.
  2838. *
  2839. * @since 2.8.6
  2840. *
  2841. * @param int|WP_User $user Optional. User to check. Defaults to current user.
  2842. * @return string[] Array of mime types keyed by the file extension regex corresponding
  2843. * to those types.
  2844. */
  2845. function get_allowed_mime_types( $user = null ) {
  2846. $t = wp_get_mime_types();
  2847. unset( $t['swf'], $t['exe'] );
  2848. if ( function_exists( 'current_user_can' ) ) {
  2849. $unfiltered = $user ? user_can( $user, 'unfiltered_html' ) : current_user_can( 'unfiltered_html' );
  2850. }
  2851. if ( empty( $unfiltered ) ) {
  2852. unset( $t['htm|html'], $t['js'] );
  2853. }
  2854. /**
  2855. * Filters list of allowed mime types and file extensions.
  2856. *
  2857. * @since 2.0.0
  2858. *
  2859. * @param array $t Mime types keyed by the file extension regex corresponding to those types.
  2860. * @param int|WP_User|null $user User ID, User object or null if not provided (indicates current user).
  2861. */
  2862. return apply_filters( 'upload_mimes', $t, $user );
  2863. }
  2864. /**
  2865. * Display "Are You Sure" message to confirm the action being taken.
  2866. *
  2867. * If the action has the nonce explain message, then it will be displayed
  2868. * along with the "Are you sure?" message.
  2869. *
  2870. * @since 2.0.4
  2871. *
  2872. * @param string $action The nonce action.
  2873. */
  2874. function wp_nonce_ays( $action ) {
  2875. if ( 'log-out' == $action ) {
  2876. $html = sprintf(
  2877. /* translators: %s: Site title. */
  2878. __( 'You are attempting to log out of %s' ),
  2879. get_bloginfo( 'name' )
  2880. );
  2881. $html .= '</p><p>';
  2882. $redirect_to = isset( $_REQUEST['redirect_to'] ) ? $_REQUEST['redirect_to'] : '';
  2883. $html .= sprintf(
  2884. /* translators: %s: Logout URL. */
  2885. __( 'Do you really want to <a href="%s">log out</a>?' ),
  2886. wp_logout_url( $redirect_to )
  2887. );
  2888. } else {
  2889. $html = __( 'The link you followed has expired.' );
  2890. if ( wp_get_referer() ) {
  2891. $html .= '</p><p>';
  2892. $html .= sprintf(
  2893. '<a href="%s">%s</a>',
  2894. esc_url( remove_query_arg( 'updated', wp_get_referer() ) ),
  2895. __( 'Please try again.' )
  2896. );
  2897. }
  2898. }
  2899. wp_die( $html, __( 'Something went wrong.' ), 403 );
  2900. }
  2901. /**
  2902. * Kills WordPress execution and displays HTML page with an error message.
  2903. *
  2904. * This function complements the `die()` PHP function. The difference is that
  2905. * HTML will be displayed to the user. It is recommended to use this function
  2906. * only when the execution should not continue any further. It is not recommended
  2907. * to call this function very often, and try to handle as many errors as possible
  2908. * silently or more gracefully.
  2909. *
  2910. * As a shorthand, the desired HTTP response code may be passed as an integer to
  2911. * the `$title` parameter (the default title would apply) or the `$args` parameter.
  2912. *
  2913. * @since 2.0.4
  2914. * @since 4.1.0 The `$title` and `$args` parameters were changed to optionally accept
  2915. * an integer to be used as the response code.
  2916. * @since 5.1.0 The `$link_url`, `$link_text`, and `$exit` arguments were added.
  2917. * @since 5.3.0 The `$charset` argument was added.
  2918. *
  2919. * @global WP_Query $wp_query WordPress Query object.
  2920. *
  2921. * @param string|WP_Error $message Optional. Error message. If this is a WP_Error object,
  2922. * and not an Ajax or XML-RPC request, the error's messages are used.
  2923. * Default empty.
  2924. * @param string|int $title Optional. Error title. If `$message` is a `WP_Error` object,
  2925. * error data with the key 'title' may be used to specify the title.
  2926. * If `$title` is an integer, then it is treated as the response
  2927. * code. Default empty.
  2928. * @param string|array|int $args {
  2929. * Optional. Arguments to control behavior. If `$args` is an integer, then it is treated
  2930. * as the response code. Default empty array.
  2931. *
  2932. * @type int $response The HTTP response code. Default 200 for Ajax requests, 500 otherwise.
  2933. * @type string $link_url A URL to include a link to. Only works in combination with $link_text.
  2934. * Default empty string.
  2935. * @type string $link_text A label for the link to include. Only works in combination with $link_url.
  2936. * Default empty string.
  2937. * @type bool $back_link Whether to include a link to go back. Default false.
  2938. * @type string $text_direction The text direction. This is only useful internally, when WordPress
  2939. * is still loading and the site's locale is not set up yet. Accepts 'rtl'.
  2940. * Default is the value of is_rtl().
  2941. * @type string $charset Character set of the HTML output. Default 'utf-8'.
  2942. * @type string $code Error code to use. Default is 'wp_die', or the main error code if $message
  2943. * is a WP_Error.
  2944. * @type bool $exit Whether to exit the process after completion. Default true.
  2945. * }
  2946. */
  2947. function wp_die( $message = '', $title = '', $args = array() ) {
  2948. global $wp_query;
  2949. if ( is_int( $args ) ) {
  2950. $args = array( 'response' => $args );
  2951. } elseif ( is_int( $title ) ) {
  2952. $args = array( 'response' => $title );
  2953. $title = '';
  2954. }
  2955. if ( wp_doing_ajax() ) {
  2956. /**
  2957. * Filters the callback for killing WordPress execution for Ajax requests.
  2958. *
  2959. * @since 3.4.0
  2960. *
  2961. * @param callable $function Callback function name.
  2962. */
  2963. $function = apply_filters( 'wp_die_ajax_handler', '_ajax_wp_die_handler' );
  2964. } elseif ( wp_is_json_request() ) {
  2965. /**
  2966. * Filters the callback for killing WordPress execution for JSON requests.
  2967. *
  2968. * @since 5.1.0
  2969. *
  2970. * @param callable $function Callback function name.
  2971. */
  2972. $function = apply_filters( 'wp_die_json_handler', '_json_wp_die_handler' );
  2973. } elseif ( wp_is_jsonp_request() ) {
  2974. /**
  2975. * Filters the callback for killing WordPress execution for JSONP requests.
  2976. *
  2977. * @since 5.2.0
  2978. *
  2979. * @param callable $function Callback function name.
  2980. */
  2981. $function = apply_filters( 'wp_die_jsonp_handler', '_jsonp_wp_die_handler' );
  2982. } elseif ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) {
  2983. /**
  2984. * Filters the callback for killing WordPress execution for XML-RPC requests.
  2985. *
  2986. * @since 3.4.0
  2987. *
  2988. * @param callable $function Callback function name.
  2989. */
  2990. $function = apply_filters( 'wp_die_xmlrpc_handler', '_xmlrpc_wp_die_handler' );
  2991. } elseif ( wp_is_xml_request()
  2992. || isset( $wp_query ) &&
  2993. ( function_exists( 'is_feed' ) && is_feed()
  2994. || function_exists( 'is_comment_feed' ) && is_comment_feed()
  2995. || function_exists( 'is_trackback' ) && is_trackback() ) ) {
  2996. /**
  2997. * Filters the callback for killing WordPress execution for XML requests.
  2998. *
  2999. * @since 5.2.0
  3000. *
  3001. * @param callable $function Callback function name.
  3002. */
  3003. $function = apply_filters( 'wp_die_xml_handler', '_xml_wp_die_handler' );
  3004. } else {
  3005. /**
  3006. * Filters the callback for killing WordPress execution for all non-Ajax, non-JSON, non-XML requests.
  3007. *
  3008. * @since 3.0.0
  3009. *
  3010. * @param callable $function Callback function name.
  3011. */
  3012. $function = apply_filters( 'wp_die_handler', '_default_wp_die_handler' );
  3013. }
  3014. call_user_func( $function, $message, $title, $args );
  3015. }
  3016. /**
  3017. * Kills WordPress execution and displays HTML page with an error message.
  3018. *
  3019. * This is the default handler for wp_die(). If you want a custom one,
  3020. * you can override this using the {@see 'wp_die_handler'} filter in wp_die().
  3021. *
  3022. * @since 3.0.0
  3023. * @access private
  3024. *
  3025. * @param string|WP_Error $message Error message or WP_Error object.
  3026. * @param string $title Optional. Error title. Default empty.
  3027. * @param string|array $args Optional. Arguments to control behavior. Default empty array.
  3028. */
  3029. function _default_wp_die_handler( $message, $title = '', $args = array() ) {
  3030. list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args );
  3031. if ( is_string( $message ) ) {
  3032. if ( ! empty( $parsed_args['additional_errors'] ) ) {
  3033. $message = array_merge(
  3034. array( $message ),
  3035. wp_list_pluck( $parsed_args['additional_errors'], 'message' )
  3036. );
  3037. $message = "<ul>\n\t\t<li>" . join( "</li>\n\t\t<li>", $message ) . "</li>\n\t</ul>";
  3038. }
  3039. $message = sprintf(
  3040. '<div class="wp-die-message">%s</div>',
  3041. $message
  3042. );
  3043. }
  3044. $have_gettext = function_exists( '__' );
  3045. if ( ! empty( $parsed_args['link_url'] ) && ! empty( $parsed_args['link_text'] ) ) {
  3046. $link_url = $parsed_args['link_url'];
  3047. if ( function_exists( 'esc_url' ) ) {
  3048. $link_url = esc_url( $link_url );
  3049. }
  3050. $link_text = $parsed_args['link_text'];
  3051. $message .= "\n<p><a href='{$link_url}'>{$link_text}</a></p>";
  3052. }
  3053. if ( isset( $parsed_args['back_link'] ) && $parsed_args['back_link'] ) {
  3054. $back_text = $have_gettext ? __( '&laquo; Back' ) : '&laquo; Back';
  3055. $message .= "\n<p><a href='javascript:history.back()'>$back_text</a></p>";
  3056. }
  3057. if ( ! did_action( 'admin_head' ) ) :
  3058. if ( ! headers_sent() ) {
  3059. header( "Content-Type: text/html; charset={$parsed_args['charset']}" );
  3060. status_header( $parsed_args['response'] );
  3061. nocache_headers();
  3062. }
  3063. $text_direction = $parsed_args['text_direction'];
  3064. if ( function_exists( 'language_attributes' ) && function_exists( 'is_rtl' ) ) {
  3065. $dir_attr = get_language_attributes();
  3066. } else {
  3067. $dir_attr = "dir='$text_direction'";
  3068. }
  3069. ?>
  3070. <!DOCTYPE html>
  3071. <html xmlns="http://www.w3.org/1999/xhtml" <?php echo $dir_attr; ?>>
  3072. <head>
  3073. <meta http-equiv="Content-Type" content="text/html; charset=<?php echo $parsed_args['charset']; ?>" />
  3074. <meta name="viewport" content="width=device-width">
  3075. <?php
  3076. if ( function_exists( 'wp_no_robots' ) ) {
  3077. wp_no_robots();
  3078. }
  3079. ?>
  3080. <title><?php echo $title; ?></title>
  3081. <style type="text/css">
  3082. html {
  3083. background: #f1f1f1;
  3084. }
  3085. body {
  3086. background: #fff;
  3087. color: #444;
  3088. font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
  3089. margin: 2em auto;
  3090. padding: 1em 2em;
  3091. max-width: 700px;
  3092. -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.13);
  3093. box-shadow: 0 1px 3px rgba(0, 0, 0, 0.13);
  3094. }
  3095. h1 {
  3096. border-bottom: 1px solid #dadada;
  3097. clear: both;
  3098. color: #666;
  3099. font-size: 24px;
  3100. margin: 30px 0 0 0;
  3101. padding: 0;
  3102. padding-bottom: 7px;
  3103. }
  3104. #error-page {
  3105. margin-top: 50px;
  3106. }
  3107. #error-page p,
  3108. #error-page .wp-die-message {
  3109. font-size: 14px;
  3110. line-height: 1.5;
  3111. margin: 25px 0 20px;
  3112. }
  3113. #error-page code {
  3114. font-family: Consolas, Monaco, monospace;
  3115. }
  3116. ul li {
  3117. margin-bottom: 10px;
  3118. font-size: 14px ;
  3119. }
  3120. a {
  3121. color: #0073aa;
  3122. }
  3123. a:hover,
  3124. a:active {
  3125. color: #00a0d2;
  3126. }
  3127. a:focus {
  3128. color: #124964;
  3129. -webkit-box-shadow:
  3130. 0 0 0 1px #5b9dd9,
  3131. 0 0 2px 1px rgba(30, 140, 190, 0.8);
  3132. box-shadow:
  3133. 0 0 0 1px #5b9dd9,
  3134. 0 0 2px 1px rgba(30, 140, 190, 0.8);
  3135. outline: none;
  3136. }
  3137. .button {
  3138. background: #f7f7f7;
  3139. border: 1px solid #ccc;
  3140. color: #555;
  3141. display: inline-block;
  3142. text-decoration: none;
  3143. font-size: 13px;
  3144. line-height: 2;
  3145. height: 28px;
  3146. margin: 0;
  3147. padding: 0 10px 1px;
  3148. cursor: pointer;
  3149. -webkit-border-radius: 3px;
  3150. -webkit-appearance: none;
  3151. border-radius: 3px;
  3152. white-space: nowrap;
  3153. -webkit-box-sizing: border-box;
  3154. -moz-box-sizing: border-box;
  3155. box-sizing: border-box;
  3156. -webkit-box-shadow: 0 1px 0 #ccc;
  3157. box-shadow: 0 1px 0 #ccc;
  3158. vertical-align: top;
  3159. }
  3160. .button.button-large {
  3161. height: 30px;
  3162. line-height: 2.15384615;
  3163. padding: 0 12px 2px;
  3164. }
  3165. .button:hover,
  3166. .button:focus {
  3167. background: #fafafa;
  3168. border-color: #999;
  3169. color: #23282d;
  3170. }
  3171. .button:focus {
  3172. border-color: #5b9dd9;
  3173. -webkit-box-shadow: 0 0 3px rgba(0, 115, 170, 0.8);
  3174. box-shadow: 0 0 3px rgba(0, 115, 170, 0.8);
  3175. outline: none;
  3176. }
  3177. .button:active {
  3178. background: #eee;
  3179. border-color: #999;
  3180. -webkit-box-shadow: inset 0 2px 5px -3px rgba(0, 0, 0, 0.5);
  3181. box-shadow: inset 0 2px 5px -3px rgba(0, 0, 0, 0.5);
  3182. }
  3183. <?php
  3184. if ( 'rtl' == $text_direction ) {
  3185. echo 'body { font-family: Tahoma, Arial; }';
  3186. }
  3187. ?>
  3188. </style>
  3189. </head>
  3190. <body id="error-page">
  3191. <?php endif; // ! did_action( 'admin_head' ) ?>
  3192. <?php echo $message; ?>
  3193. </body>
  3194. </html>
  3195. <?php
  3196. if ( $parsed_args['exit'] ) {
  3197. die();
  3198. }
  3199. }
  3200. /**
  3201. * Kills WordPress execution and displays Ajax response with an error message.
  3202. *
  3203. * This is the handler for wp_die() when processing Ajax requests.
  3204. *
  3205. * @since 3.4.0
  3206. * @access private
  3207. *
  3208. * @param string $message Error message.
  3209. * @param string $title Optional. Error title (unused). Default empty.
  3210. * @param string|array $args Optional. Arguments to control behavior. Default empty array.
  3211. */
  3212. function _ajax_wp_die_handler( $message, $title = '', $args = array() ) {
  3213. // Set default 'response' to 200 for AJAX requests.
  3214. $args = wp_parse_args(
  3215. $args,
  3216. array( 'response' => 200 )
  3217. );
  3218. list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args );
  3219. if ( ! headers_sent() ) {
  3220. // This is intentional. For backward-compatibility, support passing null here.
  3221. if ( null !== $args['response'] ) {
  3222. status_header( $parsed_args['response'] );
  3223. }
  3224. nocache_headers();
  3225. }
  3226. if ( is_scalar( $message ) ) {
  3227. $message = (string) $message;
  3228. } else {
  3229. $message = '0';
  3230. }
  3231. if ( $parsed_args['exit'] ) {
  3232. die( $message );
  3233. }
  3234. echo $message;
  3235. }
  3236. /**
  3237. * Kills WordPress execution and displays JSON response with an error message.
  3238. *
  3239. * This is the handler for wp_die() when processing JSON requests.
  3240. *
  3241. * @since 5.1.0
  3242. * @access private
  3243. *
  3244. * @param string $message Error message.
  3245. * @param string $title Optional. Error title. Default empty.
  3246. * @param string|array $args Optional. Arguments to control behavior. Default empty array.
  3247. */
  3248. function _json_wp_die_handler( $message, $title = '', $args = array() ) {
  3249. list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args );
  3250. $data = array(
  3251. 'code' => $parsed_args['code'],
  3252. 'message' => $message,
  3253. 'data' => array(
  3254. 'status' => $parsed_args['response'],
  3255. ),
  3256. 'additional_errors' => $parsed_args['additional_errors'],
  3257. );
  3258. if ( ! headers_sent() ) {
  3259. header( "Content-Type: application/json; charset={$parsed_args['charset']}" );
  3260. if ( null !== $parsed_args['response'] ) {
  3261. status_header( $parsed_args['response'] );
  3262. }
  3263. nocache_headers();
  3264. }
  3265. echo wp_json_encode( $data );
  3266. if ( $parsed_args['exit'] ) {
  3267. die();
  3268. }
  3269. }
  3270. /**
  3271. * Kills WordPress execution and displays JSONP response with an error message.
  3272. *
  3273. * This is the handler for wp_die() when processing JSONP requests.
  3274. *
  3275. * @since 5.2.0
  3276. * @access private
  3277. *
  3278. * @param string $message Error message.
  3279. * @param string $title Optional. Error title. Default empty.
  3280. * @param string|array $args Optional. Arguments to control behavior. Default empty array.
  3281. */
  3282. function _jsonp_wp_die_handler( $message, $title = '', $args = array() ) {
  3283. list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args );
  3284. $data = array(
  3285. 'code' => $parsed_args['code'],
  3286. 'message' => $message,
  3287. 'data' => array(
  3288. 'status' => $parsed_args['response'],
  3289. ),
  3290. 'additional_errors' => $parsed_args['additional_errors'],
  3291. );
  3292. if ( ! headers_sent() ) {
  3293. header( "Content-Type: application/javascript; charset={$parsed_args['charset']}" );
  3294. header( 'X-Content-Type-Options: nosniff' );
  3295. header( 'X-Robots-Tag: noindex' );
  3296. if ( null !== $parsed_args['response'] ) {
  3297. status_header( $parsed_args['response'] );
  3298. }
  3299. nocache_headers();
  3300. }
  3301. $result = wp_json_encode( $data );
  3302. $jsonp_callback = $_GET['_jsonp'];
  3303. echo '/**/' . $jsonp_callback . '(' . $result . ')';
  3304. if ( $parsed_args['exit'] ) {
  3305. die();
  3306. }
  3307. }
  3308. /**
  3309. * Kills WordPress execution and displays XML response with an error message.
  3310. *
  3311. * This is the handler for wp_die() when processing XMLRPC requests.
  3312. *
  3313. * @since 3.2.0
  3314. * @access private
  3315. *
  3316. * @global wp_xmlrpc_server $wp_xmlrpc_server
  3317. *
  3318. * @param string $message Error message.
  3319. * @param string $title Optional. Error title. Default empty.
  3320. * @param string|array $args Optional. Arguments to control behavior. Default empty array.
  3321. */
  3322. function _xmlrpc_wp_die_handler( $message, $title = '', $args = array() ) {
  3323. global $wp_xmlrpc_server;
  3324. list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args );
  3325. if ( ! headers_sent() ) {
  3326. nocache_headers();
  3327. }
  3328. if ( $wp_xmlrpc_server ) {
  3329. $error = new IXR_Error( $parsed_args['response'], $message );
  3330. $wp_xmlrpc_server->output( $error->getXml() );
  3331. }
  3332. if ( $parsed_args['exit'] ) {
  3333. die();
  3334. }
  3335. }
  3336. /**
  3337. * Kills WordPress execution and displays XML response with an error message.
  3338. *
  3339. * This is the handler for wp_die() when processing XML requests.
  3340. *
  3341. * @since 5.2.0
  3342. * @access private
  3343. *
  3344. * @param string $message Error message.
  3345. * @param string $title Optional. Error title. Default empty.
  3346. * @param string|array $args Optional. Arguments to control behavior. Default empty array.
  3347. */
  3348. function _xml_wp_die_handler( $message, $title = '', $args = array() ) {
  3349. list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args );
  3350. $message = htmlspecialchars( $message );
  3351. $title = htmlspecialchars( $title );
  3352. $xml = <<<EOD
  3353. <error>
  3354. <code>{$parsed_args['code']}</code>
  3355. <title><![CDATA[{$title}]]></title>
  3356. <message><![CDATA[{$message}]]></message>
  3357. <data>
  3358. <status>{$parsed_args['response']}</status>
  3359. </data>
  3360. </error>
  3361. EOD;
  3362. if ( ! headers_sent() ) {
  3363. header( "Content-Type: text/xml; charset={$parsed_args['charset']}" );
  3364. if ( null !== $parsed_args['response'] ) {
  3365. status_header( $parsed_args['response'] );
  3366. }
  3367. nocache_headers();
  3368. }
  3369. echo $xml;
  3370. if ( $parsed_args['exit'] ) {
  3371. die();
  3372. }
  3373. }
  3374. /**
  3375. * Kills WordPress execution and displays an error message.
  3376. *
  3377. * This is the handler for wp_die() when processing APP requests.
  3378. *
  3379. * @since 3.4.0
  3380. * @since 5.1.0 Added the $title and $args parameters.
  3381. * @access private
  3382. *
  3383. * @param string $message Optional. Response to print. Default empty.
  3384. * @param string $title Optional. Error title (unused). Default empty.
  3385. * @param string|array $args Optional. Arguments to control behavior. Default empty array.
  3386. */
  3387. function _scalar_wp_die_handler( $message = '', $title = '', $args = array() ) {
  3388. list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args );
  3389. if ( $parsed_args['exit'] ) {
  3390. if ( is_scalar( $message ) ) {
  3391. die( (string) $message );
  3392. }
  3393. die();
  3394. }
  3395. if ( is_scalar( $message ) ) {
  3396. echo (string) $message;
  3397. }
  3398. }
  3399. /**
  3400. * Processes arguments passed to wp_die() consistently for its handlers.
  3401. *
  3402. * @since 5.1.0
  3403. * @access private
  3404. *
  3405. * @param string|WP_Error $message Error message or WP_Error object.
  3406. * @param string $title Optional. Error title. Default empty.
  3407. * @param string|array $args Optional. Arguments to control behavior. Default empty array.
  3408. * @return array {
  3409. * Processed arguments.
  3410. *
  3411. * @type string $0 Error message.
  3412. * @type string $1 Error title.
  3413. * @type array $2 Arguments to control behavior.
  3414. * }
  3415. */
  3416. function _wp_die_process_input( $message, $title = '', $args = array() ) {
  3417. $defaults = array(
  3418. 'response' => 0,
  3419. 'code' => '',
  3420. 'exit' => true,
  3421. 'back_link' => false,
  3422. 'link_url' => '',
  3423. 'link_text' => '',
  3424. 'text_direction' => '',
  3425. 'charset' => 'utf-8',
  3426. 'additional_errors' => array(),
  3427. );
  3428. $args = wp_parse_args( $args, $defaults );
  3429. if ( function_exists( 'is_wp_error' ) && is_wp_error( $message ) ) {
  3430. if ( ! empty( $message->errors ) ) {
  3431. $errors = array();
  3432. foreach ( (array) $message->errors as $error_code => $error_messages ) {
  3433. foreach ( (array) $error_messages as $error_message ) {
  3434. $errors[] = array(
  3435. 'code' => $error_code,
  3436. 'message' => $error_message,
  3437. 'data' => $message->get_error_data( $error_code ),
  3438. );
  3439. }
  3440. }
  3441. $message = $errors[0]['message'];
  3442. if ( empty( $args['code'] ) ) {
  3443. $args['code'] = $errors[0]['code'];
  3444. }
  3445. if ( empty( $args['response'] ) && is_array( $errors[0]['data'] ) && ! empty( $errors[0]['data']['status'] ) ) {
  3446. $args['response'] = $errors[0]['data']['status'];
  3447. }
  3448. if ( empty( $title ) && is_array( $errors[0]['data'] ) && ! empty( $errors[0]['data']['title'] ) ) {
  3449. $title = $errors[0]['data']['title'];
  3450. }
  3451. unset( $errors[0] );
  3452. $args['additional_errors'] = array_values( $errors );
  3453. } else {
  3454. $message = '';
  3455. }
  3456. }
  3457. $have_gettext = function_exists( '__' );
  3458. // The $title and these specific $args must always have a non-empty value.
  3459. if ( empty( $args['code'] ) ) {
  3460. $args['code'] = 'wp_die';
  3461. }
  3462. if ( empty( $args['response'] ) ) {
  3463. $args['response'] = 500;
  3464. }
  3465. if ( empty( $title ) ) {
  3466. $title = $have_gettext ? __( 'WordPress &rsaquo; Error' ) : 'WordPress &rsaquo; Error';
  3467. }
  3468. if ( empty( $args['text_direction'] ) || ! in_array( $args['text_direction'], array( 'ltr', 'rtl' ), true ) ) {
  3469. $args['text_direction'] = 'ltr';
  3470. if ( function_exists( 'is_rtl' ) && is_rtl() ) {
  3471. $args['text_direction'] = 'rtl';
  3472. }
  3473. }
  3474. if ( ! empty( $args['charset'] ) ) {
  3475. $args['charset'] = _canonical_charset( $args['charset'] );
  3476. }
  3477. return array( $message, $title, $args );
  3478. }
  3479. /**
  3480. * Encode a variable into JSON, with some sanity checks.
  3481. *
  3482. * @since 4.1.0
  3483. * @since 5.3.0 No longer handles support for PHP < 5.6.
  3484. *
  3485. * @param mixed $data Variable (usually an array or object) to encode as JSON.
  3486. * @param int $options Optional. Options to be passed to json_encode(). Default 0.
  3487. * @param int $depth Optional. Maximum depth to walk through $data. Must be
  3488. * greater than 0. Default 512.
  3489. * @return string|false The JSON encoded string, or false if it cannot be encoded.
  3490. */
  3491. function wp_json_encode( $data, $options = 0, $depth = 512 ) {
  3492. $json = json_encode( $data, $options, $depth );
  3493. // If json_encode() was successful, no need to do more sanity checking.
  3494. if ( false !== $json ) {
  3495. return $json;
  3496. }
  3497. try {
  3498. $data = _wp_json_sanity_check( $data, $depth );
  3499. } catch ( Exception $e ) {
  3500. return false;
  3501. }
  3502. return json_encode( $data, $options, $depth );
  3503. }
  3504. /**
  3505. * Perform sanity checks on data that shall be encoded to JSON.
  3506. *
  3507. * @ignore
  3508. * @since 4.1.0
  3509. * @access private
  3510. *
  3511. * @see wp_json_encode()
  3512. *
  3513. * @throws Exception If depth limit is reached.
  3514. *
  3515. * @param mixed $data Variable (usually an array or object) to encode as JSON.
  3516. * @param int $depth Maximum depth to walk through $data. Must be greater than 0.
  3517. * @return mixed The sanitized data that shall be encoded to JSON.
  3518. */
  3519. function _wp_json_sanity_check( $data, $depth ) {
  3520. if ( $depth < 0 ) {
  3521. throw new Exception( 'Reached depth limit' );
  3522. }
  3523. if ( is_array( $data ) ) {
  3524. $output = array();
  3525. foreach ( $data as $id => $el ) {
  3526. // Don't forget to sanitize the ID!
  3527. if ( is_string( $id ) ) {
  3528. $clean_id = _wp_json_convert_string( $id );
  3529. } else {
  3530. $clean_id = $id;
  3531. }
  3532. // Check the element type, so that we're only recursing if we really have to.
  3533. if ( is_array( $el ) || is_object( $el ) ) {
  3534. $output[ $clean_id ] = _wp_json_sanity_check( $el, $depth - 1 );
  3535. } elseif ( is_string( $el ) ) {
  3536. $output[ $clean_id ] = _wp_json_convert_string( $el );
  3537. } else {
  3538. $output[ $clean_id ] = $el;
  3539. }
  3540. }
  3541. } elseif ( is_object( $data ) ) {
  3542. $output = new stdClass;
  3543. foreach ( $data as $id => $el ) {
  3544. if ( is_string( $id ) ) {
  3545. $clean_id = _wp_json_convert_string( $id );
  3546. } else {
  3547. $clean_id = $id;
  3548. }
  3549. if ( is_array( $el ) || is_object( $el ) ) {
  3550. $output->$clean_id = _wp_json_sanity_check( $el, $depth - 1 );
  3551. } elseif ( is_string( $el ) ) {
  3552. $output->$clean_id = _wp_json_convert_string( $el );
  3553. } else {
  3554. $output->$clean_id = $el;
  3555. }
  3556. }
  3557. } elseif ( is_string( $data ) ) {
  3558. return _wp_json_convert_string( $data );
  3559. } else {
  3560. return $data;
  3561. }
  3562. return $output;
  3563. }
  3564. /**
  3565. * Convert a string to UTF-8, so that it can be safely encoded to JSON.
  3566. *
  3567. * @ignore
  3568. * @since 4.1.0
  3569. * @access private
  3570. *
  3571. * @see _wp_json_sanity_check()
  3572. *
  3573. * @staticvar bool $use_mb
  3574. *
  3575. * @param string $string The string which is to be converted.
  3576. * @return string The checked string.
  3577. */
  3578. function _wp_json_convert_string( $string ) {
  3579. static $use_mb = null;
  3580. if ( is_null( $use_mb ) ) {
  3581. $use_mb = function_exists( 'mb_convert_encoding' );
  3582. }
  3583. if ( $use_mb ) {
  3584. $encoding = mb_detect_encoding( $string, mb_detect_order(), true );
  3585. if ( $encoding ) {
  3586. return mb_convert_encoding( $string, 'UTF-8', $encoding );
  3587. } else {
  3588. return mb_convert_encoding( $string, 'UTF-8', 'UTF-8' );
  3589. }
  3590. } else {
  3591. return wp_check_invalid_utf8( $string, true );
  3592. }
  3593. }
  3594. /**
  3595. * Prepares response data to be serialized to JSON.
  3596. *
  3597. * This supports the JsonSerializable interface for PHP 5.2-5.3 as well.
  3598. *
  3599. * @ignore
  3600. * @since 4.4.0
  3601. * @deprecated 5.3.0 This function is no longer needed as support for PHP 5.2-5.3
  3602. * has been dropped.
  3603. * @access private
  3604. *
  3605. * @param mixed $data Native representation.
  3606. * @return bool|int|float|null|string|array Data ready for `json_encode()`.
  3607. */
  3608. function _wp_json_prepare_data( $data ) {
  3609. _deprecated_function( __FUNCTION__, '5.3.0' );
  3610. return $data;
  3611. }
  3612. /**
  3613. * Send a JSON response back to an Ajax request.
  3614. *
  3615. * @since 3.5.0
  3616. * @since 4.7.0 The `$status_code` parameter was added.
  3617. *
  3618. * @param mixed $response Variable (usually an array or object) to encode as JSON,
  3619. * then print and die.
  3620. * @param int $status_code The HTTP status code to output.
  3621. */
  3622. function wp_send_json( $response, $status_code = null ) {
  3623. if ( ! headers_sent() ) {
  3624. header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );
  3625. if ( null !== $status_code ) {
  3626. status_header( $status_code );
  3627. }
  3628. }
  3629. echo wp_json_encode( $response );
  3630. if ( wp_doing_ajax() ) {
  3631. wp_die(
  3632. '',
  3633. '',
  3634. array(
  3635. 'response' => null,
  3636. )
  3637. );
  3638. } else {
  3639. die;
  3640. }
  3641. }
  3642. /**
  3643. * Send a JSON response back to an Ajax request, indicating success.
  3644. *
  3645. * @since 3.5.0
  3646. * @since 4.7.0 The `$status_code` parameter was added.
  3647. *
  3648. * @param mixed $data Data to encode as JSON, then print and die.
  3649. * @param int $status_code The HTTP status code to output.
  3650. */
  3651. function wp_send_json_success( $data = null, $status_code = null ) {
  3652. $response = array( 'success' => true );
  3653. if ( isset( $data ) ) {
  3654. $response['data'] = $data;
  3655. }
  3656. wp_send_json( $response, $status_code );
  3657. }
  3658. /**
  3659. * Send a JSON response back to an Ajax request, indicating failure.
  3660. *
  3661. * If the `$data` parameter is a WP_Error object, the errors
  3662. * within the object are processed and output as an array of error
  3663. * codes and corresponding messages. All other types are output
  3664. * without further processing.
  3665. *
  3666. * @since 3.5.0
  3667. * @since 4.1.0 The `$data` parameter is now processed if a WP_Error object is passed in.
  3668. * @since 4.7.0 The `$status_code` parameter was added.
  3669. *
  3670. * @param mixed $data Data to encode as JSON, then print and die.
  3671. * @param int $status_code The HTTP status code to output.
  3672. */
  3673. function wp_send_json_error( $data = null, $status_code = null ) {
  3674. $response = array( 'success' => false );
  3675. if ( isset( $data ) ) {
  3676. if ( is_wp_error( $data ) ) {
  3677. $result = array();
  3678. foreach ( $data->errors as $code => $messages ) {
  3679. foreach ( $messages as $message ) {
  3680. $result[] = array(
  3681. 'code' => $code,
  3682. 'message' => $message,
  3683. );
  3684. }
  3685. }
  3686. $response['data'] = $result;
  3687. } else {
  3688. $response['data'] = $data;
  3689. }
  3690. }
  3691. wp_send_json( $response, $status_code );
  3692. }
  3693. /**
  3694. * Checks that a JSONP callback is a valid JavaScript callback.
  3695. *
  3696. * Only allows alphanumeric characters and the dot character in callback
  3697. * function names. This helps to mitigate XSS attacks caused by directly
  3698. * outputting user input.
  3699. *
  3700. * @since 4.6.0
  3701. *
  3702. * @param string $callback Supplied JSONP callback function.
  3703. * @return bool True if valid callback, otherwise false.
  3704. */
  3705. function wp_check_jsonp_callback( $callback ) {
  3706. if ( ! is_string( $callback ) ) {
  3707. return false;
  3708. }
  3709. preg_replace( '/[^\w\.]/', '', $callback, -1, $illegal_char_count );
  3710. return 0 === $illegal_char_count;
  3711. }
  3712. /**
  3713. * Retrieve the WordPress home page URL.
  3714. *
  3715. * If the constant named 'WP_HOME' exists, then it will be used and returned
  3716. * by the function. This can be used to counter the redirection on your local
  3717. * development environment.
  3718. *
  3719. * @since 2.2.0
  3720. * @access private
  3721. *
  3722. * @see WP_HOME
  3723. *
  3724. * @param string $url URL for the home location.
  3725. * @return string Homepage location.
  3726. */
  3727. function _config_wp_home( $url = '' ) {
  3728. if ( defined( 'WP_HOME' ) ) {
  3729. return untrailingslashit( WP_HOME );
  3730. }
  3731. return $url;
  3732. }
  3733. /**
  3734. * Retrieve the WordPress site URL.
  3735. *
  3736. * If the constant named 'WP_SITEURL' is defined, then the value in that
  3737. * constant will always be returned. This can be used for debugging a site
  3738. * on your localhost while not having to change the database to your URL.
  3739. *
  3740. * @since 2.2.0
  3741. * @access private
  3742. *
  3743. * @see WP_SITEURL
  3744. *
  3745. * @param string $url URL to set the WordPress site location.
  3746. * @return string The WordPress Site URL.
  3747. */
  3748. function _config_wp_siteurl( $url = '' ) {
  3749. if ( defined( 'WP_SITEURL' ) ) {
  3750. return untrailingslashit( WP_SITEURL );
  3751. }
  3752. return $url;
  3753. }
  3754. /**
  3755. * Delete the fresh site option.
  3756. *
  3757. * @since 4.7.0
  3758. * @access private
  3759. */
  3760. function _delete_option_fresh_site() {
  3761. update_option( 'fresh_site', '0' );
  3762. }
  3763. /**
  3764. * Set the localized direction for MCE plugin.
  3765. *
  3766. * Will only set the direction to 'rtl', if the WordPress locale has
  3767. * the text direction set to 'rtl'.
  3768. *
  3769. * Fills in the 'directionality' setting, enables the 'directionality'
  3770. * plugin, and adds the 'ltr' button to 'toolbar1', formerly
  3771. * 'theme_advanced_buttons1' array keys. These keys are then returned
  3772. * in the $mce_init (TinyMCE settings) array.
  3773. *
  3774. * @since 2.1.0
  3775. * @access private
  3776. *
  3777. * @param array $mce_init MCE settings array.
  3778. * @return array Direction set for 'rtl', if needed by locale.
  3779. */
  3780. function _mce_set_direction( $mce_init ) {
  3781. if ( is_rtl() ) {
  3782. $mce_init['directionality'] = 'rtl';
  3783. $mce_init['rtl_ui'] = true;
  3784. if ( ! empty( $mce_init['plugins'] ) && strpos( $mce_init['plugins'], 'directionality' ) === false ) {
  3785. $mce_init['plugins'] .= ',directionality';
  3786. }
  3787. if ( ! empty( $mce_init['toolbar1'] ) && ! preg_match( '/\bltr\b/', $mce_init['toolbar1'] ) ) {
  3788. $mce_init['toolbar1'] .= ',ltr';
  3789. }
  3790. }
  3791. return $mce_init;
  3792. }
  3793. /**
  3794. * Convert smiley code to the icon graphic file equivalent.
  3795. *
  3796. * You can turn off smilies, by going to the write setting screen and unchecking
  3797. * the box, or by setting 'use_smilies' option to false or removing the option.
  3798. *
  3799. * Plugins may override the default smiley list by setting the $wpsmiliestrans
  3800. * to an array, with the key the code the blogger types in and the value the
  3801. * image file.
  3802. *
  3803. * The $wp_smiliessearch global is for the regular expression and is set each
  3804. * time the function is called.
  3805. *
  3806. * The full list of smilies can be found in the function and won't be listed in
  3807. * the description. Probably should create a Codex page for it, so that it is
  3808. * available.
  3809. *
  3810. * @global array $wpsmiliestrans
  3811. * @global array $wp_smiliessearch
  3812. *
  3813. * @since 2.2.0
  3814. */
  3815. function smilies_init() {
  3816. global $wpsmiliestrans, $wp_smiliessearch;
  3817. // Don't bother setting up smilies if they are disabled.
  3818. if ( ! get_option( 'use_smilies' ) ) {
  3819. return;
  3820. }
  3821. if ( ! isset( $wpsmiliestrans ) ) {
  3822. $wpsmiliestrans = array(
  3823. ':mrgreen:' => 'mrgreen.png',
  3824. ':neutral:' => "\xf0\x9f\x98\x90",
  3825. ':twisted:' => "\xf0\x9f\x98\x88",
  3826. ':arrow:' => "\xe2\x9e\xa1",
  3827. ':shock:' => "\xf0\x9f\x98\xaf",
  3828. ':smile:' => "\xf0\x9f\x99\x82",
  3829. ':???:' => "\xf0\x9f\x98\x95",
  3830. ':cool:' => "\xf0\x9f\x98\x8e",
  3831. ':evil:' => "\xf0\x9f\x91\xbf",
  3832. ':grin:' => "\xf0\x9f\x98\x80",
  3833. ':idea:' => "\xf0\x9f\x92\xa1",
  3834. ':oops:' => "\xf0\x9f\x98\xb3",
  3835. ':razz:' => "\xf0\x9f\x98\x9b",
  3836. ':roll:' => "\xf0\x9f\x99\x84",
  3837. ':wink:' => "\xf0\x9f\x98\x89",
  3838. ':cry:' => "\xf0\x9f\x98\xa5",
  3839. ':eek:' => "\xf0\x9f\x98\xae",
  3840. ':lol:' => "\xf0\x9f\x98\x86",
  3841. ':mad:' => "\xf0\x9f\x98\xa1",
  3842. ':sad:' => "\xf0\x9f\x99\x81",
  3843. '8-)' => "\xf0\x9f\x98\x8e",
  3844. '8-O' => "\xf0\x9f\x98\xaf",
  3845. ':-(' => "\xf0\x9f\x99\x81",
  3846. ':-)' => "\xf0\x9f\x99\x82",
  3847. ':-?' => "\xf0\x9f\x98\x95",
  3848. ':-D' => "\xf0\x9f\x98\x80",
  3849. ':-P' => "\xf0\x9f\x98\x9b",
  3850. ':-o' => "\xf0\x9f\x98\xae",
  3851. ':-x' => "\xf0\x9f\x98\xa1",
  3852. ':-|' => "\xf0\x9f\x98\x90",
  3853. ';-)' => "\xf0\x9f\x98\x89",
  3854. // This one transformation breaks regular text with frequency.
  3855. // '8)' => "\xf0\x9f\x98\x8e",
  3856. '8O' => "\xf0\x9f\x98\xaf",
  3857. ':(' => "\xf0\x9f\x99\x81",
  3858. ':)' => "\xf0\x9f\x99\x82",
  3859. ':?' => "\xf0\x9f\x98\x95",
  3860. ':D' => "\xf0\x9f\x98\x80",
  3861. ':P' => "\xf0\x9f\x98\x9b",
  3862. ':o' => "\xf0\x9f\x98\xae",
  3863. ':x' => "\xf0\x9f\x98\xa1",
  3864. ':|' => "\xf0\x9f\x98\x90",
  3865. ';)' => "\xf0\x9f\x98\x89",
  3866. ':!:' => "\xe2\x9d\x97",
  3867. ':?:' => "\xe2\x9d\x93",
  3868. );
  3869. }
  3870. /**
  3871. * Filters all the smilies.
  3872. *
  3873. * This filter must be added before `smilies_init` is run, as
  3874. * it is normally only run once to setup the smilies regex.
  3875. *
  3876. * @since 4.7.0
  3877. *
  3878. * @param string[] $wpsmiliestrans List of the smilies' hexadecimal representations, keyed by their smily code.
  3879. */
  3880. $wpsmiliestrans = apply_filters( 'smilies', $wpsmiliestrans );
  3881. if ( count( $wpsmiliestrans ) == 0 ) {
  3882. return;
  3883. }
  3884. /*
  3885. * NOTE: we sort the smilies in reverse key order. This is to make sure
  3886. * we match the longest possible smilie (:???: vs :?) as the regular
  3887. * expression used below is first-match
  3888. */
  3889. krsort( $wpsmiliestrans );
  3890. $spaces = wp_spaces_regexp();
  3891. // Begin first "subpattern".
  3892. $wp_smiliessearch = '/(?<=' . $spaces . '|^)';
  3893. $subchar = '';
  3894. foreach ( (array) $wpsmiliestrans as $smiley => $img ) {
  3895. $firstchar = substr( $smiley, 0, 1 );
  3896. $rest = substr( $smiley, 1 );
  3897. // New subpattern?
  3898. if ( $firstchar != $subchar ) {
  3899. if ( '' != $subchar ) {
  3900. $wp_smiliessearch .= ')(?=' . $spaces . '|$)'; // End previous "subpattern".
  3901. $wp_smiliessearch .= '|(?<=' . $spaces . '|^)'; // Begin another "subpattern".
  3902. }
  3903. $subchar = $firstchar;
  3904. $wp_smiliessearch .= preg_quote( $firstchar, '/' ) . '(?:';
  3905. } else {
  3906. $wp_smiliessearch .= '|';
  3907. }
  3908. $wp_smiliessearch .= preg_quote( $rest, '/' );
  3909. }
  3910. $wp_smiliessearch .= ')(?=' . $spaces . '|$)/m';
  3911. }
  3912. /**
  3913. * Merge user defined arguments into defaults array.
  3914. *
  3915. * This function is used throughout WordPress to allow for both string or array
  3916. * to be merged into another array.
  3917. *
  3918. * @since 2.2.0
  3919. * @since 2.3.0 `$args` can now also be an object.
  3920. *
  3921. * @param string|array|object $args Value to merge with $defaults.
  3922. * @param array $defaults Optional. Array that serves as the defaults.
  3923. * Default empty array.
  3924. * @return array Merged user defined values with defaults.
  3925. */
  3926. function wp_parse_args( $args, $defaults = array() ) {
  3927. if ( is_object( $args ) ) {
  3928. $parsed_args = get_object_vars( $args );
  3929. } elseif ( is_array( $args ) ) {
  3930. $parsed_args =& $args;
  3931. } else {
  3932. wp_parse_str( $args, $parsed_args );
  3933. }
  3934. if ( is_array( $defaults ) && $defaults ) {
  3935. return array_merge( $defaults, $parsed_args );
  3936. }
  3937. return $parsed_args;
  3938. }
  3939. /**
  3940. * Cleans up an array, comma- or space-separated list of scalar values.
  3941. *
  3942. * @since 5.1.0
  3943. *
  3944. * @param array|string $list List of values.
  3945. * @return array Sanitized array of values.
  3946. */
  3947. function wp_parse_list( $list ) {
  3948. if ( ! is_array( $list ) ) {
  3949. return preg_split( '/[\s,]+/', $list, -1, PREG_SPLIT_NO_EMPTY );
  3950. }
  3951. return $list;
  3952. }
  3953. /**
  3954. * Clean up an array, comma- or space-separated list of IDs.
  3955. *
  3956. * @since 3.0.0
  3957. *
  3958. * @param array|string $list List of ids.
  3959. * @return int[] Sanitized array of IDs.
  3960. */
  3961. function wp_parse_id_list( $list ) {
  3962. $list = wp_parse_list( $list );
  3963. return array_unique( array_map( 'absint', $list ) );
  3964. }
  3965. /**
  3966. * Clean up an array, comma- or space-separated list of slugs.
  3967. *
  3968. * @since 4.7.0
  3969. *
  3970. * @param array|string $list List of slugs.
  3971. * @return string[] Sanitized array of slugs.
  3972. */
  3973. function wp_parse_slug_list( $list ) {
  3974. $list = wp_parse_list( $list );
  3975. return array_unique( array_map( 'sanitize_title', $list ) );
  3976. }
  3977. /**
  3978. * Extract a slice of an array, given a list of keys.
  3979. *
  3980. * @since 3.1.0
  3981. *
  3982. * @param array $array The original array.
  3983. * @param array $keys The list of keys.
  3984. * @return array The array slice.
  3985. */
  3986. function wp_array_slice_assoc( $array, $keys ) {
  3987. $slice = array();
  3988. foreach ( $keys as $key ) {
  3989. if ( isset( $array[ $key ] ) ) {
  3990. $slice[ $key ] = $array[ $key ];
  3991. }
  3992. }
  3993. return $slice;
  3994. }
  3995. /**
  3996. * Determines if the variable is a numeric-indexed array.
  3997. *
  3998. * @since 4.4.0
  3999. *
  4000. * @param mixed $data Variable to check.
  4001. * @return bool Whether the variable is a list.
  4002. */
  4003. function wp_is_numeric_array( $data ) {
  4004. if ( ! is_array( $data ) ) {
  4005. return false;
  4006. }
  4007. $keys = array_keys( $data );
  4008. $string_keys = array_filter( $keys, 'is_string' );
  4009. return count( $string_keys ) === 0;
  4010. }
  4011. /**
  4012. * Filters a list of objects, based on a set of key => value arguments.
  4013. *
  4014. * @since 3.0.0
  4015. * @since 4.7.0 Uses `WP_List_Util` class.
  4016. *
  4017. * @param array $list An array of objects to filter
  4018. * @param array $args Optional. An array of key => value arguments to match
  4019. * against each object. Default empty array.
  4020. * @param string $operator Optional. The logical operation to perform. 'or' means
  4021. * only one element from the array needs to match; 'and'
  4022. * means all elements must match; 'not' means no elements may
  4023. * match. Default 'and'.
  4024. * @param bool|string $field A field from the object to place instead of the entire object.
  4025. * Default false.
  4026. * @return array A list of objects or object fields.
  4027. */
  4028. function wp_filter_object_list( $list, $args = array(), $operator = 'and', $field = false ) {
  4029. if ( ! is_array( $list ) ) {
  4030. return array();
  4031. }
  4032. $util = new WP_List_Util( $list );
  4033. $util->filter( $args, $operator );
  4034. if ( $field ) {
  4035. $util->pluck( $field );
  4036. }
  4037. return $util->get_output();
  4038. }
  4039. /**
  4040. * Filters a list of objects, based on a set of key => value arguments.
  4041. *
  4042. * @since 3.1.0
  4043. * @since 4.7.0 Uses `WP_List_Util` class.
  4044. *
  4045. * @param array $list An array of objects to filter.
  4046. * @param array $args Optional. An array of key => value arguments to match
  4047. * against each object. Default empty array.
  4048. * @param string $operator Optional. The logical operation to perform. 'AND' means
  4049. * all elements from the array must match. 'OR' means only
  4050. * one element needs to match. 'NOT' means no elements may
  4051. * match. Default 'AND'.
  4052. * @return array Array of found values.
  4053. */
  4054. function wp_list_filter( $list, $args = array(), $operator = 'AND' ) {
  4055. if ( ! is_array( $list ) ) {
  4056. return array();
  4057. }
  4058. $util = new WP_List_Util( $list );
  4059. return $util->filter( $args, $operator );
  4060. }
  4061. /**
  4062. * Pluck a certain field out of each object in a list.
  4063. *
  4064. * This has the same functionality and prototype of
  4065. * array_column() (PHP 5.5) but also supports objects.
  4066. *
  4067. * @since 3.1.0
  4068. * @since 4.0.0 $index_key parameter added.
  4069. * @since 4.7.0 Uses `WP_List_Util` class.
  4070. *
  4071. * @param array $list List of objects or arrays
  4072. * @param int|string $field Field from the object to place instead of the entire object
  4073. * @param int|string $index_key Optional. Field from the object to use as keys for the new array.
  4074. * Default null.
  4075. * @return array Array of found values. If `$index_key` is set, an array of found values with keys
  4076. * corresponding to `$index_key`. If `$index_key` is null, array keys from the original
  4077. * `$list` will be preserved in the results.
  4078. */
  4079. function wp_list_pluck( $list, $field, $index_key = null ) {
  4080. $util = new WP_List_Util( $list );
  4081. return $util->pluck( $field, $index_key );
  4082. }
  4083. /**
  4084. * Sorts a list of objects, based on one or more orderby arguments.
  4085. *
  4086. * @since 4.7.0
  4087. *
  4088. * @param array $list An array of objects to sort.
  4089. * @param string|array $orderby Optional. Either the field name to order by or an array
  4090. * of multiple orderby fields as $orderby => $order.
  4091. * @param string $order Optional. Either 'ASC' or 'DESC'. Only used if $orderby
  4092. * is a string.
  4093. * @param bool $preserve_keys Optional. Whether to preserve keys. Default false.
  4094. * @return array The sorted array.
  4095. */
  4096. function wp_list_sort( $list, $orderby = array(), $order = 'ASC', $preserve_keys = false ) {
  4097. if ( ! is_array( $list ) ) {
  4098. return array();
  4099. }
  4100. $util = new WP_List_Util( $list );
  4101. return $util->sort( $orderby, $order, $preserve_keys );
  4102. }
  4103. /**
  4104. * Determines if Widgets library should be loaded.
  4105. *
  4106. * Checks to make sure that the widgets library hasn't already been loaded.
  4107. * If it hasn't, then it will load the widgets library and run an action hook.
  4108. *
  4109. * @since 2.2.0
  4110. */
  4111. function wp_maybe_load_widgets() {
  4112. /**
  4113. * Filters whether to load the Widgets library.
  4114. *
  4115. * Passing a falsey value to the filter will effectively short-circuit
  4116. * the Widgets library from loading.
  4117. *
  4118. * @since 2.8.0
  4119. *
  4120. * @param bool $wp_maybe_load_widgets Whether to load the Widgets library.
  4121. * Default true.
  4122. */
  4123. if ( ! apply_filters( 'load_default_widgets', true ) ) {
  4124. return;
  4125. }
  4126. require_once ABSPATH . WPINC . '/default-widgets.php';
  4127. add_action( '_admin_menu', 'wp_widgets_add_menu' );
  4128. }
  4129. /**
  4130. * Append the Widgets menu to the themes main menu.
  4131. *
  4132. * @since 2.2.0
  4133. *
  4134. * @global array $submenu
  4135. */
  4136. function wp_widgets_add_menu() {
  4137. global $submenu;
  4138. if ( ! current_theme_supports( 'widgets' ) ) {
  4139. return;
  4140. }
  4141. $submenu['themes.php'][7] = array( __( 'Widgets' ), 'edit_theme_options', 'widgets.php' );
  4142. ksort( $submenu['themes.php'], SORT_NUMERIC );
  4143. }
  4144. /**
  4145. * Flush all output buffers for PHP 5.2.
  4146. *
  4147. * Make sure all output buffers are flushed before our singletons are destroyed.
  4148. *
  4149. * @since 2.2.0
  4150. */
  4151. function wp_ob_end_flush_all() {
  4152. $levels = ob_get_level();
  4153. for ( $i = 0; $i < $levels; $i++ ) {
  4154. ob_end_flush();
  4155. }
  4156. }
  4157. /**
  4158. * Load custom DB error or display WordPress DB error.
  4159. *
  4160. * If a file exists in the wp-content directory named db-error.php, then it will
  4161. * be loaded instead of displaying the WordPress DB error. If it is not found,
  4162. * then the WordPress DB error will be displayed instead.
  4163. *
  4164. * The WordPress DB error sets the HTTP status header to 500 to try to prevent
  4165. * search engines from caching the message. Custom DB messages should do the
  4166. * same.
  4167. *
  4168. * This function was backported to WordPress 2.3.2, but originally was added
  4169. * in WordPress 2.5.0.
  4170. *
  4171. * @since 2.3.2
  4172. *
  4173. * @global wpdb $wpdb WordPress database abstraction object.
  4174. */
  4175. function dead_db() {
  4176. global $wpdb;
  4177. wp_load_translations_early();
  4178. // Load custom DB error template, if present.
  4179. if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
  4180. require_once WP_CONTENT_DIR . '/db-error.php';
  4181. die();
  4182. }
  4183. // If installing or in the admin, provide the verbose message.
  4184. if ( wp_installing() || defined( 'WP_ADMIN' ) ) {
  4185. wp_die( $wpdb->error );
  4186. }
  4187. // Otherwise, be terse.
  4188. wp_die( '<h1>' . __( 'Error establishing a database connection' ) . '</h1>', __( 'Database Error' ) );
  4189. }
  4190. /**
  4191. * Convert a value to non-negative integer.
  4192. *
  4193. * @since 2.5.0
  4194. *
  4195. * @param mixed $maybeint Data you wish to have converted to a non-negative integer.
  4196. * @return int A non-negative integer.
  4197. */
  4198. function absint( $maybeint ) {
  4199. return abs( intval( $maybeint ) );
  4200. }
  4201. /**
  4202. * Mark a function as deprecated and inform when it has been used.
  4203. *
  4204. * There is a {@see 'hook deprecated_function_run'} that will be called that can be used
  4205. * to get the backtrace up to what file and function called the deprecated
  4206. * function.
  4207. *
  4208. * The current behavior is to trigger a user error if `WP_DEBUG` is true.
  4209. *
  4210. * This function is to be used in every function that is deprecated.
  4211. *
  4212. * @since 2.5.0
  4213. * @since 5.4.0 This function is no longer marked as "private".
  4214. * @since 5.4.0 The error type is now classified as E_USER_DEPRECATED (used to default to E_USER_NOTICE).
  4215. *
  4216. * @param string $function The function that was called.
  4217. * @param string $version The version of WordPress that deprecated the function.
  4218. * @param string $replacement Optional. The function that should have been called. Default null.
  4219. */
  4220. function _deprecated_function( $function, $version, $replacement = null ) {
  4221. /**
  4222. * Fires when a deprecated function is called.
  4223. *
  4224. * @since 2.5.0
  4225. *
  4226. * @param string $function The function that was called.
  4227. * @param string $replacement The function that should have been called.
  4228. * @param string $version The version of WordPress that deprecated the function.
  4229. */
  4230. do_action( 'deprecated_function_run', $function, $replacement, $version );
  4231. /**
  4232. * Filters whether to trigger an error for deprecated functions.
  4233. *
  4234. * @since 2.5.0
  4235. *
  4236. * @param bool $trigger Whether to trigger the error for deprecated functions. Default true.
  4237. */
  4238. if ( WP_DEBUG && apply_filters( 'deprecated_function_trigger_error', true ) ) {
  4239. if ( function_exists( '__' ) ) {
  4240. if ( ! is_null( $replacement ) ) {
  4241. trigger_error(
  4242. sprintf(
  4243. /* translators: 1: PHP function name, 2: Version number, 3: Alternative function name. */
  4244. __( '%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.' ),
  4245. $function,
  4246. $version,
  4247. $replacement
  4248. ),
  4249. E_USER_DEPRECATED
  4250. );
  4251. } else {
  4252. trigger_error(
  4253. sprintf(
  4254. /* translators: 1: PHP function name, 2: Version number. */
  4255. __( '%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.' ),
  4256. $function,
  4257. $version
  4258. ),
  4259. E_USER_DEPRECATED
  4260. );
  4261. }
  4262. } else {
  4263. if ( ! is_null( $replacement ) ) {
  4264. trigger_error(
  4265. sprintf(
  4266. '%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.',
  4267. $function,
  4268. $version,
  4269. $replacement
  4270. ),
  4271. E_USER_DEPRECATED
  4272. );
  4273. } else {
  4274. trigger_error(
  4275. sprintf(
  4276. '%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.',
  4277. $function,
  4278. $version
  4279. ),
  4280. E_USER_DEPRECATED
  4281. );
  4282. }
  4283. }
  4284. }
  4285. }
  4286. /**
  4287. * Marks a constructor as deprecated and informs when it has been used.
  4288. *
  4289. * Similar to _deprecated_function(), but with different strings. Used to
  4290. * remove PHP4 style constructors.
  4291. *
  4292. * The current behavior is to trigger a user error if `WP_DEBUG` is true.
  4293. *
  4294. * This function is to be used in every PHP4 style constructor method that is deprecated.
  4295. *
  4296. * @since 4.3.0
  4297. * @since 4.5.0 Added the `$parent_class` parameter.
  4298. * @since 5.4.0 This function is no longer marked as "private".
  4299. * @since 5.4.0 The error type is now classified as E_USER_DEPRECATED (used to default to E_USER_NOTICE).
  4300. *
  4301. * @param string $class The class containing the deprecated constructor.
  4302. * @param string $version The version of WordPress that deprecated the function.
  4303. * @param string $parent_class Optional. The parent class calling the deprecated constructor.
  4304. * Default empty string.
  4305. */
  4306. function _deprecated_constructor( $class, $version, $parent_class = '' ) {
  4307. /**
  4308. * Fires when a deprecated constructor is called.
  4309. *
  4310. * @since 4.3.0
  4311. * @since 4.5.0 Added the `$parent_class` parameter.
  4312. *
  4313. * @param string $class The class containing the deprecated constructor.
  4314. * @param string $version The version of WordPress that deprecated the function.
  4315. * @param string $parent_class The parent class calling the deprecated constructor.
  4316. */
  4317. do_action( 'deprecated_constructor_run', $class, $version, $parent_class );
  4318. /**
  4319. * Filters whether to trigger an error for deprecated functions.
  4320. *
  4321. * `WP_DEBUG` must be true in addition to the filter evaluating to true.
  4322. *
  4323. * @since 4.3.0
  4324. *
  4325. * @param bool $trigger Whether to trigger the error for deprecated functions. Default true.
  4326. */
  4327. if ( WP_DEBUG && apply_filters( 'deprecated_constructor_trigger_error', true ) ) {
  4328. if ( function_exists( '__' ) ) {
  4329. if ( ! empty( $parent_class ) ) {
  4330. trigger_error(
  4331. sprintf(
  4332. /* translators: 1: PHP class name, 2: PHP parent class name, 3: Version number, 4: __construct() method. */
  4333. __( 'The called constructor method for %1$s in %2$s is <strong>deprecated</strong> since version %3$s! Use %4$s instead.' ),
  4334. $class,
  4335. $parent_class,
  4336. $version,
  4337. '<code>__construct()</code>'
  4338. ),
  4339. E_USER_DEPRECATED
  4340. );
  4341. } else {
  4342. trigger_error(
  4343. sprintf(
  4344. /* translators: 1: PHP class name, 2: Version number, 3: __construct() method. */
  4345. __( 'The called constructor method for %1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.' ),
  4346. $class,
  4347. $version,
  4348. '<code>__construct()</code>'
  4349. ),
  4350. E_USER_DEPRECATED
  4351. );
  4352. }
  4353. } else {
  4354. if ( ! empty( $parent_class ) ) {
  4355. trigger_error(
  4356. sprintf(
  4357. 'The called constructor method for %1$s in %2$s is <strong>deprecated</strong> since version %3$s! Use %4$s instead.',
  4358. $class,
  4359. $parent_class,
  4360. $version,
  4361. '<code>__construct()</code>'
  4362. ),
  4363. E_USER_DEPRECATED
  4364. );
  4365. } else {
  4366. trigger_error(
  4367. sprintf(
  4368. 'The called constructor method for %1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.',
  4369. $class,
  4370. $version,
  4371. '<code>__construct()</code>'
  4372. ),
  4373. E_USER_DEPRECATED
  4374. );
  4375. }
  4376. }
  4377. }
  4378. }
  4379. /**
  4380. * Mark a file as deprecated and inform when it has been used.
  4381. *
  4382. * There is a hook {@see 'deprecated_file_included'} that will be called that can be used
  4383. * to get the backtrace up to what file and function included the deprecated
  4384. * file.
  4385. *
  4386. * The current behavior is to trigger a user error if `WP_DEBUG` is true.
  4387. *
  4388. * This function is to be used in every file that is deprecated.
  4389. *
  4390. * @since 2.5.0
  4391. * @since 5.4.0 This function is no longer marked as "private".
  4392. * @since 5.4.0 The error type is now classified as E_USER_DEPRECATED (used to default to E_USER_NOTICE).
  4393. *
  4394. * @param string $file The file that was included.
  4395. * @param string $version The version of WordPress that deprecated the file.
  4396. * @param string $replacement Optional. The file that should have been included based on ABSPATH.
  4397. * Default null.
  4398. * @param string $message Optional. A message regarding the change. Default empty.
  4399. */
  4400. function _deprecated_file( $file, $version, $replacement = null, $message = '' ) {
  4401. /**
  4402. * Fires when a deprecated file is called.
  4403. *
  4404. * @since 2.5.0
  4405. *
  4406. * @param string $file The file that was called.
  4407. * @param string $replacement The file that should have been included based on ABSPATH.
  4408. * @param string $version The version of WordPress that deprecated the file.
  4409. * @param string $message A message regarding the change.
  4410. */
  4411. do_action( 'deprecated_file_included', $file, $replacement, $version, $message );
  4412. /**
  4413. * Filters whether to trigger an error for deprecated files.
  4414. *
  4415. * @since 2.5.0
  4416. *
  4417. * @param bool $trigger Whether to trigger the error for deprecated files. Default true.
  4418. */
  4419. if ( WP_DEBUG && apply_filters( 'deprecated_file_trigger_error', true ) ) {
  4420. $message = empty( $message ) ? '' : ' ' . $message;
  4421. if ( function_exists( '__' ) ) {
  4422. if ( ! is_null( $replacement ) ) {
  4423. trigger_error(
  4424. sprintf(
  4425. /* translators: 1: PHP file name, 2: Version number, 3: Alternative file name. */
  4426. __( '%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.' ),
  4427. $file,
  4428. $version,
  4429. $replacement
  4430. ) . $message,
  4431. E_USER_DEPRECATED
  4432. );
  4433. } else {
  4434. trigger_error(
  4435. sprintf(
  4436. /* translators: 1: PHP file name, 2: Version number. */
  4437. __( '%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.' ),
  4438. $file,
  4439. $version
  4440. ) . $message,
  4441. E_USER_DEPRECATED
  4442. );
  4443. }
  4444. } else {
  4445. if ( ! is_null( $replacement ) ) {
  4446. trigger_error(
  4447. sprintf(
  4448. '%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.',
  4449. $file,
  4450. $version,
  4451. $replacement
  4452. ) . $message,
  4453. E_USER_DEPRECATED
  4454. );
  4455. } else {
  4456. trigger_error(
  4457. sprintf(
  4458. '%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.',
  4459. $file,
  4460. $version
  4461. ) . $message,
  4462. E_USER_DEPRECATED
  4463. );
  4464. }
  4465. }
  4466. }
  4467. }
  4468. /**
  4469. * Mark a function argument as deprecated and inform when it has been used.
  4470. *
  4471. * This function is to be used whenever a deprecated function argument is used.
  4472. * Before this function is called, the argument must be checked for whether it was
  4473. * used by comparing it to its default value or evaluating whether it is empty.
  4474. * For example:
  4475. *
  4476. * if ( ! empty( $deprecated ) ) {
  4477. * _deprecated_argument( __FUNCTION__, '3.0.0' );
  4478. * }
  4479. *
  4480. * There is a hook deprecated_argument_run that will be called that can be used
  4481. * to get the backtrace up to what file and function used the deprecated
  4482. * argument.
  4483. *
  4484. * The current behavior is to trigger a user error if WP_DEBUG is true.
  4485. *
  4486. * @since 3.0.0
  4487. * @since 5.4.0 This function is no longer marked as "private".
  4488. * @since 5.4.0 The error type is now classified as E_USER_DEPRECATED (used to default to E_USER_NOTICE).
  4489. *
  4490. * @param string $function The function that was called.
  4491. * @param string $version The version of WordPress that deprecated the argument used.
  4492. * @param string $message Optional. A message regarding the change. Default null.
  4493. */
  4494. function _deprecated_argument( $function, $version, $message = null ) {
  4495. /**
  4496. * Fires when a deprecated argument is called.
  4497. *
  4498. * @since 3.0.0
  4499. *
  4500. * @param string $function The function that was called.
  4501. * @param string $message A message regarding the change.
  4502. * @param string $version The version of WordPress that deprecated the argument used.
  4503. */
  4504. do_action( 'deprecated_argument_run', $function, $message, $version );
  4505. /**
  4506. * Filters whether to trigger an error for deprecated arguments.
  4507. *
  4508. * @since 3.0.0
  4509. *
  4510. * @param bool $trigger Whether to trigger the error for deprecated arguments. Default true.
  4511. */
  4512. if ( WP_DEBUG && apply_filters( 'deprecated_argument_trigger_error', true ) ) {
  4513. if ( function_exists( '__' ) ) {
  4514. if ( ! is_null( $message ) ) {
  4515. trigger_error(
  4516. sprintf(
  4517. /* translators: 1: PHP function name, 2: Version number, 3: Optional message regarding the change. */
  4518. __( '%1$s was called with an argument that is <strong>deprecated</strong> since version %2$s! %3$s' ),
  4519. $function,
  4520. $version,
  4521. $message
  4522. ),
  4523. E_USER_DEPRECATED
  4524. );
  4525. } else {
  4526. trigger_error(
  4527. sprintf(
  4528. /* translators: 1: PHP function name, 2: Version number. */
  4529. __( '%1$s was called with an argument that is <strong>deprecated</strong> since version %2$s with no alternative available.' ),
  4530. $function,
  4531. $version
  4532. ),
  4533. E_USER_DEPRECATED
  4534. );
  4535. }
  4536. } else {
  4537. if ( ! is_null( $message ) ) {
  4538. trigger_error(
  4539. sprintf(
  4540. '%1$s was called with an argument that is <strong>deprecated</strong> since version %2$s! %3$s',
  4541. $function,
  4542. $version,
  4543. $message
  4544. ),
  4545. E_USER_DEPRECATED
  4546. );
  4547. } else {
  4548. trigger_error(
  4549. sprintf(
  4550. '%1$s was called with an argument that is <strong>deprecated</strong> since version %2$s with no alternative available.',
  4551. $function,
  4552. $version
  4553. ),
  4554. E_USER_DEPRECATED
  4555. );
  4556. }
  4557. }
  4558. }
  4559. }
  4560. /**
  4561. * Marks a deprecated action or filter hook as deprecated and throws a notice.
  4562. *
  4563. * Use the {@see 'deprecated_hook_run'} action to get the backtrace describing where
  4564. * the deprecated hook was called.
  4565. *
  4566. * Default behavior is to trigger a user error if `WP_DEBUG` is true.
  4567. *
  4568. * This function is called by the do_action_deprecated() and apply_filters_deprecated()
  4569. * functions, and so generally does not need to be called directly.
  4570. *
  4571. * @since 4.6.0
  4572. * @since 5.4.0 The error type is now classified as E_USER_DEPRECATED (used to default to E_USER_NOTICE).
  4573. * @access private
  4574. *
  4575. * @param string $hook The hook that was used.
  4576. * @param string $version The version of WordPress that deprecated the hook.
  4577. * @param string $replacement Optional. The hook that should have been used. Default null.
  4578. * @param string $message Optional. A message regarding the change. Default null.
  4579. */
  4580. function _deprecated_hook( $hook, $version, $replacement = null, $message = null ) {
  4581. /**
  4582. * Fires when a deprecated hook is called.
  4583. *
  4584. * @since 4.6.0
  4585. *
  4586. * @param string $hook The hook that was called.
  4587. * @param string $replacement The hook that should be used as a replacement.
  4588. * @param string $version The version of WordPress that deprecated the argument used.
  4589. * @param string $message A message regarding the change.
  4590. */
  4591. do_action( 'deprecated_hook_run', $hook, $replacement, $version, $message );
  4592. /**
  4593. * Filters whether to trigger deprecated hook errors.
  4594. *
  4595. * @since 4.6.0
  4596. *
  4597. * @param bool $trigger Whether to trigger deprecated hook errors. Requires
  4598. * `WP_DEBUG` to be defined true.
  4599. */
  4600. if ( WP_DEBUG && apply_filters( 'deprecated_hook_trigger_error', true ) ) {
  4601. $message = empty( $message ) ? '' : ' ' . $message;
  4602. if ( ! is_null( $replacement ) ) {
  4603. trigger_error(
  4604. sprintf(
  4605. /* translators: 1: WordPress hook name, 2: Version number, 3: Alternative hook name. */
  4606. __( '%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.' ),
  4607. $hook,
  4608. $version,
  4609. $replacement
  4610. ) . $message,
  4611. E_USER_DEPRECATED
  4612. );
  4613. } else {
  4614. trigger_error(
  4615. sprintf(
  4616. /* translators: 1: WordPress hook name, 2: Version number. */
  4617. __( '%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.' ),
  4618. $hook,
  4619. $version
  4620. ) . $message,
  4621. E_USER_DEPRECATED
  4622. );
  4623. }
  4624. }
  4625. }
  4626. /**
  4627. * Mark something as being incorrectly called.
  4628. *
  4629. * There is a hook {@see 'doing_it_wrong_run'} that will be called that can be used
  4630. * to get the backtrace up to what file and function called the deprecated
  4631. * function.
  4632. *
  4633. * The current behavior is to trigger a user error if `WP_DEBUG` is true.
  4634. *
  4635. * @since 3.1.0
  4636. * @since 5.4.0 This function is no longer marked as "private".
  4637. *
  4638. * @param string $function The function that was called.
  4639. * @param string $message A message explaining what has been done incorrectly.
  4640. * @param string $version The version of WordPress where the message was added.
  4641. */
  4642. function _doing_it_wrong( $function, $message, $version ) {
  4643. /**
  4644. * Fires when the given function is being used incorrectly.
  4645. *
  4646. * @since 3.1.0
  4647. *
  4648. * @param string $function The function that was called.
  4649. * @param string $message A message explaining what has been done incorrectly.
  4650. * @param string $version The version of WordPress where the message was added.
  4651. */
  4652. do_action( 'doing_it_wrong_run', $function, $message, $version );
  4653. /**
  4654. * Filters whether to trigger an error for _doing_it_wrong() calls.
  4655. *
  4656. * @since 3.1.0
  4657. * @since 5.1.0 Added the $function, $message and $version parameters.
  4658. *
  4659. * @param bool $trigger Whether to trigger the error for _doing_it_wrong() calls. Default true.
  4660. * @param string $function The function that was called.
  4661. * @param string $message A message explaining what has been done incorrectly.
  4662. * @param string $version The version of WordPress where the message was added.
  4663. */
  4664. if ( WP_DEBUG && apply_filters( 'doing_it_wrong_trigger_error', true, $function, $message, $version ) ) {
  4665. if ( function_exists( '__' ) ) {
  4666. if ( is_null( $version ) ) {
  4667. $version = '';
  4668. } else {
  4669. /* translators: %s: Version number. */
  4670. $version = sprintf( __( '(This message was added in version %s.)' ), $version );
  4671. }
  4672. $message .= ' ' . sprintf(
  4673. /* translators: %s: Documentation URL. */
  4674. __( 'Please see <a href="%s">Debugging in WordPress</a> for more information.' ),
  4675. __( 'https://wordpress.org/support/article/debugging-in-wordpress/' )
  4676. );
  4677. trigger_error(
  4678. sprintf(
  4679. /* translators: Developer debugging message. 1: PHP function name, 2: Explanatory message, 3: Version information message. */
  4680. __( '%1$s was called <strong>incorrectly</strong>. %2$s %3$s' ),
  4681. $function,
  4682. $message,
  4683. $version
  4684. ),
  4685. E_USER_NOTICE
  4686. );
  4687. } else {
  4688. if ( is_null( $version ) ) {
  4689. $version = '';
  4690. } else {
  4691. $version = sprintf( '(This message was added in version %s.)', $version );
  4692. }
  4693. $message .= sprintf(
  4694. ' Please see <a href="%s">Debugging in WordPress</a> for more information.',
  4695. 'https://wordpress.org/support/article/debugging-in-wordpress/'
  4696. );
  4697. trigger_error(
  4698. sprintf(
  4699. '%1$s was called <strong>incorrectly</strong>. %2$s %3$s',
  4700. $function,
  4701. $message,
  4702. $version
  4703. ),
  4704. E_USER_NOTICE
  4705. );
  4706. }
  4707. }
  4708. }
  4709. /**
  4710. * Is the server running earlier than 1.5.0 version of lighttpd?
  4711. *
  4712. * @since 2.5.0
  4713. *
  4714. * @return bool Whether the server is running lighttpd < 1.5.0.
  4715. */
  4716. function is_lighttpd_before_150() {
  4717. $server_parts = explode( '/', isset( $_SERVER['SERVER_SOFTWARE'] ) ? $_SERVER['SERVER_SOFTWARE'] : '' );
  4718. $server_parts[1] = isset( $server_parts[1] ) ? $server_parts[1] : '';
  4719. return 'lighttpd' == $server_parts[0] && -1 == version_compare( $server_parts[1], '1.5.0' );
  4720. }
  4721. /**
  4722. * Does the specified module exist in the Apache config?
  4723. *
  4724. * @since 2.5.0
  4725. *
  4726. * @global bool $is_apache
  4727. *
  4728. * @param string $mod The module, e.g. mod_rewrite.
  4729. * @param bool $default Optional. The default return value if the module is not found. Default false.
  4730. * @return bool Whether the specified module is loaded.
  4731. */
  4732. function apache_mod_loaded( $mod, $default = false ) {
  4733. global $is_apache;
  4734. if ( ! $is_apache ) {
  4735. return false;
  4736. }
  4737. if ( function_exists( 'apache_get_modules' ) ) {
  4738. $mods = apache_get_modules();
  4739. if ( in_array( $mod, $mods, true ) ) {
  4740. return true;
  4741. }
  4742. } elseif ( function_exists( 'phpinfo' ) && false === strpos( ini_get( 'disable_functions' ), 'phpinfo' ) ) {
  4743. ob_start();
  4744. phpinfo( 8 );
  4745. $phpinfo = ob_get_clean();
  4746. if ( false !== strpos( $phpinfo, $mod ) ) {
  4747. return true;
  4748. }
  4749. }
  4750. return $default;
  4751. }
  4752. /**
  4753. * Check if IIS 7+ supports pretty permalinks.
  4754. *
  4755. * @since 2.8.0
  4756. *
  4757. * @global bool $is_iis7
  4758. *
  4759. * @return bool Whether IIS7 supports permalinks.
  4760. */
  4761. function iis7_supports_permalinks() {
  4762. global $is_iis7;
  4763. $supports_permalinks = false;
  4764. if ( $is_iis7 ) {
  4765. /* First we check if the DOMDocument class exists. If it does not exist, then we cannot
  4766. * easily update the xml configuration file, hence we just bail out and tell user that
  4767. * pretty permalinks cannot be used.
  4768. *
  4769. * Next we check if the URL Rewrite Module 1.1 is loaded and enabled for the web site. When
  4770. * URL Rewrite 1.1 is loaded it always sets a server variable called 'IIS_UrlRewriteModule'.
  4771. * Lastly we make sure that PHP is running via FastCGI. This is important because if it runs
  4772. * via ISAPI then pretty permalinks will not work.
  4773. */
  4774. $supports_permalinks = class_exists( 'DOMDocument', false ) && isset( $_SERVER['IIS_UrlRewriteModule'] ) && ( PHP_SAPI == 'cgi-fcgi' );
  4775. }
  4776. /**
  4777. * Filters whether IIS 7+ supports pretty permalinks.
  4778. *
  4779. * @since 2.8.0
  4780. *
  4781. * @param bool $supports_permalinks Whether IIS7 supports permalinks. Default false.
  4782. */
  4783. return apply_filters( 'iis7_supports_permalinks', $supports_permalinks );
  4784. }
  4785. /**
  4786. * Validates a file name and path against an allowed set of rules.
  4787. *
  4788. * A return value of `1` means the file path contains directory traversal.
  4789. *
  4790. * A return value of `2` means the file path contains a Windows drive path.
  4791. *
  4792. * A return value of `3` means the file is not in the allowed files list.
  4793. *
  4794. * @since 1.2.0
  4795. *
  4796. * @param string $file File path.
  4797. * @param string[] $allowed_files Optional. Array of allowed files.
  4798. * @return int 0 means nothing is wrong, greater than 0 means something was wrong.
  4799. */
  4800. function validate_file( $file, $allowed_files = array() ) {
  4801. // `../` on its own is not allowed:
  4802. if ( '../' === $file ) {
  4803. return 1;
  4804. }
  4805. // More than one occurence of `../` is not allowed:
  4806. if ( preg_match_all( '#\.\./#', $file, $matches, PREG_SET_ORDER ) && ( count( $matches ) > 1 ) ) {
  4807. return 1;
  4808. }
  4809. // `../` which does not occur at the end of the path is not allowed:
  4810. if ( false !== strpos( $file, '../' ) && '../' !== mb_substr( $file, -3, 3 ) ) {
  4811. return 1;
  4812. }
  4813. // Files not in the allowed file list are not allowed:
  4814. if ( ! empty( $allowed_files ) && ! in_array( $file, $allowed_files, true ) ) {
  4815. return 3;
  4816. }
  4817. // Absolute Windows drive paths are not allowed:
  4818. if ( ':' == substr( $file, 1, 1 ) ) {
  4819. return 2;
  4820. }
  4821. return 0;
  4822. }
  4823. /**
  4824. * Whether to force SSL used for the Administration Screens.
  4825. *
  4826. * @since 2.6.0
  4827. *
  4828. * @staticvar bool $forced
  4829. *
  4830. * @param string|bool $force Optional. Whether to force SSL in admin screens. Default null.
  4831. * @return bool True if forced, false if not forced.
  4832. */
  4833. function force_ssl_admin( $force = null ) {
  4834. static $forced = false;
  4835. if ( ! is_null( $force ) ) {
  4836. $old_forced = $forced;
  4837. $forced = $force;
  4838. return $old_forced;
  4839. }
  4840. return $forced;
  4841. }
  4842. /**
  4843. * Guess the URL for the site.
  4844. *
  4845. * Will remove wp-admin links to retrieve only return URLs not in the wp-admin
  4846. * directory.
  4847. *
  4848. * @since 2.6.0
  4849. *
  4850. * @return string The guessed URL.
  4851. */
  4852. function wp_guess_url() {
  4853. if ( defined( 'WP_SITEURL' ) && '' != WP_SITEURL ) {
  4854. $url = WP_SITEURL;
  4855. } else {
  4856. $abspath_fix = str_replace( '\\', '/', ABSPATH );
  4857. $script_filename_dir = dirname( $_SERVER['SCRIPT_FILENAME'] );
  4858. // The request is for the admin.
  4859. if ( strpos( $_SERVER['REQUEST_URI'], 'wp-admin' ) !== false || strpos( $_SERVER['REQUEST_URI'], 'wp-login.php' ) !== false ) {
  4860. $path = preg_replace( '#/(wp-admin/.*|wp-login.php)#i', '', $_SERVER['REQUEST_URI'] );
  4861. // The request is for a file in ABSPATH.
  4862. } elseif ( $script_filename_dir . '/' == $abspath_fix ) {
  4863. // Strip off any file/query params in the path.
  4864. $path = preg_replace( '#/[^/]*$#i', '', $_SERVER['PHP_SELF'] );
  4865. } else {
  4866. if ( false !== strpos( $_SERVER['SCRIPT_FILENAME'], $abspath_fix ) ) {
  4867. // Request is hitting a file inside ABSPATH.
  4868. $directory = str_replace( ABSPATH, '', $script_filename_dir );
  4869. // Strip off the subdirectory, and any file/query params.
  4870. $path = preg_replace( '#/' . preg_quote( $directory, '#' ) . '/[^/]*$#i', '', $_SERVER['REQUEST_URI'] );
  4871. } elseif ( false !== strpos( $abspath_fix, $script_filename_dir ) ) {
  4872. // Request is hitting a file above ABSPATH.
  4873. $subdirectory = substr( $abspath_fix, strpos( $abspath_fix, $script_filename_dir ) + strlen( $script_filename_dir ) );
  4874. // Strip off any file/query params from the path, appending the subdirectory to the installation.
  4875. $path = preg_replace( '#/[^/]*$#i', '', $_SERVER['REQUEST_URI'] ) . $subdirectory;
  4876. } else {
  4877. $path = $_SERVER['REQUEST_URI'];
  4878. }
  4879. }
  4880. $schema = is_ssl() ? 'https://' : 'http://'; // set_url_scheme() is not defined yet.
  4881. $url = $schema . $_SERVER['HTTP_HOST'] . $path;
  4882. }
  4883. return rtrim( $url, '/' );
  4884. }
  4885. /**
  4886. * Temporarily suspend cache additions.
  4887. *
  4888. * Stops more data being added to the cache, but still allows cache retrieval.
  4889. * This is useful for actions, such as imports, when a lot of data would otherwise
  4890. * be almost uselessly added to the cache.
  4891. *
  4892. * Suspension lasts for a single page load at most. Remember to call this
  4893. * function again if you wish to re-enable cache adds earlier.
  4894. *
  4895. * @since 3.3.0
  4896. *
  4897. * @staticvar bool $_suspend
  4898. *
  4899. * @param bool $suspend Optional. Suspends additions if true, re-enables them if false.
  4900. * @return bool The current suspend setting
  4901. */
  4902. function wp_suspend_cache_addition( $suspend = null ) {
  4903. static $_suspend = false;
  4904. if ( is_bool( $suspend ) ) {
  4905. $_suspend = $suspend;
  4906. }
  4907. return $_suspend;
  4908. }
  4909. /**
  4910. * Suspend cache invalidation.
  4911. *
  4912. * Turns cache invalidation on and off. Useful during imports where you don't want to do
  4913. * invalidations every time a post is inserted. Callers must be sure that what they are
  4914. * doing won't lead to an inconsistent cache when invalidation is suspended.
  4915. *
  4916. * @since 2.7.0
  4917. *
  4918. * @global bool $_wp_suspend_cache_invalidation
  4919. *
  4920. * @param bool $suspend Optional. Whether to suspend or enable cache invalidation. Default true.
  4921. * @return bool The current suspend setting.
  4922. */
  4923. function wp_suspend_cache_invalidation( $suspend = true ) {
  4924. global $_wp_suspend_cache_invalidation;
  4925. $current_suspend = $_wp_suspend_cache_invalidation;
  4926. $_wp_suspend_cache_invalidation = $suspend;
  4927. return $current_suspend;
  4928. }
  4929. /**
  4930. * Determine whether a site is the main site of the current network.
  4931. *
  4932. * @since 3.0.0
  4933. * @since 4.9.0 The `$network_id` parameter was added.
  4934. *
  4935. * @param int $site_id Optional. Site ID to test. Defaults to current site.
  4936. * @param int $network_id Optional. Network ID of the network to check for.
  4937. * Defaults to current network.
  4938. * @return bool True if $site_id is the main site of the network, or if not
  4939. * running Multisite.
  4940. */
  4941. function is_main_site( $site_id = null, $network_id = null ) {
  4942. if ( ! is_multisite() ) {
  4943. return true;
  4944. }
  4945. if ( ! $site_id ) {
  4946. $site_id = get_current_blog_id();
  4947. }
  4948. $site_id = (int) $site_id;
  4949. return get_main_site_id( $network_id ) === $site_id;
  4950. }
  4951. /**
  4952. * Gets the main site ID.
  4953. *
  4954. * @since 4.9.0
  4955. *
  4956. * @param int $network_id Optional. The ID of the network for which to get the main site.
  4957. * Defaults to the current network.
  4958. * @return int The ID of the main site.
  4959. */
  4960. function get_main_site_id( $network_id = null ) {
  4961. if ( ! is_multisite() ) {
  4962. return get_current_blog_id();
  4963. }
  4964. $network = get_network( $network_id );
  4965. if ( ! $network ) {
  4966. return 0;
  4967. }
  4968. return $network->site_id;
  4969. }
  4970. /**
  4971. * Determine whether a network is the main network of the Multisite installation.
  4972. *
  4973. * @since 3.7.0
  4974. *
  4975. * @param int $network_id Optional. Network ID to test. Defaults to current network.
  4976. * @return bool True if $network_id is the main network, or if not running Multisite.
  4977. */
  4978. function is_main_network( $network_id = null ) {
  4979. if ( ! is_multisite() ) {
  4980. return true;
  4981. }
  4982. if ( null === $network_id ) {
  4983. $network_id = get_current_network_id();
  4984. }
  4985. $network_id = (int) $network_id;
  4986. return ( get_main_network_id() === $network_id );
  4987. }
  4988. /**
  4989. * Get the main network ID.
  4990. *
  4991. * @since 4.3.0
  4992. *
  4993. * @return int The ID of the main network.
  4994. */
  4995. function get_main_network_id() {
  4996. if ( ! is_multisite() ) {
  4997. return 1;
  4998. }
  4999. $current_network = get_network();
  5000. if ( defined( 'PRIMARY_NETWORK_ID' ) ) {
  5001. $main_network_id = PRIMARY_NETWORK_ID;
  5002. } elseif ( isset( $current_network->id ) && 1 === (int) $current_network->id ) {
  5003. // If the current network has an ID of 1, assume it is the main network.
  5004. $main_network_id = 1;
  5005. } else {
  5006. $_networks = get_networks(
  5007. array(
  5008. 'fields' => 'ids',
  5009. 'number' => 1,
  5010. )
  5011. );
  5012. $main_network_id = array_shift( $_networks );
  5013. }
  5014. /**
  5015. * Filters the main network ID.
  5016. *
  5017. * @since 4.3.0
  5018. *
  5019. * @param int $main_network_id The ID of the main network.
  5020. */
  5021. return (int) apply_filters( 'get_main_network_id', $main_network_id );
  5022. }
  5023. /**
  5024. * Determine whether global terms are enabled.
  5025. *
  5026. * @since 3.0.0
  5027. *
  5028. * @staticvar bool $global_terms
  5029. *
  5030. * @return bool True if multisite and global terms enabled.
  5031. */
  5032. function global_terms_enabled() {
  5033. if ( ! is_multisite() ) {
  5034. return false;
  5035. }
  5036. static $global_terms = null;
  5037. if ( is_null( $global_terms ) ) {
  5038. /**
  5039. * Filters whether global terms are enabled.
  5040. *
  5041. * Passing a non-null value to the filter will effectively short-circuit the function,
  5042. * returning the value of the 'global_terms_enabled' site option instead.
  5043. *
  5044. * @since 3.0.0
  5045. *
  5046. * @param null $enabled Whether global terms are enabled.
  5047. */
  5048. $filter = apply_filters( 'global_terms_enabled', null );
  5049. if ( ! is_null( $filter ) ) {
  5050. $global_terms = (bool) $filter;
  5051. } else {
  5052. $global_terms = (bool) get_site_option( 'global_terms_enabled', false );
  5053. }
  5054. }
  5055. return $global_terms;
  5056. }
  5057. /**
  5058. * Determines whether site meta is enabled.
  5059. *
  5060. * This function checks whether the 'blogmeta' database table exists. The result is saved as
  5061. * a setting for the main network, making it essentially a global setting. Subsequent requests
  5062. * will refer to this setting instead of running the query.
  5063. *
  5064. * @since 5.1.0
  5065. *
  5066. * @global wpdb $wpdb WordPress database abstraction object.
  5067. *
  5068. * @return bool True if site meta is supported, false otherwise.
  5069. */
  5070. function is_site_meta_supported() {
  5071. global $wpdb;
  5072. if ( ! is_multisite() ) {
  5073. return false;
  5074. }
  5075. $network_id = get_main_network_id();
  5076. $supported = get_network_option( $network_id, 'site_meta_supported', false );
  5077. if ( false === $supported ) {
  5078. $supported = $wpdb->get_var( "SHOW TABLES LIKE '{$wpdb->blogmeta}'" ) ? 1 : 0;
  5079. update_network_option( $network_id, 'site_meta_supported', $supported );
  5080. }
  5081. return (bool) $supported;
  5082. }
  5083. /**
  5084. * gmt_offset modification for smart timezone handling.
  5085. *
  5086. * Overrides the gmt_offset option if we have a timezone_string available.
  5087. *
  5088. * @since 2.8.0
  5089. *
  5090. * @return float|false Timezone GMT offset, false otherwise.
  5091. */
  5092. function wp_timezone_override_offset() {
  5093. $timezone_string = get_option( 'timezone_string' );
  5094. if ( ! $timezone_string ) {
  5095. return false;
  5096. }
  5097. $timezone_object = timezone_open( $timezone_string );
  5098. $datetime_object = date_create();
  5099. if ( false === $timezone_object || false === $datetime_object ) {
  5100. return false;
  5101. }
  5102. return round( timezone_offset_get( $timezone_object, $datetime_object ) / HOUR_IN_SECONDS, 2 );
  5103. }
  5104. /**
  5105. * Sort-helper for timezones.
  5106. *
  5107. * @since 2.9.0
  5108. * @access private
  5109. *
  5110. * @param array $a
  5111. * @param array $b
  5112. * @return int
  5113. */
  5114. function _wp_timezone_choice_usort_callback( $a, $b ) {
  5115. // Don't use translated versions of Etc.
  5116. if ( 'Etc' === $a['continent'] && 'Etc' === $b['continent'] ) {
  5117. // Make the order of these more like the old dropdown.
  5118. if ( 'GMT+' === substr( $a['city'], 0, 4 ) && 'GMT+' === substr( $b['city'], 0, 4 ) ) {
  5119. return -1 * ( strnatcasecmp( $a['city'], $b['city'] ) );
  5120. }
  5121. if ( 'UTC' === $a['city'] ) {
  5122. if ( 'GMT+' === substr( $b['city'], 0, 4 ) ) {
  5123. return 1;
  5124. }
  5125. return -1;
  5126. }
  5127. if ( 'UTC' === $b['city'] ) {
  5128. if ( 'GMT+' === substr( $a['city'], 0, 4 ) ) {
  5129. return -1;
  5130. }
  5131. return 1;
  5132. }
  5133. return strnatcasecmp( $a['city'], $b['city'] );
  5134. }
  5135. if ( $a['t_continent'] == $b['t_continent'] ) {
  5136. if ( $a['t_city'] == $b['t_city'] ) {
  5137. return strnatcasecmp( $a['t_subcity'], $b['t_subcity'] );
  5138. }
  5139. return strnatcasecmp( $a['t_city'], $b['t_city'] );
  5140. } else {
  5141. // Force Etc to the bottom of the list.
  5142. if ( 'Etc' === $a['continent'] ) {
  5143. return 1;
  5144. }
  5145. if ( 'Etc' === $b['continent'] ) {
  5146. return -1;
  5147. }
  5148. return strnatcasecmp( $a['t_continent'], $b['t_continent'] );
  5149. }
  5150. }
  5151. /**
  5152. * Gives a nicely-formatted list of timezone strings.
  5153. *
  5154. * @since 2.9.0
  5155. * @since 4.7.0 Added the `$locale` parameter.
  5156. *
  5157. * @staticvar bool $mo_loaded
  5158. * @staticvar string $locale_loaded
  5159. *
  5160. * @param string $selected_zone Selected timezone.
  5161. * @param string $locale Optional. Locale to load the timezones in. Default current site locale.
  5162. * @return string
  5163. */
  5164. function wp_timezone_choice( $selected_zone, $locale = null ) {
  5165. static $mo_loaded = false, $locale_loaded = null;
  5166. $continents = array( 'Africa', 'America', 'Antarctica', 'Arctic', 'Asia', 'Atlantic', 'Australia', 'Europe', 'Indian', 'Pacific' );
  5167. // Load translations for continents and cities.
  5168. if ( ! $mo_loaded || $locale !== $locale_loaded ) {
  5169. $locale_loaded = $locale ? $locale : get_locale();
  5170. $mofile = WP_LANG_DIR . '/continents-cities-' . $locale_loaded . '.mo';
  5171. unload_textdomain( 'continents-cities' );
  5172. load_textdomain( 'continents-cities', $mofile );
  5173. $mo_loaded = true;
  5174. }
  5175. $zonen = array();
  5176. foreach ( timezone_identifiers_list() as $zone ) {
  5177. $zone = explode( '/', $zone );
  5178. if ( ! in_array( $zone[0], $continents, true ) ) {
  5179. continue;
  5180. }
  5181. // This determines what gets set and translated - we don't translate Etc/* strings here, they are done later.
  5182. $exists = array(
  5183. 0 => ( isset( $zone[0] ) && $zone[0] ),
  5184. 1 => ( isset( $zone[1] ) && $zone[1] ),
  5185. 2 => ( isset( $zone[2] ) && $zone[2] ),
  5186. );
  5187. $exists[3] = ( $exists[0] && 'Etc' !== $zone[0] );
  5188. $exists[4] = ( $exists[1] && $exists[3] );
  5189. $exists[5] = ( $exists[2] && $exists[3] );
  5190. // phpcs:disable WordPress.WP.I18n.LowLevelTranslationFunction,WordPress.WP.I18n.NonSingularStringLiteralText
  5191. $zonen[] = array(
  5192. 'continent' => ( $exists[0] ? $zone[0] : '' ),
  5193. 'city' => ( $exists[1] ? $zone[1] : '' ),
  5194. 'subcity' => ( $exists[2] ? $zone[2] : '' ),
  5195. 't_continent' => ( $exists[3] ? translate( str_replace( '_', ' ', $zone[0] ), 'continents-cities' ) : '' ),
  5196. 't_city' => ( $exists[4] ? translate( str_replace( '_', ' ', $zone[1] ), 'continents-cities' ) : '' ),
  5197. 't_subcity' => ( $exists[5] ? translate( str_replace( '_', ' ', $zone[2] ), 'continents-cities' ) : '' ),
  5198. );
  5199. // phpcs:enable
  5200. }
  5201. usort( $zonen, '_wp_timezone_choice_usort_callback' );
  5202. $structure = array();
  5203. if ( empty( $selected_zone ) ) {
  5204. $structure[] = '<option selected="selected" value="">' . __( 'Select a city' ) . '</option>';
  5205. }
  5206. foreach ( $zonen as $key => $zone ) {
  5207. // Build value in an array to join later.
  5208. $value = array( $zone['continent'] );
  5209. if ( empty( $zone['city'] ) ) {
  5210. // It's at the continent level (generally won't happen).
  5211. $display = $zone['t_continent'];
  5212. } else {
  5213. // It's inside a continent group.
  5214. // Continent optgroup.
  5215. if ( ! isset( $zonen[ $key - 1 ] ) || $zonen[ $key - 1 ]['continent'] !== $zone['continent'] ) {
  5216. $label = $zone['t_continent'];
  5217. $structure[] = '<optgroup label="' . esc_attr( $label ) . '">';
  5218. }
  5219. // Add the city to the value.
  5220. $value[] = $zone['city'];
  5221. $display = $zone['t_city'];
  5222. if ( ! empty( $zone['subcity'] ) ) {
  5223. // Add the subcity to the value.
  5224. $value[] = $zone['subcity'];
  5225. $display .= ' - ' . $zone['t_subcity'];
  5226. }
  5227. }
  5228. // Build the value.
  5229. $value = join( '/', $value );
  5230. $selected = '';
  5231. if ( $value === $selected_zone ) {
  5232. $selected = 'selected="selected" ';
  5233. }
  5234. $structure[] = '<option ' . $selected . 'value="' . esc_attr( $value ) . '">' . esc_html( $display ) . '</option>';
  5235. // Close continent optgroup.
  5236. if ( ! empty( $zone['city'] ) && ( ! isset( $zonen[ $key + 1 ] ) || ( isset( $zonen[ $key + 1 ] ) && $zonen[ $key + 1 ]['continent'] !== $zone['continent'] ) ) ) {
  5237. $structure[] = '</optgroup>';
  5238. }
  5239. }
  5240. // Do UTC.
  5241. $structure[] = '<optgroup label="' . esc_attr__( 'UTC' ) . '">';
  5242. $selected = '';
  5243. if ( 'UTC' === $selected_zone ) {
  5244. $selected = 'selected="selected" ';
  5245. }
  5246. $structure[] = '<option ' . $selected . 'value="' . esc_attr( 'UTC' ) . '">' . __( 'UTC' ) . '</option>';
  5247. $structure[] = '</optgroup>';
  5248. // Do manual UTC offsets.
  5249. $structure[] = '<optgroup label="' . esc_attr__( 'Manual Offsets' ) . '">';
  5250. $offset_range = array(
  5251. -12,
  5252. -11.5,
  5253. -11,
  5254. -10.5,
  5255. -10,
  5256. -9.5,
  5257. -9,
  5258. -8.5,
  5259. -8,
  5260. -7.5,
  5261. -7,
  5262. -6.5,
  5263. -6,
  5264. -5.5,
  5265. -5,
  5266. -4.5,
  5267. -4,
  5268. -3.5,
  5269. -3,
  5270. -2.5,
  5271. -2,
  5272. -1.5,
  5273. -1,
  5274. -0.5,
  5275. 0,
  5276. 0.5,
  5277. 1,
  5278. 1.5,
  5279. 2,
  5280. 2.5,
  5281. 3,
  5282. 3.5,
  5283. 4,
  5284. 4.5,
  5285. 5,
  5286. 5.5,
  5287. 5.75,
  5288. 6,
  5289. 6.5,
  5290. 7,
  5291. 7.5,
  5292. 8,
  5293. 8.5,
  5294. 8.75,
  5295. 9,
  5296. 9.5,
  5297. 10,
  5298. 10.5,
  5299. 11,
  5300. 11.5,
  5301. 12,
  5302. 12.75,
  5303. 13,
  5304. 13.75,
  5305. 14,
  5306. );
  5307. foreach ( $offset_range as $offset ) {
  5308. if ( 0 <= $offset ) {
  5309. $offset_name = '+' . $offset;
  5310. } else {
  5311. $offset_name = (string) $offset;
  5312. }
  5313. $offset_value = $offset_name;
  5314. $offset_name = str_replace( array( '.25', '.5', '.75' ), array( ':15', ':30', ':45' ), $offset_name );
  5315. $offset_name = 'UTC' . $offset_name;
  5316. $offset_value = 'UTC' . $offset_value;
  5317. $selected = '';
  5318. if ( $offset_value === $selected_zone ) {
  5319. $selected = 'selected="selected" ';
  5320. }
  5321. $structure[] = '<option ' . $selected . 'value="' . esc_attr( $offset_value ) . '">' . esc_html( $offset_name ) . '</option>';
  5322. }
  5323. $structure[] = '</optgroup>';
  5324. return join( "\n", $structure );
  5325. }
  5326. /**
  5327. * Strip close comment and close php tags from file headers used by WP.
  5328. *
  5329. * @since 2.8.0
  5330. * @access private
  5331. *
  5332. * @see https://core.trac.wordpress.org/ticket/8497
  5333. *
  5334. * @param string $str Header comment to clean up.
  5335. * @return string
  5336. */
  5337. function _cleanup_header_comment( $str ) {
  5338. return trim( preg_replace( '/\s*(?:\*\/|\?>).*/', '', $str ) );
  5339. }
  5340. /**
  5341. * Permanently delete comments or posts of any type that have held a status
  5342. * of 'trash' for the number of days defined in EMPTY_TRASH_DAYS.
  5343. *
  5344. * The default value of `EMPTY_TRASH_DAYS` is 30 (days).
  5345. *
  5346. * @since 2.9.0
  5347. *
  5348. * @global wpdb $wpdb WordPress database abstraction object.
  5349. */
  5350. function wp_scheduled_delete() {
  5351. global $wpdb;
  5352. $delete_timestamp = time() - ( DAY_IN_SECONDS * EMPTY_TRASH_DAYS );
  5353. $posts_to_delete = $wpdb->get_results( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wp_trash_meta_time' AND meta_value < %d", $delete_timestamp ), ARRAY_A );
  5354. foreach ( (array) $posts_to_delete as $post ) {
  5355. $post_id = (int) $post['post_id'];
  5356. if ( ! $post_id ) {
  5357. continue;
  5358. }
  5359. $del_post = get_post( $post_id );
  5360. if ( ! $del_post || 'trash' != $del_post->post_status ) {
  5361. delete_post_meta( $post_id, '_wp_trash_meta_status' );
  5362. delete_post_meta( $post_id, '_wp_trash_meta_time' );
  5363. } else {
  5364. wp_delete_post( $post_id );
  5365. }
  5366. }
  5367. $comments_to_delete = $wpdb->get_results( $wpdb->prepare( "SELECT comment_id FROM $wpdb->commentmeta WHERE meta_key = '_wp_trash_meta_time' AND meta_value < %d", $delete_timestamp ), ARRAY_A );
  5368. foreach ( (array) $comments_to_delete as $comment ) {
  5369. $comment_id = (int) $comment['comment_id'];
  5370. if ( ! $comment_id ) {
  5371. continue;
  5372. }
  5373. $del_comment = get_comment( $comment_id );
  5374. if ( ! $del_comment || 'trash' != $del_comment->comment_approved ) {
  5375. delete_comment_meta( $comment_id, '_wp_trash_meta_time' );
  5376. delete_comment_meta( $comment_id, '_wp_trash_meta_status' );
  5377. } else {
  5378. wp_delete_comment( $del_comment );
  5379. }
  5380. }
  5381. }
  5382. /**
  5383. * Retrieve metadata from a file.
  5384. *
  5385. * Searches for metadata in the first 8 KB of a file, such as a plugin or theme.
  5386. * Each piece of metadata must be on its own line. Fields can not span multiple
  5387. * lines, the value will get cut at the end of the first line.
  5388. *
  5389. * If the file data is not within that first 8 KB, then the author should correct
  5390. * their plugin file and move the data headers to the top.
  5391. *
  5392. * @link https://codex.wordpress.org/File_Header
  5393. *
  5394. * @since 2.9.0
  5395. *
  5396. * @param string $file Absolute path to the file.
  5397. * @param array $default_headers List of headers, in the format `array( 'HeaderKey' => 'Header Name' )`.
  5398. * @param string $context Optional. If specified adds filter hook {@see 'extra_$context_headers'}.
  5399. * Default empty.
  5400. * @return string[] Array of file header values keyed by header name.
  5401. */
  5402. function get_file_data( $file, $default_headers, $context = '' ) {
  5403. // We don't need to write to the file, so just open for reading.
  5404. $fp = fopen( $file, 'r' );
  5405. // Pull only the first 8 KB of the file in.
  5406. $file_data = fread( $fp, 8 * KB_IN_BYTES );
  5407. // PHP will close file handle, but we are good citizens.
  5408. fclose( $fp );
  5409. // Make sure we catch CR-only line endings.
  5410. $file_data = str_replace( "\r", "\n", $file_data );
  5411. /**
  5412. * Filters extra file headers by context.
  5413. *
  5414. * The dynamic portion of the hook name, `$context`, refers to
  5415. * the context where extra headers might be loaded.
  5416. *
  5417. * @since 2.9.0
  5418. *
  5419. * @param array $extra_context_headers Empty array by default.
  5420. */
  5421. $extra_headers = $context ? apply_filters( "extra_{$context}_headers", array() ) : array();
  5422. if ( $extra_headers ) {
  5423. $extra_headers = array_combine( $extra_headers, $extra_headers ); // Keys equal values.
  5424. $all_headers = array_merge( $extra_headers, (array) $default_headers );
  5425. } else {
  5426. $all_headers = $default_headers;
  5427. }
  5428. foreach ( $all_headers as $field => $regex ) {
  5429. if ( preg_match( '/^[ \t\/*#@]*' . preg_quote( $regex, '/' ) . ':(.*)$/mi', $file_data, $match ) && $match[1] ) {
  5430. $all_headers[ $field ] = _cleanup_header_comment( $match[1] );
  5431. } else {
  5432. $all_headers[ $field ] = '';
  5433. }
  5434. }
  5435. return $all_headers;
  5436. }
  5437. /**
  5438. * Returns true.
  5439. *
  5440. * Useful for returning true to filters easily.
  5441. *
  5442. * @since 3.0.0
  5443. *
  5444. * @see __return_false()
  5445. *
  5446. * @return true True.
  5447. */
  5448. function __return_true() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionDoubleUnderscore,PHPCompatibility.FunctionNameRestrictions.ReservedFunctionNames.FunctionDoubleUnderscore
  5449. return true;
  5450. }
  5451. /**
  5452. * Returns false.
  5453. *
  5454. * Useful for returning false to filters easily.
  5455. *
  5456. * @since 3.0.0
  5457. *
  5458. * @see __return_true()
  5459. *
  5460. * @return false False.
  5461. */
  5462. function __return_false() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionDoubleUnderscore,PHPCompatibility.FunctionNameRestrictions.ReservedFunctionNames.FunctionDoubleUnderscore
  5463. return false;
  5464. }
  5465. /**
  5466. * Returns 0.
  5467. *
  5468. * Useful for returning 0 to filters easily.
  5469. *
  5470. * @since 3.0.0
  5471. *
  5472. * @return int 0.
  5473. */
  5474. function __return_zero() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionDoubleUnderscore,PHPCompatibility.FunctionNameRestrictions.ReservedFunctionNames.FunctionDoubleUnderscore
  5475. return 0;
  5476. }
  5477. /**
  5478. * Returns an empty array.
  5479. *
  5480. * Useful for returning an empty array to filters easily.
  5481. *
  5482. * @since 3.0.0
  5483. *
  5484. * @return array Empty array.
  5485. */
  5486. function __return_empty_array() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionDoubleUnderscore,PHPCompatibility.FunctionNameRestrictions.ReservedFunctionNames.FunctionDoubleUnderscore
  5487. return array();
  5488. }
  5489. /**
  5490. * Returns null.
  5491. *
  5492. * Useful for returning null to filters easily.
  5493. *
  5494. * @since 3.4.0
  5495. *
  5496. * @return null Null value.
  5497. */
  5498. function __return_null() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionDoubleUnderscore,PHPCompatibility.FunctionNameRestrictions.ReservedFunctionNames.FunctionDoubleUnderscore
  5499. return null;
  5500. }
  5501. /**
  5502. * Returns an empty string.
  5503. *
  5504. * Useful for returning an empty string to filters easily.
  5505. *
  5506. * @since 3.7.0
  5507. *
  5508. * @see __return_null()
  5509. *
  5510. * @return string Empty string.
  5511. */
  5512. function __return_empty_string() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionDoubleUnderscore,PHPCompatibility.FunctionNameRestrictions.ReservedFunctionNames.FunctionDoubleUnderscore
  5513. return '';
  5514. }
  5515. /**
  5516. * Send a HTTP header to disable content type sniffing in browsers which support it.
  5517. *
  5518. * @since 3.0.0
  5519. *
  5520. * @see https://blogs.msdn.com/ie/archive/2008/07/02/ie8-security-part-v-comprehensive-protection.aspx
  5521. * @see https://src.chromium.org/viewvc/chrome?view=rev&revision=6985
  5522. */
  5523. function send_nosniff_header() {
  5524. header( 'X-Content-Type-Options: nosniff' );
  5525. }
  5526. /**
  5527. * Return a MySQL expression for selecting the week number based on the start_of_week option.
  5528. *
  5529. * @ignore
  5530. * @since 3.0.0
  5531. *
  5532. * @param string $column Database column.
  5533. * @return string SQL clause.
  5534. */
  5535. function _wp_mysql_week( $column ) {
  5536. $start_of_week = (int) get_option( 'start_of_week' );
  5537. switch ( $start_of_week ) {
  5538. case 1:
  5539. return "WEEK( $column, 1 )";
  5540. case 2:
  5541. case 3:
  5542. case 4:
  5543. case 5:
  5544. case 6:
  5545. return "WEEK( DATE_SUB( $column, INTERVAL $start_of_week DAY ), 0 )";
  5546. case 0:
  5547. default:
  5548. return "WEEK( $column, 0 )";
  5549. }
  5550. }
  5551. /**
  5552. * Find hierarchy loops using a callback function that maps object IDs to parent IDs.
  5553. *
  5554. * @since 3.1.0
  5555. * @access private
  5556. *
  5557. * @param callable $callback Function that accepts ( ID, $callback_args ) and outputs parent_ID.
  5558. * @param int $start The ID to start the loop check at.
  5559. * @param int $start_parent The parent_ID of $start to use instead of calling $callback( $start ).
  5560. * Use null to always use $callback
  5561. * @param array $callback_args Optional. Additional arguments to send to $callback.
  5562. * @return array IDs of all members of loop.
  5563. */
  5564. function wp_find_hierarchy_loop( $callback, $start, $start_parent, $callback_args = array() ) {
  5565. $override = is_null( $start_parent ) ? array() : array( $start => $start_parent );
  5566. $arbitrary_loop_member = wp_find_hierarchy_loop_tortoise_hare( $callback, $start, $override, $callback_args );
  5567. if ( ! $arbitrary_loop_member ) {
  5568. return array();
  5569. }
  5570. return wp_find_hierarchy_loop_tortoise_hare( $callback, $arbitrary_loop_member, $override, $callback_args, true );
  5571. }
  5572. /**
  5573. * Use the "The Tortoise and the Hare" algorithm to detect loops.
  5574. *
  5575. * For every step of the algorithm, the hare takes two steps and the tortoise one.
  5576. * If the hare ever laps the tortoise, there must be a loop.
  5577. *
  5578. * @since 3.1.0
  5579. * @access private
  5580. *
  5581. * @param callable $callback Function that accepts ( ID, callback_arg, ... ) and outputs parent_ID.
  5582. * @param int $start The ID to start the loop check at.
  5583. * @param array $override Optional. An array of ( ID => parent_ID, ... ) to use instead of $callback.
  5584. * Default empty array.
  5585. * @param array $callback_args Optional. Additional arguments to send to $callback. Default empty array.
  5586. * @param bool $_return_loop Optional. Return loop members or just detect presence of loop? Only set
  5587. * to true if you already know the given $start is part of a loop (otherwise
  5588. * the returned array might include branches). Default false.
  5589. * @return mixed Scalar ID of some arbitrary member of the loop, or array of IDs of all members of loop if
  5590. * $_return_loop
  5591. */
  5592. function wp_find_hierarchy_loop_tortoise_hare( $callback, $start, $override = array(), $callback_args = array(), $_return_loop = false ) {
  5593. $tortoise = $start;
  5594. $hare = $start;
  5595. $evanescent_hare = $start;
  5596. $return = array();
  5597. // Set evanescent_hare to one past hare.
  5598. // Increment hare two steps.
  5599. while (
  5600. $tortoise
  5601. &&
  5602. ( $evanescent_hare = isset( $override[ $hare ] ) ? $override[ $hare ] : call_user_func_array( $callback, array_merge( array( $hare ), $callback_args ) ) )
  5603. &&
  5604. ( $hare = isset( $override[ $evanescent_hare ] ) ? $override[ $evanescent_hare ] : call_user_func_array( $callback, array_merge( array( $evanescent_hare ), $callback_args ) ) )
  5605. ) {
  5606. if ( $_return_loop ) {
  5607. $return[ $tortoise ] = true;
  5608. $return[ $evanescent_hare ] = true;
  5609. $return[ $hare ] = true;
  5610. }
  5611. // Tortoise got lapped - must be a loop.
  5612. if ( $tortoise == $evanescent_hare || $tortoise == $hare ) {
  5613. return $_return_loop ? $return : $tortoise;
  5614. }
  5615. // Increment tortoise by one step.
  5616. $tortoise = isset( $override[ $tortoise ] ) ? $override[ $tortoise ] : call_user_func_array( $callback, array_merge( array( $tortoise ), $callback_args ) );
  5617. }
  5618. return false;
  5619. }
  5620. /**
  5621. * Send a HTTP header to limit rendering of pages to same origin iframes.
  5622. *
  5623. * @since 3.1.3
  5624. *
  5625. * @see https://developer.mozilla.org/en/the_x-frame-options_response_header
  5626. */
  5627. function send_frame_options_header() {
  5628. header( 'X-Frame-Options: SAMEORIGIN' );
  5629. }
  5630. /**
  5631. * Retrieve a list of protocols to allow in HTML attributes.
  5632. *
  5633. * @since 3.3.0
  5634. * @since 4.3.0 Added 'webcal' to the protocols array.
  5635. * @since 4.7.0 Added 'urn' to the protocols array.
  5636. * @since 5.3.0 Added 'sms' to the protocols array.
  5637. *
  5638. * @see wp_kses()
  5639. * @see esc_url()
  5640. *
  5641. * @staticvar array $protocols
  5642. *
  5643. * @return string[] Array of allowed protocols. Defaults to an array containing 'http', 'https',
  5644. * 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet',
  5645. * 'mms', 'rtsp', 'sms', 'svn', 'tel', 'fax', 'xmpp', 'webcal', and 'urn'.
  5646. * This covers all common link protocols, except for 'javascript' which should not
  5647. * be allowed for untrusted users.
  5648. */
  5649. function wp_allowed_protocols() {
  5650. static $protocols = array();
  5651. if ( empty( $protocols ) ) {
  5652. $protocols = array( 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'sms', 'svn', 'tel', 'fax', 'xmpp', 'webcal', 'urn' );
  5653. }
  5654. if ( ! did_action( 'wp_loaded' ) ) {
  5655. /**
  5656. * Filters the list of protocols allowed in HTML attributes.
  5657. *
  5658. * @since 3.0.0
  5659. *
  5660. * @param string[] $protocols Array of allowed protocols e.g. 'http', 'ftp', 'tel', and more.
  5661. */
  5662. $protocols = array_unique( (array) apply_filters( 'kses_allowed_protocols', $protocols ) );
  5663. }
  5664. return $protocols;
  5665. }
  5666. /**
  5667. * Return a comma-separated string of functions that have been called to get
  5668. * to the current point in code.
  5669. *
  5670. * @since 3.4.0
  5671. *
  5672. * @see https://core.trac.wordpress.org/ticket/19589
  5673. *
  5674. * @staticvar array $truncate_paths Array of paths to truncate.
  5675. *
  5676. * @param string $ignore_class Optional. A class to ignore all function calls within - useful
  5677. * when you want to just give info about the callee. Default null.
  5678. * @param int $skip_frames Optional. A number of stack frames to skip - useful for unwinding
  5679. * back to the source of the issue. Default 0.
  5680. * @param bool $pretty Optional. Whether or not you want a comma separated string or raw
  5681. * array returned. Default true.
  5682. * @return string|array Either a string containing a reversed comma separated trace or an array
  5683. * of individual calls.
  5684. */
  5685. function wp_debug_backtrace_summary( $ignore_class = null, $skip_frames = 0, $pretty = true ) {
  5686. static $truncate_paths;
  5687. $trace = debug_backtrace( false );
  5688. $caller = array();
  5689. $check_class = ! is_null( $ignore_class );
  5690. $skip_frames++; // Skip this function.
  5691. if ( ! isset( $truncate_paths ) ) {
  5692. $truncate_paths = array(
  5693. wp_normalize_path( WP_CONTENT_DIR ),
  5694. wp_normalize_path( ABSPATH ),
  5695. );
  5696. }
  5697. foreach ( $trace as $call ) {
  5698. if ( $skip_frames > 0 ) {
  5699. $skip_frames--;
  5700. } elseif ( isset( $call['class'] ) ) {
  5701. if ( $check_class && $ignore_class == $call['class'] ) {
  5702. continue; // Filter out calls.
  5703. }
  5704. $caller[] = "{$call['class']}{$call['type']}{$call['function']}";
  5705. } else {
  5706. if ( in_array( $call['function'], array( 'do_action', 'apply_filters', 'do_action_ref_array', 'apply_filters_ref_array' ), true ) ) {
  5707. $caller[] = "{$call['function']}('{$call['args'][0]}')";
  5708. } elseif ( in_array( $call['function'], array( 'include', 'include_once', 'require', 'require_once' ), true ) ) {
  5709. $filename = isset( $call['args'][0] ) ? $call['args'][0] : '';
  5710. $caller[] = $call['function'] . "('" . str_replace( $truncate_paths, '', wp_normalize_path( $filename ) ) . "')";
  5711. } else {
  5712. $caller[] = $call['function'];
  5713. }
  5714. }
  5715. }
  5716. if ( $pretty ) {
  5717. return join( ', ', array_reverse( $caller ) );
  5718. } else {
  5719. return $caller;
  5720. }
  5721. }
  5722. /**
  5723. * Retrieve IDs that are not already present in the cache.
  5724. *
  5725. * @since 3.4.0
  5726. * @access private
  5727. *
  5728. * @param int[] $object_ids Array of IDs.
  5729. * @param string $cache_key The cache bucket to check against.
  5730. * @return int[] Array of IDs not present in the cache.
  5731. */
  5732. function _get_non_cached_ids( $object_ids, $cache_key ) {
  5733. $clean = array();
  5734. foreach ( $object_ids as $id ) {
  5735. $id = (int) $id;
  5736. if ( ! wp_cache_get( $id, $cache_key ) ) {
  5737. $clean[] = $id;
  5738. }
  5739. }
  5740. return $clean;
  5741. }
  5742. /**
  5743. * Test if the current device has the capability to upload files.
  5744. *
  5745. * @since 3.4.0
  5746. * @access private
  5747. *
  5748. * @return bool Whether the device is able to upload files.
  5749. */
  5750. function _device_can_upload() {
  5751. if ( ! wp_is_mobile() ) {
  5752. return true;
  5753. }
  5754. $ua = $_SERVER['HTTP_USER_AGENT'];
  5755. if ( strpos( $ua, 'iPhone' ) !== false
  5756. || strpos( $ua, 'iPad' ) !== false
  5757. || strpos( $ua, 'iPod' ) !== false ) {
  5758. return preg_match( '#OS ([\d_]+) like Mac OS X#', $ua, $version ) && version_compare( $version[1], '6', '>=' );
  5759. }
  5760. return true;
  5761. }
  5762. /**
  5763. * Test if a given path is a stream URL
  5764. *
  5765. * @since 3.5.0
  5766. *
  5767. * @param string $path The resource path or URL.
  5768. * @return bool True if the path is a stream URL.
  5769. */
  5770. function wp_is_stream( $path ) {
  5771. $scheme_separator = strpos( $path, '://' );
  5772. if ( false === $scheme_separator ) {
  5773. // $path isn't a stream.
  5774. return false;
  5775. }
  5776. $stream = substr( $path, 0, $scheme_separator );
  5777. return in_array( $stream, stream_get_wrappers(), true );
  5778. }
  5779. /**
  5780. * Test if the supplied date is valid for the Gregorian calendar.
  5781. *
  5782. * @since 3.5.0
  5783. *
  5784. * @link https://www.php.net/manual/en/function.checkdate.php
  5785. *
  5786. * @param int $month Month number.
  5787. * @param int $day Day number.
  5788. * @param int $year Year number.
  5789. * @param string $source_date The date to filter.
  5790. * @return bool True if valid date, false if not valid date.
  5791. */
  5792. function wp_checkdate( $month, $day, $year, $source_date ) {
  5793. /**
  5794. * Filters whether the given date is valid for the Gregorian calendar.
  5795. *
  5796. * @since 3.5.0
  5797. *
  5798. * @param bool $checkdate Whether the given date is valid.
  5799. * @param string $source_date Date to check.
  5800. */
  5801. return apply_filters( 'wp_checkdate', checkdate( $month, $day, $year ), $source_date );
  5802. }
  5803. /**
  5804. * Load the auth check for monitoring whether the user is still logged in.
  5805. *
  5806. * Can be disabled with remove_action( 'admin_enqueue_scripts', 'wp_auth_check_load' );
  5807. *
  5808. * This is disabled for certain screens where a login screen could cause an
  5809. * inconvenient interruption. A filter called {@see 'wp_auth_check_load'} can be used
  5810. * for fine-grained control.
  5811. *
  5812. * @since 3.6.0
  5813. */
  5814. function wp_auth_check_load() {
  5815. if ( ! is_admin() && ! is_user_logged_in() ) {
  5816. return;
  5817. }
  5818. if ( defined( 'IFRAME_REQUEST' ) ) {
  5819. return;
  5820. }
  5821. $screen = get_current_screen();
  5822. $hidden = array( 'update', 'update-network', 'update-core', 'update-core-network', 'upgrade', 'upgrade-network', 'network' );
  5823. $show = ! in_array( $screen->id, $hidden, true );
  5824. /**
  5825. * Filters whether to load the authentication check.
  5826. *
  5827. * Passing a falsey value to the filter will effectively short-circuit
  5828. * loading the authentication check.
  5829. *
  5830. * @since 3.6.0
  5831. *
  5832. * @param bool $show Whether to load the authentication check.
  5833. * @param WP_Screen $screen The current screen object.
  5834. */
  5835. if ( apply_filters( 'wp_auth_check_load', $show, $screen ) ) {
  5836. wp_enqueue_style( 'wp-auth-check' );
  5837. wp_enqueue_script( 'wp-auth-check' );
  5838. add_action( 'admin_print_footer_scripts', 'wp_auth_check_html', 5 );
  5839. add_action( 'wp_print_footer_scripts', 'wp_auth_check_html', 5 );
  5840. }
  5841. }
  5842. /**
  5843. * Output the HTML that shows the wp-login dialog when the user is no longer logged in.
  5844. *
  5845. * @since 3.6.0
  5846. */
  5847. function wp_auth_check_html() {
  5848. $login_url = wp_login_url();
  5849. $current_domain = ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'];
  5850. $same_domain = ( strpos( $login_url, $current_domain ) === 0 );
  5851. /**
  5852. * Filters whether the authentication check originated at the same domain.
  5853. *
  5854. * @since 3.6.0
  5855. *
  5856. * @param bool $same_domain Whether the authentication check originated at the same domain.
  5857. */
  5858. $same_domain = apply_filters( 'wp_auth_check_same_domain', $same_domain );
  5859. $wrap_class = $same_domain ? 'hidden' : 'hidden fallback';
  5860. ?>
  5861. <div id="wp-auth-check-wrap" class="<?php echo $wrap_class; ?>">
  5862. <div id="wp-auth-check-bg"></div>
  5863. <div id="wp-auth-check">
  5864. <button type="button" class="wp-auth-check-close button-link"><span class="screen-reader-text"><?php _e( 'Close dialog' ); ?></span></button>
  5865. <?php
  5866. if ( $same_domain ) {
  5867. $login_src = add_query_arg(
  5868. array(
  5869. 'interim-login' => '1',
  5870. 'wp_lang' => get_user_locale(),
  5871. ),
  5872. $login_url
  5873. );
  5874. ?>
  5875. <div id="wp-auth-check-form" class="loading" data-src="<?php echo esc_url( $login_src ); ?>"></div>
  5876. <?php
  5877. }
  5878. ?>
  5879. <div class="wp-auth-fallback">
  5880. <p><b class="wp-auth-fallback-expired" tabindex="0"><?php _e( 'Session expired' ); ?></b></p>
  5881. <p><a href="<?php echo esc_url( $login_url ); ?>" target="_blank"><?php _e( 'Please log in again.' ); ?></a>
  5882. <?php _e( 'The login page will open in a new tab. After logging in you can close it and return to this page.' ); ?></p>
  5883. </div>
  5884. </div>
  5885. </div>
  5886. <?php
  5887. }
  5888. /**
  5889. * Check whether a user is still logged in, for the heartbeat.
  5890. *
  5891. * Send a result that shows a log-in box if the user is no longer logged in,
  5892. * or if their cookie is within the grace period.
  5893. *
  5894. * @since 3.6.0
  5895. *
  5896. * @global int $login_grace_period
  5897. *
  5898. * @param array $response The Heartbeat response.
  5899. * @return array The Heartbeat response with 'wp-auth-check' value set.
  5900. */
  5901. function wp_auth_check( $response ) {
  5902. $response['wp-auth-check'] = is_user_logged_in() && empty( $GLOBALS['login_grace_period'] );
  5903. return $response;
  5904. }
  5905. /**
  5906. * Return RegEx body to liberally match an opening HTML tag.
  5907. *
  5908. * Matches an opening HTML tag that:
  5909. * 1. Is self-closing or
  5910. * 2. Has no body but has a closing tag of the same name or
  5911. * 3. Contains a body and a closing tag of the same name
  5912. *
  5913. * Note: this RegEx does not balance inner tags and does not attempt
  5914. * to produce valid HTML
  5915. *
  5916. * @since 3.6.0
  5917. *
  5918. * @param string $tag An HTML tag name. Example: 'video'.
  5919. * @return string Tag RegEx.
  5920. */
  5921. function get_tag_regex( $tag ) {
  5922. if ( empty( $tag ) ) {
  5923. return '';
  5924. }
  5925. return sprintf( '<%1$s[^<]*(?:>[\s\S]*<\/%1$s>|\s*\/>)', tag_escape( $tag ) );
  5926. }
  5927. /**
  5928. * Retrieve a canonical form of the provided charset appropriate for passing to PHP
  5929. * functions such as htmlspecialchars() and charset html attributes.
  5930. *
  5931. * @since 3.6.0
  5932. * @access private
  5933. *
  5934. * @see https://core.trac.wordpress.org/ticket/23688
  5935. *
  5936. * @param string $charset A charset name.
  5937. * @return string The canonical form of the charset.
  5938. */
  5939. function _canonical_charset( $charset ) {
  5940. if ( 'utf-8' === strtolower( $charset ) || 'utf8' === strtolower( $charset ) ) {
  5941. return 'UTF-8';
  5942. }
  5943. if ( 'iso-8859-1' === strtolower( $charset ) || 'iso8859-1' === strtolower( $charset ) ) {
  5944. return 'ISO-8859-1';
  5945. }
  5946. return $charset;
  5947. }
  5948. /**
  5949. * Set the mbstring internal encoding to a binary safe encoding when func_overload
  5950. * is enabled.
  5951. *
  5952. * When mbstring.func_overload is in use for multi-byte encodings, the results from
  5953. * strlen() and similar functions respect the utf8 characters, causing binary data
  5954. * to return incorrect lengths.
  5955. *
  5956. * This function overrides the mbstring encoding to a binary-safe encoding, and
  5957. * resets it to the users expected encoding afterwards through the
  5958. * `reset_mbstring_encoding` function.
  5959. *
  5960. * It is safe to recursively call this function, however each
  5961. * `mbstring_binary_safe_encoding()` call must be followed up with an equal number
  5962. * of `reset_mbstring_encoding()` calls.
  5963. *
  5964. * @since 3.7.0
  5965. *
  5966. * @see reset_mbstring_encoding()
  5967. *
  5968. * @staticvar array $encodings
  5969. * @staticvar bool $overloaded
  5970. *
  5971. * @param bool $reset Optional. Whether to reset the encoding back to a previously-set encoding.
  5972. * Default false.
  5973. */
  5974. function mbstring_binary_safe_encoding( $reset = false ) {
  5975. static $encodings = array();
  5976. static $overloaded = null;
  5977. if ( is_null( $overloaded ) ) {
  5978. $overloaded = function_exists( 'mb_internal_encoding' ) && ( ini_get( 'mbstring.func_overload' ) & 2 );
  5979. }
  5980. if ( false === $overloaded ) {
  5981. return;
  5982. }
  5983. if ( ! $reset ) {
  5984. $encoding = mb_internal_encoding();
  5985. array_push( $encodings, $encoding );
  5986. mb_internal_encoding( 'ISO-8859-1' );
  5987. }
  5988. if ( $reset && $encodings ) {
  5989. $encoding = array_pop( $encodings );
  5990. mb_internal_encoding( $encoding );
  5991. }
  5992. }
  5993. /**
  5994. * Reset the mbstring internal encoding to a users previously set encoding.
  5995. *
  5996. * @see mbstring_binary_safe_encoding()
  5997. *
  5998. * @since 3.7.0
  5999. */
  6000. function reset_mbstring_encoding() {
  6001. mbstring_binary_safe_encoding( true );
  6002. }
  6003. /**
  6004. * Filter/validate a variable as a boolean.
  6005. *
  6006. * Alternative to `filter_var( $var, FILTER_VALIDATE_BOOLEAN )`.
  6007. *
  6008. * @since 4.0.0
  6009. *
  6010. * @param mixed $var Boolean value to validate.
  6011. * @return bool Whether the value is validated.
  6012. */
  6013. function wp_validate_boolean( $var ) {
  6014. if ( is_bool( $var ) ) {
  6015. return $var;
  6016. }
  6017. if ( is_string( $var ) && 'false' === strtolower( $var ) ) {
  6018. return false;
  6019. }
  6020. return (bool) $var;
  6021. }
  6022. /**
  6023. * Delete a file
  6024. *
  6025. * @since 4.2.0
  6026. *
  6027. * @param string $file The path to the file to delete.
  6028. */
  6029. function wp_delete_file( $file ) {
  6030. /**
  6031. * Filters the path of the file to delete.
  6032. *
  6033. * @since 2.1.0
  6034. *
  6035. * @param string $file Path to the file to delete.
  6036. */
  6037. $delete = apply_filters( 'wp_delete_file', $file );
  6038. if ( ! empty( $delete ) ) {
  6039. @unlink( $delete );
  6040. }
  6041. }
  6042. /**
  6043. * Deletes a file if its path is within the given directory.
  6044. *
  6045. * @since 4.9.7
  6046. *
  6047. * @param string $file Absolute path to the file to delete.
  6048. * @param string $directory Absolute path to a directory.
  6049. * @return bool True on success, false on failure.
  6050. */
  6051. function wp_delete_file_from_directory( $file, $directory ) {
  6052. if ( wp_is_stream( $file ) ) {
  6053. $real_file = $file;
  6054. $real_directory = $directory;
  6055. } else {
  6056. $real_file = realpath( wp_normalize_path( $file ) );
  6057. $real_directory = realpath( wp_normalize_path( $directory ) );
  6058. }
  6059. if ( false !== $real_file ) {
  6060. $real_file = wp_normalize_path( $real_file );
  6061. }
  6062. if ( false !== $real_directory ) {
  6063. $real_directory = wp_normalize_path( $real_directory );
  6064. }
  6065. if ( false === $real_file || false === $real_directory || strpos( $real_file, trailingslashit( $real_directory ) ) !== 0 ) {
  6066. return false;
  6067. }
  6068. wp_delete_file( $file );
  6069. return true;
  6070. }
  6071. /**
  6072. * Outputs a small JS snippet on preview tabs/windows to remove `window.name` on unload.
  6073. *
  6074. * This prevents reusing the same tab for a preview when the user has navigated away.
  6075. *
  6076. * @since 4.3.0
  6077. *
  6078. * @global WP_Post $post Global post object.
  6079. */
  6080. function wp_post_preview_js() {
  6081. global $post;
  6082. if ( ! is_preview() || empty( $post ) ) {
  6083. return;
  6084. }
  6085. // Has to match the window name used in post_submit_meta_box().
  6086. $name = 'wp-preview-' . (int) $post->ID;
  6087. ?>
  6088. <script>
  6089. ( function() {
  6090. var query = document.location.search;
  6091. if ( query && query.indexOf( 'preview=true' ) !== -1 ) {
  6092. window.name = '<?php echo $name; ?>';
  6093. }
  6094. if ( window.addEventListener ) {
  6095. window.addEventListener( 'unload', function() { window.name = ''; }, false );
  6096. }
  6097. }());
  6098. </script>
  6099. <?php
  6100. }
  6101. /**
  6102. * Parses and formats a MySQL datetime (Y-m-d H:i:s) for ISO8601 (Y-m-d\TH:i:s).
  6103. *
  6104. * Explicitly strips timezones, as datetimes are not saved with any timezone
  6105. * information. Including any information on the offset could be misleading.
  6106. *
  6107. * Despite historical function name, the output does not conform to RFC3339 format,
  6108. * which must contain timezone.
  6109. *
  6110. * @since 4.4.0
  6111. *
  6112. * @param string $date_string Date string to parse and format.
  6113. * @return string Date formatted for ISO8601 without time zone.
  6114. */
  6115. function mysql_to_rfc3339( $date_string ) {
  6116. return mysql2date( 'Y-m-d\TH:i:s', $date_string, false );
  6117. }
  6118. /**
  6119. * Attempts to raise the PHP memory limit for memory intensive processes.
  6120. *
  6121. * Only allows raising the existing limit and prevents lowering it.
  6122. *
  6123. * @since 4.6.0
  6124. *
  6125. * @param string $context Optional. Context in which the function is called. Accepts either 'admin',
  6126. * 'image', or an arbitrary other context. If an arbitrary context is passed,
  6127. * the similarly arbitrary {@see '{$context}_memory_limit'} filter will be
  6128. * invoked. Default 'admin'.
  6129. * @return bool|int|string The limit that was set or false on failure.
  6130. */
  6131. function wp_raise_memory_limit( $context = 'admin' ) {
  6132. // Exit early if the limit cannot be changed.
  6133. if ( false === wp_is_ini_value_changeable( 'memory_limit' ) ) {
  6134. return false;
  6135. }
  6136. $current_limit = ini_get( 'memory_limit' );
  6137. $current_limit_int = wp_convert_hr_to_bytes( $current_limit );
  6138. if ( -1 === $current_limit_int ) {
  6139. return false;
  6140. }
  6141. $wp_max_limit = WP_MAX_MEMORY_LIMIT;
  6142. $wp_max_limit_int = wp_convert_hr_to_bytes( $wp_max_limit );
  6143. $filtered_limit = $wp_max_limit;
  6144. switch ( $context ) {
  6145. case 'admin':
  6146. /**
  6147. * Filters the maximum memory limit available for administration screens.
  6148. *
  6149. * This only applies to administrators, who may require more memory for tasks
  6150. * like updates. Memory limits when processing images (uploaded or edited by
  6151. * users of any role) are handled separately.
  6152. *
  6153. * The `WP_MAX_MEMORY_LIMIT` constant specifically defines the maximum memory
  6154. * limit available when in the administration back end. The default is 256M
  6155. * (256 megabytes of memory) or the original `memory_limit` php.ini value if
  6156. * this is higher.
  6157. *
  6158. * @since 3.0.0
  6159. * @since 4.6.0 The default now takes the original `memory_limit` into account.
  6160. *
  6161. * @param int|string $filtered_limit The maximum WordPress memory limit. Accepts an integer
  6162. * (bytes), or a shorthand string notation, such as '256M'.
  6163. */
  6164. $filtered_limit = apply_filters( 'admin_memory_limit', $filtered_limit );
  6165. break;
  6166. case 'image':
  6167. /**
  6168. * Filters the memory limit allocated for image manipulation.
  6169. *
  6170. * @since 3.5.0
  6171. * @since 4.6.0 The default now takes the original `memory_limit` into account.
  6172. *
  6173. * @param int|string $filtered_limit Maximum memory limit to allocate for images.
  6174. * Default `WP_MAX_MEMORY_LIMIT` or the original
  6175. * php.ini `memory_limit`, whichever is higher.
  6176. * Accepts an integer (bytes), or a shorthand string
  6177. * notation, such as '256M'.
  6178. */
  6179. $filtered_limit = apply_filters( 'image_memory_limit', $filtered_limit );
  6180. break;
  6181. default:
  6182. /**
  6183. * Filters the memory limit allocated for arbitrary contexts.
  6184. *
  6185. * The dynamic portion of the hook name, `$context`, refers to an arbitrary
  6186. * context passed on calling the function. This allows for plugins to define
  6187. * their own contexts for raising the memory limit.
  6188. *
  6189. * @since 4.6.0
  6190. *
  6191. * @param int|string $filtered_limit Maximum memory limit to allocate for images.
  6192. * Default '256M' or the original php.ini `memory_limit`,
  6193. * whichever is higher. Accepts an integer (bytes), or a
  6194. * shorthand string notation, such as '256M'.
  6195. */
  6196. $filtered_limit = apply_filters( "{$context}_memory_limit", $filtered_limit );
  6197. break;
  6198. }
  6199. $filtered_limit_int = wp_convert_hr_to_bytes( $filtered_limit );
  6200. if ( -1 === $filtered_limit_int || ( $filtered_limit_int > $wp_max_limit_int && $filtered_limit_int > $current_limit_int ) ) {
  6201. if ( false !== ini_set( 'memory_limit', $filtered_limit ) ) {
  6202. return $filtered_limit;
  6203. } else {
  6204. return false;
  6205. }
  6206. } elseif ( -1 === $wp_max_limit_int || $wp_max_limit_int > $current_limit_int ) {
  6207. if ( false !== ini_set( 'memory_limit', $wp_max_limit ) ) {
  6208. return $wp_max_limit;
  6209. } else {
  6210. return false;
  6211. }
  6212. }
  6213. return false;
  6214. }
  6215. /**
  6216. * Generate a random UUID (version 4).
  6217. *
  6218. * @since 4.7.0
  6219. *
  6220. * @return string UUID.
  6221. */
  6222. function wp_generate_uuid4() {
  6223. return sprintf(
  6224. '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
  6225. mt_rand( 0, 0xffff ),
  6226. mt_rand( 0, 0xffff ),
  6227. mt_rand( 0, 0xffff ),
  6228. mt_rand( 0, 0x0fff ) | 0x4000,
  6229. mt_rand( 0, 0x3fff ) | 0x8000,
  6230. mt_rand( 0, 0xffff ),
  6231. mt_rand( 0, 0xffff ),
  6232. mt_rand( 0, 0xffff )
  6233. );
  6234. }
  6235. /**
  6236. * Validates that a UUID is valid.
  6237. *
  6238. * @since 4.9.0
  6239. *
  6240. * @param mixed $uuid UUID to check.
  6241. * @param int $version Specify which version of UUID to check against. Default is none,
  6242. * to accept any UUID version. Otherwise, only version allowed is `4`.
  6243. * @return bool The string is a valid UUID or false on failure.
  6244. */
  6245. function wp_is_uuid( $uuid, $version = null ) {
  6246. if ( ! is_string( $uuid ) ) {
  6247. return false;
  6248. }
  6249. if ( is_numeric( $version ) ) {
  6250. if ( 4 !== (int) $version ) {
  6251. _doing_it_wrong( __FUNCTION__, __( 'Only UUID V4 is supported at this time.' ), '4.9.0' );
  6252. return false;
  6253. }
  6254. $regex = '/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/';
  6255. } else {
  6256. $regex = '/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/';
  6257. }
  6258. return (bool) preg_match( $regex, $uuid );
  6259. }
  6260. /**
  6261. * Get unique ID.
  6262. *
  6263. * This is a PHP implementation of Underscore's uniqueId method. A static variable
  6264. * contains an integer that is incremented with each call. This number is returned
  6265. * with the optional prefix. As such the returned value is not universally unique,
  6266. * but it is unique across the life of the PHP process.
  6267. *
  6268. * @since 5.0.3
  6269. *
  6270. * @staticvar int $id_counter
  6271. *
  6272. * @param string $prefix Prefix for the returned ID.
  6273. * @return string Unique ID.
  6274. */
  6275. function wp_unique_id( $prefix = '' ) {
  6276. static $id_counter = 0;
  6277. return $prefix . (string) ++$id_counter;
  6278. }
  6279. /**
  6280. * Get last changed date for the specified cache group.
  6281. *
  6282. * @since 4.7.0
  6283. *
  6284. * @param string $group Where the cache contents are grouped.
  6285. *
  6286. * @return string $last_changed UNIX timestamp with microseconds representing when the group was last changed.
  6287. */
  6288. function wp_cache_get_last_changed( $group ) {
  6289. $last_changed = wp_cache_get( 'last_changed', $group );
  6290. if ( ! $last_changed ) {
  6291. $last_changed = microtime();
  6292. wp_cache_set( 'last_changed', $last_changed, $group );
  6293. }
  6294. return $last_changed;
  6295. }
  6296. /**
  6297. * Send an email to the old site admin email address when the site admin email address changes.
  6298. *
  6299. * @since 4.9.0
  6300. *
  6301. * @param string $old_email The old site admin email address.
  6302. * @param string $new_email The new site admin email address.
  6303. * @param string $option_name The relevant database option name.
  6304. */
  6305. function wp_site_admin_email_change_notification( $old_email, $new_email, $option_name ) {
  6306. $send = true;
  6307. // Don't send the notification to the default 'admin_email' value.
  6308. if ( 'you@example.com' === $old_email ) {
  6309. $send = false;
  6310. }
  6311. /**
  6312. * Filters whether to send the site admin email change notification email.
  6313. *
  6314. * @since 4.9.0
  6315. *
  6316. * @param bool $send Whether to send the email notification.
  6317. * @param string $old_email The old site admin email address.
  6318. * @param string $new_email The new site admin email address.
  6319. */
  6320. $send = apply_filters( 'send_site_admin_email_change_email', $send, $old_email, $new_email );
  6321. if ( ! $send ) {
  6322. return;
  6323. }
  6324. /* translators: Do not translate OLD_EMAIL, NEW_EMAIL, SITENAME, SITEURL: those are placeholders. */
  6325. $email_change_text = __(
  6326. 'Hi,
  6327. This notice confirms that the admin email address was changed on ###SITENAME###.
  6328. The new admin email address is ###NEW_EMAIL###.
  6329. This email has been sent to ###OLD_EMAIL###
  6330. Regards,
  6331. All at ###SITENAME###
  6332. ###SITEURL###'
  6333. );
  6334. $email_change_email = array(
  6335. 'to' => $old_email,
  6336. /* translators: Site admin email change notification email subject. %s: Site title. */
  6337. 'subject' => __( '[%s] Admin Email Changed' ),
  6338. 'message' => $email_change_text,
  6339. 'headers' => '',
  6340. );
  6341. // Get site name.
  6342. $site_name = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
  6343. /**
  6344. * Filters the contents of the email notification sent when the site admin email address is changed.
  6345. *
  6346. * @since 4.9.0
  6347. *
  6348. * @param array $email_change_email {
  6349. * Used to build wp_mail().
  6350. *
  6351. * @type string $to The intended recipient.
  6352. * @type string $subject The subject of the email.
  6353. * @type string $message The content of the email.
  6354. * The following strings have a special meaning and will get replaced dynamically:
  6355. * - ###OLD_EMAIL### The old site admin email address.
  6356. * - ###NEW_EMAIL### The new site admin email address.
  6357. * - ###SITENAME### The name of the site.
  6358. * - ###SITEURL### The URL to the site.
  6359. * @type string $headers Headers.
  6360. * }
  6361. * @param string $old_email The old site admin email address.
  6362. * @param string $new_email The new site admin email address.
  6363. */
  6364. $email_change_email = apply_filters( 'site_admin_email_change_email', $email_change_email, $old_email, $new_email );
  6365. $email_change_email['message'] = str_replace( '###OLD_EMAIL###', $old_email, $email_change_email['message'] );
  6366. $email_change_email['message'] = str_replace( '###NEW_EMAIL###', $new_email, $email_change_email['message'] );
  6367. $email_change_email['message'] = str_replace( '###SITENAME###', $site_name, $email_change_email['message'] );
  6368. $email_change_email['message'] = str_replace( '###SITEURL###', home_url(), $email_change_email['message'] );
  6369. wp_mail(
  6370. $email_change_email['to'],
  6371. sprintf(
  6372. $email_change_email['subject'],
  6373. $site_name
  6374. ),
  6375. $email_change_email['message'],
  6376. $email_change_email['headers']
  6377. );
  6378. }
  6379. /**
  6380. * Return an anonymized IPv4 or IPv6 address.
  6381. *
  6382. * @since 4.9.6 Abstracted from `WP_Community_Events::get_unsafe_client_ip()`.
  6383. *
  6384. * @param string $ip_addr The IPv4 or IPv6 address to be anonymized.
  6385. * @param bool $ipv6_fallback Optional. Whether to return the original IPv6 address if the needed functions
  6386. * to anonymize it are not present. Default false, return `::` (unspecified address).
  6387. * @return string The anonymized IP address.
  6388. */
  6389. function wp_privacy_anonymize_ip( $ip_addr, $ipv6_fallback = false ) {
  6390. // Detect what kind of IP address this is.
  6391. $ip_prefix = '';
  6392. $is_ipv6 = substr_count( $ip_addr, ':' ) > 1;
  6393. $is_ipv4 = ( 3 === substr_count( $ip_addr, '.' ) );
  6394. if ( $is_ipv6 && $is_ipv4 ) {
  6395. // IPv6 compatibility mode, temporarily strip the IPv6 part, and treat it like IPv4.
  6396. $ip_prefix = '::ffff:';
  6397. $ip_addr = preg_replace( '/^\[?[0-9a-f:]*:/i', '', $ip_addr );
  6398. $ip_addr = str_replace( ']', '', $ip_addr );
  6399. $is_ipv6 = false;
  6400. }
  6401. if ( $is_ipv6 ) {
  6402. // IPv6 addresses will always be enclosed in [] if there's a port.
  6403. $left_bracket = strpos( $ip_addr, '[' );
  6404. $right_bracket = strpos( $ip_addr, ']' );
  6405. $percent = strpos( $ip_addr, '%' );
  6406. $netmask = 'ffff:ffff:ffff:ffff:0000:0000:0000:0000';
  6407. // Strip the port (and [] from IPv6 addresses), if they exist.
  6408. if ( false !== $left_bracket && false !== $right_bracket ) {
  6409. $ip_addr = substr( $ip_addr, $left_bracket + 1, $right_bracket - $left_bracket - 1 );
  6410. } elseif ( false !== $left_bracket || false !== $right_bracket ) {
  6411. // The IP has one bracket, but not both, so it's malformed.
  6412. return '::';
  6413. }
  6414. // Strip the reachability scope.
  6415. if ( false !== $percent ) {
  6416. $ip_addr = substr( $ip_addr, 0, $percent );
  6417. }
  6418. // No invalid characters should be left.
  6419. if ( preg_match( '/[^0-9a-f:]/i', $ip_addr ) ) {
  6420. return '::';
  6421. }
  6422. // Partially anonymize the IP by reducing it to the corresponding network ID.
  6423. if ( function_exists( 'inet_pton' ) && function_exists( 'inet_ntop' ) ) {
  6424. $ip_addr = inet_ntop( inet_pton( $ip_addr ) & inet_pton( $netmask ) );
  6425. if ( false === $ip_addr ) {
  6426. return '::';
  6427. }
  6428. } elseif ( ! $ipv6_fallback ) {
  6429. return '::';
  6430. }
  6431. } elseif ( $is_ipv4 ) {
  6432. // Strip any port and partially anonymize the IP.
  6433. $last_octet_position = strrpos( $ip_addr, '.' );
  6434. $ip_addr = substr( $ip_addr, 0, $last_octet_position ) . '.0';
  6435. } else {
  6436. return '0.0.0.0';
  6437. }
  6438. // Restore the IPv6 prefix to compatibility mode addresses.
  6439. return $ip_prefix . $ip_addr;
  6440. }
  6441. /**
  6442. * Return uniform "anonymous" data by type.
  6443. *
  6444. * @since 4.9.6
  6445. *
  6446. * @param string $type The type of data to be anonymized.
  6447. * @param string $data Optional The data to be anonymized.
  6448. * @return string The anonymous data for the requested type.
  6449. */
  6450. function wp_privacy_anonymize_data( $type, $data = '' ) {
  6451. switch ( $type ) {
  6452. case 'email':
  6453. $anonymous = 'deleted@site.invalid';
  6454. break;
  6455. case 'url':
  6456. $anonymous = 'https://site.invalid';
  6457. break;
  6458. case 'ip':
  6459. $anonymous = wp_privacy_anonymize_ip( $data );
  6460. break;
  6461. case 'date':
  6462. $anonymous = '0000-00-00 00:00:00';
  6463. break;
  6464. case 'text':
  6465. /* translators: Deleted text. */
  6466. $anonymous = __( '[deleted]' );
  6467. break;
  6468. case 'longtext':
  6469. /* translators: Deleted long text. */
  6470. $anonymous = __( 'This content was deleted by the author.' );
  6471. break;
  6472. default:
  6473. $anonymous = '';
  6474. break;
  6475. }
  6476. /**
  6477. * Filters the anonymous data for each type.
  6478. *
  6479. * @since 4.9.6
  6480. *
  6481. * @param string $anonymous Anonymized data.
  6482. * @param string $type Type of the data.
  6483. * @param string $data Original data.
  6484. */
  6485. return apply_filters( 'wp_privacy_anonymize_data', $anonymous, $type, $data );
  6486. }
  6487. /**
  6488. * Returns the directory used to store personal data export files.
  6489. *
  6490. * @since 4.9.6
  6491. *
  6492. * @see wp_privacy_exports_url
  6493. *
  6494. * @return string Exports directory.
  6495. */
  6496. function wp_privacy_exports_dir() {
  6497. $upload_dir = wp_upload_dir();
  6498. $exports_dir = trailingslashit( $upload_dir['basedir'] ) . 'wp-personal-data-exports/';
  6499. /**
  6500. * Filters the directory used to store personal data export files.
  6501. *
  6502. * @since 4.9.6
  6503. *
  6504. * @param string $exports_dir Exports directory.
  6505. */
  6506. return apply_filters( 'wp_privacy_exports_dir', $exports_dir );
  6507. }
  6508. /**
  6509. * Returns the URL of the directory used to store personal data export files.
  6510. *
  6511. * @since 4.9.6
  6512. *
  6513. * @see wp_privacy_exports_dir
  6514. *
  6515. * @return string Exports directory URL.
  6516. */
  6517. function wp_privacy_exports_url() {
  6518. $upload_dir = wp_upload_dir();
  6519. $exports_url = trailingslashit( $upload_dir['baseurl'] ) . 'wp-personal-data-exports/';
  6520. /**
  6521. * Filters the URL of the directory used to store personal data export files.
  6522. *
  6523. * @since 4.9.6
  6524. *
  6525. * @param string $exports_url Exports directory URL.
  6526. */
  6527. return apply_filters( 'wp_privacy_exports_url', $exports_url );
  6528. }
  6529. /**
  6530. * Schedule a `WP_Cron` job to delete expired export files.
  6531. *
  6532. * @since 4.9.6
  6533. */
  6534. function wp_schedule_delete_old_privacy_export_files() {
  6535. if ( wp_installing() ) {
  6536. return;
  6537. }
  6538. if ( ! wp_next_scheduled( 'wp_privacy_delete_old_export_files' ) ) {
  6539. wp_schedule_event( time(), 'hourly', 'wp_privacy_delete_old_export_files' );
  6540. }
  6541. }
  6542. /**
  6543. * Cleans up export files older than three days old.
  6544. *
  6545. * The export files are stored in `wp-content/uploads`, and are therefore publicly
  6546. * accessible. A CSPRN is appended to the filename to mitigate the risk of an
  6547. * unauthorized person downloading the file, but it is still possible. Deleting
  6548. * the file after the data subject has had a chance to delete it adds an additional
  6549. * layer of protection.
  6550. *
  6551. * @since 4.9.6
  6552. */
  6553. function wp_privacy_delete_old_export_files() {
  6554. $exports_dir = wp_privacy_exports_dir();
  6555. if ( ! is_dir( $exports_dir ) ) {
  6556. return;
  6557. }
  6558. require_once ABSPATH . 'wp-admin/includes/file.php';
  6559. $export_files = list_files( $exports_dir, 100, array( 'index.html' ) );
  6560. /**
  6561. * Filters the lifetime, in seconds, of a personal data export file.
  6562. *
  6563. * By default, the lifetime is 3 days. Once the file reaches that age, it will automatically
  6564. * be deleted by a cron job.
  6565. *
  6566. * @since 4.9.6
  6567. *
  6568. * @param int $expiration The expiration age of the export, in seconds.
  6569. */
  6570. $expiration = apply_filters( 'wp_privacy_export_expiration', 3 * DAY_IN_SECONDS );
  6571. foreach ( (array) $export_files as $export_file ) {
  6572. $file_age_in_seconds = time() - filemtime( $export_file );
  6573. if ( $expiration < $file_age_in_seconds ) {
  6574. unlink( $export_file );
  6575. }
  6576. }
  6577. }
  6578. /**
  6579. * Gets the URL to learn more about updating the PHP version the site is running on.
  6580. *
  6581. * This URL can be overridden by specifying an environment variable `WP_UPDATE_PHP_URL` or by using the
  6582. * {@see 'wp_update_php_url'} filter. Providing an empty string is not allowed and will result in the
  6583. * default URL being used. Furthermore the page the URL links to should preferably be localized in the
  6584. * site language.
  6585. *
  6586. * @since 5.1.0
  6587. *
  6588. * @return string URL to learn more about updating PHP.
  6589. */
  6590. function wp_get_update_php_url() {
  6591. $default_url = wp_get_default_update_php_url();
  6592. $update_url = $default_url;
  6593. if ( false !== getenv( 'WP_UPDATE_PHP_URL' ) ) {
  6594. $update_url = getenv( 'WP_UPDATE_PHP_URL' );
  6595. }
  6596. /**
  6597. * Filters the URL to learn more about updating the PHP version the site is running on.
  6598. *
  6599. * Providing an empty string is not allowed and will result in the default URL being used. Furthermore
  6600. * the page the URL links to should preferably be localized in the site language.
  6601. *
  6602. * @since 5.1.0
  6603. *
  6604. * @param string $update_url URL to learn more about updating PHP.
  6605. */
  6606. $update_url = apply_filters( 'wp_update_php_url', $update_url );
  6607. if ( empty( $update_url ) ) {
  6608. $update_url = $default_url;
  6609. }
  6610. return $update_url;
  6611. }
  6612. /**
  6613. * Gets the default URL to learn more about updating the PHP version the site is running on.
  6614. *
  6615. * Do not use this function to retrieve this URL. Instead, use {@see wp_get_update_php_url()} when relying on the URL.
  6616. * This function does not allow modifying the returned URL, and is only used to compare the actually used URL with the
  6617. * default one.
  6618. *
  6619. * @since 5.1.0
  6620. * @access private
  6621. *
  6622. * @return string Default URL to learn more about updating PHP.
  6623. */
  6624. function wp_get_default_update_php_url() {
  6625. return _x( 'https://wordpress.org/support/update-php/', 'localized PHP upgrade information page' );
  6626. }
  6627. /**
  6628. * Prints the default annotation for the web host altering the "Update PHP" page URL.
  6629. *
  6630. * This function is to be used after {@see wp_get_update_php_url()} to display a consistent
  6631. * annotation if the web host has altered the default "Update PHP" page URL.
  6632. *
  6633. * @since 5.1.0
  6634. * @since 5.2.0 Added the `$before` and `$after` parameters.
  6635. *
  6636. * @param string $before Markup to output before the annotation. Default `<p class="description">`.
  6637. * @param string $after Markup to output after the annotation. Default `</p>`.
  6638. */
  6639. function wp_update_php_annotation( $before = '<p class="description">', $after = '</p>' ) {
  6640. $annotation = wp_get_update_php_annotation();
  6641. if ( $annotation ) {
  6642. echo $before . $annotation . $after;
  6643. }
  6644. }
  6645. /**
  6646. * Returns the default annotation for the web hosting altering the "Update PHP" page URL.
  6647. *
  6648. * This function is to be used after {@see wp_get_update_php_url()} to return a consistent
  6649. * annotation if the web host has altered the default "Update PHP" page URL.
  6650. *
  6651. * @since 5.2.0
  6652. *
  6653. * @return string $message Update PHP page annotation. An empty string if no custom URLs are provided.
  6654. */
  6655. function wp_get_update_php_annotation() {
  6656. $update_url = wp_get_update_php_url();
  6657. $default_url = wp_get_default_update_php_url();
  6658. if ( $update_url === $default_url ) {
  6659. return '';
  6660. }
  6661. $annotation = sprintf(
  6662. /* translators: %s: Default Update PHP page URL. */
  6663. __( 'This resource is provided by your web host, and is specific to your site. For more information, <a href="%s" target="_blank">see the official WordPress documentation</a>.' ),
  6664. esc_url( $default_url )
  6665. );
  6666. return $annotation;
  6667. }
  6668. /**
  6669. * Gets the URL for directly updating the PHP version the site is running on.
  6670. *
  6671. * A URL will only be returned if the `WP_DIRECT_UPDATE_PHP_URL` environment variable is specified or
  6672. * by using the {@see 'wp_direct_php_update_url'} filter. This allows hosts to send users directly to
  6673. * the page where they can update PHP to a newer version.
  6674. *
  6675. * @since 5.1.1
  6676. *
  6677. * @return string URL for directly updating PHP or empty string.
  6678. */
  6679. function wp_get_direct_php_update_url() {
  6680. $direct_update_url = '';
  6681. if ( false !== getenv( 'WP_DIRECT_UPDATE_PHP_URL' ) ) {
  6682. $direct_update_url = getenv( 'WP_DIRECT_UPDATE_PHP_URL' );
  6683. }
  6684. /**
  6685. * Filters the URL for directly updating the PHP version the site is running on from the host.
  6686. *
  6687. * @since 5.1.1
  6688. *
  6689. * @param string $direct_update_url URL for directly updating PHP.
  6690. */
  6691. $direct_update_url = apply_filters( 'wp_direct_php_update_url', $direct_update_url );
  6692. return $direct_update_url;
  6693. }
  6694. /**
  6695. * Display a button directly linking to a PHP update process.
  6696. *
  6697. * This provides hosts with a way for users to be sent directly to their PHP update process.
  6698. *
  6699. * The button is only displayed if a URL is returned by `wp_get_direct_php_update_url()`.
  6700. *
  6701. * @since 5.1.1
  6702. */
  6703. function wp_direct_php_update_button() {
  6704. $direct_update_url = wp_get_direct_php_update_url();
  6705. if ( empty( $direct_update_url ) ) {
  6706. return;
  6707. }
  6708. echo '<p class="button-container">';
  6709. printf(
  6710. '<a class="button button-primary" href="%1$s" target="_blank" rel="noopener noreferrer">%2$s <span class="screen-reader-text">%3$s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a>',
  6711. esc_url( $direct_update_url ),
  6712. __( 'Update PHP' ),
  6713. /* translators: Accessibility text. */
  6714. __( '(opens in a new tab)' )
  6715. );
  6716. echo '</p>';
  6717. }
  6718. /**
  6719. * Get the size of a directory.
  6720. *
  6721. * A helper function that is used primarily to check whether
  6722. * a blog has exceeded its allowed upload space.
  6723. *
  6724. * @since MU (3.0.0)
  6725. * @since 5.2.0 $max_execution_time parameter added.
  6726. *
  6727. * @param string $directory Full path of a directory.
  6728. * @param int $max_execution_time Maximum time to run before giving up. In seconds.
  6729. * The timeout is global and is measured from the moment WordPress started to load.
  6730. * @return int|false|null Size in bytes if a valid directory. False if not. Null if timeout.
  6731. */
  6732. function get_dirsize( $directory, $max_execution_time = null ) {
  6733. $dirsize = get_transient( 'dirsize_cache' );
  6734. if ( is_array( $dirsize ) && isset( $dirsize[ $directory ]['size'] ) ) {
  6735. return $dirsize[ $directory ]['size'];
  6736. }
  6737. if ( ! is_array( $dirsize ) ) {
  6738. $dirsize = array();
  6739. }
  6740. // Exclude individual site directories from the total when checking the main site of a network,
  6741. // as they are subdirectories and should not be counted.
  6742. if ( is_multisite() && is_main_site() ) {
  6743. $dirsize[ $directory ]['size'] = recurse_dirsize( $directory, $directory . '/sites', $max_execution_time );
  6744. } else {
  6745. $dirsize[ $directory ]['size'] = recurse_dirsize( $directory, null, $max_execution_time );
  6746. }
  6747. set_transient( 'dirsize_cache', $dirsize, HOUR_IN_SECONDS );
  6748. return $dirsize[ $directory ]['size'];
  6749. }
  6750. /**
  6751. * Get the size of a directory recursively.
  6752. *
  6753. * Used by get_dirsize() to get a directory's size when it contains
  6754. * other directories.
  6755. *
  6756. * @since MU (3.0.0)
  6757. * @since 4.3.0 $exclude parameter added.
  6758. * @since 5.2.0 $max_execution_time parameter added.
  6759. *
  6760. * @param string $directory Full path of a directory.
  6761. * @param string|array $exclude Optional. Full path of a subdirectory to exclude from the total, or array of paths.
  6762. * Expected without trailing slash(es).
  6763. * @param int $max_execution_time Maximum time to run before giving up. In seconds.
  6764. * The timeout is global and is measured from the moment WordPress started to load.
  6765. * @return int|false|null Size in bytes if a valid directory. False if not. Null if timeout.
  6766. */
  6767. function recurse_dirsize( $directory, $exclude = null, $max_execution_time = null ) {
  6768. $size = 0;
  6769. $directory = untrailingslashit( $directory );
  6770. if ( ! file_exists( $directory ) || ! is_dir( $directory ) || ! is_readable( $directory ) ) {
  6771. return false;
  6772. }
  6773. if (
  6774. ( is_string( $exclude ) && $directory === $exclude ) ||
  6775. ( is_array( $exclude ) && in_array( $directory, $exclude, true ) )
  6776. ) {
  6777. return false;
  6778. }
  6779. if ( null === $max_execution_time ) {
  6780. // Keep the previous behavior but attempt to prevent fatal errors from timeout if possible.
  6781. if ( function_exists( 'ini_get' ) ) {
  6782. $max_execution_time = ini_get( 'max_execution_time' );
  6783. } else {
  6784. // Disable...
  6785. $max_execution_time = 0;
  6786. }
  6787. // Leave 1 second "buffer" for other operations if $max_execution_time has reasonable value.
  6788. if ( $max_execution_time > 10 ) {
  6789. $max_execution_time -= 1;
  6790. }
  6791. }
  6792. $handle = opendir( $directory );
  6793. if ( $handle ) {
  6794. while ( ( $file = readdir( $handle ) ) !== false ) {
  6795. $path = $directory . '/' . $file;
  6796. if ( '.' !== $file && '..' !== $file ) {
  6797. if ( is_file( $path ) ) {
  6798. $size += filesize( $path );
  6799. } elseif ( is_dir( $path ) ) {
  6800. $handlesize = recurse_dirsize( $path, $exclude, $max_execution_time );
  6801. if ( $handlesize > 0 ) {
  6802. $size += $handlesize;
  6803. }
  6804. }
  6805. if ( $max_execution_time > 0 && microtime( true ) - WP_START_TIMESTAMP > $max_execution_time ) {
  6806. // Time exceeded. Give up instead of risking a fatal timeout.
  6807. $size = null;
  6808. break;
  6809. }
  6810. }
  6811. }
  6812. closedir( $handle );
  6813. }
  6814. return $size;
  6815. }
  6816. /**
  6817. * Checks compatibility with the current WordPress version.
  6818. *
  6819. * @since 5.2.0
  6820. *
  6821. * @param string $required Minimum required WordPress version.
  6822. * @return bool True if required version is compatible or empty, false if not.
  6823. */
  6824. function is_wp_version_compatible( $required ) {
  6825. return empty( $required ) || version_compare( get_bloginfo( 'version' ), $required, '>=' );
  6826. }
  6827. /**
  6828. * Checks compatibility with the current PHP version.
  6829. *
  6830. * @since 5.2.0
  6831. *
  6832. * @param string $required Minimum required PHP version.
  6833. * @return bool True if required version is compatible or empty, false if not.
  6834. */
  6835. function is_php_version_compatible( $required ) {
  6836. return empty( $required ) || version_compare( phpversion(), $required, '>=' );
  6837. }
  6838. /**
  6839. * Check if two numbers are nearly the same.
  6840. *
  6841. * This is similar to using `round()` but the precision is more fine-grained.
  6842. *
  6843. * @since 5.3.0
  6844. *
  6845. * @param int|float $expected The expected value.
  6846. * @param int|float $actual The actual number.
  6847. * @param int|float $precision The allowed variation.
  6848. * @return bool Whether the numbers match whithin the specified precision.
  6849. */
  6850. function wp_fuzzy_number_match( $expected, $actual, $precision = 1 ) {
  6851. return abs( (float) $expected - (float) $actual ) <= $precision;
  6852. }