PageRenderTime 104ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/functions.php

https://github.com/markjaquith/WordPress
PHP | 8373 lines | 4871 code | 714 blank | 2788 comment | 653 complexity | f866d284c4d9204f45a98bdff8f35f6e MD5 | raw file
Possible License(s): GPL-2.0, AGPL-1.0, LGPL-2.1
  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 an integer 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 Integer if `$format` is 'U' or 'G', string otherwise.
  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' or 'U' types 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 a truthy value then both types will use GMT time, otherwise the
  54. * output is adjusted with the GMT offset for the site.
  55. *
  56. * @since 1.0.0
  57. * @since 5.3.0 Now returns an integer if `$type` is 'U'. Previously a string was returned.
  58. *
  59. * @param string $type Type of time to retrieve. Accepts 'mysql', 'timestamp', 'U',
  60. * or PHP date format string (e.g. 'Y-m-d').
  61. * @param int|bool $gmt Optional. Whether to use GMT timezone. Default false.
  62. * @return int|string Integer if `$type` is 'timestamp' or 'U', string otherwise.
  63. */
  64. function current_time( $type, $gmt = 0 ) {
  65. // Don't use non-GMT timestamp, unless you know the difference and really need to.
  66. if ( 'timestamp' === $type || 'U' === $type ) {
  67. return $gmt ? time() : time() + (int) ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
  68. }
  69. if ( 'mysql' === $type ) {
  70. $type = 'Y-m-d H:i:s';
  71. }
  72. $timezone = $gmt ? new DateTimeZone( 'UTC' ) : wp_timezone();
  73. $datetime = new DateTime( 'now', $timezone );
  74. return $datetime->format( $type );
  75. }
  76. /**
  77. * Retrieves the current time as an object using the site's timezone.
  78. *
  79. * @since 5.3.0
  80. *
  81. * @return DateTimeImmutable Date and time object.
  82. */
  83. function current_datetime() {
  84. return new DateTimeImmutable( 'now', wp_timezone() );
  85. }
  86. /**
  87. * Retrieves the timezone of the site as a string.
  88. *
  89. * Uses the `timezone_string` option to get a proper timezone name if available,
  90. * otherwise falls back to a manual UTC ± offset.
  91. *
  92. * Example return values:
  93. *
  94. * - 'Europe/Rome'
  95. * - 'America/North_Dakota/New_Salem'
  96. * - 'UTC'
  97. * - '-06:30'
  98. * - '+00:00'
  99. * - '+08:45'
  100. *
  101. * @since 5.3.0
  102. *
  103. * @return string PHP timezone name or a ±HH:MM offset.
  104. */
  105. function wp_timezone_string() {
  106. $timezone_string = get_option( 'timezone_string' );
  107. if ( $timezone_string ) {
  108. return $timezone_string;
  109. }
  110. $offset = (float) get_option( 'gmt_offset' );
  111. $hours = (int) $offset;
  112. $minutes = ( $offset - $hours );
  113. $sign = ( $offset < 0 ) ? '-' : '+';
  114. $abs_hour = abs( $hours );
  115. $abs_mins = abs( $minutes * 60 );
  116. $tz_offset = sprintf( '%s%02d:%02d', $sign, $abs_hour, $abs_mins );
  117. return $tz_offset;
  118. }
  119. /**
  120. * Retrieves the timezone of the site as a `DateTimeZone` object.
  121. *
  122. * Timezone can be based on a PHP timezone string or a ±HH:MM offset.
  123. *
  124. * @since 5.3.0
  125. *
  126. * @return DateTimeZone Timezone object.
  127. */
  128. function wp_timezone() {
  129. return new DateTimeZone( wp_timezone_string() );
  130. }
  131. /**
  132. * Retrieves the date in localized format, based on a sum of Unix timestamp and
  133. * timezone offset in seconds.
  134. *
  135. * If the locale specifies the locale month and weekday, then the locale will
  136. * take over the format for the date. If it isn't, then the date format string
  137. * will be used instead.
  138. *
  139. * Note that due to the way WP typically generates a sum of timestamp and offset
  140. * with `strtotime()`, it implies offset added at a _current_ time, not at the time
  141. * the timestamp represents. Storing such timestamps or calculating them differently
  142. * will lead to invalid output.
  143. *
  144. * @since 0.71
  145. * @since 5.3.0 Converted into a wrapper for wp_date().
  146. *
  147. * @global WP_Locale $wp_locale WordPress date and time locale object.
  148. *
  149. * @param string $format Format to display the date.
  150. * @param int|bool $timestamp_with_offset Optional. A sum of Unix timestamp and timezone offset
  151. * in seconds. Default false.
  152. * @param bool $gmt Optional. Whether to use GMT timezone. Only applies
  153. * if timestamp is not provided. Default false.
  154. * @return string The date, translated if locale specifies it.
  155. */
  156. function date_i18n( $format, $timestamp_with_offset = false, $gmt = false ) {
  157. $timestamp = $timestamp_with_offset;
  158. // If timestamp is omitted it should be current time (summed with offset, unless `$gmt` is true).
  159. if ( ! is_numeric( $timestamp ) ) {
  160. // phpcs:ignore WordPress.DateTime.CurrentTimeTimestamp.Requested
  161. $timestamp = current_time( 'timestamp', $gmt );
  162. }
  163. /*
  164. * This is a legacy implementation quirk that the returned timestamp is also with offset.
  165. * Ideally this function should never be used to produce a timestamp.
  166. */
  167. if ( 'U' === $format ) {
  168. $date = $timestamp;
  169. } elseif ( $gmt && false === $timestamp_with_offset ) { // Current time in UTC.
  170. $date = wp_date( $format, null, new DateTimeZone( 'UTC' ) );
  171. } elseif ( false === $timestamp_with_offset ) { // Current time in site's timezone.
  172. $date = wp_date( $format );
  173. } else {
  174. /*
  175. * Timestamp with offset is typically produced by a UTC `strtotime()` call on an input without timezone.
  176. * This is the best attempt to reverse that operation into a local time to use.
  177. */
  178. $local_time = gmdate( 'Y-m-d H:i:s', $timestamp );
  179. $timezone = wp_timezone();
  180. $datetime = date_create( $local_time, $timezone );
  181. $date = wp_date( $format, $datetime->getTimestamp(), $timezone );
  182. }
  183. /**
  184. * Filters the date formatted based on the locale.
  185. *
  186. * @since 2.8.0
  187. *
  188. * @param string $date Formatted date string.
  189. * @param string $format Format to display the date.
  190. * @param int $timestamp A sum of Unix timestamp and timezone offset in seconds.
  191. * Might be without offset if input omitted timestamp but requested GMT.
  192. * @param bool $gmt Whether to use GMT timezone. Only applies if timestamp was not provided.
  193. * Default false.
  194. */
  195. $date = apply_filters( 'date_i18n', $date, $format, $timestamp, $gmt );
  196. return $date;
  197. }
  198. /**
  199. * Retrieves the date, in localized format.
  200. *
  201. * This is a newer function, intended to replace `date_i18n()` without legacy quirks in it.
  202. *
  203. * Note that, unlike `date_i18n()`, this function accepts a true Unix timestamp, not summed
  204. * with timezone offset.
  205. *
  206. * @since 5.3.0
  207. *
  208. * @global WP_Locale $wp_locale WordPress date and time locale object.
  209. *
  210. * @param string $format PHP date format.
  211. * @param int $timestamp Optional. Unix timestamp. Defaults to current time.
  212. * @param DateTimeZone $timezone Optional. Timezone to output result in. Defaults to timezone
  213. * from site settings.
  214. * @return string|false The date, translated if locale specifies it. False on invalid timestamp input.
  215. */
  216. function wp_date( $format, $timestamp = null, $timezone = null ) {
  217. global $wp_locale;
  218. if ( null === $timestamp ) {
  219. $timestamp = time();
  220. } elseif ( ! is_numeric( $timestamp ) ) {
  221. return false;
  222. }
  223. if ( ! $timezone ) {
  224. $timezone = wp_timezone();
  225. }
  226. $datetime = date_create( '@' . $timestamp );
  227. $datetime->setTimezone( $timezone );
  228. if ( empty( $wp_locale->month ) || empty( $wp_locale->weekday ) ) {
  229. $date = $datetime->format( $format );
  230. } else {
  231. // We need to unpack shorthand `r` format because it has parts that might be localized.
  232. $format = preg_replace( '/(?<!\\\\)r/', DATE_RFC2822, $format );
  233. $new_format = '';
  234. $format_length = strlen( $format );
  235. $month = $wp_locale->get_month( $datetime->format( 'm' ) );
  236. $weekday = $wp_locale->get_weekday( $datetime->format( 'w' ) );
  237. for ( $i = 0; $i < $format_length; $i ++ ) {
  238. switch ( $format[ $i ] ) {
  239. case 'D':
  240. $new_format .= addcslashes( $wp_locale->get_weekday_abbrev( $weekday ), '\\A..Za..z' );
  241. break;
  242. case 'F':
  243. $new_format .= addcslashes( $month, '\\A..Za..z' );
  244. break;
  245. case 'l':
  246. $new_format .= addcslashes( $weekday, '\\A..Za..z' );
  247. break;
  248. case 'M':
  249. $new_format .= addcslashes( $wp_locale->get_month_abbrev( $month ), '\\A..Za..z' );
  250. break;
  251. case 'a':
  252. $new_format .= addcslashes( $wp_locale->get_meridiem( $datetime->format( 'a' ) ), '\\A..Za..z' );
  253. break;
  254. case 'A':
  255. $new_format .= addcslashes( $wp_locale->get_meridiem( $datetime->format( 'A' ) ), '\\A..Za..z' );
  256. break;
  257. case '\\':
  258. $new_format .= $format[ $i ];
  259. // If character follows a slash, we add it without translating.
  260. if ( $i < $format_length ) {
  261. $new_format .= $format[ ++$i ];
  262. }
  263. break;
  264. default:
  265. $new_format .= $format[ $i ];
  266. break;
  267. }
  268. }
  269. $date = $datetime->format( $new_format );
  270. $date = wp_maybe_decline_date( $date, $format );
  271. }
  272. /**
  273. * Filters the date formatted based on the locale.
  274. *
  275. * @since 5.3.0
  276. *
  277. * @param string $date Formatted date string.
  278. * @param string $format Format to display the date.
  279. * @param int $timestamp Unix timestamp.
  280. * @param DateTimeZone $timezone Timezone.
  281. */
  282. $date = apply_filters( 'wp_date', $date, $format, $timestamp, $timezone );
  283. return $date;
  284. }
  285. /**
  286. * Determines if the date should be declined.
  287. *
  288. * If the locale specifies that month names require a genitive case in certain
  289. * formats (like 'j F Y'), the month name will be replaced with a correct form.
  290. *
  291. * @since 4.4.0
  292. * @since 5.4.0 The `$format` parameter was added.
  293. *
  294. * @global WP_Locale $wp_locale WordPress date and time locale object.
  295. *
  296. * @param string $date Formatted date string.
  297. * @param string $format Optional. Date format to check. Default empty string.
  298. * @return string The date, declined if locale specifies it.
  299. */
  300. function wp_maybe_decline_date( $date, $format = '' ) {
  301. global $wp_locale;
  302. // i18n functions are not available in SHORTINIT mode.
  303. if ( ! function_exists( '_x' ) ) {
  304. return $date;
  305. }
  306. /*
  307. * translators: If months in your language require a genitive case,
  308. * translate this to 'on'. Do not translate into your own language.
  309. */
  310. if ( 'on' === _x( 'off', 'decline months names: on or off' ) ) {
  311. $months = $wp_locale->month;
  312. $months_genitive = $wp_locale->month_genitive;
  313. /*
  314. * Match a format like 'j F Y' or 'j. F' (day of the month, followed by month name)
  315. * and decline the month.
  316. */
  317. if ( $format ) {
  318. $decline = preg_match( '#[dj]\.? F#', $format );
  319. } else {
  320. // If the format is not passed, try to guess it from the date string.
  321. $decline = preg_match( '#\b\d{1,2}\.? [^\d ]+\b#u', $date );
  322. }
  323. if ( $decline ) {
  324. foreach ( $months as $key => $month ) {
  325. $months[ $key ] = '# ' . preg_quote( $month, '#' ) . '\b#u';
  326. }
  327. foreach ( $months_genitive as $key => $month ) {
  328. $months_genitive[ $key ] = ' ' . $month;
  329. }
  330. $date = preg_replace( $months, $months_genitive, $date );
  331. }
  332. /*
  333. * Match a format like 'F jS' or 'F j' (month name, followed by day with an optional ordinal suffix)
  334. * and change it to declined 'j F'.
  335. */
  336. if ( $format ) {
  337. $decline = preg_match( '#F [dj]#', $format );
  338. } else {
  339. // If the format is not passed, try to guess it from the date string.
  340. $decline = preg_match( '#\b[^\d ]+ \d{1,2}(st|nd|rd|th)?\b#u', trim( $date ) );
  341. }
  342. if ( $decline ) {
  343. foreach ( $months as $key => $month ) {
  344. $months[ $key ] = '#\b' . preg_quote( $month, '#' ) . ' (\d{1,2})(st|nd|rd|th)?([-–]\d{1,2})?(st|nd|rd|th)?\b#u';
  345. }
  346. foreach ( $months_genitive as $key => $month ) {
  347. $months_genitive[ $key ] = '$1$3 ' . $month;
  348. }
  349. $date = preg_replace( $months, $months_genitive, $date );
  350. }
  351. }
  352. // Used for locale-specific rules.
  353. $locale = get_locale();
  354. if ( 'ca' === $locale ) {
  355. // " de abril| de agost| de octubre..." -> " d'abril| d'agost| d'octubre..."
  356. $date = preg_replace( '# de ([ao])#i', " d'\\1", $date );
  357. }
  358. return $date;
  359. }
  360. /**
  361. * Convert float number to format based on the locale.
  362. *
  363. * @since 2.3.0
  364. *
  365. * @global WP_Locale $wp_locale WordPress date and time locale object.
  366. *
  367. * @param float $number The number to convert based on locale.
  368. * @param int $decimals Optional. Precision of the number of decimal places. Default 0.
  369. * @return string Converted number in string format.
  370. */
  371. function number_format_i18n( $number, $decimals = 0 ) {
  372. global $wp_locale;
  373. if ( isset( $wp_locale ) ) {
  374. $formatted = number_format( $number, absint( $decimals ), $wp_locale->number_format['decimal_point'], $wp_locale->number_format['thousands_sep'] );
  375. } else {
  376. $formatted = number_format( $number, absint( $decimals ) );
  377. }
  378. /**
  379. * Filters the number formatted based on the locale.
  380. *
  381. * @since 2.8.0
  382. * @since 4.9.0 The `$number` and `$decimals` parameters were added.
  383. *
  384. * @param string $formatted Converted number in string format.
  385. * @param float $number The number to convert based on locale.
  386. * @param int $decimals Precision of the number of decimal places.
  387. */
  388. return apply_filters( 'number_format_i18n', $formatted, $number, $decimals );
  389. }
  390. /**
  391. * Convert number of bytes largest unit bytes will fit into.
  392. *
  393. * It is easier to read 1 KB than 1024 bytes and 1 MB than 1048576 bytes. Converts
  394. * number of bytes to human readable number by taking the number of that unit
  395. * that the bytes will go into it. Supports TB value.
  396. *
  397. * Please note that integers in PHP are limited to 32 bits, unless they are on
  398. * 64 bit architecture, then they have 64 bit size. If you need to place the
  399. * larger size then what PHP integer type will hold, then use a string. It will
  400. * be converted to a double, which should always have 64 bit length.
  401. *
  402. * Technically the correct unit names for powers of 1024 are KiB, MiB etc.
  403. *
  404. * @since 2.3.0
  405. *
  406. * @param int|string $bytes Number of bytes. Note max integer size for integers.
  407. * @param int $decimals Optional. Precision of number of decimal places. Default 0.
  408. * @return string|false Number string on success, false on failure.
  409. */
  410. function size_format( $bytes, $decimals = 0 ) {
  411. $quant = array(
  412. /* translators: Unit symbol for terabyte. */
  413. _x( 'TB', 'unit symbol' ) => TB_IN_BYTES,
  414. /* translators: Unit symbol for gigabyte. */
  415. _x( 'GB', 'unit symbol' ) => GB_IN_BYTES,
  416. /* translators: Unit symbol for megabyte. */
  417. _x( 'MB', 'unit symbol' ) => MB_IN_BYTES,
  418. /* translators: Unit symbol for kilobyte. */
  419. _x( 'KB', 'unit symbol' ) => KB_IN_BYTES,
  420. /* translators: Unit symbol for byte. */
  421. _x( 'B', 'unit symbol' ) => 1,
  422. );
  423. if ( 0 === $bytes ) {
  424. /* translators: Unit symbol for byte. */
  425. return number_format_i18n( 0, $decimals ) . ' ' . _x( 'B', 'unit symbol' );
  426. }
  427. foreach ( $quant as $unit => $mag ) {
  428. if ( (float) $bytes >= $mag ) {
  429. return number_format_i18n( $bytes / $mag, $decimals ) . ' ' . $unit;
  430. }
  431. }
  432. return false;
  433. }
  434. /**
  435. * Convert a duration to human readable format.
  436. *
  437. * @since 5.1.0
  438. *
  439. * @param string $duration Duration will be in string format (HH:ii:ss) OR (ii:ss),
  440. * with a possible prepended negative sign (-).
  441. * @return string|false A human readable duration string, false on failure.
  442. */
  443. function human_readable_duration( $duration = '' ) {
  444. if ( ( empty( $duration ) || ! is_string( $duration ) ) ) {
  445. return false;
  446. }
  447. $duration = trim( $duration );
  448. // Remove prepended negative sign.
  449. if ( '-' === substr( $duration, 0, 1 ) ) {
  450. $duration = substr( $duration, 1 );
  451. }
  452. // Extract duration parts.
  453. $duration_parts = array_reverse( explode( ':', $duration ) );
  454. $duration_count = count( $duration_parts );
  455. $hour = null;
  456. $minute = null;
  457. $second = null;
  458. if ( 3 === $duration_count ) {
  459. // Validate HH:ii:ss duration format.
  460. if ( ! ( (bool) preg_match( '/^([0-9]+):([0-5]?[0-9]):([0-5]?[0-9])$/', $duration ) ) ) {
  461. return false;
  462. }
  463. // Three parts: hours, minutes & seconds.
  464. list( $second, $minute, $hour ) = $duration_parts;
  465. } elseif ( 2 === $duration_count ) {
  466. // Validate ii:ss duration format.
  467. if ( ! ( (bool) preg_match( '/^([0-5]?[0-9]):([0-5]?[0-9])$/', $duration ) ) ) {
  468. return false;
  469. }
  470. // Two parts: minutes & seconds.
  471. list( $second, $minute ) = $duration_parts;
  472. } else {
  473. return false;
  474. }
  475. $human_readable_duration = array();
  476. // Add the hour part to the string.
  477. if ( is_numeric( $hour ) ) {
  478. /* translators: %s: Time duration in hour or hours. */
  479. $human_readable_duration[] = sprintf( _n( '%s hour', '%s hours', $hour ), (int) $hour );
  480. }
  481. // Add the minute part to the string.
  482. if ( is_numeric( $minute ) ) {
  483. /* translators: %s: Time duration in minute or minutes. */
  484. $human_readable_duration[] = sprintf( _n( '%s minute', '%s minutes', $minute ), (int) $minute );
  485. }
  486. // Add the second part to the string.
  487. if ( is_numeric( $second ) ) {
  488. /* translators: %s: Time duration in second or seconds. */
  489. $human_readable_duration[] = sprintf( _n( '%s second', '%s seconds', $second ), (int) $second );
  490. }
  491. return implode( ', ', $human_readable_duration );
  492. }
  493. /**
  494. * Get the week start and end from the datetime or date string from MySQL.
  495. *
  496. * @since 0.71
  497. *
  498. * @param string $mysqlstring Date or datetime field type from MySQL.
  499. * @param int|string $start_of_week Optional. Start of the week as an integer. Default empty string.
  500. * @return int[] {
  501. * Week start and end dates as Unix timestamps.
  502. *
  503. * @type int $start The week start date as a Unix timestamp.
  504. * @type int $end The week end date as a Unix timestamp.
  505. * }
  506. */
  507. function get_weekstartend( $mysqlstring, $start_of_week = '' ) {
  508. // MySQL string year.
  509. $my = substr( $mysqlstring, 0, 4 );
  510. // MySQL string month.
  511. $mm = substr( $mysqlstring, 8, 2 );
  512. // MySQL string day.
  513. $md = substr( $mysqlstring, 5, 2 );
  514. // The timestamp for MySQL string day.
  515. $day = mktime( 0, 0, 0, $md, $mm, $my );
  516. // The day of the week from the timestamp.
  517. $weekday = gmdate( 'w', $day );
  518. if ( ! is_numeric( $start_of_week ) ) {
  519. $start_of_week = get_option( 'start_of_week' );
  520. }
  521. if ( $weekday < $start_of_week ) {
  522. $weekday += 7;
  523. }
  524. // The most recent week start day on or before $day.
  525. $start = $day - DAY_IN_SECONDS * ( $weekday - $start_of_week );
  526. // $start + 1 week - 1 second.
  527. $end = $start + WEEK_IN_SECONDS - 1;
  528. return compact( 'start', 'end' );
  529. }
  530. /**
  531. * Serialize data, if needed.
  532. *
  533. * @since 2.0.5
  534. *
  535. * @param string|array|object $data Data that might be serialized.
  536. * @return mixed A scalar data.
  537. */
  538. function maybe_serialize( $data ) {
  539. if ( is_array( $data ) || is_object( $data ) ) {
  540. return serialize( $data );
  541. }
  542. /*
  543. * Double serialization is required for backward compatibility.
  544. * See https://core.trac.wordpress.org/ticket/12930
  545. * Also the world will end. See WP 3.6.1.
  546. */
  547. if ( is_serialized( $data, false ) ) {
  548. return serialize( $data );
  549. }
  550. return $data;
  551. }
  552. /**
  553. * Unserialize data only if it was serialized.
  554. *
  555. * @since 2.0.0
  556. *
  557. * @param string $data Data that might be unserialized.
  558. * @return mixed Unserialized data can be any type.
  559. */
  560. function maybe_unserialize( $data ) {
  561. if ( is_serialized( $data ) ) { // Don't attempt to unserialize data that wasn't serialized going in.
  562. return @unserialize( trim( $data ) );
  563. }
  564. return $data;
  565. }
  566. /**
  567. * Check value to find if it was serialized.
  568. *
  569. * If $data is not an string, then returned value will always be false.
  570. * Serialized data is always a string.
  571. *
  572. * @since 2.0.5
  573. *
  574. * @param string $data Value to check to see if was serialized.
  575. * @param bool $strict Optional. Whether to be strict about the end of the string. Default true.
  576. * @return bool False if not serialized and true if it was.
  577. */
  578. function is_serialized( $data, $strict = true ) {
  579. // If it isn't a string, it isn't serialized.
  580. if ( ! is_string( $data ) ) {
  581. return false;
  582. }
  583. $data = trim( $data );
  584. if ( 'N;' === $data ) {
  585. return true;
  586. }
  587. if ( strlen( $data ) < 4 ) {
  588. return false;
  589. }
  590. if ( ':' !== $data[1] ) {
  591. return false;
  592. }
  593. if ( $strict ) {
  594. $lastc = substr( $data, -1 );
  595. if ( ';' !== $lastc && '}' !== $lastc ) {
  596. return false;
  597. }
  598. } else {
  599. $semicolon = strpos( $data, ';' );
  600. $brace = strpos( $data, '}' );
  601. // Either ; or } must exist.
  602. if ( false === $semicolon && false === $brace ) {
  603. return false;
  604. }
  605. // But neither must be in the first X characters.
  606. if ( false !== $semicolon && $semicolon < 3 ) {
  607. return false;
  608. }
  609. if ( false !== $brace && $brace < 4 ) {
  610. return false;
  611. }
  612. }
  613. $token = $data[0];
  614. switch ( $token ) {
  615. case 's':
  616. if ( $strict ) {
  617. if ( '"' !== substr( $data, -2, 1 ) ) {
  618. return false;
  619. }
  620. } elseif ( false === strpos( $data, '"' ) ) {
  621. return false;
  622. }
  623. // Or else fall through.
  624. case 'a':
  625. case 'O':
  626. return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
  627. case 'b':
  628. case 'i':
  629. case 'd':
  630. $end = $strict ? '$' : '';
  631. return (bool) preg_match( "/^{$token}:[0-9.E+-]+;$end/", $data );
  632. }
  633. return false;
  634. }
  635. /**
  636. * Check whether serialized data is of string type.
  637. *
  638. * @since 2.0.5
  639. *
  640. * @param string $data Serialized data.
  641. * @return bool False if not a serialized string, true if it is.
  642. */
  643. function is_serialized_string( $data ) {
  644. // if it isn't a string, it isn't a serialized string.
  645. if ( ! is_string( $data ) ) {
  646. return false;
  647. }
  648. $data = trim( $data );
  649. if ( strlen( $data ) < 4 ) {
  650. return false;
  651. } elseif ( ':' !== $data[1] ) {
  652. return false;
  653. } elseif ( ';' !== substr( $data, -1 ) ) {
  654. return false;
  655. } elseif ( 's' !== $data[0] ) {
  656. return false;
  657. } elseif ( '"' !== substr( $data, -2, 1 ) ) {
  658. return false;
  659. } else {
  660. return true;
  661. }
  662. }
  663. /**
  664. * Retrieve post title from XMLRPC XML.
  665. *
  666. * If the title element is not part of the XML, then the default post title from
  667. * the $post_default_title will be used instead.
  668. *
  669. * @since 0.71
  670. *
  671. * @global string $post_default_title Default XML-RPC post title.
  672. *
  673. * @param string $content XMLRPC XML Request content
  674. * @return string Post title
  675. */
  676. function xmlrpc_getposttitle( $content ) {
  677. global $post_default_title;
  678. if ( preg_match( '/<title>(.+?)<\/title>/is', $content, $matchtitle ) ) {
  679. $post_title = $matchtitle[1];
  680. } else {
  681. $post_title = $post_default_title;
  682. }
  683. return $post_title;
  684. }
  685. /**
  686. * Retrieve the post category or categories from XMLRPC XML.
  687. *
  688. * If the category element is not found, then the default post category will be
  689. * used. The return type then would be what $post_default_category. If the
  690. * category is found, then it will always be an array.
  691. *
  692. * @since 0.71
  693. *
  694. * @global string $post_default_category Default XML-RPC post category.
  695. *
  696. * @param string $content XMLRPC XML Request content
  697. * @return string|array List of categories or category name.
  698. */
  699. function xmlrpc_getpostcategory( $content ) {
  700. global $post_default_category;
  701. if ( preg_match( '/<category>(.+?)<\/category>/is', $content, $matchcat ) ) {
  702. $post_category = trim( $matchcat[1], ',' );
  703. $post_category = explode( ',', $post_category );
  704. } else {
  705. $post_category = $post_default_category;
  706. }
  707. return $post_category;
  708. }
  709. /**
  710. * XMLRPC XML content without title and category elements.
  711. *
  712. * @since 0.71
  713. *
  714. * @param string $content XML-RPC XML Request content.
  715. * @return string XMLRPC XML Request content without title and category elements.
  716. */
  717. function xmlrpc_removepostdata( $content ) {
  718. $content = preg_replace( '/<title>(.+?)<\/title>/si', '', $content );
  719. $content = preg_replace( '/<category>(.+?)<\/category>/si', '', $content );
  720. $content = trim( $content );
  721. return $content;
  722. }
  723. /**
  724. * Use RegEx to extract URLs from arbitrary content.
  725. *
  726. * @since 3.7.0
  727. *
  728. * @param string $content Content to extract URLs from.
  729. * @return string[] Array of URLs found in passed string.
  730. */
  731. function wp_extract_urls( $content ) {
  732. preg_match_all(
  733. "#([\"']?)("
  734. . '(?:([\w-]+:)?//?)'
  735. . '[^\s()<>]+'
  736. . '[.]'
  737. . '(?:'
  738. . '\([\w\d]+\)|'
  739. . '(?:'
  740. . "[^`!()\[\]{};:'\".,<>«»“”‘’\s]|"
  741. . '(?:[:]\d+)?/?'
  742. . ')+'
  743. . ')'
  744. . ")\\1#",
  745. $content,
  746. $post_links
  747. );
  748. $post_links = array_unique( array_map( 'html_entity_decode', $post_links[2] ) );
  749. return array_values( $post_links );
  750. }
  751. /**
  752. * Check content for video and audio links to add as enclosures.
  753. *
  754. * Will not add enclosures that have already been added and will
  755. * remove enclosures that are no longer in the post. This is called as
  756. * pingbacks and trackbacks.
  757. *
  758. * @since 1.5.0
  759. * @since 5.3.0 The `$content` parameter was made optional, and the `$post` parameter was
  760. * updated to accept a post ID or a WP_Post object.
  761. * @since 5.6.0 The `$content` parameter is no longer optional, but passing `null` to skip it
  762. * is still supported.
  763. *
  764. * @global wpdb $wpdb WordPress database abstraction object.
  765. *
  766. * @param string|null $content Post content. If `null`, the `post_content` field from `$post` is used.
  767. * @param int|WP_Post $post Post ID or post object.
  768. * @return void|false Void on success, false if the post is not found.
  769. */
  770. function do_enclose( $content, $post ) {
  771. global $wpdb;
  772. // @todo Tidy this code and make the debug code optional.
  773. include_once ABSPATH . WPINC . '/class-IXR.php';
  774. $post = get_post( $post );
  775. if ( ! $post ) {
  776. return false;
  777. }
  778. if ( null === $content ) {
  779. $content = $post->post_content;
  780. }
  781. $post_links = array();
  782. $pung = get_enclosed( $post->ID );
  783. $post_links_temp = wp_extract_urls( $content );
  784. foreach ( $pung as $link_test ) {
  785. // Link is no longer in post.
  786. if ( ! in_array( $link_test, $post_links_temp, true ) ) {
  787. $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 ) . '%' ) );
  788. foreach ( $mids as $mid ) {
  789. delete_metadata_by_mid( 'post', $mid );
  790. }
  791. }
  792. }
  793. foreach ( (array) $post_links_temp as $link_test ) {
  794. // If we haven't pung it already.
  795. if ( ! in_array( $link_test, $pung, true ) ) {
  796. $test = parse_url( $link_test );
  797. if ( false === $test ) {
  798. continue;
  799. }
  800. if ( isset( $test['query'] ) ) {
  801. $post_links[] = $link_test;
  802. } elseif ( isset( $test['path'] ) && ( '/' !== $test['path'] ) && ( '' !== $test['path'] ) ) {
  803. $post_links[] = $link_test;
  804. }
  805. }
  806. }
  807. /**
  808. * Filters the list of enclosure links before querying the database.
  809. *
  810. * Allows for the addition and/or removal of potential enclosures to save
  811. * to postmeta before checking the database for existing enclosures.
  812. *
  813. * @since 4.4.0
  814. *
  815. * @param string[] $post_links An array of enclosure links.
  816. * @param int $post_ID Post ID.
  817. */
  818. $post_links = apply_filters( 'enclosure_links', $post_links, $post->ID );
  819. foreach ( (array) $post_links as $url ) {
  820. $url = strip_fragment_from_url( $url );
  821. 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 ) . '%' ) ) ) {
  822. $headers = wp_get_http_headers( $url );
  823. if ( $headers ) {
  824. $len = isset( $headers['content-length'] ) ? (int) $headers['content-length'] : 0;
  825. $type = isset( $headers['content-type'] ) ? $headers['content-type'] : '';
  826. $allowed_types = array( 'video', 'audio' );
  827. // Check to see if we can figure out the mime type from the extension.
  828. $url_parts = parse_url( $url );
  829. if ( false !== $url_parts && ! empty( $url_parts['path'] ) ) {
  830. $extension = pathinfo( $url_parts['path'], PATHINFO_EXTENSION );
  831. if ( ! empty( $extension ) ) {
  832. foreach ( wp_get_mime_types() as $exts => $mime ) {
  833. if ( preg_match( '!^(' . $exts . ')$!i', $extension ) ) {
  834. $type = $mime;
  835. break;
  836. }
  837. }
  838. }
  839. }
  840. if ( in_array( substr( $type, 0, strpos( $type, '/' ) ), $allowed_types, true ) ) {
  841. add_post_meta( $post->ID, 'enclosure', "$url\n$len\n$mime\n" );
  842. }
  843. }
  844. }
  845. }
  846. }
  847. /**
  848. * Retrieve HTTP Headers from URL.
  849. *
  850. * @since 1.5.1
  851. *
  852. * @param string $url URL to retrieve HTTP headers from.
  853. * @param bool $deprecated Not Used.
  854. * @return string|false Headers on success, false on failure.
  855. */
  856. function wp_get_http_headers( $url, $deprecated = false ) {
  857. if ( ! empty( $deprecated ) ) {
  858. _deprecated_argument( __FUNCTION__, '2.7.0' );
  859. }
  860. $response = wp_safe_remote_head( $url );
  861. if ( is_wp_error( $response ) ) {
  862. return false;
  863. }
  864. return wp_remote_retrieve_headers( $response );
  865. }
  866. /**
  867. * Determines whether the publish date of the current post in the loop is different
  868. * from the publish date of the previous post in the loop.
  869. *
  870. * For more information on this and similar theme functions, check out
  871. * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
  872. * Conditional Tags} article in the Theme Developer Handbook.
  873. *
  874. * @since 0.71
  875. *
  876. * @global string $currentday The day of the current post in the loop.
  877. * @global string $previousday The day of the previous post in the loop.
  878. *
  879. * @return int 1 when new day, 0 if not a new day.
  880. */
  881. function is_new_day() {
  882. global $currentday, $previousday;
  883. if ( $currentday !== $previousday ) {
  884. return 1;
  885. } else {
  886. return 0;
  887. }
  888. }
  889. /**
  890. * Build URL query based on an associative and, or indexed array.
  891. *
  892. * This is a convenient function for easily building url queries. It sets the
  893. * separator to '&' and uses _http_build_query() function.
  894. *
  895. * @since 2.3.0
  896. *
  897. * @see _http_build_query() Used to build the query
  898. * @link https://www.php.net/manual/en/function.http-build-query.php for more on what
  899. * http_build_query() does.
  900. *
  901. * @param array $data URL-encode key/value pairs.
  902. * @return string URL-encoded string.
  903. */
  904. function build_query( $data ) {
  905. return _http_build_query( $data, null, '&', '', false );
  906. }
  907. /**
  908. * From php.net (modified by Mark Jaquith to behave like the native PHP5 function).
  909. *
  910. * @since 3.2.0
  911. * @access private
  912. *
  913. * @see https://www.php.net/manual/en/function.http-build-query.php
  914. *
  915. * @param array|object $data An array or object of data. Converted to array.
  916. * @param string $prefix Optional. Numeric index. If set, start parameter numbering with it.
  917. * Default null.
  918. * @param string $sep Optional. Argument separator; defaults to 'arg_separator.output'.
  919. * Default null.
  920. * @param string $key Optional. Used to prefix key name. Default empty.
  921. * @param bool $urlencode Optional. Whether to use urlencode() in the result. Default true.
  922. * @return string The query string.
  923. */
  924. function _http_build_query( $data, $prefix = null, $sep = null, $key = '', $urlencode = true ) {
  925. $ret = array();
  926. foreach ( (array) $data as $k => $v ) {
  927. if ( $urlencode ) {
  928. $k = urlencode( $k );
  929. }
  930. if ( is_int( $k ) && null != $prefix ) {
  931. $k = $prefix . $k;
  932. }
  933. if ( ! empty( $key ) ) {
  934. $k = $key . '%5B' . $k . '%5D';
  935. }
  936. if ( null === $v ) {
  937. continue;
  938. } elseif ( false === $v ) {
  939. $v = '0';
  940. }
  941. if ( is_array( $v ) || is_object( $v ) ) {
  942. array_push( $ret, _http_build_query( $v, '', $sep, $k, $urlencode ) );
  943. } elseif ( $urlencode ) {
  944. array_push( $ret, $k . '=' . urlencode( $v ) );
  945. } else {
  946. array_push( $ret, $k . '=' . $v );
  947. }
  948. }
  949. if ( null === $sep ) {
  950. $sep = ini_get( 'arg_separator.output' );
  951. }
  952. return implode( $sep, $ret );
  953. }
  954. /**
  955. * Retrieves a modified URL query string.
  956. *
  957. * You can rebuild the URL and append query variables to the URL query by using this function.
  958. * There are two ways to use this function; either a single key and value, or an associative array.
  959. *
  960. * Using a single key and value:
  961. *
  962. * add_query_arg( 'key', 'value', 'http://example.com' );
  963. *
  964. * Using an associative array:
  965. *
  966. * add_query_arg( array(
  967. * 'key1' => 'value1',
  968. * 'key2' => 'value2',
  969. * ), 'http://example.com' );
  970. *
  971. * Omitting the URL from either use results in the current URL being used
  972. * (the value of `$_SERVER['REQUEST_URI']`).
  973. *
  974. * Values are expected to be encoded appropriately with urlencode() or rawurlencode().
  975. *
  976. * Setting any query variable's value to boolean false removes the key (see remove_query_arg()).
  977. *
  978. * Important: The return value of add_query_arg() is not escaped by default. Output should be
  979. * late-escaped with esc_url() or similar to help prevent vulnerability to cross-site scripting
  980. * (XSS) attacks.
  981. *
  982. * @since 1.5.0
  983. * @since 5.3.0 Formalized the existing and already documented parameters
  984. * by adding `...$args` to the function signature.
  985. *
  986. * @param string|array $key Either a query variable key, or an associative array of query variables.
  987. * @param string $value Optional. Either a query variable value, or a URL to act upon.
  988. * @param string $url Optional. A URL to act upon.
  989. * @return string New URL query string (unescaped).
  990. */
  991. function add_query_arg( ...$args ) {
  992. if ( is_array( $args[0] ) ) {
  993. if ( count( $args ) < 2 || false === $args[1] ) {
  994. $uri = $_SERVER['REQUEST_URI'];
  995. } else {
  996. $uri = $args[1];
  997. }
  998. } else {
  999. if ( count( $args ) < 3 || false === $args[2] ) {
  1000. $uri = $_SERVER['REQUEST_URI'];
  1001. } else {
  1002. $uri = $args[2];
  1003. }
  1004. }
  1005. $frag = strstr( $uri, '#' );
  1006. if ( $frag ) {
  1007. $uri = substr( $uri, 0, -strlen( $frag ) );
  1008. } else {
  1009. $frag = '';
  1010. }
  1011. if ( 0 === stripos( $uri, 'http://' ) ) {
  1012. $protocol = 'http://';
  1013. $uri = substr( $uri, 7 );
  1014. } elseif ( 0 === stripos( $uri, 'https://' ) ) {
  1015. $protocol = 'https://';
  1016. $uri = substr( $uri, 8 );
  1017. } else {
  1018. $protocol = '';
  1019. }
  1020. if ( strpos( $uri, '?' ) !== false ) {
  1021. list( $base, $query ) = explode( '?', $uri, 2 );
  1022. $base .= '?';
  1023. } elseif ( $protocol || strpos( $uri, '=' ) === false ) {
  1024. $base = $uri . '?';
  1025. $query = '';
  1026. } else {
  1027. $base = '';
  1028. $query = $uri;
  1029. }
  1030. wp_parse_str( $query, $qs );
  1031. $qs = urlencode_deep( $qs ); // This re-URL-encodes things that were already in the query string.
  1032. if ( is_array( $args[0] ) ) {
  1033. foreach ( $args[0] as $k => $v ) {
  1034. $qs[ $k ] = $v;
  1035. }
  1036. } else {
  1037. $qs[ $args[0] ] = $args[1];
  1038. }
  1039. foreach ( $qs as $k => $v ) {
  1040. if ( false === $v ) {
  1041. unset( $qs[ $k ] );
  1042. }
  1043. }
  1044. $ret = build_query( $qs );
  1045. $ret = trim( $ret, '?' );
  1046. $ret = preg_replace( '#=(&|$)#', '$1', $ret );
  1047. $ret = $protocol . $base . $ret . $frag;
  1048. $ret = rtrim( $ret, '?' );
  1049. $ret = str_replace( '?#', '#', $ret );
  1050. return $ret;
  1051. }
  1052. /**
  1053. * Removes an item or items from a query string.
  1054. *
  1055. * @since 1.5.0
  1056. *
  1057. * @param string|string[] $key Query key or keys to remove.
  1058. * @param false|string $query Optional. When false uses the current URL. Default false.
  1059. * @return string New URL query string.
  1060. */
  1061. function remove_query_arg( $key, $query = false ) {
  1062. if ( is_array( $key ) ) { // Removing multiple keys.
  1063. foreach ( $key as $k ) {
  1064. $query = add_query_arg( $k, false, $query );
  1065. }
  1066. return $query;
  1067. }
  1068. return add_query_arg( $key, false, $query );
  1069. }
  1070. /**
  1071. * Returns an array of single-use query variable names that can be removed from a URL.
  1072. *
  1073. * @since 4.4.0
  1074. *
  1075. * @return string[] An array of query variable names to remove from the URL.
  1076. */
  1077. function wp_removable_query_args() {
  1078. $removable_query_args = array(
  1079. 'activate',
  1080. 'activated',
  1081. 'admin_email_remind_later',
  1082. 'approved',
  1083. 'core-major-auto-updates-saved',
  1084. 'deactivate',
  1085. 'delete_count',
  1086. 'deleted',
  1087. 'disabled',
  1088. 'doing_wp_cron',
  1089. 'enabled',
  1090. 'error',
  1091. 'hotkeys_highlight_first',
  1092. 'hotkeys_highlight_last',
  1093. 'ids',
  1094. 'locked',
  1095. 'message',
  1096. 'same',
  1097. 'saved',
  1098. 'settings-updated',
  1099. 'skipped',
  1100. 'spammed',
  1101. 'trashed',
  1102. 'unspammed',
  1103. 'untrashed',
  1104. 'update',
  1105. 'updated',
  1106. 'wp-post-new-reload',
  1107. );
  1108. /**
  1109. * Filters the list of query variable names to remove.
  1110. *
  1111. * @since 4.2.0
  1112. *
  1113. * @param string[] $removable_query_args An array of query variable names to remove from a URL.
  1114. */
  1115. return apply_filters( 'removable_query_args', $removable_query_args );
  1116. }
  1117. /**
  1118. * Walks the array while sanitizing the contents.
  1119. *
  1120. * @since 0.71
  1121. * @since 5.5.0 Non-string values are left untouched.
  1122. *
  1123. * @param array $array Array to walk while sanitizing contents.
  1124. * @return array Sanitized $array.
  1125. */
  1126. function add_magic_quotes( $array ) {
  1127. foreach ( (array) $array as $k => $v ) {
  1128. if ( is_array( $v ) ) {
  1129. $array[ $k ] = add_magic_quotes( $v );
  1130. } elseif ( is_string( $v ) ) {
  1131. $array[ $k ] = addslashes( $v );
  1132. } else {
  1133. continue;
  1134. }
  1135. }
  1136. return $array;
  1137. }
  1138. /**
  1139. * HTTP request for URI to retrieve content.
  1140. *
  1141. * @since 1.5.1
  1142. *
  1143. * @see wp_safe_remote_get()
  1144. *
  1145. * @param string $uri URI/URL of web page to retrieve.
  1146. * @return string|false HTTP content. False on failure.
  1147. */
  1148. function wp_remote_fopen( $uri ) {
  1149. $parsed_url = parse_url( $uri );
  1150. if ( ! $parsed_url || ! is_array( $parsed_url ) ) {
  1151. return false;
  1152. }
  1153. $options = array();
  1154. $options['timeout'] = 10;
  1155. $response = wp_safe_remote_get( $uri, $options );
  1156. if ( is_wp_error( $response ) ) {
  1157. return false;
  1158. }
  1159. return wp_remote_retrieve_body( $response );
  1160. }
  1161. /**
  1162. * Set up the WordPress query.
  1163. *
  1164. * @since 2.0.0
  1165. *
  1166. * @global WP $wp Current WordPress environment instance.
  1167. * @global WP_Query $wp_query WordPress Query object.
  1168. * @global WP_Query $wp_the_query Copy of the WordPress Query object.
  1169. *
  1170. * @param string|array $query_vars Default WP_Query arguments.
  1171. */
  1172. function wp( $query_vars = '' ) {
  1173. global $wp, $wp_query, $wp_the_query;
  1174. $wp->main( $query_vars );
  1175. if ( ! isset( $wp_the_query ) ) {
  1176. $wp_the_query = $wp_query;
  1177. }
  1178. }
  1179. /**
  1180. * Retrieve the description for the HTTP status.
  1181. *
  1182. * @since 2.3.0
  1183. * @since 3.9.0 Added status codes 418, 428, 429, 431, and 511.
  1184. * @since 4.5.0 Added status codes 308, 421, and 451.
  1185. * @since 5.1.0 Added status code 103.
  1186. *
  1187. * @global array $wp_header_to_desc
  1188. *
  1189. * @param int $code HTTP status code.
  1190. * @return string Status description if found, an empty string otherwise.
  1191. */
  1192. function get_status_header_desc( $code ) {
  1193. global $wp_header_to_desc;
  1194. $code = absint( $code );
  1195. if ( ! isset( $wp_header_to_desc ) ) {
  1196. $wp_header_to_desc = array(
  1197. 100 => 'Continue',
  1198. 101 => 'Switching Protocols',
  1199. 102 => 'Processing',
  1200. 103 => 'Early Hints',
  1201. 200 => 'OK',
  1202. 201 => 'Created',
  1203. 202 => 'Accepted',
  1204. 203 => 'Non-Authoritative Information',
  1205. 204 => 'No Content',
  1206. 205 => 'Reset Content',
  1207. 206 => 'Partial Content',
  1208. 207 => 'Multi-Status',
  1209. 226 => 'IM Used',
  1210. 300 => 'Multiple Choices',
  1211. 301 => 'Moved Permanently',
  1212. 302 => 'Found',
  1213. 303 => 'See Other',
  1214. 304 => 'Not Modified',
  1215. 305 => 'Use Proxy',
  1216. 306 => 'Reserved',
  1217. 307 => 'Temporary Redirect',
  1218. 308 => 'Permanent Redirect',
  1219. 400 => 'Bad Request',
  1220. 401 => 'Unauthorized',
  1221. 402 => 'Payment Required',
  1222. 403 => 'Forbidden',
  1223. 404 => 'Not Found',
  1224. 405 => 'Method Not Allowed',
  1225. 406 => 'Not Acceptable',
  1226. 407 => 'Proxy Authentication Required',
  1227. 408 => 'Request Timeout',
  1228. 409 => 'Conflict',
  1229. 410 => 'Gone',
  1230. 411 => 'Length Required',
  1231. 412 => 'Precondition Failed',
  1232. 413 => 'Request Entity Too Large',
  1233. 414 => 'Request-URI Too Long',
  1234. 415 => 'Unsupported Media Type',
  1235. 416 => 'Requested Range Not Satisfiable',
  1236. 417 => 'Expectation Failed',
  1237. 418 => 'I\'m a teapot',
  1238. 421 => 'Misdirected Request',
  1239. 422 => 'Unprocessable Entity',
  1240. 423 => 'Locked',
  1241. 424 => 'Failed Dependency',
  1242. 426 => 'Upgrade Required',
  1243. 428 => 'Precondition Required',
  1244. 429 => 'Too Many Requests',
  1245. 431 => 'Request Header Fields Too Large',
  1246. 451 => 'Unavailable For Legal Reasons',
  1247. 500 => 'Internal Server Error',
  1248. 501 => 'Not Implemented',
  1249. 502 => 'Bad Gateway',
  1250. 503 => 'Service Unavailable',
  1251. 504 => 'Gateway Timeout',
  1252. 505 => 'HTTP Version Not Supported',
  1253. 506 => 'Variant Also Negotiates',
  1254. 507 => 'Insufficient Storage',
  1255. 510 => 'Not Extended',
  1256. 511 => 'Network Authentication Required',
  1257. );
  1258. }
  1259. if ( isset( $wp_header_to_desc[ $code ] ) ) {
  1260. return $wp_header_to_desc[ $code ];
  1261. } else {
  1262. return '';
  1263. }
  1264. }
  1265. /**
  1266. * Set HTTP status header.
  1267. *
  1268. * @since 2.0.0
  1269. * @since 4.4.0 Added the `$description` parameter.
  1270. *
  1271. * @see get_status_header_desc()
  1272. *
  1273. * @param int $code HTTP status code.
  1274. * @param string $description Optional. A custom description for the HTTP status.
  1275. */
  1276. function status_header( $code, $description = '' ) {
  1277. if ( ! $description ) {
  1278. $description = get_status_header_desc( $code );
  1279. }
  1280. if ( empty( $description ) ) {
  1281. return;
  1282. }
  1283. $protocol = wp_get_server_protocol();
  1284. $status_header = "$protocol $code $description";
  1285. if ( function_exists( 'apply_filters' ) ) {
  1286. /**
  1287. * Filters an HTTP status header.
  1288. *
  1289. * @since 2.2.0
  1290. *
  1291. * @param string $status_header HTTP status header.
  1292. * @param int $code HTTP status code.
  1293. * @param string $description Description for the status code.
  1294. * @param string $protocol Server protocol.
  1295. */
  1296. $status_header = apply_filters( 'status_header', $status_header, $code, $description, $protocol );
  1297. }
  1298. if ( ! headers_sent() ) {
  1299. header( $status_header, true, $code );
  1300. }
  1301. }
  1302. /**
  1303. * Get the header information to prevent caching.
  1304. *
  1305. * The several different headers cover the different ways cache prevention
  1306. * is handled by different browsers
  1307. *
  1308. * @since 2.8.0
  1309. *
  1310. * @return array The associative array of header names and field values.
  1311. */
  1312. function wp_get_nocache_headers() {
  1313. $headers = array(
  1314. 'Expires' => 'Wed, 11 Jan 1984 05:00:00 GMT',
  1315. 'Cache-Control' => 'no-cache, must-revalidate, max-age=0',
  1316. );
  1317. if ( function_exists( 'apply_filters' ) ) {
  1318. /**
  1319. * Filters the cache-controlling headers.
  1320. *
  1321. * @since 2.8.0
  1322. *
  1323. * @see wp_get_nocache_headers()
  1324. *
  1325. * @param array $headers {
  1326. * Header names and field values.
  1327. *
  1328. * @type string $Expires Expires header.
  1329. * @type string $Cache-Control Cache-Control header.
  1330. * }
  1331. */
  1332. $headers = (array) apply_filters( 'nocache_headers', $headers );
  1333. }
  1334. $headers['Last-Modified'] = false;
  1335. return $headers;
  1336. }
  1337. /**
  1338. * Set the headers to prevent caching for the different browsers.
  1339. *
  1340. * Different browsers support different nocache headers, so several
  1341. * headers must be sent so that all of them get the point that no
  1342. * caching should occur.
  1343. *
  1344. * @since 2.0.0
  1345. *
  1346. * @see wp_get_nocache_headers()
  1347. */
  1348. function nocache_headers() {
  1349. if ( headers_sent() ) {
  1350. return;
  1351. }
  1352. $headers = wp_get_nocache_headers();
  1353. unset( $headers['Last-Modified'] );
  1354. header_remove( 'Last-Modified' );
  1355. foreach ( $headers as $name => $field_value ) {
  1356. header( "{$name}: {$field_value}" );
  1357. }
  1358. }
  1359. /**
  1360. * Set the headers for caching for 10 days with JavaScript content type.
  1361. *
  1362. * @since 2.1.0
  1363. */
  1364. function cache_javascript_headers() {
  1365. $expiresOffset = 10 * DAY_IN_SECONDS;
  1366. header( 'Content-Type: text/javascript; charset=' . get_bloginfo( 'charset' ) );
  1367. header( 'Vary: Accept-Encoding' ); // Handle proxies.
  1368. header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', time() + $expiresOffset ) . ' GMT' );
  1369. }
  1370. /**
  1371. * Retrieve the number of database queries during the WordPress execution.
  1372. *
  1373. * @since 2.0.0
  1374. *
  1375. * @global wpdb $wpdb WordPress database abstraction object.
  1376. *
  1377. * @return int Number of database queries.
  1378. */
  1379. function get_num_queries() {
  1380. global $wpdb;
  1381. return $wpdb->num_queries;
  1382. }
  1383. /**
  1384. * Whether input is yes or no.
  1385. *
  1386. * Must be 'y' to be true.
  1387. *
  1388. * @since 1.0.0
  1389. *
  1390. * @param string $yn Character string containing either 'y' (yes) or 'n' (no).
  1391. * @return bool True if 'y', false on anything else.
  1392. */
  1393. function bool_from_yn( $yn ) {
  1394. return ( 'y' === strtolower( $yn ) );
  1395. }
  1396. /**
  1397. * Load the feed template from the use of an action hook.
  1398. *
  1399. * If the feed action does not have a hook, then the function will die with a
  1400. * message telling the visitor that the feed is not valid.
  1401. *
  1402. * It is better to only have one hook for each feed.
  1403. *
  1404. * @since 2.1.0
  1405. *
  1406. * @global WP_Query $wp_query WordPress Query object.
  1407. */
  1408. function do_feed() {
  1409. global $wp_query;
  1410. $feed = get_query_var( 'feed' );
  1411. // Remove the pad, if present.
  1412. $feed = preg_replace( '/^_+/', '', $feed );
  1413. if ( '' === $feed || 'feed' === $feed ) {
  1414. $feed = get_default_feed();
  1415. }
  1416. if ( ! has_action( "do_feed_{$feed}" ) ) {
  1417. wp_die( __( 'Error: This is not a valid feed template.' ), '', array( 'response' => 404 ) );
  1418. }
  1419. /**
  1420. * Fires once the given feed is loaded.
  1421. *
  1422. * The dynamic portion of the hook name, `$feed`, refers to the feed template name.
  1423. *
  1424. * Possible hook names include:
  1425. *
  1426. * - `do_feed_atom`
  1427. * - `do_feed_rdf`
  1428. * - `do_feed_rss`
  1429. * - `do_feed_rss2`
  1430. *
  1431. * @since 2.1.0
  1432. * @since 4.4.0 The `$feed` parameter was added.
  1433. *
  1434. * @param bool $is_comment_feed Whether the feed is a comment feed.
  1435. * @param string $feed The feed name.
  1436. */
  1437. do_action( "do_feed_{$feed}", $wp_query->is_comment_feed, $feed );
  1438. }
  1439. /**
  1440. * Load the RDF RSS 0.91 Feed template.
  1441. *
  1442. * @since 2.1.0
  1443. *
  1444. * @see load_template()
  1445. */
  1446. function do_feed_rdf() {
  1447. load_template( ABSPATH . WPINC . '/feed-rdf.php' );
  1448. }
  1449. /**
  1450. * Load the RSS 1.0 Feed Template.
  1451. *
  1452. * @since 2.1.0
  1453. *
  1454. * @see load_template()
  1455. */
  1456. function do_feed_rss() {
  1457. load_template( ABSPATH . WPINC . '/feed-rss.php' );
  1458. }
  1459. /**
  1460. * Load either the RSS2 comment feed or the RSS2 posts feed.
  1461. *
  1462. * @since 2.1.0
  1463. *
  1464. * @see load_template()
  1465. *
  1466. * @param bool $for_comments True for the comment feed, false for normal feed.
  1467. */
  1468. function do_feed_rss2( $for_comments ) {
  1469. if ( $for_comments ) {
  1470. load_template( ABSPATH . WPINC . '/feed-rss2-comments.php' );
  1471. } else {
  1472. load_template( ABSPATH . WPINC . '/feed-rss2.php' );
  1473. }
  1474. }
  1475. /**
  1476. * Load either Atom comment feed or Atom posts feed.
  1477. *
  1478. * @since 2.1.0
  1479. *
  1480. * @see load_template()
  1481. *
  1482. * @param bool $for_comments True for the comment feed, false for normal feed.
  1483. */
  1484. function do_feed_atom( $for_comments ) {
  1485. if ( $for_comments ) {
  1486. load_template( ABSPATH . WPINC . '/feed-atom-comments.php' );
  1487. } else {
  1488. load_template( ABSPATH . WPINC . '/feed-atom.php' );
  1489. }
  1490. }
  1491. /**
  1492. * Displays the default robots.txt file content.
  1493. *
  1494. * @since 2.1.0
  1495. * @since 5.3.0 Remove the "Disallow: /" output if search engine visiblity is
  1496. * discouraged in favor of robots meta HTML tag via wp_robots_no_robots()
  1497. * filter callback.
  1498. */
  1499. function do_robots() {
  1500. header( 'Content-Type: text/plain; charset=utf-8' );
  1501. /**
  1502. * Fires when displaying the robots.txt file.
  1503. *
  1504. * @since 2.1.0
  1505. */
  1506. do_action( 'do_robotstxt' );
  1507. $output = "User-agent: *\n";
  1508. $public = get_option( 'blog_public' );
  1509. $site_url = parse_url( site_url() );
  1510. $path = ( ! empty( $site_url['path'] ) ) ? $site_url['path'] : '';
  1511. $output .= "Disallow: $path/wp-admin/\n";
  1512. $output .= "Allow: $path/wp-admin/admin-ajax.php\n";
  1513. /**
  1514. * Filters the robots.txt output.
  1515. *
  1516. * @since 3.0.0
  1517. *
  1518. * @param string $output The robots.txt output.
  1519. * @param bool $public Whether the site is considered "public".
  1520. */
  1521. echo apply_filters( 'robots_txt', $output, $public );
  1522. }
  1523. /**
  1524. * Display the favicon.ico file content.
  1525. *
  1526. * @since 5.4.0
  1527. */
  1528. function do_favicon() {
  1529. /**
  1530. * Fires when serving the favicon.ico file.
  1531. *
  1532. * @since 5.4.0
  1533. */
  1534. do_action( 'do_faviconico' );
  1535. wp_redirect( get_site_icon_url( 32, includes_url( 'images/w-logo-blue-white-bg.png' ) ) );
  1536. exit;
  1537. }
  1538. /**
  1539. * Determines whether WordPress is already installed.
  1540. *
  1541. * The cache will be checked first. If you have a cache plugin, which saves
  1542. * the cache values, then this will work. If you use the default WordPress
  1543. * cache, and the database goes away, then you might have problems.
  1544. *
  1545. * Checks for the 'siteurl' option for whether WordPress is installed.
  1546. *
  1547. * For more information on this and similar theme functions, check out
  1548. * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
  1549. * Conditional Tags} article in the Theme Developer Handbook.
  1550. *
  1551. * @since 2.1.0
  1552. *
  1553. * @global wpdb $wpdb WordPress database abstraction object.
  1554. *
  1555. * @return bool Whether the site is already installed.
  1556. */
  1557. function is_blog_installed() {
  1558. global $wpdb;
  1559. /*
  1560. * Check cache first. If options table goes away and we have true
  1561. * cached, oh well.
  1562. */
  1563. if ( wp_cache_get( 'is_blog_installed' ) ) {
  1564. return true;
  1565. }
  1566. $suppress = $wpdb->suppress_errors();
  1567. if ( ! wp_installing() ) {
  1568. $alloptions = wp_load_alloptions();
  1569. }
  1570. // If siteurl is not set to autoload, check it specifically.
  1571. if ( ! isset( $alloptions['siteurl'] ) ) {
  1572. $installed = $wpdb->get_var( "SELECT option_value FROM $wpdb->options WHERE option_name = 'siteurl'" );
  1573. } else {
  1574. $installed = $alloptions['siteurl'];
  1575. }
  1576. $wpdb->suppress_errors( $suppress );
  1577. $installed = ! empty( $installed );
  1578. wp_cache_set( 'is_blog_installed', $installed );
  1579. if ( $installed ) {
  1580. return true;
  1581. }
  1582. // If visiting repair.php, return true and let it take over.
  1583. if ( defined( 'WP_REPAIRING' ) ) {
  1584. return true;
  1585. }
  1586. $suppress = $wpdb->suppress_errors();
  1587. /*
  1588. * Loop over the WP tables. If none exist, then scratch installation is allowed.
  1589. * If one or more exist, suggest table repair since we got here because the
  1590. * options table could not be accessed.
  1591. */
  1592. $wp_tables = $wpdb->tables();
  1593. foreach ( $wp_tables as $table ) {
  1594. // The existence of custom user tables shouldn't suggest an unwise state or prevent a clean installation.
  1595. if ( defined( 'CUSTOM_USER_TABLE' ) && CUSTOM_USER_TABLE == $table ) {
  1596. continue;
  1597. }
  1598. if ( defined( 'CUSTOM_USER_META_TABLE' ) && CUSTOM_USER_META_TABLE == $table ) {
  1599. continue;
  1600. }
  1601. $described_table = $wpdb->get_results( "DESCRIBE $table;" );
  1602. if (
  1603. ( ! $described_table && empty( $wpdb->last_error ) ) ||
  1604. ( is_array( $described_table ) && 0 === count( $described_table ) )
  1605. ) {
  1606. continue;
  1607. }
  1608. // One or more tables exist. This is not good.
  1609. wp_load_translations_early();
  1610. // Die with a DB error.
  1611. $wpdb->error = sprintf(
  1612. /* translators: %s: Database repair URL. */
  1613. __( 'One or more database tables are unavailable. The database may need to be <a href="%s">repaired</a>.' ),
  1614. 'maint/repair.php?referrer=is_blog_installed'
  1615. );
  1616. dead_db();
  1617. }
  1618. $wpdb->suppress_errors( $suppress );
  1619. wp_cache_set( 'is_blog_installed', false );
  1620. return false;
  1621. }
  1622. /**
  1623. * Retrieve URL with nonce added to URL query.
  1624. *
  1625. * @since 2.0.4
  1626. *
  1627. * @param string $actionurl URL to add nonce action.
  1628. * @param int|string $action Optional. Nonce action name. Default -1.
  1629. * @param string $name Optional. Nonce name. Default '_wpnonce'.
  1630. * @return string Escaped URL with nonce action added.
  1631. */
  1632. function wp_nonce_url( $actionurl, $action = -1, $name = '_wpnonce' ) {
  1633. $actionurl = str_replace( '&amp;', '&', $actionurl );
  1634. return esc_html( add_query_arg( $name, wp_create_nonce( $action ), $actionurl ) );
  1635. }
  1636. /**
  1637. * Retrieve or display nonce hidden field for forms.
  1638. *
  1639. * The nonce field is used to validate that the contents of the form came from
  1640. * the location on the current site and not somewhere else. The nonce does not
  1641. * offer absolute protection, but should protect against most cases. It is very
  1642. * important to use nonce field in forms.
  1643. *
  1644. * The $action and $name are optional, but if you want to have better security,
  1645. * it is strongly suggested to set those two parameters. It is easier to just
  1646. * call the function without any parameters, because validation of the nonce
  1647. * doesn't require any parameters, but since crackers know what the default is
  1648. * it won't be difficult for them to find a way around your nonce and cause
  1649. * damage.
  1650. *
  1651. * The input name will be whatever $name value you gave. The input value will be
  1652. * the nonce creation value.
  1653. *
  1654. * @since 2.0.4
  1655. *
  1656. * @param int|string $action Optional. Action name. Default -1.
  1657. * @param string $name Optional. Nonce name. Default '_wpnonce'.
  1658. * @param bool $referer Optional. Whether to set the referer field for validation. Default true.
  1659. * @param bool $echo Optional. Whether to display or return hidden form field. Default true.
  1660. * @return string Nonce field HTML markup.
  1661. */
  1662. function wp_nonce_field( $action = -1, $name = '_wpnonce', $referer = true, $echo = true ) {
  1663. $name = esc_attr( $name );
  1664. $nonce_field = '<input type="hidden" id="' . $name . '" name="' . $name . '" value="' . wp_create_nonce( $action ) . '" />';
  1665. if ( $referer ) {
  1666. $nonce_field .= wp_referer_field( false );
  1667. }
  1668. if ( $echo ) {
  1669. echo $nonce_field;
  1670. }
  1671. return $nonce_field;
  1672. }
  1673. /**
  1674. * Retrieve or display referer hidden field for forms.
  1675. *
  1676. * The referer link is the current Request URI from the server super global. The
  1677. * input name is '_wp_http_referer', in case you wanted to check manually.
  1678. *
  1679. * @since 2.0.4
  1680. *
  1681. * @param bool $echo Optional. Whether to echo or return the referer field. Default true.
  1682. * @return string Referer field HTML markup.
  1683. */
  1684. function wp_referer_field( $echo = true ) {
  1685. $referer_field = '<input type="hidden" name="_wp_http_referer" value="' . esc_attr( wp_unslash( $_SERVER['REQUEST_URI'] ) ) . '" />';
  1686. if ( $echo ) {
  1687. echo $referer_field;
  1688. }
  1689. return $referer_field;
  1690. }
  1691. /**
  1692. * Retrieve or display original referer hidden field for forms.
  1693. *
  1694. * The input name is '_wp_original_http_referer' and will be either the same
  1695. * value of wp_referer_field(), if that was posted already or it will be the
  1696. * current page, if it doesn't exist.
  1697. *
  1698. * @since 2.0.4
  1699. *
  1700. * @param bool $echo Optional. Whether to echo the original http referer. Default true.
  1701. * @param string $jump_back_to Optional. Can be 'previous' or page you want to jump back to.
  1702. * Default 'current'.
  1703. * @return string Original referer field.
  1704. */
  1705. function wp_original_referer_field( $echo = true, $jump_back_to = 'current' ) {
  1706. $ref = wp_get_original_referer();
  1707. if ( ! $ref ) {
  1708. $ref = ( 'previous' === $jump_back_to ) ? wp_get_referer() : wp_unslash( $_SERVER['REQUEST_URI'] );
  1709. }
  1710. $orig_referer_field = '<input type="hidden" name="_wp_original_http_referer" value="' . esc_attr( $ref ) . '" />';
  1711. if ( $echo ) {
  1712. echo $orig_referer_field;
  1713. }
  1714. return $orig_referer_field;
  1715. }
  1716. /**
  1717. * Retrieve referer from '_wp_http_referer' or HTTP referer.
  1718. *
  1719. * If it's the same as the current request URL, will return false.
  1720. *
  1721. * @since 2.0.4
  1722. *
  1723. * @return string|false Referer URL on success, false on failure.
  1724. */
  1725. function wp_get_referer() {
  1726. if ( ! function_exists( 'wp_validate_redirect' ) ) {
  1727. return false;
  1728. }
  1729. $ref = wp_get_raw_referer();
  1730. if ( $ref && wp_unslash( $_SERVER['REQUEST_URI'] ) !== $ref && home_url() . wp_unslash( $_SERVER['REQUEST_URI'] ) !== $ref ) {
  1731. return wp_validate_redirect( $ref, false );
  1732. }
  1733. return false;
  1734. }
  1735. /**
  1736. * Retrieves unvalidated referer from '_wp_http_referer' or HTTP referer.
  1737. *
  1738. * Do not use for redirects, use wp_get_referer() instead.
  1739. *
  1740. * @since 4.5.0
  1741. *
  1742. * @return string|false Referer URL on success, false on failure.
  1743. */
  1744. function wp_get_raw_referer() {
  1745. if ( ! empty( $_REQUEST['_wp_http_referer'] ) ) {
  1746. return wp_unslash( $_REQUEST['_wp_http_referer'] );
  1747. } elseif ( ! empty( $_SERVER['HTTP_REFERER'] ) ) {
  1748. return wp_unslash( $_SERVER['HTTP_REFERER'] );
  1749. }
  1750. return false;
  1751. }
  1752. /**
  1753. * Retrieve original referer that was posted, if it exists.
  1754. *
  1755. * @since 2.0.4
  1756. *
  1757. * @return string|false Original referer URL on success, false on failure.
  1758. */
  1759. function wp_get_original_referer() {
  1760. if ( ! empty( $_REQUEST['_wp_original_http_referer'] ) && function_exists( 'wp_validate_redirect' ) ) {
  1761. return wp_validate_redirect( wp_unslash( $_REQUEST['_wp_original_http_referer'] ), false );
  1762. }
  1763. return false;
  1764. }
  1765. /**
  1766. * Recursive directory creation based on full path.
  1767. *
  1768. * Will attempt to set permissions on folders.
  1769. *
  1770. * @since 2.0.1
  1771. *
  1772. * @param string $target Full path to attempt to create.
  1773. * @return bool Whether the path was created. True if path already exists.
  1774. */
  1775. function wp_mkdir_p( $target ) {
  1776. $wrapper = null;
  1777. // Strip the protocol.
  1778. if ( wp_is_stream( $target ) ) {
  1779. list( $wrapper, $target ) = explode( '://', $target, 2 );
  1780. }
  1781. // From php.net/mkdir user contributed notes.
  1782. $target = str_replace( '//', '/', $target );
  1783. // Put the wrapper back on the target.
  1784. if ( null !== $wrapper ) {
  1785. $target = $wrapper . '://' . $target;
  1786. }
  1787. /*
  1788. * Safe mode fails with a trailing slash under certain PHP versions.
  1789. * Use rtrim() instead of untrailingslashit to avoid formatting.php dependency.
  1790. */
  1791. $target = rtrim( $target, '/' );
  1792. if ( empty( $target ) ) {
  1793. $target = '/';
  1794. }
  1795. if ( file_exists( $target ) ) {
  1796. return @is_dir( $target );
  1797. }
  1798. // Do not allow path traversals.
  1799. if ( false !== strpos( $target, '../' ) || false !== strpos( $target, '..' . DIRECTORY_SEPARATOR ) ) {
  1800. return false;
  1801. }
  1802. // We need to find the permissions of the parent folder that exists and inherit that.
  1803. $target_parent = dirname( $target );
  1804. while ( '.' !== $target_parent && ! is_dir( $target_parent ) && dirname( $target_parent ) !== $target_parent ) {
  1805. $target_parent = dirname( $target_parent );
  1806. }
  1807. // Get the permission bits.
  1808. $stat = @stat( $target_parent );
  1809. if ( $stat ) {
  1810. $dir_perms = $stat['mode'] & 0007777;
  1811. } else {
  1812. $dir_perms = 0777;
  1813. }
  1814. if ( @mkdir( $target, $dir_perms, true ) ) {
  1815. /*
  1816. * If a umask is set that modifies $dir_perms, we'll have to re-set
  1817. * the $dir_perms correctly with chmod()
  1818. */
  1819. if ( ( $dir_perms & ~umask() ) != $dir_perms ) {
  1820. $folder_parts = explode( '/', substr( $target, strlen( $target_parent ) + 1 ) );
  1821. for ( $i = 1, $c = count( $folder_parts ); $i <= $c; $i++ ) {
  1822. chmod( $target_parent . '/' . implode( '/', array_slice( $folder_parts, 0, $i ) ), $dir_perms );
  1823. }
  1824. }
  1825. return true;
  1826. }
  1827. return false;
  1828. }
  1829. /**
  1830. * Test if a given filesystem path is absolute.
  1831. *
  1832. * For example, '/foo/bar', or 'c:\windows'.
  1833. *
  1834. * @since 2.5.0
  1835. *
  1836. * @param string $path File path.
  1837. * @return bool True if path is absolute, false is not absolute.
  1838. */
  1839. function path_is_absolute( $path ) {
  1840. /*
  1841. * Check to see if the path is a stream and check to see if its an actual
  1842. * path or file as realpath() does not support stream wrappers.
  1843. */
  1844. if ( wp_is_stream( $path ) && ( is_dir( $path ) || is_file( $path ) ) ) {
  1845. return true;
  1846. }
  1847. /*
  1848. * This is definitive if true but fails if $path does not exist or contains
  1849. * a symbolic link.
  1850. */
  1851. if ( realpath( $path ) == $path ) {
  1852. return true;
  1853. }
  1854. if ( strlen( $path ) == 0 || '.' === $path[0] ) {
  1855. return false;
  1856. }
  1857. // Windows allows absolute paths like this.
  1858. if ( preg_match( '#^[a-zA-Z]:\\\\#', $path ) ) {
  1859. return true;
  1860. }
  1861. // A path starting with / or \ is absolute; anything else is relative.
  1862. return ( '/' === $path[0] || '\\' === $path[0] );
  1863. }
  1864. /**
  1865. * Join two filesystem paths together.
  1866. *
  1867. * For example, 'give me $path relative to $base'. If the $path is absolute,
  1868. * then it the full path is returned.
  1869. *
  1870. * @since 2.5.0
  1871. *
  1872. * @param string $base Base path.
  1873. * @param string $path Path relative to $base.
  1874. * @return string The path with the base or absolute path.
  1875. */
  1876. function path_join( $base, $path ) {
  1877. if ( path_is_absolute( $path ) ) {
  1878. return $path;
  1879. }
  1880. return rtrim( $base, '/' ) . '/' . ltrim( $path, '/' );
  1881. }
  1882. /**
  1883. * Normalize a filesystem path.
  1884. *
  1885. * On windows systems, replaces backslashes with forward slashes
  1886. * and forces upper-case drive letters.
  1887. * Allows for two leading slashes for Windows network shares, but
  1888. * ensures that all other duplicate slashes are reduced to a single.
  1889. *
  1890. * @since 3.9.0
  1891. * @since 4.4.0 Ensures upper-case drive letters on Windows systems.
  1892. * @since 4.5.0 Allows for Windows network shares.
  1893. * @since 4.9.7 Allows for PHP file wrappers.
  1894. *
  1895. * @param string $path Path to normalize.
  1896. * @return string Normalized path.
  1897. */
  1898. function wp_normalize_path( $path ) {
  1899. $wrapper = '';
  1900. if ( wp_is_stream( $path ) ) {
  1901. list( $wrapper, $path ) = explode( '://', $path, 2 );
  1902. $wrapper .= '://';
  1903. }
  1904. // Standardize all paths to use '/'.
  1905. $path = str_replace( '\\', '/', $path );
  1906. // Replace multiple slashes down to a singular, allowing for network shares having two slashes.
  1907. $path = preg_replace( '|(?<=.)/+|', '/', $path );
  1908. // Windows paths should uppercase the drive letter.
  1909. if ( ':' === substr( $path, 1, 1 ) ) {
  1910. $path = ucfirst( $path );
  1911. }
  1912. return $wrapper . $path;
  1913. }
  1914. /**
  1915. * Determine a writable directory for temporary files.
  1916. *
  1917. * Function's preference is the return value of sys_get_temp_dir(),
  1918. * followed by your PHP temporary upload directory, followed by WP_CONTENT_DIR,
  1919. * before finally defaulting to /tmp/
  1920. *
  1921. * In the event that this function does not find a writable location,
  1922. * It may be overridden by the WP_TEMP_DIR constant in your wp-config.php file.
  1923. *
  1924. * @since 2.5.0
  1925. *
  1926. * @return string Writable temporary directory.
  1927. */
  1928. function get_temp_dir() {
  1929. static $temp = '';
  1930. if ( defined( 'WP_TEMP_DIR' ) ) {
  1931. return trailingslashit( WP_TEMP_DIR );
  1932. }
  1933. if ( $temp ) {
  1934. return trailingslashit( $temp );
  1935. }
  1936. if ( function_exists( 'sys_get_temp_dir' ) ) {
  1937. $temp = sys_get_temp_dir();
  1938. if ( @is_dir( $temp ) && wp_is_writable( $temp ) ) {
  1939. return trailingslashit( $temp );
  1940. }
  1941. }
  1942. $temp = ini_get( 'upload_tmp_dir' );
  1943. if ( @is_dir( $temp ) && wp_is_writable( $temp ) ) {
  1944. return trailingslashit( $temp );
  1945. }
  1946. $temp = WP_CONTENT_DIR . '/';
  1947. if ( is_dir( $temp ) && wp_is_writable( $temp ) ) {
  1948. return $temp;
  1949. }
  1950. return '/tmp/';
  1951. }
  1952. /**
  1953. * Determine if a directory is writable.
  1954. *
  1955. * This function is used to work around certain ACL issues in PHP primarily
  1956. * affecting Windows Servers.
  1957. *
  1958. * @since 3.6.0
  1959. *
  1960. * @see win_is_writable()
  1961. *
  1962. * @param string $path Path to check for write-ability.
  1963. * @return bool Whether the path is writable.
  1964. */
  1965. function wp_is_writable( $path ) {
  1966. if ( 'WIN' === strtoupper( substr( PHP_OS, 0, 3 ) ) ) {
  1967. return win_is_writable( $path );
  1968. } else {
  1969. return @is_writable( $path );
  1970. }
  1971. }
  1972. /**
  1973. * Workaround for Windows bug in is_writable() function
  1974. *
  1975. * PHP has issues with Windows ACL's for determine if a
  1976. * directory is writable or not, this works around them by
  1977. * checking the ability to open files rather than relying
  1978. * upon PHP to interprate the OS ACL.
  1979. *
  1980. * @since 2.8.0
  1981. *
  1982. * @see https://bugs.php.net/bug.php?id=27609
  1983. * @see https://bugs.php.net/bug.php?id=30931
  1984. *
  1985. * @param string $path Windows path to check for write-ability.
  1986. * @return bool Whether the path is writable.
  1987. */
  1988. function win_is_writable( $path ) {
  1989. if ( '/' === $path[ strlen( $path ) - 1 ] ) {
  1990. // If it looks like a directory, check a random file within the directory.
  1991. return win_is_writable( $path . uniqid( mt_rand() ) . '.tmp' );
  1992. } elseif ( is_dir( $path ) ) {
  1993. // If it's a directory (and not a file), check a random file within the directory.
  1994. return win_is_writable( $path . '/' . uniqid( mt_rand() ) . '.tmp' );
  1995. }
  1996. // Check tmp file for read/write capabilities.
  1997. $should_delete_tmp_file = ! file_exists( $path );
  1998. $f = @fopen( $path, 'a' );
  1999. if ( false === $f ) {
  2000. return false;
  2001. }
  2002. fclose( $f );
  2003. if ( $should_delete_tmp_file ) {
  2004. unlink( $path );
  2005. }
  2006. return true;
  2007. }
  2008. /**
  2009. * Retrieves uploads directory information.
  2010. *
  2011. * Same as wp_upload_dir() but "light weight" as it doesn't attempt to create the uploads directory.
  2012. * Intended for use in themes, when only 'basedir' and 'baseurl' are needed, generally in all cases
  2013. * when not uploading files.
  2014. *
  2015. * @since 4.5.0
  2016. *
  2017. * @see wp_upload_dir()
  2018. *
  2019. * @return array See wp_upload_dir() for description.
  2020. */
  2021. function wp_get_upload_dir() {
  2022. return wp_upload_dir( null, false );
  2023. }
  2024. /**
  2025. * Returns an array containing the current upload directory's path and URL.
  2026. *
  2027. * Checks the 'upload_path' option, which should be from the web root folder,
  2028. * and if it isn't empty it will be used. If it is empty, then the path will be
  2029. * 'WP_CONTENT_DIR/uploads'. If the 'UPLOADS' constant is defined, then it will
  2030. * override the 'upload_path' option and 'WP_CONTENT_DIR/uploads' path.
  2031. *
  2032. * The upload URL path is set either by the 'upload_url_path' option or by using
  2033. * the 'WP_CONTENT_URL' constant and appending '/uploads' to the path.
  2034. *
  2035. * If the 'uploads_use_yearmonth_folders' is set to true (checkbox if checked in
  2036. * the administration settings panel), then the time will be used. The format
  2037. * will be year first and then month.
  2038. *
  2039. * If the path couldn't be created, then an error will be returned with the key
  2040. * 'error' containing the error message. The error suggests that the parent
  2041. * directory is not writable by the server.
  2042. *
  2043. * @since 2.0.0
  2044. * @uses _wp_upload_dir()
  2045. *
  2046. * @param string $time Optional. Time formatted in 'yyyy/mm'. Default null.
  2047. * @param bool $create_dir Optional. Whether to check and create the uploads directory.
  2048. * Default true for backward compatibility.
  2049. * @param bool $refresh_cache Optional. Whether to refresh the cache. Default false.
  2050. * @return array {
  2051. * Array of information about the upload directory.
  2052. *
  2053. * @type string $path Base directory and subdirectory or full path to upload directory.
  2054. * @type string $url Base URL and subdirectory or absolute URL to upload directory.
  2055. * @type string $subdir Subdirectory if uploads use year/month folders option is on.
  2056. * @type string $basedir Path without subdir.
  2057. * @type string $baseurl URL path without subdir.
  2058. * @type string|false $error False or error message.
  2059. * }
  2060. */
  2061. function wp_upload_dir( $time = null, $create_dir = true, $refresh_cache = false ) {
  2062. static $cache = array(), $tested_paths = array();
  2063. $key = sprintf( '%d-%s', get_current_blog_id(), (string) $time );
  2064. if ( $refresh_cache || empty( $cache[ $key ] ) ) {
  2065. $cache[ $key ] = _wp_upload_dir( $time );
  2066. }
  2067. /**
  2068. * Filters the uploads directory data.
  2069. *
  2070. * @since 2.0.0
  2071. *
  2072. * @param array $uploads {
  2073. * Array of information about the upload directory.
  2074. *
  2075. * @type string $path Base directory and subdirectory or full path to upload directory.
  2076. * @type string $url Base URL and subdirectory or absolute URL to upload directory.
  2077. * @type string $subdir Subdirectory if uploads use year/month folders option is on.
  2078. * @type string $basedir Path without subdir.
  2079. * @type string $baseurl URL path without subdir.
  2080. * @type string|false $error False or error message.
  2081. * }
  2082. */
  2083. $uploads = apply_filters( 'upload_dir', $cache[ $key ] );
  2084. if ( $create_dir ) {
  2085. $path = $uploads['path'];
  2086. if ( array_key_exists( $path, $tested_paths ) ) {
  2087. $uploads['error'] = $tested_paths[ $path ];
  2088. } else {
  2089. if ( ! wp_mkdir_p( $path ) ) {
  2090. if ( 0 === strpos( $uploads['basedir'], ABSPATH ) ) {
  2091. $error_path = str_replace( ABSPATH, '', $uploads['basedir'] ) . $uploads['subdir'];
  2092. } else {
  2093. $error_path = wp_basename( $uploads['basedir'] ) . $uploads['subdir'];
  2094. }
  2095. $uploads['error'] = sprintf(
  2096. /* translators: %s: Directory path. */
  2097. __( 'Unable to create directory %s. Is its parent directory writable by the server?' ),
  2098. esc_html( $error_path )
  2099. );
  2100. }
  2101. $tested_paths[ $path ] = $uploads['error'];
  2102. }
  2103. }
  2104. return $uploads;
  2105. }
  2106. /**
  2107. * A non-filtered, non-cached version of wp_upload_dir() that doesn't check the path.
  2108. *
  2109. * @since 4.5.0
  2110. * @access private
  2111. *
  2112. * @param string $time Optional. Time formatted in 'yyyy/mm'. Default null.
  2113. * @return array See wp_upload_dir()
  2114. */
  2115. function _wp_upload_dir( $time = null ) {
  2116. $siteurl = get_option( 'siteurl' );
  2117. $upload_path = trim( get_option( 'upload_path' ) );
  2118. if ( empty( $upload_path ) || 'wp-content/uploads' === $upload_path ) {
  2119. $dir = WP_CONTENT_DIR . '/uploads';
  2120. } elseif ( 0 !== strpos( $upload_path, ABSPATH ) ) {
  2121. // $dir is absolute, $upload_path is (maybe) relative to ABSPATH.
  2122. $dir = path_join( ABSPATH, $upload_path );
  2123. } else {
  2124. $dir = $upload_path;
  2125. }
  2126. $url = get_option( 'upload_url_path' );
  2127. if ( ! $url ) {
  2128. if ( empty( $upload_path ) || ( 'wp-content/uploads' === $upload_path ) || ( $upload_path == $dir ) ) {
  2129. $url = WP_CONTENT_URL . '/uploads';
  2130. } else {
  2131. $url = trailingslashit( $siteurl ) . $upload_path;
  2132. }
  2133. }
  2134. /*
  2135. * Honor the value of UPLOADS. This happens as long as ms-files rewriting is disabled.
  2136. * We also sometimes obey UPLOADS when rewriting is enabled -- see the next block.
  2137. */
  2138. if ( defined( 'UPLOADS' ) && ! ( is_multisite() && get_site_option( 'ms_files_rewriting' ) ) ) {
  2139. $dir = ABSPATH . UPLOADS;
  2140. $url = trailingslashit( $siteurl ) . UPLOADS;
  2141. }
  2142. // If multisite (and if not the main site in a post-MU network).
  2143. if ( is_multisite() && ! ( is_main_network() && is_main_site() && defined( 'MULTISITE' ) ) ) {
  2144. if ( ! get_site_option( 'ms_files_rewriting' ) ) {
  2145. /*
  2146. * If ms-files rewriting is disabled (networks created post-3.5), it is fairly
  2147. * straightforward: Append sites/%d if we're not on the main site (for post-MU
  2148. * networks). (The extra directory prevents a four-digit ID from conflicting with
  2149. * a year-based directory for the main site. But if a MU-era network has disabled
  2150. * ms-files rewriting manually, they don't need the extra directory, as they never
  2151. * had wp-content/uploads for the main site.)
  2152. */
  2153. if ( defined( 'MULTISITE' ) ) {
  2154. $ms_dir = '/sites/' . get_current_blog_id();
  2155. } else {
  2156. $ms_dir = '/' . get_current_blog_id();
  2157. }
  2158. $dir .= $ms_dir;
  2159. $url .= $ms_dir;
  2160. } elseif ( defined( 'UPLOADS' ) && ! ms_is_switched() ) {
  2161. /*
  2162. * Handle the old-form ms-files.php rewriting if the network still has that enabled.
  2163. * When ms-files rewriting is enabled, then we only listen to UPLOADS when:
  2164. * 1) We are not on the main site in a post-MU network, as wp-content/uploads is used
  2165. * there, and
  2166. * 2) We are not switched, as ms_upload_constants() hardcodes these constants to reflect
  2167. * the original blog ID.
  2168. *
  2169. * Rather than UPLOADS, we actually use BLOGUPLOADDIR if it is set, as it is absolute.
  2170. * (And it will be set, see ms_upload_constants().) Otherwise, UPLOADS can be used, as
  2171. * as it is relative to ABSPATH. For the final piece: when UPLOADS is used with ms-files
  2172. * rewriting in multisite, the resulting URL is /files. (#WP22702 for background.)
  2173. */
  2174. if ( defined( 'BLOGUPLOADDIR' ) ) {
  2175. $dir = untrailingslashit( BLOGUPLOADDIR );
  2176. } else {
  2177. $dir = ABSPATH . UPLOADS;
  2178. }
  2179. $url = trailingslashit( $siteurl ) . 'files';
  2180. }
  2181. }
  2182. $basedir = $dir;
  2183. $baseurl = $url;
  2184. $subdir = '';
  2185. if ( get_option( 'uploads_use_yearmonth_folders' ) ) {
  2186. // Generate the yearly and monthly directories.
  2187. if ( ! $time ) {
  2188. $time = current_time( 'mysql' );
  2189. }
  2190. $y = substr( $time, 0, 4 );
  2191. $m = substr( $time, 5, 2 );
  2192. $subdir = "/$y/$m";
  2193. }
  2194. $dir .= $subdir;
  2195. $url .= $subdir;
  2196. return array(
  2197. 'path' => $dir,
  2198. 'url' => $url,
  2199. 'subdir' => $subdir,
  2200. 'basedir' => $basedir,
  2201. 'baseurl' => $baseurl,
  2202. 'error' => false,
  2203. );
  2204. }
  2205. /**
  2206. * Get a filename that is sanitized and unique for the given directory.
  2207. *
  2208. * If the filename is not unique, then a number will be added to the filename
  2209. * before the extension, and will continue adding numbers until the filename
  2210. * is unique.
  2211. *
  2212. * The callback function allows the caller to use their own method to create
  2213. * unique file names. If defined, the callback should take three arguments:
  2214. * - directory, base filename, and extension - and return a unique filename.
  2215. *
  2216. * @since 2.5.0
  2217. *
  2218. * @param string $dir Directory.
  2219. * @param string $filename File name.
  2220. * @param callable $unique_filename_callback Callback. Default null.
  2221. * @return string New filename, if given wasn't unique.
  2222. */
  2223. function wp_unique_filename( $dir, $filename, $unique_filename_callback = null ) {
  2224. // Sanitize the file name before we begin processing.
  2225. $filename = sanitize_file_name( $filename );
  2226. $ext2 = null;
  2227. // Initialize vars used in the wp_unique_filename filter.
  2228. $number = '';
  2229. $alt_filenames = array();
  2230. // Separate the filename into a name and extension.
  2231. $ext = pathinfo( $filename, PATHINFO_EXTENSION );
  2232. $name = pathinfo( $filename, PATHINFO_BASENAME );
  2233. if ( $ext ) {
  2234. $ext = '.' . $ext;
  2235. }
  2236. // Edge case: if file is named '.ext', treat as an empty name.
  2237. if ( $name === $ext ) {
  2238. $name = '';
  2239. }
  2240. /*
  2241. * Increment the file number until we have a unique file to save in $dir.
  2242. * Use callback if supplied.
  2243. */
  2244. if ( $unique_filename_callback && is_callable( $unique_filename_callback ) ) {
  2245. $filename = call_user_func( $unique_filename_callback, $dir, $name, $ext );
  2246. } else {
  2247. $fname = pathinfo( $filename, PATHINFO_FILENAME );
  2248. // Always append a number to file names that can potentially match image sub-size file names.
  2249. if ( $fname && preg_match( '/-(?:\d+x\d+|scaled|rotated)$/', $fname ) ) {
  2250. $number = 1;
  2251. // At this point the file name may not be unique. This is tested below and the $number is incremented.
  2252. $filename = str_replace( "{$fname}{$ext}", "{$fname}-{$number}{$ext}", $filename );
  2253. }
  2254. /*
  2255. * Get the mime type. Uploaded files were already checked with wp_check_filetype_and_ext()
  2256. * in _wp_handle_upload(). Using wp_check_filetype() would be sufficient here.
  2257. */
  2258. $file_type = wp_check_filetype( $filename );
  2259. $mime_type = $file_type['type'];
  2260. $is_image = ( ! empty( $mime_type ) && 0 === strpos( $mime_type, 'image/' ) );
  2261. $upload_dir = wp_get_upload_dir();
  2262. $lc_filename = null;
  2263. $lc_ext = strtolower( $ext );
  2264. $_dir = trailingslashit( $dir );
  2265. /*
  2266. * If the extension is uppercase add an alternate file name with lowercase extension.
  2267. * Both need to be tested for uniqueness as the extension will be changed to lowercase
  2268. * for better compatibility with different filesystems. Fixes an inconsistency in WP < 2.9
  2269. * where uppercase extensions were allowed but image sub-sizes were created with
  2270. * lowercase extensions.
  2271. */
  2272. if ( $ext && $lc_ext !== $ext ) {
  2273. $lc_filename = preg_replace( '|' . preg_quote( $ext ) . '$|', $lc_ext, $filename );
  2274. }
  2275. /*
  2276. * Increment the number added to the file name if there are any files in $dir
  2277. * whose names match one of the possible name variations.
  2278. */
  2279. while ( file_exists( $_dir . $filename ) || ( $lc_filename && file_exists( $_dir . $lc_filename ) ) ) {
  2280. $new_number = (int) $number + 1;
  2281. if ( $lc_filename ) {
  2282. $lc_filename = str_replace(
  2283. array( "-{$number}{$lc_ext}", "{$number}{$lc_ext}" ),
  2284. "-{$new_number}{$lc_ext}",
  2285. $lc_filename
  2286. );
  2287. }
  2288. if ( '' === "{$number}{$ext}" ) {
  2289. $filename = "{$filename}-{$new_number}";
  2290. } else {
  2291. $filename = str_replace(
  2292. array( "-{$number}{$ext}", "{$number}{$ext}" ),
  2293. "-{$new_number}{$ext}",
  2294. $filename
  2295. );
  2296. }
  2297. $number = $new_number;
  2298. }
  2299. // Change the extension to lowercase if needed.
  2300. if ( $lc_filename ) {
  2301. $filename = $lc_filename;
  2302. }
  2303. /*
  2304. * Prevent collisions with existing file names that contain dimension-like strings
  2305. * (whether they are subsizes or originals uploaded prior to #42437).
  2306. */
  2307. $files = array();
  2308. $count = 10000;
  2309. // The (resized) image files would have name and extension, and will be in the uploads dir.
  2310. if ( $name && $ext && @is_dir( $dir ) && false !== strpos( $dir, $upload_dir['basedir'] ) ) {
  2311. /**
  2312. * Filters the file list used for calculating a unique filename for a newly added file.
  2313. *
  2314. * Returning an array from the filter will effectively short-circuit retrieval
  2315. * from the filesystem and return the passed value instead.
  2316. *
  2317. * @since 5.5.0
  2318. *
  2319. * @param array|null $files The list of files to use for filename comparisons.
  2320. * Default null (to retrieve the list from the filesystem).
  2321. * @param string $dir The directory for the new file.
  2322. * @param string $filename The proposed filename for the new file.
  2323. */
  2324. $files = apply_filters( 'pre_wp_unique_filename_file_list', null, $dir, $filename );
  2325. if ( null === $files ) {
  2326. // List of all files and directories contained in $dir.
  2327. $files = @scandir( $dir );
  2328. }
  2329. if ( ! empty( $files ) ) {
  2330. // Remove "dot" dirs.
  2331. $files = array_diff( $files, array( '.', '..' ) );
  2332. }
  2333. if ( ! empty( $files ) ) {
  2334. $count = count( $files );
  2335. /*
  2336. * Ensure this never goes into infinite loop as it uses pathinfo() and regex in the check,
  2337. * but string replacement for the changes.
  2338. */
  2339. $i = 0;
  2340. while ( $i <= $count && _wp_check_existing_file_names( $filename, $files ) ) {
  2341. $new_number = (int) $number + 1;
  2342. // If $ext is uppercase it was replaced with the lowercase version after the previous loop.
  2343. $filename = str_replace(
  2344. array( "-{$number}{$lc_ext}", "{$number}{$lc_ext}" ),
  2345. "-{$new_number}{$lc_ext}",
  2346. $filename
  2347. );
  2348. $number = $new_number;
  2349. $i++;
  2350. }
  2351. }
  2352. }
  2353. /*
  2354. * Check if an image will be converted after uploading or some existing image sub-size file names may conflict
  2355. * when regenerated. If yes, ensure the new file name will be unique and will produce unique sub-sizes.
  2356. */
  2357. if ( $is_image ) {
  2358. /** This filter is documented in wp-includes/class-wp-image-editor.php */
  2359. $output_formats = apply_filters( 'image_editor_output_format', array(), $_dir . $filename, $mime_type );
  2360. $alt_types = array();
  2361. if ( ! empty( $output_formats[ $mime_type ] ) ) {
  2362. // The image will be converted to this format/mime type.
  2363. $alt_mime_type = $output_formats[ $mime_type ];
  2364. // Other types of images whose names may conflict if their sub-sizes are regenerated.
  2365. $alt_types = array_keys( array_intersect( $output_formats, array( $mime_type, $alt_mime_type ) ) );
  2366. $alt_types[] = $alt_mime_type;
  2367. } elseif ( ! empty( $output_formats ) ) {
  2368. $alt_types = array_keys( array_intersect( $output_formats, array( $mime_type ) ) );
  2369. }
  2370. // Remove duplicates and the original mime type. It will be added later if needed.
  2371. $alt_types = array_unique( array_diff( $alt_types, array( $mime_type ) ) );
  2372. foreach ( $alt_types as $alt_type ) {
  2373. $alt_ext = wp_get_default_extension_for_mime_type( $alt_type );
  2374. if ( ! $alt_ext ) {
  2375. continue;
  2376. }
  2377. $alt_ext = ".{$alt_ext}";
  2378. $alt_filename = preg_replace( '|' . preg_quote( $lc_ext ) . '$|', $alt_ext, $filename );
  2379. $alt_filenames[ $alt_ext ] = $alt_filename;
  2380. }
  2381. if ( ! empty( $alt_filenames ) ) {
  2382. /*
  2383. * Add the original filename. It needs to be checked again
  2384. * together with the alternate filenames when $number is incremented.
  2385. */
  2386. $alt_filenames[ $lc_ext ] = $filename;
  2387. // Ensure no infinite loop.
  2388. $i = 0;
  2389. while ( $i <= $count && _wp_check_alternate_file_names( $alt_filenames, $_dir, $files ) ) {
  2390. $new_number = (int) $number + 1;
  2391. foreach ( $alt_filenames as $alt_ext => $alt_filename ) {
  2392. $alt_filenames[ $alt_ext ] = str_replace(
  2393. array( "-{$number}{$alt_ext}", "{$number}{$alt_ext}" ),
  2394. "-{$new_number}{$alt_ext}",
  2395. $alt_filename
  2396. );
  2397. }
  2398. /*
  2399. * Also update the $number in (the output) $filename.
  2400. * If the extension was uppercase it was already replaced with the lowercase version.
  2401. */
  2402. $filename = str_replace(
  2403. array( "-{$number}{$lc_ext}", "{$number}{$lc_ext}" ),
  2404. "-{$new_number}{$lc_ext}",
  2405. $filename
  2406. );
  2407. $number = $new_number;
  2408. $i++;
  2409. }
  2410. }
  2411. }
  2412. }
  2413. /**
  2414. * Filters the result when generating a unique file name.
  2415. *
  2416. * @since 4.5.0
  2417. * @since 5.8.1 The `$alt_filenames` and `$number` parameters were added.
  2418. *
  2419. * @param string $filename Unique file name.
  2420. * @param string $ext File extension. Example: ".png".
  2421. * @param string $dir Directory path.
  2422. * @param callable|null $unique_filename_callback Callback function that generates the unique file name.
  2423. * @param string[] $alt_filenames Array of alternate file names that were checked for collisions.
  2424. * @param int|string $number The highest number that was used to make the file name unique
  2425. * or an empty string if unused.
  2426. */
  2427. return apply_filters( 'wp_unique_filename', $filename, $ext, $dir, $unique_filename_callback, $alt_filenames, $number );
  2428. }
  2429. /**
  2430. * Helper function to test if each of an array of file names could conflict with existing files.
  2431. *
  2432. * @since 5.8.1
  2433. * @access private
  2434. *
  2435. * @param string[] $filenames Array of file names to check.
  2436. * @param string $dir The directory containing the files.
  2437. * @param array $files An array of existing files in the directory. May be empty.
  2438. * @return bool True if the tested file name could match an existing file, false otherwise.
  2439. */
  2440. function _wp_check_alternate_file_names( $filenames, $dir, $files ) {
  2441. foreach ( $filenames as $filename ) {
  2442. if ( file_exists( $dir . $filename ) ) {
  2443. return true;
  2444. }
  2445. if ( ! empty( $files ) && _wp_check_existing_file_names( $filename, $files ) ) {
  2446. return true;
  2447. }
  2448. }
  2449. return false;
  2450. }
  2451. /**
  2452. * Helper function to check if a file name could match an existing image sub-size file name.
  2453. *
  2454. * @since 5.3.1
  2455. * @access private
  2456. *
  2457. * @param string $filename The file name to check.
  2458. * @param array $files An array of existing files in the directory.
  2459. * @return bool True if the tested file name could match an existing file, false otherwise.
  2460. */
  2461. function _wp_check_existing_file_names( $filename, $files ) {
  2462. $fname = pathinfo( $filename, PATHINFO_FILENAME );
  2463. $ext = pathinfo( $filename, PATHINFO_EXTENSION );
  2464. // Edge case, file names like `.ext`.
  2465. if ( empty( $fname ) ) {
  2466. return false;
  2467. }
  2468. if ( $ext ) {
  2469. $ext = ".$ext";
  2470. }
  2471. $regex = '/^' . preg_quote( $fname ) . '-(?:\d+x\d+|scaled|rotated)' . preg_quote( $ext ) . '$/i';
  2472. foreach ( $files as $file ) {
  2473. if ( preg_match( $regex, $file ) ) {
  2474. return true;
  2475. }
  2476. }
  2477. return false;
  2478. }
  2479. /**
  2480. * Create a file in the upload folder with given content.
  2481. *
  2482. * If there is an error, then the key 'error' will exist with the error message.
  2483. * If success, then the key 'file' will have the unique file path, the 'url' key
  2484. * will have the link to the new file. and the 'error' key will be set to false.
  2485. *
  2486. * This function will not move an uploaded file to the upload folder. It will
  2487. * create a new file with the content in $bits parameter. If you move the upload
  2488. * file, read the content of the uploaded file, and then you can give the
  2489. * filename and content to this function, which will add it to the upload
  2490. * folder.
  2491. *
  2492. * The permissions will be set on the new file automatically by this function.
  2493. *
  2494. * @since 2.0.0
  2495. *
  2496. * @param string $name Filename.
  2497. * @param null|string $deprecated Never used. Set to null.
  2498. * @param string $bits File content
  2499. * @param string $time Optional. Time formatted in 'yyyy/mm'. Default null.
  2500. * @return array {
  2501. * Information about the newly-uploaded file.
  2502. *
  2503. * @type string $file Filename of the newly-uploaded file.
  2504. * @type string $url URL of the uploaded file.
  2505. * @type string $type File type.
  2506. * @type string|false $error Error message, if there has been an error.
  2507. * }
  2508. */
  2509. function wp_upload_bits( $name, $deprecated, $bits, $time = null ) {
  2510. if ( ! empty( $deprecated ) ) {
  2511. _deprecated_argument( __FUNCTION__, '2.0.0' );
  2512. }
  2513. if ( empty( $name ) ) {
  2514. return array( 'error' => __( 'Empty filename' ) );
  2515. }
  2516. $wp_filetype = wp_check_filetype( $name );
  2517. if ( ! $wp_filetype['ext'] && ! current_user_can( 'unfiltered_upload' ) ) {
  2518. return array( 'error' => __( 'Sorry, you are not allowed to upload this file type.' ) );
  2519. }
  2520. $upload = wp_upload_dir( $time );
  2521. if ( false !== $upload['error'] ) {
  2522. return $upload;
  2523. }
  2524. /**
  2525. * Filters whether to treat the upload bits as an error.
  2526. *
  2527. * Returning a non-array from the filter will effectively short-circuit preparing the upload bits
  2528. * and return that value instead. An error message should be returned as a string.
  2529. *
  2530. * @since 3.0.0
  2531. *
  2532. * @param array|string $upload_bits_error An array of upload bits data, or error message to return.
  2533. */
  2534. $upload_bits_error = apply_filters(
  2535. 'wp_upload_bits',
  2536. array(
  2537. 'name' => $name,
  2538. 'bits' => $bits,
  2539. 'time' => $time,
  2540. )
  2541. );
  2542. if ( ! is_array( $upload_bits_error ) ) {
  2543. $upload['error'] = $upload_bits_error;
  2544. return $upload;
  2545. }
  2546. $filename = wp_unique_filename( $upload['path'], $name );
  2547. $new_file = $upload['path'] . "/$filename";
  2548. if ( ! wp_mkdir_p( dirname( $new_file ) ) ) {
  2549. if ( 0 === strpos( $upload['basedir'], ABSPATH ) ) {
  2550. $error_path = str_replace( ABSPATH, '', $upload['basedir'] ) . $upload['subdir'];
  2551. } else {
  2552. $error_path = wp_basename( $upload['basedir'] ) . $upload['subdir'];
  2553. }
  2554. $message = sprintf(
  2555. /* translators: %s: Directory path. */
  2556. __( 'Unable to create directory %s. Is its parent directory writable by the server?' ),
  2557. $error_path
  2558. );
  2559. return array( 'error' => $message );
  2560. }
  2561. $ifp = @fopen( $new_file, 'wb' );
  2562. if ( ! $ifp ) {
  2563. return array(
  2564. /* translators: %s: File name. */
  2565. 'error' => sprintf( __( 'Could not write file %s' ), $new_file ),
  2566. );
  2567. }
  2568. fwrite( $ifp, $bits );
  2569. fclose( $ifp );
  2570. clearstatcache();
  2571. // Set correct file permissions.
  2572. $stat = @ stat( dirname( $new_file ) );
  2573. $perms = $stat['mode'] & 0007777;
  2574. $perms = $perms & 0000666;
  2575. chmod( $new_file, $perms );
  2576. clearstatcache();
  2577. // Compute the URL.
  2578. $url = $upload['url'] . "/$filename";
  2579. if ( is_multisite() ) {
  2580. clean_dirsize_cache( $new_file );
  2581. }
  2582. /** This filter is documented in wp-admin/includes/file.php */
  2583. return apply_filters(
  2584. 'wp_handle_upload',
  2585. array(
  2586. 'file' => $new_file,
  2587. 'url' => $url,
  2588. 'type' => $wp_filetype['type'],
  2589. 'error' => false,
  2590. ),
  2591. 'sideload'
  2592. );
  2593. }
  2594. /**
  2595. * Retrieve the file type based on the extension name.
  2596. *
  2597. * @since 2.5.0
  2598. *
  2599. * @param string $ext The extension to search.
  2600. * @return string|void The file type, example: audio, video, document, spreadsheet, etc.
  2601. */
  2602. function wp_ext2type( $ext ) {
  2603. $ext = strtolower( $ext );
  2604. $ext2type = wp_get_ext_types();
  2605. foreach ( $ext2type as $type => $exts ) {
  2606. if ( in_array( $ext, $exts, true ) ) {
  2607. return $type;
  2608. }
  2609. }
  2610. }
  2611. /**
  2612. * Returns first matched extension for the mime-type,
  2613. * as mapped from wp_get_mime_types().
  2614. *
  2615. * @since 5.8.1
  2616. *
  2617. * @param string $mime_type
  2618. *
  2619. * @return string|false
  2620. */
  2621. function wp_get_default_extension_for_mime_type( $mime_type ) {
  2622. $extensions = explode( '|', array_search( $mime_type, wp_get_mime_types(), true ) );
  2623. if ( empty( $extensions[0] ) ) {
  2624. return false;
  2625. }
  2626. return $extensions[0];
  2627. }
  2628. /**
  2629. * Retrieve the file type from the file name.
  2630. *
  2631. * You can optionally define the mime array, if needed.
  2632. *
  2633. * @since 2.0.4
  2634. *
  2635. * @param string $filename File name or path.
  2636. * @param string[] $mimes Optional. Array of allowed mime types keyed by their file extension regex.
  2637. * @return array {
  2638. * Values for the extension and mime type.
  2639. *
  2640. * @type string|false $ext File extension, or false if the file doesn't match a mime type.
  2641. * @type string|false $type File mime type, or false if the file doesn't match a mime type.
  2642. * }
  2643. */
  2644. function wp_check_filetype( $filename, $mimes = null ) {
  2645. if ( empty( $mimes ) ) {
  2646. $mimes = get_allowed_mime_types();
  2647. }
  2648. $type = false;
  2649. $ext = false;
  2650. foreach ( $mimes as $ext_preg => $mime_match ) {
  2651. $ext_preg = '!\.(' . $ext_preg . ')$!i';
  2652. if ( preg_match( $ext_preg, $filename, $ext_matches ) ) {
  2653. $type = $mime_match;
  2654. $ext = $ext_matches[1];
  2655. break;
  2656. }
  2657. }
  2658. return compact( 'ext', 'type' );
  2659. }
  2660. /**
  2661. * Attempt to determine the real file type of a file.
  2662. *
  2663. * If unable to, the file name extension will be used to determine type.
  2664. *
  2665. * If it's determined that the extension does not match the file's real type,
  2666. * then the "proper_filename" value will be set with a proper filename and extension.
  2667. *
  2668. * Currently this function only supports renaming images validated via wp_get_image_mime().
  2669. *
  2670. * @since 3.0.0
  2671. *
  2672. * @param string $file Full path to the file.
  2673. * @param string $filename The name of the file (may differ from $file due to $file being
  2674. * in a tmp directory).
  2675. * @param string[] $mimes Optional. Array of allowed mime types keyed by their file extension regex.
  2676. * @return array {
  2677. * Values for the extension, mime type, and corrected filename.
  2678. *
  2679. * @type string|false $ext File extension, or false if the file doesn't match a mime type.
  2680. * @type string|false $type File mime type, or false if the file doesn't match a mime type.
  2681. * @type string|false $proper_filename File name with its correct extension, or false if it cannot be determined.
  2682. * }
  2683. */
  2684. function wp_check_filetype_and_ext( $file, $filename, $mimes = null ) {
  2685. $proper_filename = false;
  2686. // Do basic extension validation and MIME mapping.
  2687. $wp_filetype = wp_check_filetype( $filename, $mimes );
  2688. $ext = $wp_filetype['ext'];
  2689. $type = $wp_filetype['type'];
  2690. // We can't do any further validation without a file to work with.
  2691. if ( ! file_exists( $file ) ) {
  2692. return compact( 'ext', 'type', 'proper_filename' );
  2693. }
  2694. $real_mime = false;
  2695. // Validate image types.
  2696. if ( $type && 0 === strpos( $type, 'image/' ) ) {
  2697. // Attempt to figure out what type of image it actually is.
  2698. $real_mime = wp_get_image_mime( $file );
  2699. if ( $real_mime && $real_mime != $type ) {
  2700. /**
  2701. * Filters the list mapping image mime types to their respective extensions.
  2702. *
  2703. * @since 3.0.0
  2704. *
  2705. * @param array $mime_to_ext Array of image mime types and their matching extensions.
  2706. */
  2707. $mime_to_ext = apply_filters(
  2708. 'getimagesize_mimes_to_exts',
  2709. array(
  2710. 'image/jpeg' => 'jpg',
  2711. 'image/png' => 'png',
  2712. 'image/gif' => 'gif',
  2713. 'image/bmp' => 'bmp',
  2714. 'image/tiff' => 'tif',
  2715. 'image/webp' => 'webp',
  2716. )
  2717. );
  2718. // Replace whatever is after the last period in the filename with the correct extension.
  2719. if ( ! empty( $mime_to_ext[ $real_mime ] ) ) {
  2720. $filename_parts = explode( '.', $filename );
  2721. array_pop( $filename_parts );
  2722. $filename_parts[] = $mime_to_ext[ $real_mime ];
  2723. $new_filename = implode( '.', $filename_parts );
  2724. if ( $new_filename != $filename ) {
  2725. $proper_filename = $new_filename; // Mark that it changed.
  2726. }
  2727. // Redefine the extension / MIME.
  2728. $wp_filetype = wp_check_filetype( $new_filename, $mimes );
  2729. $ext = $wp_filetype['ext'];
  2730. $type = $wp_filetype['type'];
  2731. } else {
  2732. // Reset $real_mime and try validating again.
  2733. $real_mime = false;
  2734. }
  2735. }
  2736. }
  2737. // Validate files that didn't get validated during previous checks.
  2738. if ( $type && ! $real_mime && extension_loaded( 'fileinfo' ) ) {
  2739. $finfo = finfo_open( FILEINFO_MIME_TYPE );
  2740. $real_mime = finfo_file( $finfo, $file );
  2741. finfo_close( $finfo );
  2742. // fileinfo often misidentifies obscure files as one of these types.
  2743. $nonspecific_types = array(
  2744. 'application/octet-stream',
  2745. 'application/encrypted',
  2746. 'application/CDFV2-encrypted',
  2747. 'application/zip',
  2748. );
  2749. /*
  2750. * If $real_mime doesn't match the content type we're expecting from the file's extension,
  2751. * we need to do some additional vetting. Media types and those listed in $nonspecific_types are
  2752. * allowed some leeway, but anything else must exactly match the real content type.
  2753. */
  2754. if ( in_array( $real_mime, $nonspecific_types, true ) ) {
  2755. // File is a non-specific binary type. That's ok if it's a type that generally tends to be binary.
  2756. if ( ! in_array( substr( $type, 0, strcspn( $type, '/' ) ), array( 'application', 'video', 'audio' ), true ) ) {
  2757. $type = false;
  2758. $ext = false;
  2759. }
  2760. } elseif ( 0 === strpos( $real_mime, 'video/' ) || 0 === strpos( $real_mime, 'audio/' ) ) {
  2761. /*
  2762. * For these types, only the major type must match the real value.
  2763. * This means that common mismatches are forgiven: application/vnd.apple.numbers is often misidentified as application/zip,
  2764. * and some media files are commonly named with the wrong extension (.mov instead of .mp4)
  2765. */
  2766. if ( substr( $real_mime, 0, strcspn( $real_mime, '/' ) ) !== substr( $type, 0, strcspn( $type, '/' ) ) ) {
  2767. $type = false;
  2768. $ext = false;
  2769. }
  2770. } elseif ( 'text/plain' === $real_mime ) {
  2771. // A few common file types are occasionally detected as text/plain; allow those.
  2772. if ( ! in_array(
  2773. $type,
  2774. array(
  2775. 'text/plain',
  2776. 'text/csv',
  2777. 'application/csv',
  2778. 'text/richtext',
  2779. 'text/tsv',
  2780. 'text/vtt',
  2781. ),
  2782. true
  2783. )
  2784. ) {
  2785. $type = false;
  2786. $ext = false;
  2787. }
  2788. } elseif ( 'application/csv' === $real_mime ) {
  2789. // Special casing for CSV files.
  2790. if ( ! in_array(
  2791. $type,
  2792. array(
  2793. 'text/csv',
  2794. 'text/plain',
  2795. 'application/csv',
  2796. ),
  2797. true
  2798. )
  2799. ) {
  2800. $type = false;
  2801. $ext = false;
  2802. }
  2803. } elseif ( 'text/rtf' === $real_mime ) {
  2804. // Special casing for RTF files.
  2805. if ( ! in_array(
  2806. $type,
  2807. array(
  2808. 'text/rtf',
  2809. 'text/plain',
  2810. 'application/rtf',
  2811. ),
  2812. true
  2813. )
  2814. ) {
  2815. $type = false;
  2816. $ext = false;
  2817. }
  2818. } else {
  2819. if ( $type !== $real_mime ) {
  2820. /*
  2821. * Everything else including image/* and application/*:
  2822. * If the real content type doesn't match the file extension, assume it's dangerous.
  2823. */
  2824. $type = false;
  2825. $ext = false;
  2826. }
  2827. }
  2828. }
  2829. // The mime type must be allowed.
  2830. if ( $type ) {
  2831. $allowed = get_allowed_mime_types();
  2832. if ( ! in_array( $type, $allowed, true ) ) {
  2833. $type = false;
  2834. $ext = false;
  2835. }
  2836. }
  2837. /**
  2838. * Filters the "real" file type of the given file.
  2839. *
  2840. * @since 3.0.0
  2841. * @since 5.1.0 The $real_mime parameter was added.
  2842. *
  2843. * @param array $wp_check_filetype_and_ext {
  2844. * Values for the extension, mime type, and corrected filename.
  2845. *
  2846. * @type string|false $ext File extension, or false if the file doesn't match a mime type.
  2847. * @type string|false $type File mime type, or false if the file doesn't match a mime type.
  2848. * @type string|false $proper_filename File name with its correct extension, or false if it cannot be determined.
  2849. * }
  2850. * @param string $file Full path to the file.
  2851. * @param string $filename The name of the file (may differ from $file due to
  2852. * $file being in a tmp directory).
  2853. * @param string[] $mimes Array of mime types keyed by their file extension regex.
  2854. * @param string|false $real_mime The actual mime type or false if the type cannot be determined.
  2855. */
  2856. return apply_filters( 'wp_check_filetype_and_ext', compact( 'ext', 'type', 'proper_filename' ), $file, $filename, $mimes, $real_mime );
  2857. }
  2858. /**
  2859. * Returns the real mime type of an image file.
  2860. *
  2861. * This depends on exif_imagetype() or getimagesize() to determine real mime types.
  2862. *
  2863. * @since 4.7.1
  2864. * @since 5.8.0 Added support for WebP images.
  2865. *
  2866. * @param string $file Full path to the file.
  2867. * @return string|false The actual mime type or false if the type cannot be determined.
  2868. */
  2869. function wp_get_image_mime( $file ) {
  2870. /*
  2871. * Use exif_imagetype() to check the mimetype if available or fall back to
  2872. * getimagesize() if exif isn't available. If either function throws an Exception
  2873. * we assume the file could not be validated.
  2874. */
  2875. try {
  2876. if ( is_callable( 'exif_imagetype' ) ) {
  2877. $imagetype = exif_imagetype( $file );
  2878. $mime = ( $imagetype ) ? image_type_to_mime_type( $imagetype ) : false;
  2879. } elseif ( function_exists( 'getimagesize' ) ) {
  2880. // Don't silence errors when in debug mode, unless running unit tests.
  2881. if ( defined( 'WP_DEBUG' ) && WP_DEBUG
  2882. && ! defined( 'WP_RUN_CORE_TESTS' )
  2883. ) {
  2884. // Not using wp_getimagesize() here to avoid an infinite loop.
  2885. $imagesize = getimagesize( $file );
  2886. } else {
  2887. // phpcs:ignore WordPress.PHP.NoSilencedErrors
  2888. $imagesize = @getimagesize( $file );
  2889. }
  2890. $mime = ( isset( $imagesize['mime'] ) ) ? $imagesize['mime'] : false;
  2891. } else {
  2892. $mime = false;
  2893. }
  2894. if ( false !== $mime ) {
  2895. return $mime;
  2896. }
  2897. $magic = file_get_contents( $file, false, null, 0, 12 );
  2898. if ( false === $magic ) {
  2899. return false;
  2900. }
  2901. /*
  2902. * Add WebP fallback detection when image library doesn't support WebP.
  2903. * Note: detection values come from LibWebP, see
  2904. * https://github.com/webmproject/libwebp/blob/master/imageio/image_dec.c#L30
  2905. */
  2906. $magic = bin2hex( $magic );
  2907. if (
  2908. // RIFF.
  2909. ( 0 === strpos( $magic, '52494646' ) ) &&
  2910. // WEBP.
  2911. ( 16 === strpos( $magic, '57454250' ) )
  2912. ) {
  2913. $mime = 'image/webp';
  2914. }
  2915. } catch ( Exception $e ) {
  2916. $mime = false;
  2917. }
  2918. return $mime;
  2919. }
  2920. /**
  2921. * Retrieve list of mime types and file extensions.
  2922. *
  2923. * @since 3.5.0
  2924. * @since 4.2.0 Support was added for GIMP (.xcf) files.
  2925. * @since 4.9.2 Support was added for Flac (.flac) files.
  2926. * @since 4.9.6 Support was added for AAC (.aac) files.
  2927. *
  2928. * @return string[] Array of mime types keyed by the file extension regex corresponding to those types.
  2929. */
  2930. function wp_get_mime_types() {
  2931. /**
  2932. * Filters the list of mime types and file extensions.
  2933. *
  2934. * This filter should be used to add, not remove, mime types. To remove
  2935. * mime types, use the {@see 'upload_mimes'} filter.
  2936. *
  2937. * @since 3.5.0
  2938. *
  2939. * @param string[] $wp_get_mime_types Mime types keyed by the file extension regex
  2940. * corresponding to those types.
  2941. */
  2942. return apply_filters(
  2943. 'mime_types',
  2944. array(
  2945. // Image formats.
  2946. 'jpg|jpeg|jpe' => 'image/jpeg',
  2947. 'gif' => 'image/gif',
  2948. 'png' => 'image/png',
  2949. 'bmp' => 'image/bmp',
  2950. 'tiff|tif' => 'image/tiff',
  2951. 'webp' => 'image/webp',
  2952. 'ico' => 'image/x-icon',
  2953. 'heic' => 'image/heic',
  2954. // Video formats.
  2955. 'asf|asx' => 'video/x-ms-asf',
  2956. 'wmv' => 'video/x-ms-wmv',
  2957. 'wmx' => 'video/x-ms-wmx',
  2958. 'wm' => 'video/x-ms-wm',
  2959. 'avi' => 'video/avi',
  2960. 'divx' => 'video/divx',
  2961. 'flv' => 'video/x-flv',
  2962. 'mov|qt' => 'video/quicktime',
  2963. 'mpeg|mpg|mpe' => 'video/mpeg',
  2964. 'mp4|m4v' => 'video/mp4',
  2965. 'ogv' => 'video/ogg',
  2966. 'webm' => 'video/webm',
  2967. 'mkv' => 'video/x-matroska',
  2968. '3gp|3gpp' => 'video/3gpp', // Can also be audio.
  2969. '3g2|3gp2' => 'video/3gpp2', // Can also be audio.
  2970. // Text formats.
  2971. 'txt|asc|c|cc|h|srt' => 'text/plain',
  2972. 'csv' => 'text/csv',
  2973. 'tsv' => 'text/tab-separated-values',
  2974. 'ics' => 'text/calendar',
  2975. 'rtx' => 'text/richtext',
  2976. 'css' => 'text/css',
  2977. 'htm|html' => 'text/html',
  2978. 'vtt' => 'text/vtt',
  2979. 'dfxp' => 'application/ttaf+xml',
  2980. // Audio formats.
  2981. 'mp3|m4a|m4b' => 'audio/mpeg',
  2982. 'aac' => 'audio/aac',
  2983. 'ra|ram' => 'audio/x-realaudio',
  2984. 'wav' => 'audio/wav',
  2985. 'ogg|oga' => 'audio/ogg',
  2986. 'flac' => 'audio/flac',
  2987. 'mid|midi' => 'audio/midi',
  2988. 'wma' => 'audio/x-ms-wma',
  2989. 'wax' => 'audio/x-ms-wax',
  2990. 'mka' => 'audio/x-matroska',
  2991. // Misc application formats.
  2992. 'rtf' => 'application/rtf',
  2993. 'js' => 'application/javascript',
  2994. 'pdf' => 'application/pdf',
  2995. 'swf' => 'application/x-shockwave-flash',
  2996. 'class' => 'application/java',
  2997. 'tar' => 'application/x-tar',
  2998. 'zip' => 'application/zip',
  2999. 'gz|gzip' => 'application/x-gzip',
  3000. 'rar' => 'application/rar',
  3001. '7z' => 'application/x-7z-compressed',
  3002. 'exe' => 'application/x-msdownload',
  3003. 'psd' => 'application/octet-stream',
  3004. 'xcf' => 'application/octet-stream',
  3005. // MS Office formats.
  3006. 'doc' => 'application/msword',
  3007. 'pot|pps|ppt' => 'application/vnd.ms-powerpoint',
  3008. 'wri' => 'application/vnd.ms-write',
  3009. 'xla|xls|xlt|xlw' => 'application/vnd.ms-excel',
  3010. 'mdb' => 'application/vnd.ms-access',
  3011. 'mpp' => 'application/vnd.ms-project',
  3012. 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  3013. 'docm' => 'application/vnd.ms-word.document.macroEnabled.12',
  3014. 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
  3015. 'dotm' => 'application/vnd.ms-word.template.macroEnabled.12',
  3016. 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  3017. 'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12',
  3018. 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
  3019. 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
  3020. 'xltm' => 'application/vnd.ms-excel.template.macroEnabled.12',
  3021. 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
  3022. 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  3023. 'pptm' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12',
  3024. 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
  3025. 'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12',
  3026. 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
  3027. 'potm' => 'application/vnd.ms-powerpoint.template.macroEnabled.12',
  3028. 'ppam' => 'application/vnd.ms-powerpoint.addin.macroEnabled.12',
  3029. 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
  3030. 'sldm' => 'application/vnd.ms-powerpoint.slide.macroEnabled.12',
  3031. 'onetoc|onetoc2|onetmp|onepkg' => 'application/onenote',
  3032. 'oxps' => 'application/oxps',
  3033. 'xps' => 'application/vnd.ms-xpsdocument',
  3034. // OpenOffice formats.
  3035. 'odt' => 'application/vnd.oasis.opendocument.text',
  3036. 'odp' => 'application/vnd.oasis.opendocument.presentation',
  3037. 'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
  3038. 'odg' => 'application/vnd.oasis.opendocument.graphics',
  3039. 'odc' => 'application/vnd.oasis.opendocument.chart',
  3040. 'odb' => 'application/vnd.oasis.opendocument.database',
  3041. 'odf' => 'application/vnd.oasis.opendocument.formula',
  3042. // WordPerfect formats.
  3043. 'wp|wpd' => 'application/wordperfect',
  3044. // iWork formats.
  3045. 'key' => 'application/vnd.apple.keynote',
  3046. 'numbers' => 'application/vnd.apple.numbers',
  3047. 'pages' => 'application/vnd.apple.pages',
  3048. )
  3049. );
  3050. }
  3051. /**
  3052. * Retrieves the list of common file extensions and their types.
  3053. *
  3054. * @since 4.6.0
  3055. *
  3056. * @return array[] Multi-dimensional array of file extensions types keyed by the type of file.
  3057. */
  3058. function wp_get_ext_types() {
  3059. /**
  3060. * Filters file type based on the extension name.
  3061. *
  3062. * @since 2.5.0
  3063. *
  3064. * @see wp_ext2type()
  3065. *
  3066. * @param array[] $ext2type Multi-dimensional array of file extensions types keyed by the type of file.
  3067. */
  3068. return apply_filters(
  3069. 'ext2type',
  3070. array(
  3071. 'image' => array( 'jpg', 'jpeg', 'jpe', 'gif', 'png', 'bmp', 'tif', 'tiff', 'ico', 'heic', 'webp' ),
  3072. 'audio' => array( 'aac', 'ac3', 'aif', 'aiff', 'flac', 'm3a', 'm4a', 'm4b', 'mka', 'mp1', 'mp2', 'mp3', 'ogg', 'oga', 'ram', 'wav', 'wma' ),
  3073. 'video' => array( '3g2', '3gp', '3gpp', 'asf', 'avi', 'divx', 'dv', 'flv', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'mpv', 'ogm', 'ogv', 'qt', 'rm', 'vob', 'wmv' ),
  3074. 'document' => array( 'doc', 'docx', 'docm', 'dotm', 'odt', 'pages', 'pdf', 'xps', 'oxps', 'rtf', 'wp', 'wpd', 'psd', 'xcf' ),
  3075. 'spreadsheet' => array( 'numbers', 'ods', 'xls', 'xlsx', 'xlsm', 'xlsb' ),
  3076. 'interactive' => array( 'swf', 'key', 'ppt', 'pptx', 'pptm', 'pps', 'ppsx', 'ppsm', 'sldx', 'sldm', 'odp' ),
  3077. 'text' => array( 'asc', 'csv', 'tsv', 'txt' ),
  3078. 'archive' => array( 'bz2', 'cab', 'dmg', 'gz', 'rar', 'sea', 'sit', 'sqx', 'tar', 'tgz', 'zip', '7z' ),
  3079. 'code' => array( 'css', 'htm', 'html', 'php', 'js' ),
  3080. )
  3081. );
  3082. }
  3083. /**
  3084. * Retrieve list of allowed mime types and file extensions.
  3085. *
  3086. * @since 2.8.6
  3087. *
  3088. * @param int|WP_User $user Optional. User to check. Defaults to current user.
  3089. * @return string[] Array of mime types keyed by the file extension regex corresponding
  3090. * to those types.
  3091. */
  3092. function get_allowed_mime_types( $user = null ) {
  3093. $t = wp_get_mime_types();
  3094. unset( $t['swf'], $t['exe'] );
  3095. if ( function_exists( 'current_user_can' ) ) {
  3096. $unfiltered = $user ? user_can( $user, 'unfiltered_html' ) : current_user_can( 'unfiltered_html' );
  3097. }
  3098. if ( empty( $unfiltered ) ) {
  3099. unset( $t['htm|html'], $t['js'] );
  3100. }
  3101. /**
  3102. * Filters list of allowed mime types and file extensions.
  3103. *
  3104. * @since 2.0.0
  3105. *
  3106. * @param array $t Mime types keyed by the file extension regex corresponding to those types.
  3107. * @param int|WP_User|null $user User ID, User object or null if not provided (indicates current user).
  3108. */
  3109. return apply_filters( 'upload_mimes', $t, $user );
  3110. }
  3111. /**
  3112. * Display "Are You Sure" message to confirm the action being taken.
  3113. *
  3114. * If the action has the nonce explain message, then it will be displayed
  3115. * along with the "Are you sure?" message.
  3116. *
  3117. * @since 2.0.4
  3118. *
  3119. * @param string $action The nonce action.
  3120. */
  3121. function wp_nonce_ays( $action ) {
  3122. // Default title and response code.
  3123. $title = __( 'Something went wrong.' );
  3124. $response_code = 403;
  3125. if ( 'log-out' === $action ) {
  3126. $title = sprintf(
  3127. /* translators: %s: Site title. */
  3128. __( 'You are attempting to log out of %s' ),
  3129. get_bloginfo( 'name' )
  3130. );
  3131. $html = $title;
  3132. $html .= '</p><p>';
  3133. $redirect_to = isset( $_REQUEST['redirect_to'] ) ? $_REQUEST['redirect_to'] : '';
  3134. $html .= sprintf(
  3135. /* translators: %s: Logout URL. */
  3136. __( 'Do you really want to <a href="%s">log out</a>?' ),
  3137. wp_logout_url( $redirect_to )
  3138. );
  3139. } else {
  3140. $html = __( 'The link you followed has expired.' );
  3141. if ( wp_get_referer() ) {
  3142. $html .= '</p><p>';
  3143. $html .= sprintf(
  3144. '<a href="%s">%s</a>',
  3145. esc_url( remove_query_arg( 'updated', wp_get_referer() ) ),
  3146. __( 'Please try again.' )
  3147. );
  3148. }
  3149. }
  3150. wp_die( $html, $title, $response_code );
  3151. }
  3152. /**
  3153. * Kills WordPress execution and displays HTML page with an error message.
  3154. *
  3155. * This function complements the `die()` PHP function. The difference is that
  3156. * HTML will be displayed to the user. It is recommended to use this function
  3157. * only when the execution should not continue any further. It is not recommended
  3158. * to call this function very often, and try to handle as many errors as possible
  3159. * silently or more gracefully.
  3160. *
  3161. * As a shorthand, the desired HTTP response code may be passed as an integer to
  3162. * the `$title` parameter (the default title would apply) or the `$args` parameter.
  3163. *
  3164. * @since 2.0.4
  3165. * @since 4.1.0 The `$title` and `$args` parameters were changed to optionally accept
  3166. * an integer to be used as the response code.
  3167. * @since 5.1.0 The `$link_url`, `$link_text`, and `$exit` arguments were added.
  3168. * @since 5.3.0 The `$charset` argument was added.
  3169. * @since 5.5.0 The `$text_direction` argument has a priority over get_language_attributes()
  3170. * in the default handler.
  3171. *
  3172. * @global WP_Query $wp_query WordPress Query object.
  3173. *
  3174. * @param string|WP_Error $message Optional. Error message. If this is a WP_Error object,
  3175. * and not an Ajax or XML-RPC request, the error's messages are used.
  3176. * Default empty.
  3177. * @param string|int $title Optional. Error title. If `$message` is a `WP_Error` object,
  3178. * error data with the key 'title' may be used to specify the title.
  3179. * If `$title` is an integer, then it is treated as the response
  3180. * code. Default empty.
  3181. * @param string|array|int $args {
  3182. * Optional. Arguments to control behavior. If `$args` is an integer, then it is treated
  3183. * as the response code. Default empty array.
  3184. *
  3185. * @type int $response The HTTP response code. Default 200 for Ajax requests, 500 otherwise.
  3186. * @type string $link_url A URL to include a link to. Only works in combination with $link_text.
  3187. * Default empty string.
  3188. * @type string $link_text A label for the link to include. Only works in combination with $link_url.
  3189. * Default empty string.
  3190. * @type bool $back_link Whether to include a link to go back. Default false.
  3191. * @type string $text_direction The text direction. This is only useful internally, when WordPress is still
  3192. * loading and the site's locale is not set up yet. Accepts 'rtl' and 'ltr'.
  3193. * Default is the value of is_rtl().
  3194. * @type string $charset Character set of the HTML output. Default 'utf-8'.
  3195. * @type string $code Error code to use. Default is 'wp_die', or the main error code if $message
  3196. * is a WP_Error.
  3197. * @type bool $exit Whether to exit the process after completion. Default true.
  3198. * }
  3199. */
  3200. function wp_die( $message = '', $title = '', $args = array() ) {
  3201. global $wp_query;
  3202. if ( is_int( $args ) ) {
  3203. $args = array( 'response' => $args );
  3204. } elseif ( is_int( $title ) ) {
  3205. $args = array( 'response' => $title );
  3206. $title = '';
  3207. }
  3208. if ( wp_doing_ajax() ) {
  3209. /**
  3210. * Filters the callback for killing WordPress execution for Ajax requests.
  3211. *
  3212. * @since 3.4.0
  3213. *
  3214. * @param callable $function Callback function name.
  3215. */
  3216. $function = apply_filters( 'wp_die_ajax_handler', '_ajax_wp_die_handler' );
  3217. } elseif ( wp_is_json_request() ) {
  3218. /**
  3219. * Filters the callback for killing WordPress execution for JSON requests.
  3220. *
  3221. * @since 5.1.0
  3222. *
  3223. * @param callable $function Callback function name.
  3224. */
  3225. $function = apply_filters( 'wp_die_json_handler', '_json_wp_die_handler' );
  3226. } elseif ( defined( 'REST_REQUEST' ) && REST_REQUEST && wp_is_jsonp_request() ) {
  3227. /**
  3228. * Filters the callback for killing WordPress execution for JSONP REST requests.
  3229. *
  3230. * @since 5.2.0
  3231. *
  3232. * @param callable $function Callback function name.
  3233. */
  3234. $function = apply_filters( 'wp_die_jsonp_handler', '_jsonp_wp_die_handler' );
  3235. } elseif ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) {
  3236. /**
  3237. * Filters the callback for killing WordPress execution for XML-RPC requests.
  3238. *
  3239. * @since 3.4.0
  3240. *
  3241. * @param callable $function Callback function name.
  3242. */
  3243. $function = apply_filters( 'wp_die_xmlrpc_handler', '_xmlrpc_wp_die_handler' );
  3244. } elseif ( wp_is_xml_request()
  3245. || isset( $wp_query ) &&
  3246. ( function_exists( 'is_feed' ) && is_feed()
  3247. || function_exists( 'is_comment_feed' ) && is_comment_feed()
  3248. || function_exists( 'is_trackback' ) && is_trackback() ) ) {
  3249. /**
  3250. * Filters the callback for killing WordPress execution for XML requests.
  3251. *
  3252. * @since 5.2.0
  3253. *
  3254. * @param callable $function Callback function name.
  3255. */
  3256. $function = apply_filters( 'wp_die_xml_handler', '_xml_wp_die_handler' );
  3257. } else {
  3258. /**
  3259. * Filters the callback for killing WordPress execution for all non-Ajax, non-JSON, non-XML requests.
  3260. *
  3261. * @since 3.0.0
  3262. *
  3263. * @param callable $function Callback function name.
  3264. */
  3265. $function = apply_filters( 'wp_die_handler', '_default_wp_die_handler' );
  3266. }
  3267. call_user_func( $function, $message, $title, $args );
  3268. }
  3269. /**
  3270. * Kills WordPress execution and displays HTML page with an error message.
  3271. *
  3272. * This is the default handler for wp_die(). If you want a custom one,
  3273. * you can override this using the {@see 'wp_die_handler'} filter in wp_die().
  3274. *
  3275. * @since 3.0.0
  3276. * @access private
  3277. *
  3278. * @param string|WP_Error $message Error message or WP_Error object.
  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 _default_wp_die_handler( $message, $title = '', $args = array() ) {
  3283. list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args );
  3284. if ( is_string( $message ) ) {
  3285. if ( ! empty( $parsed_args['additional_errors'] ) ) {
  3286. $message = array_merge(
  3287. array( $message ),
  3288. wp_list_pluck( $parsed_args['additional_errors'], 'message' )
  3289. );
  3290. $message = "<ul>\n\t\t<li>" . implode( "</li>\n\t\t<li>", $message ) . "</li>\n\t</ul>";
  3291. }
  3292. $message = sprintf(
  3293. '<div class="wp-die-message">%s</div>',
  3294. $message
  3295. );
  3296. }
  3297. $have_gettext = function_exists( '__' );
  3298. if ( ! empty( $parsed_args['link_url'] ) && ! empty( $parsed_args['link_text'] ) ) {
  3299. $link_url = $parsed_args['link_url'];
  3300. if ( function_exists( 'esc_url' ) ) {
  3301. $link_url = esc_url( $link_url );
  3302. }
  3303. $link_text = $parsed_args['link_text'];
  3304. $message .= "\n<p><a href='{$link_url}'>{$link_text}</a></p>";
  3305. }
  3306. if ( isset( $parsed_args['back_link'] ) && $parsed_args['back_link'] ) {
  3307. $back_text = $have_gettext ? __( '&laquo; Back' ) : '&laquo; Back';
  3308. $message .= "\n<p><a href='javascript:history.back()'>$back_text</a></p>";
  3309. }
  3310. if ( ! did_action( 'admin_head' ) ) :
  3311. if ( ! headers_sent() ) {
  3312. header( "Content-Type: text/html; charset={$parsed_args['charset']}" );
  3313. status_header( $parsed_args['response'] );
  3314. nocache_headers();
  3315. }
  3316. $text_direction = $parsed_args['text_direction'];
  3317. $dir_attr = "dir='$text_direction'";
  3318. // If `text_direction` was not explicitly passed,
  3319. // use get_language_attributes() if available.
  3320. if ( empty( $args['text_direction'] )
  3321. && function_exists( 'language_attributes' ) && function_exists( 'is_rtl' )
  3322. ) {
  3323. $dir_attr = get_language_attributes();
  3324. }
  3325. ?>
  3326. <!DOCTYPE html>
  3327. <html <?php echo $dir_attr; ?>>
  3328. <head>
  3329. <meta http-equiv="Content-Type" content="text/html; charset=<?php echo $parsed_args['charset']; ?>" />
  3330. <meta name="viewport" content="width=device-width">
  3331. <?php
  3332. if ( function_exists( 'wp_robots' ) && function_exists( 'wp_robots_no_robots' ) && function_exists( 'add_filter' ) ) {
  3333. add_filter( 'wp_robots', 'wp_robots_no_robots' );
  3334. wp_robots();
  3335. }
  3336. ?>
  3337. <title><?php echo $title; ?></title>
  3338. <style type="text/css">
  3339. html {
  3340. background: #f1f1f1;
  3341. }
  3342. body {
  3343. background: #fff;
  3344. border: 1px solid #ccd0d4;
  3345. color: #444;
  3346. font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
  3347. margin: 2em auto;
  3348. padding: 1em 2em;
  3349. max-width: 700px;
  3350. -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .04);
  3351. box-shadow: 0 1px 1px rgba(0, 0, 0, .04);
  3352. }
  3353. h1 {
  3354. border-bottom: 1px solid #dadada;
  3355. clear: both;
  3356. color: #666;
  3357. font-size: 24px;
  3358. margin: 30px 0 0 0;
  3359. padding: 0;
  3360. padding-bottom: 7px;
  3361. }
  3362. #error-page {
  3363. margin-top: 50px;
  3364. }
  3365. #error-page p,
  3366. #error-page .wp-die-message {
  3367. font-size: 14px;
  3368. line-height: 1.5;
  3369. margin: 25px 0 20px;
  3370. }
  3371. #error-page code {
  3372. font-family: Consolas, Monaco, monospace;
  3373. }
  3374. ul li {
  3375. margin-bottom: 10px;
  3376. font-size: 14px ;
  3377. }
  3378. a {
  3379. color: #0073aa;
  3380. }
  3381. a:hover,
  3382. a:active {
  3383. color: #006799;
  3384. }
  3385. a:focus {
  3386. color: #124964;
  3387. -webkit-box-shadow:
  3388. 0 0 0 1px #5b9dd9,
  3389. 0 0 2px 1px rgba(30, 140, 190, 0.8);
  3390. box-shadow:
  3391. 0 0 0 1px #5b9dd9,
  3392. 0 0 2px 1px rgba(30, 140, 190, 0.8);
  3393. outline: none;
  3394. }
  3395. .button {
  3396. background: #f3f5f6;
  3397. border: 1px solid #016087;
  3398. color: #016087;
  3399. display: inline-block;
  3400. text-decoration: none;
  3401. font-size: 13px;
  3402. line-height: 2;
  3403. height: 28px;
  3404. margin: 0;
  3405. padding: 0 10px 1px;
  3406. cursor: pointer;
  3407. -webkit-border-radius: 3px;
  3408. -webkit-appearance: none;
  3409. border-radius: 3px;
  3410. white-space: nowrap;
  3411. -webkit-box-sizing: border-box;
  3412. -moz-box-sizing: border-box;
  3413. box-sizing: border-box;
  3414. vertical-align: top;
  3415. }
  3416. .button.button-large {
  3417. line-height: 2.30769231;
  3418. min-height: 32px;
  3419. padding: 0 12px;
  3420. }
  3421. .button:hover,
  3422. .button:focus {
  3423. background: #f1f1f1;
  3424. }
  3425. .button:focus {
  3426. background: #f3f5f6;
  3427. border-color: #007cba;
  3428. -webkit-box-shadow: 0 0 0 1px #007cba;
  3429. box-shadow: 0 0 0 1px #007cba;
  3430. color: #016087;
  3431. outline: 2px solid transparent;
  3432. outline-offset: 0;
  3433. }
  3434. .button:active {
  3435. background: #f3f5f6;
  3436. border-color: #7e8993;
  3437. -webkit-box-shadow: none;
  3438. box-shadow: none;
  3439. }
  3440. <?php
  3441. if ( 'rtl' === $text_direction ) {
  3442. echo 'body { font-family: Tahoma, Arial; }';
  3443. }
  3444. ?>
  3445. </style>
  3446. </head>
  3447. <body id="error-page">
  3448. <?php endif; // ! did_action( 'admin_head' ) ?>
  3449. <?php echo $message; ?>
  3450. </body>
  3451. </html>
  3452. <?php
  3453. if ( $parsed_args['exit'] ) {
  3454. die();
  3455. }
  3456. }
  3457. /**
  3458. * Kills WordPress execution and displays Ajax response with an error message.
  3459. *
  3460. * This is the handler for wp_die() when processing Ajax requests.
  3461. *
  3462. * @since 3.4.0
  3463. * @access private
  3464. *
  3465. * @param string $message Error message.
  3466. * @param string $title Optional. Error title (unused). Default empty.
  3467. * @param string|array $args Optional. Arguments to control behavior. Default empty array.
  3468. */
  3469. function _ajax_wp_die_handler( $message, $title = '', $args = array() ) {
  3470. // Set default 'response' to 200 for Ajax requests.
  3471. $args = wp_parse_args(
  3472. $args,
  3473. array( 'response' => 200 )
  3474. );
  3475. list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args );
  3476. if ( ! headers_sent() ) {
  3477. // This is intentional. For backward-compatibility, support passing null here.
  3478. if ( null !== $args['response'] ) {
  3479. status_header( $parsed_args['response'] );
  3480. }
  3481. nocache_headers();
  3482. }
  3483. if ( is_scalar( $message ) ) {
  3484. $message = (string) $message;
  3485. } else {
  3486. $message = '0';
  3487. }
  3488. if ( $parsed_args['exit'] ) {
  3489. die( $message );
  3490. }
  3491. echo $message;
  3492. }
  3493. /**
  3494. * Kills WordPress execution and displays JSON response with an error message.
  3495. *
  3496. * This is the handler for wp_die() when processing JSON requests.
  3497. *
  3498. * @since 5.1.0
  3499. * @access private
  3500. *
  3501. * @param string $message Error message.
  3502. * @param string $title Optional. Error title. Default empty.
  3503. * @param string|array $args Optional. Arguments to control behavior. Default empty array.
  3504. */
  3505. function _json_wp_die_handler( $message, $title = '', $args = array() ) {
  3506. list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args );
  3507. $data = array(
  3508. 'code' => $parsed_args['code'],
  3509. 'message' => $message,
  3510. 'data' => array(
  3511. 'status' => $parsed_args['response'],
  3512. ),
  3513. 'additional_errors' => $parsed_args['additional_errors'],
  3514. );
  3515. if ( ! headers_sent() ) {
  3516. header( "Content-Type: application/json; charset={$parsed_args['charset']}" );
  3517. if ( null !== $parsed_args['response'] ) {
  3518. status_header( $parsed_args['response'] );
  3519. }
  3520. nocache_headers();
  3521. }
  3522. echo wp_json_encode( $data );
  3523. if ( $parsed_args['exit'] ) {
  3524. die();
  3525. }
  3526. }
  3527. /**
  3528. * Kills WordPress execution and displays JSONP response with an error message.
  3529. *
  3530. * This is the handler for wp_die() when processing JSONP requests.
  3531. *
  3532. * @since 5.2.0
  3533. * @access private
  3534. *
  3535. * @param string $message Error message.
  3536. * @param string $title Optional. Error title. Default empty.
  3537. * @param string|array $args Optional. Arguments to control behavior. Default empty array.
  3538. */
  3539. function _jsonp_wp_die_handler( $message, $title = '', $args = array() ) {
  3540. list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args );
  3541. $data = array(
  3542. 'code' => $parsed_args['code'],
  3543. 'message' => $message,
  3544. 'data' => array(
  3545. 'status' => $parsed_args['response'],
  3546. ),
  3547. 'additional_errors' => $parsed_args['additional_errors'],
  3548. );
  3549. if ( ! headers_sent() ) {
  3550. header( "Content-Type: application/javascript; charset={$parsed_args['charset']}" );
  3551. header( 'X-Content-Type-Options: nosniff' );
  3552. header( 'X-Robots-Tag: noindex' );
  3553. if ( null !== $parsed_args['response'] ) {
  3554. status_header( $parsed_args['response'] );
  3555. }
  3556. nocache_headers();
  3557. }
  3558. $result = wp_json_encode( $data );
  3559. $jsonp_callback = $_GET['_jsonp'];
  3560. echo '/**/' . $jsonp_callback . '(' . $result . ')';
  3561. if ( $parsed_args['exit'] ) {
  3562. die();
  3563. }
  3564. }
  3565. /**
  3566. * Kills WordPress execution and displays XML response with an error message.
  3567. *
  3568. * This is the handler for wp_die() when processing XMLRPC requests.
  3569. *
  3570. * @since 3.2.0
  3571. * @access private
  3572. *
  3573. * @global wp_xmlrpc_server $wp_xmlrpc_server
  3574. *
  3575. * @param string $message Error message.
  3576. * @param string $title Optional. Error title. Default empty.
  3577. * @param string|array $args Optional. Arguments to control behavior. Default empty array.
  3578. */
  3579. function _xmlrpc_wp_die_handler( $message, $title = '', $args = array() ) {
  3580. global $wp_xmlrpc_server;
  3581. list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args );
  3582. if ( ! headers_sent() ) {
  3583. nocache_headers();
  3584. }
  3585. if ( $wp_xmlrpc_server ) {
  3586. $error = new IXR_Error( $parsed_args['response'], $message );
  3587. $wp_xmlrpc_server->output( $error->getXml() );
  3588. }
  3589. if ( $parsed_args['exit'] ) {
  3590. die();
  3591. }
  3592. }
  3593. /**
  3594. * Kills WordPress execution and displays XML response with an error message.
  3595. *
  3596. * This is the handler for wp_die() when processing XML requests.
  3597. *
  3598. * @since 5.2.0
  3599. * @access private
  3600. *
  3601. * @param string $message Error message.
  3602. * @param string $title Optional. Error title. Default empty.
  3603. * @param string|array $args Optional. Arguments to control behavior. Default empty array.
  3604. */
  3605. function _xml_wp_die_handler( $message, $title = '', $args = array() ) {
  3606. list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args );
  3607. $message = htmlspecialchars( $message );
  3608. $title = htmlspecialchars( $title );
  3609. $xml = <<<EOD
  3610. <error>
  3611. <code>{$parsed_args['code']}</code>
  3612. <title><![CDATA[{$title}]]></title>
  3613. <message><![CDATA[{$message}]]></message>
  3614. <data>
  3615. <status>{$parsed_args['response']}</status>
  3616. </data>
  3617. </error>
  3618. EOD;
  3619. if ( ! headers_sent() ) {
  3620. header( "Content-Type: text/xml; charset={$parsed_args['charset']}" );
  3621. if ( null !== $parsed_args['response'] ) {
  3622. status_header( $parsed_args['response'] );
  3623. }
  3624. nocache_headers();
  3625. }
  3626. echo $xml;
  3627. if ( $parsed_args['exit'] ) {
  3628. die();
  3629. }
  3630. }
  3631. /**
  3632. * Kills WordPress execution and displays an error message.
  3633. *
  3634. * This is the handler for wp_die() when processing APP requests.
  3635. *
  3636. * @since 3.4.0
  3637. * @since 5.1.0 Added the $title and $args parameters.
  3638. * @access private
  3639. *
  3640. * @param string $message Optional. Response to print. Default empty.
  3641. * @param string $title Optional. Error title (unused). Default empty.
  3642. * @param string|array $args Optional. Arguments to control behavior. Default empty array.
  3643. */
  3644. function _scalar_wp_die_handler( $message = '', $title = '', $args = array() ) {
  3645. list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args );
  3646. if ( $parsed_args['exit'] ) {
  3647. if ( is_scalar( $message ) ) {
  3648. die( (string) $message );
  3649. }
  3650. die();
  3651. }
  3652. if ( is_scalar( $message ) ) {
  3653. echo (string) $message;
  3654. }
  3655. }
  3656. /**
  3657. * Processes arguments passed to wp_die() consistently for its handlers.
  3658. *
  3659. * @since 5.1.0
  3660. * @access private
  3661. *
  3662. * @param string|WP_Error $message Error message or WP_Error object.
  3663. * @param string $title Optional. Error title. Default empty.
  3664. * @param string|array $args Optional. Arguments to control behavior. Default empty array.
  3665. * @return array {
  3666. * Processed arguments.
  3667. *
  3668. * @type string $0 Error message.
  3669. * @type string $1 Error title.
  3670. * @type array $2 Arguments to control behavior.
  3671. * }
  3672. */
  3673. function _wp_die_process_input( $message, $title = '', $args = array() ) {
  3674. $defaults = array(
  3675. 'response' => 0,
  3676. 'code' => '',
  3677. 'exit' => true,
  3678. 'back_link' => false,
  3679. 'link_url' => '',
  3680. 'link_text' => '',
  3681. 'text_direction' => '',
  3682. 'charset' => 'utf-8',
  3683. 'additional_errors' => array(),
  3684. );
  3685. $args = wp_parse_args( $args, $defaults );
  3686. if ( function_exists( 'is_wp_error' ) && is_wp_error( $message ) ) {
  3687. if ( ! empty( $message->errors ) ) {
  3688. $errors = array();
  3689. foreach ( (array) $message->errors as $error_code => $error_messages ) {
  3690. foreach ( (array) $error_messages as $error_message ) {
  3691. $errors[] = array(
  3692. 'code' => $error_code,
  3693. 'message' => $error_message,
  3694. 'data' => $message->get_error_data( $error_code ),
  3695. );
  3696. }
  3697. }
  3698. $message = $errors[0]['message'];
  3699. if ( empty( $args['code'] ) ) {
  3700. $args['code'] = $errors[0]['code'];
  3701. }
  3702. if ( empty( $args['response'] ) && is_array( $errors[0]['data'] ) && ! empty( $errors[0]['data']['status'] ) ) {
  3703. $args['response'] = $errors[0]['data']['status'];
  3704. }
  3705. if ( empty( $title ) && is_array( $errors[0]['data'] ) && ! empty( $errors[0]['data']['title'] ) ) {
  3706. $title = $errors[0]['data']['title'];
  3707. }
  3708. unset( $errors[0] );
  3709. $args['additional_errors'] = array_values( $errors );
  3710. } else {
  3711. $message = '';
  3712. }
  3713. }
  3714. $have_gettext = function_exists( '__' );
  3715. // The $title and these specific $args must always have a non-empty value.
  3716. if ( empty( $args['code'] ) ) {
  3717. $args['code'] = 'wp_die';
  3718. }
  3719. if ( empty( $args['response'] ) ) {
  3720. $args['response'] = 500;
  3721. }
  3722. if ( empty( $title ) ) {
  3723. $title = $have_gettext ? __( 'WordPress &rsaquo; Error' ) : 'WordPress &rsaquo; Error';
  3724. }
  3725. if ( empty( $args['text_direction'] ) || ! in_array( $args['text_direction'], array( 'ltr', 'rtl' ), true ) ) {
  3726. $args['text_direction'] = 'ltr';
  3727. if ( function_exists( 'is_rtl' ) && is_rtl() ) {
  3728. $args['text_direction'] = 'rtl';
  3729. }
  3730. }
  3731. if ( ! empty( $args['charset'] ) ) {
  3732. $args['charset'] = _canonical_charset( $args['charset'] );
  3733. }
  3734. return array( $message, $title, $args );
  3735. }
  3736. /**
  3737. * Encode a variable into JSON, with some sanity checks.
  3738. *
  3739. * @since 4.1.0
  3740. * @since 5.3.0 No longer handles support for PHP < 5.6.
  3741. *
  3742. * @param mixed $data Variable (usually an array or object) to encode as JSON.
  3743. * @param int $options Optional. Options to be passed to json_encode(). Default 0.
  3744. * @param int $depth Optional. Maximum depth to walk through $data. Must be
  3745. * greater than 0. Default 512.
  3746. * @return string|false The JSON encoded string, or false if it cannot be encoded.
  3747. */
  3748. function wp_json_encode( $data, $options = 0, $depth = 512 ) {
  3749. $json = json_encode( $data, $options, $depth );
  3750. // If json_encode() was successful, no need to do more sanity checking.
  3751. if ( false !== $json ) {
  3752. return $json;
  3753. }
  3754. try {
  3755. $data = _wp_json_sanity_check( $data, $depth );
  3756. } catch ( Exception $e ) {
  3757. return false;
  3758. }
  3759. return json_encode( $data, $options, $depth );
  3760. }
  3761. /**
  3762. * Perform sanity checks on data that shall be encoded to JSON.
  3763. *
  3764. * @ignore
  3765. * @since 4.1.0
  3766. * @access private
  3767. *
  3768. * @see wp_json_encode()
  3769. *
  3770. * @throws Exception If depth limit is reached.
  3771. *
  3772. * @param mixed $data Variable (usually an array or object) to encode as JSON.
  3773. * @param int $depth Maximum depth to walk through $data. Must be greater than 0.
  3774. * @return mixed The sanitized data that shall be encoded to JSON.
  3775. */
  3776. function _wp_json_sanity_check( $data, $depth ) {
  3777. if ( $depth < 0 ) {
  3778. throw new Exception( 'Reached depth limit' );
  3779. }
  3780. if ( is_array( $data ) ) {
  3781. $output = array();
  3782. foreach ( $data as $id => $el ) {
  3783. // Don't forget to sanitize the ID!
  3784. if ( is_string( $id ) ) {
  3785. $clean_id = _wp_json_convert_string( $id );
  3786. } else {
  3787. $clean_id = $id;
  3788. }
  3789. // Check the element type, so that we're only recursing if we really have to.
  3790. if ( is_array( $el ) || is_object( $el ) ) {
  3791. $output[ $clean_id ] = _wp_json_sanity_check( $el, $depth - 1 );
  3792. } elseif ( is_string( $el ) ) {
  3793. $output[ $clean_id ] = _wp_json_convert_string( $el );
  3794. } else {
  3795. $output[ $clean_id ] = $el;
  3796. }
  3797. }
  3798. } elseif ( is_object( $data ) ) {
  3799. $output = new stdClass;
  3800. foreach ( $data as $id => $el ) {
  3801. if ( is_string( $id ) ) {
  3802. $clean_id = _wp_json_convert_string( $id );
  3803. } else {
  3804. $clean_id = $id;
  3805. }
  3806. if ( is_array( $el ) || is_object( $el ) ) {
  3807. $output->$clean_id = _wp_json_sanity_check( $el, $depth - 1 );
  3808. } elseif ( is_string( $el ) ) {
  3809. $output->$clean_id = _wp_json_convert_string( $el );
  3810. } else {
  3811. $output->$clean_id = $el;
  3812. }
  3813. }
  3814. } elseif ( is_string( $data ) ) {
  3815. return _wp_json_convert_string( $data );
  3816. } else {
  3817. return $data;
  3818. }
  3819. return $output;
  3820. }
  3821. /**
  3822. * Convert a string to UTF-8, so that it can be safely encoded to JSON.
  3823. *
  3824. * @ignore
  3825. * @since 4.1.0
  3826. * @access private
  3827. *
  3828. * @see _wp_json_sanity_check()
  3829. *
  3830. * @param string $string The string which is to be converted.
  3831. * @return string The checked string.
  3832. */
  3833. function _wp_json_convert_string( $string ) {
  3834. static $use_mb = null;
  3835. if ( is_null( $use_mb ) ) {
  3836. $use_mb = function_exists( 'mb_convert_encoding' );
  3837. }
  3838. if ( $use_mb ) {
  3839. $encoding = mb_detect_encoding( $string, mb_detect_order(), true );
  3840. if ( $encoding ) {
  3841. return mb_convert_encoding( $string, 'UTF-8', $encoding );
  3842. } else {
  3843. return mb_convert_encoding( $string, 'UTF-8', 'UTF-8' );
  3844. }
  3845. } else {
  3846. return wp_check_invalid_utf8( $string, true );
  3847. }
  3848. }
  3849. /**
  3850. * Prepares response data to be serialized to JSON.
  3851. *
  3852. * This supports the JsonSerializable interface for PHP 5.2-5.3 as well.
  3853. *
  3854. * @ignore
  3855. * @since 4.4.0
  3856. * @deprecated 5.3.0 This function is no longer needed as support for PHP 5.2-5.3
  3857. * has been dropped.
  3858. * @access private
  3859. *
  3860. * @param mixed $data Native representation.
  3861. * @return bool|int|float|null|string|array Data ready for `json_encode()`.
  3862. */
  3863. function _wp_json_prepare_data( $data ) {
  3864. _deprecated_function( __FUNCTION__, '5.3.0' );
  3865. return $data;
  3866. }
  3867. /**
  3868. * Send a JSON response back to an Ajax request.
  3869. *
  3870. * @since 3.5.0
  3871. * @since 4.7.0 The `$status_code` parameter was added.
  3872. * @since 5.6.0 The `$options` parameter was added.
  3873. *
  3874. * @param mixed $response Variable (usually an array or object) to encode as JSON,
  3875. * then print and die.
  3876. * @param int $status_code Optional. The HTTP status code to output. Default null.
  3877. * @param int $options Optional. Options to be passed to json_encode(). Default 0.
  3878. */
  3879. function wp_send_json( $response, $status_code = null, $options = 0 ) {
  3880. if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
  3881. _doing_it_wrong(
  3882. __FUNCTION__,
  3883. sprintf(
  3884. /* translators: 1: WP_REST_Response, 2: WP_Error */
  3885. __( 'Return a %1$s or %2$s object from your callback when using the REST API.' ),
  3886. 'WP_REST_Response',
  3887. 'WP_Error'
  3888. ),
  3889. '5.5.0'
  3890. );
  3891. }
  3892. if ( ! headers_sent() ) {
  3893. header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );
  3894. if ( null !== $status_code ) {
  3895. status_header( $status_code );
  3896. }
  3897. }
  3898. echo wp_json_encode( $response, $options );
  3899. if ( wp_doing_ajax() ) {
  3900. wp_die(
  3901. '',
  3902. '',
  3903. array(
  3904. 'response' => null,
  3905. )
  3906. );
  3907. } else {
  3908. die;
  3909. }
  3910. }
  3911. /**
  3912. * Send a JSON response back to an Ajax request, indicating success.
  3913. *
  3914. * @since 3.5.0
  3915. * @since 4.7.0 The `$status_code` parameter was added.
  3916. * @since 5.6.0 The `$options` parameter was added.
  3917. *
  3918. * @param mixed $data Optional. Data to encode as JSON, then print and die. Default null.
  3919. * @param int $status_code Optional. The HTTP status code to output. Default null.
  3920. * @param int $options Optional. Options to be passed to json_encode(). Default 0.
  3921. */
  3922. function wp_send_json_success( $data = null, $status_code = null, $options = 0 ) {
  3923. $response = array( 'success' => true );
  3924. if ( isset( $data ) ) {
  3925. $response['data'] = $data;
  3926. }
  3927. wp_send_json( $response, $status_code, $options );
  3928. }
  3929. /**
  3930. * Send a JSON response back to an Ajax request, indicating failure.
  3931. *
  3932. * If the `$data` parameter is a WP_Error object, the errors
  3933. * within the object are processed and output as an array of error
  3934. * codes and corresponding messages. All other types are output
  3935. * without further processing.
  3936. *
  3937. * @since 3.5.0
  3938. * @since 4.1.0 The `$data` parameter is now processed if a WP_Error object is passed in.
  3939. * @since 4.7.0 The `$status_code` parameter was added.
  3940. * @since 5.6.0 The `$options` parameter was added.
  3941. *
  3942. * @param mixed $data Optional. Data to encode as JSON, then print and die. Default null.
  3943. * @param int $status_code Optional. The HTTP status code to output. Default null.
  3944. * @param int $options Optional. Options to be passed to json_encode(). Default 0.
  3945. */
  3946. function wp_send_json_error( $data = null, $status_code = null, $options = 0 ) {
  3947. $response = array( 'success' => false );
  3948. if ( isset( $data ) ) {
  3949. if ( is_wp_error( $data ) ) {
  3950. $result = array();
  3951. foreach ( $data->errors as $code => $messages ) {
  3952. foreach ( $messages as $message ) {
  3953. $result[] = array(
  3954. 'code' => $code,
  3955. 'message' => $message,
  3956. );
  3957. }
  3958. }
  3959. $response['data'] = $result;
  3960. } else {
  3961. $response['data'] = $data;
  3962. }
  3963. }
  3964. wp_send_json( $response, $status_code, $options );
  3965. }
  3966. /**
  3967. * Checks that a JSONP callback is a valid JavaScript callback name.
  3968. *
  3969. * Only allows alphanumeric characters and the dot character in callback
  3970. * function names. This helps to mitigate XSS attacks caused by directly
  3971. * outputting user input.
  3972. *
  3973. * @since 4.6.0
  3974. *
  3975. * @param string $callback Supplied JSONP callback function name.
  3976. * @return bool Whether the callback function name is valid.
  3977. */
  3978. function wp_check_jsonp_callback( $callback ) {
  3979. if ( ! is_string( $callback ) ) {
  3980. return false;
  3981. }
  3982. preg_replace( '/[^\w\.]/', '', $callback, -1, $illegal_char_count );
  3983. return 0 === $illegal_char_count;
  3984. }
  3985. /**
  3986. * Reads and decodes a JSON file.
  3987. *
  3988. * @since 5.9.0
  3989. *
  3990. * @param string $filename Path to the JSON file.
  3991. * @param array $options {
  3992. * Optional. Options to be used with `json_decode()`.
  3993. *
  3994. * @type bool associative Optional. When `true`, JSON objects will be returned as associative arrays.
  3995. * When `false`, JSON objects will be returned as objects.
  3996. * }
  3997. *
  3998. * @return mixed Returns the value encoded in JSON in appropriate PHP type.
  3999. * `null` is returned if the file is not found, or its content can't be decoded.
  4000. */
  4001. function wp_json_file_decode( $filename, $options = array() ) {
  4002. $result = null;
  4003. $filename = wp_normalize_path( realpath( $filename ) );
  4004. if ( ! file_exists( $filename ) ) {
  4005. trigger_error(
  4006. sprintf(
  4007. /* translators: %s: Path to the JSON file. */
  4008. __( "File %s doesn't exist!" ),
  4009. $filename
  4010. )
  4011. );
  4012. return $result;
  4013. }
  4014. $options = wp_parse_args( $options, array( 'associative' => false ) );
  4015. $decoded_file = json_decode( file_get_contents( $filename ), $options['associative'] );
  4016. if ( JSON_ERROR_NONE !== json_last_error() ) {
  4017. trigger_error(
  4018. sprintf(
  4019. /* translators: 1: Path to the JSON file, 2: Error message. */
  4020. __( 'Error when decoding a JSON file at path %1$s: %2$s' ),
  4021. $filename,
  4022. json_last_error_msg()
  4023. )
  4024. );
  4025. return $result;
  4026. }
  4027. return $decoded_file;
  4028. }
  4029. /**
  4030. * Retrieve the WordPress home page URL.
  4031. *
  4032. * If the constant named 'WP_HOME' exists, then it will be used and returned
  4033. * by the function. This can be used to counter the redirection on your local
  4034. * development environment.
  4035. *
  4036. * @since 2.2.0
  4037. * @access private
  4038. *
  4039. * @see WP_HOME
  4040. *
  4041. * @param string $url URL for the home location.
  4042. * @return string Homepage location.
  4043. */
  4044. function _config_wp_home( $url = '' ) {
  4045. if ( defined( 'WP_HOME' ) ) {
  4046. return untrailingslashit( WP_HOME );
  4047. }
  4048. return $url;
  4049. }
  4050. /**
  4051. * Retrieve the WordPress site URL.
  4052. *
  4053. * If the constant named 'WP_SITEURL' is defined, then the value in that
  4054. * constant will always be returned. This can be used for debugging a site
  4055. * on your localhost while not having to change the database to your URL.
  4056. *
  4057. * @since 2.2.0
  4058. * @access private
  4059. *
  4060. * @see WP_SITEURL
  4061. *
  4062. * @param string $url URL to set the WordPress site location.
  4063. * @return string The WordPress Site URL.
  4064. */
  4065. function _config_wp_siteurl( $url = '' ) {
  4066. if ( defined( 'WP_SITEURL' ) ) {
  4067. return untrailingslashit( WP_SITEURL );
  4068. }
  4069. return $url;
  4070. }
  4071. /**
  4072. * Delete the fresh site option.
  4073. *
  4074. * @since 4.7.0
  4075. * @access private
  4076. */
  4077. function _delete_option_fresh_site() {
  4078. update_option( 'fresh_site', '0' );
  4079. }
  4080. /**
  4081. * Set the localized direction for MCE plugin.
  4082. *
  4083. * Will only set the direction to 'rtl', if the WordPress locale has
  4084. * the text direction set to 'rtl'.
  4085. *
  4086. * Fills in the 'directionality' setting, enables the 'directionality'
  4087. * plugin, and adds the 'ltr' button to 'toolbar1', formerly
  4088. * 'theme_advanced_buttons1' array keys. These keys are then returned
  4089. * in the $mce_init (TinyMCE settings) array.
  4090. *
  4091. * @since 2.1.0
  4092. * @access private
  4093. *
  4094. * @param array $mce_init MCE settings array.
  4095. * @return array Direction set for 'rtl', if needed by locale.
  4096. */
  4097. function _mce_set_direction( $mce_init ) {
  4098. if ( is_rtl() ) {
  4099. $mce_init['directionality'] = 'rtl';
  4100. $mce_init['rtl_ui'] = true;
  4101. if ( ! empty( $mce_init['plugins'] ) && strpos( $mce_init['plugins'], 'directionality' ) === false ) {
  4102. $mce_init['plugins'] .= ',directionality';
  4103. }
  4104. if ( ! empty( $mce_init['toolbar1'] ) && ! preg_match( '/\bltr\b/', $mce_init['toolbar1'] ) ) {
  4105. $mce_init['toolbar1'] .= ',ltr';
  4106. }
  4107. }
  4108. return $mce_init;
  4109. }
  4110. /**
  4111. * Convert smiley code to the icon graphic file equivalent.
  4112. *
  4113. * You can turn off smilies, by going to the write setting screen and unchecking
  4114. * the box, or by setting 'use_smilies' option to false or removing the option.
  4115. *
  4116. * Plugins may override the default smiley list by setting the $wpsmiliestrans
  4117. * to an array, with the key the code the blogger types in and the value the
  4118. * image file.
  4119. *
  4120. * The $wp_smiliessearch global is for the regular expression and is set each
  4121. * time the function is called.
  4122. *
  4123. * The full list of smilies can be found in the function and won't be listed in
  4124. * the description. Probably should create a Codex page for it, so that it is
  4125. * available.
  4126. *
  4127. * @global array $wpsmiliestrans
  4128. * @global array $wp_smiliessearch
  4129. *
  4130. * @since 2.2.0
  4131. */
  4132. function smilies_init() {
  4133. global $wpsmiliestrans, $wp_smiliessearch;
  4134. // Don't bother setting up smilies if they are disabled.
  4135. if ( ! get_option( 'use_smilies' ) ) {
  4136. return;
  4137. }
  4138. if ( ! isset( $wpsmiliestrans ) ) {
  4139. $wpsmiliestrans = array(
  4140. ':mrgreen:' => 'mrgreen.png',
  4141. ':neutral:' => "\xf0\x9f\x98\x90",
  4142. ':twisted:' => "\xf0\x9f\x98\x88",
  4143. ':arrow:' => "\xe2\x9e\xa1",
  4144. ':shock:' => "\xf0\x9f\x98\xaf",
  4145. ':smile:' => "\xf0\x9f\x99\x82",
  4146. ':???:' => "\xf0\x9f\x98\x95",
  4147. ':cool:' => "\xf0\x9f\x98\x8e",
  4148. ':evil:' => "\xf0\x9f\x91\xbf",
  4149. ':grin:' => "\xf0\x9f\x98\x80",
  4150. ':idea:' => "\xf0\x9f\x92\xa1",
  4151. ':oops:' => "\xf0\x9f\x98\xb3",
  4152. ':razz:' => "\xf0\x9f\x98\x9b",
  4153. ':roll:' => "\xf0\x9f\x99\x84",
  4154. ':wink:' => "\xf0\x9f\x98\x89",
  4155. ':cry:' => "\xf0\x9f\x98\xa5",
  4156. ':eek:' => "\xf0\x9f\x98\xae",
  4157. ':lol:' => "\xf0\x9f\x98\x86",
  4158. ':mad:' => "\xf0\x9f\x98\xa1",
  4159. ':sad:' => "\xf0\x9f\x99\x81",
  4160. '8-)' => "\xf0\x9f\x98\x8e",
  4161. '8-O' => "\xf0\x9f\x98\xaf",
  4162. ':-(' => "\xf0\x9f\x99\x81",
  4163. ':-)' => "\xf0\x9f\x99\x82",
  4164. ':-?' => "\xf0\x9f\x98\x95",
  4165. ':-D' => "\xf0\x9f\x98\x80",
  4166. ':-P' => "\xf0\x9f\x98\x9b",
  4167. ':-o' => "\xf0\x9f\x98\xae",
  4168. ':-x' => "\xf0\x9f\x98\xa1",
  4169. ':-|' => "\xf0\x9f\x98\x90",
  4170. ';-)' => "\xf0\x9f\x98\x89",
  4171. // This one transformation breaks regular text with frequency.
  4172. // '8)' => "\xf0\x9f\x98\x8e",
  4173. '8O' => "\xf0\x9f\x98\xaf",
  4174. ':(' => "\xf0\x9f\x99\x81",
  4175. ':)' => "\xf0\x9f\x99\x82",
  4176. ':?' => "\xf0\x9f\x98\x95",
  4177. ':D' => "\xf0\x9f\x98\x80",
  4178. ':P' => "\xf0\x9f\x98\x9b",
  4179. ':o' => "\xf0\x9f\x98\xae",
  4180. ':x' => "\xf0\x9f\x98\xa1",
  4181. ':|' => "\xf0\x9f\x98\x90",
  4182. ';)' => "\xf0\x9f\x98\x89",
  4183. ':!:' => "\xe2\x9d\x97",
  4184. ':?:' => "\xe2\x9d\x93",
  4185. );
  4186. }
  4187. /**
  4188. * Filters all the smilies.
  4189. *
  4190. * This filter must be added before `smilies_init` is run, as
  4191. * it is normally only run once to setup the smilies regex.
  4192. *
  4193. * @since 4.7.0
  4194. *
  4195. * @param string[] $wpsmiliestrans List of the smilies' hexadecimal representations, keyed by their smily code.
  4196. */
  4197. $wpsmiliestrans = apply_filters( 'smilies', $wpsmiliestrans );
  4198. if ( count( $wpsmiliestrans ) == 0 ) {
  4199. return;
  4200. }
  4201. /*
  4202. * NOTE: we sort the smilies in reverse key order. This is to make sure
  4203. * we match the longest possible smilie (:???: vs :?) as the regular
  4204. * expression used below is first-match
  4205. */
  4206. krsort( $wpsmiliestrans );
  4207. $spaces = wp_spaces_regexp();
  4208. // Begin first "subpattern".
  4209. $wp_smiliessearch = '/(?<=' . $spaces . '|^)';
  4210. $subchar = '';
  4211. foreach ( (array) $wpsmiliestrans as $smiley => $img ) {
  4212. $firstchar = substr( $smiley, 0, 1 );
  4213. $rest = substr( $smiley, 1 );
  4214. // New subpattern?
  4215. if ( $firstchar != $subchar ) {
  4216. if ( '' !== $subchar ) {
  4217. $wp_smiliessearch .= ')(?=' . $spaces . '|$)'; // End previous "subpattern".
  4218. $wp_smiliessearch .= '|(?<=' . $spaces . '|^)'; // Begin another "subpattern".
  4219. }
  4220. $subchar = $firstchar;
  4221. $wp_smiliessearch .= preg_quote( $firstchar, '/' ) . '(?:';
  4222. } else {
  4223. $wp_smiliessearch .= '|';
  4224. }
  4225. $wp_smiliessearch .= preg_quote( $rest, '/' );
  4226. }
  4227. $wp_smiliessearch .= ')(?=' . $spaces . '|$)/m';
  4228. }
  4229. /**
  4230. * Merges user defined arguments into defaults array.
  4231. *
  4232. * This function is used throughout WordPress to allow for both string or array
  4233. * to be merged into another array.
  4234. *
  4235. * @since 2.2.0
  4236. * @since 2.3.0 `$args` can now also be an object.
  4237. *
  4238. * @param string|array|object $args Value to merge with $defaults.
  4239. * @param array $defaults Optional. Array that serves as the defaults.
  4240. * Default empty array.
  4241. * @return array Merged user defined values with defaults.
  4242. */
  4243. function wp_parse_args( $args, $defaults = array() ) {
  4244. if ( is_object( $args ) ) {
  4245. $parsed_args = get_object_vars( $args );
  4246. } elseif ( is_array( $args ) ) {
  4247. $parsed_args =& $args;
  4248. } else {
  4249. wp_parse_str( $args, $parsed_args );
  4250. }
  4251. if ( is_array( $defaults ) && $defaults ) {
  4252. return array_merge( $defaults, $parsed_args );
  4253. }
  4254. return $parsed_args;
  4255. }
  4256. /**
  4257. * Converts a comma- or space-separated list of scalar values to an array.
  4258. *
  4259. * @since 5.1.0
  4260. *
  4261. * @param array|string $list List of values.
  4262. * @return array Array of values.
  4263. */
  4264. function wp_parse_list( $list ) {
  4265. if ( ! is_array( $list ) ) {
  4266. return preg_split( '/[\s,]+/', $list, -1, PREG_SPLIT_NO_EMPTY );
  4267. }
  4268. return $list;
  4269. }
  4270. /**
  4271. * Cleans up an array, comma- or space-separated list of IDs.
  4272. *
  4273. * @since 3.0.0
  4274. * @since 5.1.0 Refactored to use wp_parse_list().
  4275. *
  4276. * @param array|string $list List of IDs.
  4277. * @return int[] Sanitized array of IDs.
  4278. */
  4279. function wp_parse_id_list( $list ) {
  4280. $list = wp_parse_list( $list );
  4281. return array_unique( array_map( 'absint', $list ) );
  4282. }
  4283. /**
  4284. * Cleans up an array, comma- or space-separated list of slugs.
  4285. *
  4286. * @since 4.7.0
  4287. * @since 5.1.0 Refactored to use wp_parse_list().
  4288. *
  4289. * @param array|string $list List of slugs.
  4290. * @return string[] Sanitized array of slugs.
  4291. */
  4292. function wp_parse_slug_list( $list ) {
  4293. $list = wp_parse_list( $list );
  4294. return array_unique( array_map( 'sanitize_title', $list ) );
  4295. }
  4296. /**
  4297. * Extract a slice of an array, given a list of keys.
  4298. *
  4299. * @since 3.1.0
  4300. *
  4301. * @param array $array The original array.
  4302. * @param array $keys The list of keys.
  4303. * @return array The array slice.
  4304. */
  4305. function wp_array_slice_assoc( $array, $keys ) {
  4306. $slice = array();
  4307. foreach ( $keys as $key ) {
  4308. if ( isset( $array[ $key ] ) ) {
  4309. $slice[ $key ] = $array[ $key ];
  4310. }
  4311. }
  4312. return $slice;
  4313. }
  4314. /**
  4315. * Accesses an array in depth based on a path of keys.
  4316. *
  4317. * It is the PHP equivalent of JavaScript's `lodash.get()` and mirroring it may help other components
  4318. * retain some symmetry between client and server implementations.
  4319. *
  4320. * Example usage:
  4321. *
  4322. * $array = array(
  4323. * 'a' => array(
  4324. * 'b' => array(
  4325. * 'c' => 1,
  4326. * ),
  4327. * ),
  4328. * );
  4329. * _wp_array_get( $array, array( 'a', 'b', 'c' ) );
  4330. *
  4331. * @internal
  4332. *
  4333. * @since 5.6.0
  4334. * @access private
  4335. *
  4336. * @param array $array An array from which we want to retrieve some information.
  4337. * @param array $path An array of keys describing the path with which to retrieve information.
  4338. * @param mixed $default The return value if the path does not exist within the array,
  4339. * or if `$array` or `$path` are not arrays.
  4340. * @return mixed The value from the path specified.
  4341. */
  4342. function _wp_array_get( $array, $path, $default = null ) {
  4343. // Confirm $path is valid.
  4344. if ( ! is_array( $path ) || 0 === count( $path ) ) {
  4345. return $default;
  4346. }
  4347. foreach ( $path as $path_element ) {
  4348. if (
  4349. ! is_array( $array ) ||
  4350. ( ! is_string( $path_element ) && ! is_integer( $path_element ) && ! is_null( $path_element ) ) ||
  4351. ! array_key_exists( $path_element, $array )
  4352. ) {
  4353. return $default;
  4354. }
  4355. $array = $array[ $path_element ];
  4356. }
  4357. return $array;
  4358. }
  4359. /**
  4360. * Sets an array in depth based on a path of keys.
  4361. *
  4362. * It is the PHP equivalent of JavaScript's `lodash.set()` and mirroring it may help other components
  4363. * retain some symmetry between client and server implementations.
  4364. *
  4365. * Example usage:
  4366. *
  4367. * $array = array();
  4368. * _wp_array_set( $array, array( 'a', 'b', 'c', 1 ) );
  4369. *
  4370. * $array becomes:
  4371. * array(
  4372. * 'a' => array(
  4373. * 'b' => array(
  4374. * 'c' => 1,
  4375. * ),
  4376. * ),
  4377. * );
  4378. *
  4379. * @internal
  4380. *
  4381. * @since 5.8.0
  4382. * @access private
  4383. *
  4384. * @param array $array An array that we want to mutate to include a specific value in a path.
  4385. * @param array $path An array of keys describing the path that we want to mutate.
  4386. * @param mixed $value The value that will be set.
  4387. */
  4388. function _wp_array_set( &$array, $path, $value = null ) {
  4389. // Confirm $array is valid.
  4390. if ( ! is_array( $array ) ) {
  4391. return;
  4392. }
  4393. // Confirm $path is valid.
  4394. if ( ! is_array( $path ) ) {
  4395. return;
  4396. }
  4397. $path_length = count( $path );
  4398. if ( 0 === $path_length ) {
  4399. return;
  4400. }
  4401. foreach ( $path as $path_element ) {
  4402. if (
  4403. ! is_string( $path_element ) && ! is_integer( $path_element ) &&
  4404. ! is_null( $path_element )
  4405. ) {
  4406. return;
  4407. }
  4408. }
  4409. for ( $i = 0; $i < $path_length - 1; ++$i ) {
  4410. $path_element = $path[ $i ];
  4411. if (
  4412. ! array_key_exists( $path_element, $array ) ||
  4413. ! is_array( $array[ $path_element ] )
  4414. ) {
  4415. $array[ $path_element ] = array();
  4416. }
  4417. $array = &$array[ $path_element ]; // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.VariableRedeclaration
  4418. }
  4419. $array[ $path[ $i ] ] = $value;
  4420. }
  4421. /**
  4422. * This function is trying to replicate what
  4423. * lodash's kebabCase (JS library) does in the client.
  4424. *
  4425. * The reason we need this function is that we do some processing
  4426. * in both the client and the server (e.g.: we generate
  4427. * preset classes from preset slugs) that needs to
  4428. * create the same output.
  4429. *
  4430. * We can't remove or update the client's library due to backward compatibility
  4431. * (some of the output of lodash's kebabCase is saved in the post content).
  4432. * We have to make the server behave like the client.
  4433. *
  4434. * Changes to this function should follow updates in the client
  4435. * with the same logic.
  4436. *
  4437. * @link https://github.com/lodash/lodash/blob/4.17/dist/lodash.js#L14369
  4438. * @link https://github.com/lodash/lodash/blob/4.17/dist/lodash.js#L278
  4439. * @link https://github.com/lodash-php/lodash-php/blob/master/src/String/kebabCase.php
  4440. * @link https://github.com/lodash-php/lodash-php/blob/master/src/internal/unicodeWords.php
  4441. *
  4442. * @param string $string The string to kebab-case.
  4443. *
  4444. * @return string kebab-cased-string.
  4445. */
  4446. function _wp_to_kebab_case( $string ) {
  4447. //phpcs:disable WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase
  4448. // ignore the camelCase names for variables so the names are the same as lodash
  4449. // so comparing and porting new changes is easier.
  4450. /*
  4451. * Some notable things we've removed compared to the lodash version are:
  4452. *
  4453. * - non-alphanumeric characters: rsAstralRange, rsEmoji, etc
  4454. * - the groups that processed the apostrophe, as it's removed before passing the string to preg_match: rsApos, rsOptContrLower, and rsOptContrUpper
  4455. *
  4456. */
  4457. /** Used to compose unicode character classes. */
  4458. $rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff';
  4459. $rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf';
  4460. $rsPunctuationRange = '\\x{2000}-\\x{206f}';
  4461. $rsSpaceRange = ' \\t\\x0b\\f\\xa0\\x{feff}\\n\\r\\x{2028}\\x{2029}\\x{1680}\\x{180e}\\x{2000}\\x{2001}\\x{2002}\\x{2003}\\x{2004}\\x{2005}\\x{2006}\\x{2007}\\x{2008}\\x{2009}\\x{200a}\\x{202f}\\x{205f}\\x{3000}';
  4462. $rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde';
  4463. $rsBreakRange = $rsNonCharRange . $rsPunctuationRange . $rsSpaceRange;
  4464. /** Used to compose unicode capture groups. */
  4465. $rsBreak = '[' . $rsBreakRange . ']';
  4466. $rsDigits = '\\d+'; // The last lodash version in GitHub uses a single digit here and expands it when in use.
  4467. $rsLower = '[' . $rsLowerRange . ']';
  4468. $rsMisc = '[^' . $rsBreakRange . $rsDigits . $rsLowerRange . $rsUpperRange . ']';
  4469. $rsUpper = '[' . $rsUpperRange . ']';
  4470. /** Used to compose unicode regexes. */
  4471. $rsMiscLower = '(?:' . $rsLower . '|' . $rsMisc . ')';
  4472. $rsMiscUpper = '(?:' . $rsUpper . '|' . $rsMisc . ')';
  4473. $rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])';
  4474. $rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])';
  4475. $regexp = '/' . implode(
  4476. '|',
  4477. array(
  4478. $rsUpper . '?' . $rsLower . '+' . '(?=' . implode( '|', array( $rsBreak, $rsUpper, '$' ) ) . ')',
  4479. $rsMiscUpper . '+' . '(?=' . implode( '|', array( $rsBreak, $rsUpper . $rsMiscLower, '$' ) ) . ')',
  4480. $rsUpper . '?' . $rsMiscLower . '+',
  4481. $rsUpper . '+',
  4482. $rsOrdUpper,
  4483. $rsOrdLower,
  4484. $rsDigits,
  4485. )
  4486. ) . '/u';
  4487. preg_match_all( $regexp, str_replace( "'", '', $string ), $matches );
  4488. return strtolower( implode( '-', $matches[0] ) );
  4489. //phpcs:enable WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase
  4490. }
  4491. /**
  4492. * Determines if the variable is a numeric-indexed array.
  4493. *
  4494. * @since 4.4.0
  4495. *
  4496. * @param mixed $data Variable to check.
  4497. * @return bool Whether the variable is a list.
  4498. */
  4499. function wp_is_numeric_array( $data ) {
  4500. if ( ! is_array( $data ) ) {
  4501. return false;
  4502. }
  4503. $keys = array_keys( $data );
  4504. $string_keys = array_filter( $keys, 'is_string' );
  4505. return count( $string_keys ) === 0;
  4506. }
  4507. /**
  4508. * Filters a list of objects, based on a set of key => value arguments.
  4509. *
  4510. * Retrieves the objects from the list that match the given arguments.
  4511. * Key represents property name, and value represents property value.
  4512. *
  4513. * If an object has more properties than those specified in arguments,
  4514. * that will not disqualify it. When using the 'AND' operator,
  4515. * any missing properties will disqualify it.
  4516. *
  4517. * When using the `$field` argument, this function can also retrieve
  4518. * a particular field from all matching objects, whereas wp_list_filter()
  4519. * only does the filtering.
  4520. *
  4521. * @since 3.0.0
  4522. * @since 4.7.0 Uses `WP_List_Util` class.
  4523. *
  4524. * @param array $list An array of objects to filter.
  4525. * @param array $args Optional. An array of key => value arguments to match
  4526. * against each object. Default empty array.
  4527. * @param string $operator Optional. The logical operation to perform. 'AND' means
  4528. * all elements from the array must match. 'OR' means only
  4529. * one element needs to match. 'NOT' means no elements may
  4530. * match. Default 'AND'.
  4531. * @param bool|string $field Optional. A field from the object to place instead
  4532. * of the entire object. Default false.
  4533. * @return array A list of objects or object fields.
  4534. */
  4535. function wp_filter_object_list( $list, $args = array(), $operator = 'and', $field = false ) {
  4536. if ( ! is_array( $list ) ) {
  4537. return array();
  4538. }
  4539. $util = new WP_List_Util( $list );
  4540. $util->filter( $args, $operator );
  4541. if ( $field ) {
  4542. $util->pluck( $field );
  4543. }
  4544. return $util->get_output();
  4545. }
  4546. /**
  4547. * Filters a list of objects, based on a set of key => value arguments.
  4548. *
  4549. * Retrieves the objects from the list that match the given arguments.
  4550. * Key represents property name, and value represents property value.
  4551. *
  4552. * If an object has more properties than those specified in arguments,
  4553. * that will not disqualify it. When using the 'AND' operator,
  4554. * any missing properties will disqualify it.
  4555. *
  4556. * If you want to retrieve a particular field from all matching objects,
  4557. * use wp_filter_object_list() instead.
  4558. *
  4559. * @since 3.1.0
  4560. * @since 4.7.0 Uses `WP_List_Util` class.
  4561. * @since 5.9.0 Converted into a wrapper for `wp_filter_object_list()`.
  4562. *
  4563. * @param array $list An array of objects to filter.
  4564. * @param array $args Optional. An array of key => value arguments to match
  4565. * against each object. Default empty array.
  4566. * @param string $operator Optional. The logical operation to perform. 'AND' means
  4567. * all elements from the array must match. 'OR' means only
  4568. * one element needs to match. 'NOT' means no elements may
  4569. * match. Default 'AND'.
  4570. * @return array Array of found values.
  4571. */
  4572. function wp_list_filter( $list, $args = array(), $operator = 'AND' ) {
  4573. return wp_filter_object_list( $list, $args, $operator );
  4574. }
  4575. /**
  4576. * Plucks a certain field out of each object or array in an array.
  4577. *
  4578. * This has the same functionality and prototype of
  4579. * array_column() (PHP 5.5) but also supports objects.
  4580. *
  4581. * @since 3.1.0
  4582. * @since 4.0.0 $index_key parameter added.
  4583. * @since 4.7.0 Uses `WP_List_Util` class.
  4584. *
  4585. * @param array $list List of objects or arrays.
  4586. * @param int|string $field Field from the object to place instead of the entire object.
  4587. * @param int|string $index_key Optional. Field from the object to use as keys for the new array.
  4588. * Default null.
  4589. * @return array Array of found values. If `$index_key` is set, an array of found values with keys
  4590. * corresponding to `$index_key`. If `$index_key` is null, array keys from the original
  4591. * `$list` will be preserved in the results.
  4592. */
  4593. function wp_list_pluck( $list, $field, $index_key = null ) {
  4594. $util = new WP_List_Util( $list );
  4595. return $util->pluck( $field, $index_key );
  4596. }
  4597. /**
  4598. * Sorts an array of objects or arrays based on one or more orderby arguments.
  4599. *
  4600. * @since 4.7.0
  4601. *
  4602. * @param array $list An array of objects to sort.
  4603. * @param string|array $orderby Optional. Either the field name to order by or an array
  4604. * of multiple orderby fields as $orderby => $order.
  4605. * @param string $order Optional. Either 'ASC' or 'DESC'. Only used if $orderby
  4606. * is a string.
  4607. * @param bool $preserve_keys Optional. Whether to preserve keys. Default false.
  4608. * @return array The sorted array.
  4609. */
  4610. function wp_list_sort( $list, $orderby = array(), $order = 'ASC', $preserve_keys = false ) {
  4611. if ( ! is_array( $list ) ) {
  4612. return array();
  4613. }
  4614. $util = new WP_List_Util( $list );
  4615. return $util->sort( $orderby, $order, $preserve_keys );
  4616. }
  4617. /**
  4618. * Determines if Widgets library should be loaded.
  4619. *
  4620. * Checks to make sure that the widgets library hasn't already been loaded.
  4621. * If it hasn't, then it will load the widgets library and run an action hook.
  4622. *
  4623. * @since 2.2.0
  4624. */
  4625. function wp_maybe_load_widgets() {
  4626. /**
  4627. * Filters whether to load the Widgets library.
  4628. *
  4629. * Returning a falsey value from the filter will effectively short-circuit
  4630. * the Widgets library from loading.
  4631. *
  4632. * @since 2.8.0
  4633. *
  4634. * @param bool $wp_maybe_load_widgets Whether to load the Widgets library.
  4635. * Default true.
  4636. */
  4637. if ( ! apply_filters( 'load_default_widgets', true ) ) {
  4638. return;
  4639. }
  4640. require_once ABSPATH . WPINC . '/default-widgets.php';
  4641. add_action( '_admin_menu', 'wp_widgets_add_menu' );
  4642. }
  4643. /**
  4644. * Append the Widgets menu to the themes main menu.
  4645. *
  4646. * @since 2.2.0
  4647. *
  4648. * @global array $submenu
  4649. */
  4650. function wp_widgets_add_menu() {
  4651. global $submenu;
  4652. if ( ! current_theme_supports( 'widgets' ) ) {
  4653. return;
  4654. }
  4655. $submenu['themes.php'][7] = array( __( 'Widgets' ), 'edit_theme_options', 'widgets.php' );
  4656. ksort( $submenu['themes.php'], SORT_NUMERIC );
  4657. }
  4658. /**
  4659. * Flush all output buffers for PHP 5.2.
  4660. *
  4661. * Make sure all output buffers are flushed before our singletons are destroyed.
  4662. *
  4663. * @since 2.2.0
  4664. */
  4665. function wp_ob_end_flush_all() {
  4666. $levels = ob_get_level();
  4667. for ( $i = 0; $i < $levels; $i++ ) {
  4668. ob_end_flush();
  4669. }
  4670. }
  4671. /**
  4672. * Load custom DB error or display WordPress DB error.
  4673. *
  4674. * If a file exists in the wp-content directory named db-error.php, then it will
  4675. * be loaded instead of displaying the WordPress DB error. If it is not found,
  4676. * then the WordPress DB error will be displayed instead.
  4677. *
  4678. * The WordPress DB error sets the HTTP status header to 500 to try to prevent
  4679. * search engines from caching the message. Custom DB messages should do the
  4680. * same.
  4681. *
  4682. * This function was backported to WordPress 2.3.2, but originally was added
  4683. * in WordPress 2.5.0.
  4684. *
  4685. * @since 2.3.2
  4686. *
  4687. * @global wpdb $wpdb WordPress database abstraction object.
  4688. */
  4689. function dead_db() {
  4690. global $wpdb;
  4691. wp_load_translations_early();
  4692. // Load custom DB error template, if present.
  4693. if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
  4694. require_once WP_CONTENT_DIR . '/db-error.php';
  4695. die();
  4696. }
  4697. // If installing or in the admin, provide the verbose message.
  4698. if ( wp_installing() || defined( 'WP_ADMIN' ) ) {
  4699. wp_die( $wpdb->error );
  4700. }
  4701. // Otherwise, be terse.
  4702. wp_die( '<h1>' . __( 'Error establishing a database connection' ) . '</h1>', __( 'Database Error' ) );
  4703. }
  4704. /**
  4705. * Convert a value to non-negative integer.
  4706. *
  4707. * @since 2.5.0
  4708. *
  4709. * @param mixed $maybeint Data you wish to have converted to a non-negative integer.
  4710. * @return int A non-negative integer.
  4711. */
  4712. function absint( $maybeint ) {
  4713. return abs( (int) $maybeint );
  4714. }
  4715. /**
  4716. * Mark a function as deprecated and inform when it has been used.
  4717. *
  4718. * There is a {@see 'hook deprecated_function_run'} that will be called that can be used
  4719. * to get the backtrace up to what file and function called the deprecated
  4720. * function.
  4721. *
  4722. * The current behavior is to trigger a user error if `WP_DEBUG` is true.
  4723. *
  4724. * This function is to be used in every function that is deprecated.
  4725. *
  4726. * @since 2.5.0
  4727. * @since 5.4.0 This function is no longer marked as "private".
  4728. * @since 5.4.0 The error type is now classified as E_USER_DEPRECATED (used to default to E_USER_NOTICE).
  4729. *
  4730. * @param string $function The function that was called.
  4731. * @param string $version The version of WordPress that deprecated the function.
  4732. * @param string $replacement Optional. The function that should have been called. Default empty.
  4733. */
  4734. function _deprecated_function( $function, $version, $replacement = '' ) {
  4735. /**
  4736. * Fires when a deprecated function is called.
  4737. *
  4738. * @since 2.5.0
  4739. *
  4740. * @param string $function The function that was called.
  4741. * @param string $replacement The function that should have been called.
  4742. * @param string $version The version of WordPress that deprecated the function.
  4743. */
  4744. do_action( 'deprecated_function_run', $function, $replacement, $version );
  4745. /**
  4746. * Filters whether to trigger an error for deprecated functions.
  4747. *
  4748. * @since 2.5.0
  4749. *
  4750. * @param bool $trigger Whether to trigger the error for deprecated functions. Default true.
  4751. */
  4752. if ( WP_DEBUG && apply_filters( 'deprecated_function_trigger_error', true ) ) {
  4753. if ( function_exists( '__' ) ) {
  4754. if ( $replacement ) {
  4755. trigger_error(
  4756. sprintf(
  4757. /* translators: 1: PHP function name, 2: Version number, 3: Alternative function name. */
  4758. __( 'Function %1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.' ),
  4759. $function,
  4760. $version,
  4761. $replacement
  4762. ),
  4763. E_USER_DEPRECATED
  4764. );
  4765. } else {
  4766. trigger_error(
  4767. sprintf(
  4768. /* translators: 1: PHP function name, 2: Version number. */
  4769. __( 'Function %1$s is <strong>deprecated</strong> since version %2$s with no alternative available.' ),
  4770. $function,
  4771. $version
  4772. ),
  4773. E_USER_DEPRECATED
  4774. );
  4775. }
  4776. } else {
  4777. if ( $replacement ) {
  4778. trigger_error(
  4779. sprintf(
  4780. 'Function %1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.',
  4781. $function,
  4782. $version,
  4783. $replacement
  4784. ),
  4785. E_USER_DEPRECATED
  4786. );
  4787. } else {
  4788. trigger_error(
  4789. sprintf(
  4790. 'Function %1$s is <strong>deprecated</strong> since version %2$s with no alternative available.',
  4791. $function,
  4792. $version
  4793. ),
  4794. E_USER_DEPRECATED
  4795. );
  4796. }
  4797. }
  4798. }
  4799. }
  4800. /**
  4801. * Marks a constructor as deprecated and informs when it has been used.
  4802. *
  4803. * Similar to _deprecated_function(), but with different strings. Used to
  4804. * remove PHP4 style constructors.
  4805. *
  4806. * The current behavior is to trigger a user error if `WP_DEBUG` is true.
  4807. *
  4808. * This function is to be used in every PHP4 style constructor method that is deprecated.
  4809. *
  4810. * @since 4.3.0
  4811. * @since 4.5.0 Added the `$parent_class` parameter.
  4812. * @since 5.4.0 This function is no longer marked as "private".
  4813. * @since 5.4.0 The error type is now classified as E_USER_DEPRECATED (used to default to E_USER_NOTICE).
  4814. *
  4815. * @param string $class The class containing the deprecated constructor.
  4816. * @param string $version The version of WordPress that deprecated the function.
  4817. * @param string $parent_class Optional. The parent class calling the deprecated constructor.
  4818. * Default empty string.
  4819. */
  4820. function _deprecated_constructor( $class, $version, $parent_class = '' ) {
  4821. /**
  4822. * Fires when a deprecated constructor is called.
  4823. *
  4824. * @since 4.3.0
  4825. * @since 4.5.0 Added the `$parent_class` parameter.
  4826. *
  4827. * @param string $class The class containing the deprecated constructor.
  4828. * @param string $version The version of WordPress that deprecated the function.
  4829. * @param string $parent_class The parent class calling the deprecated constructor.
  4830. */
  4831. do_action( 'deprecated_constructor_run', $class, $version, $parent_class );
  4832. /**
  4833. * Filters whether to trigger an error for deprecated functions.
  4834. *
  4835. * `WP_DEBUG` must be true in addition to the filter evaluating to true.
  4836. *
  4837. * @since 4.3.0
  4838. *
  4839. * @param bool $trigger Whether to trigger the error for deprecated functions. Default true.
  4840. */
  4841. if ( WP_DEBUG && apply_filters( 'deprecated_constructor_trigger_error', true ) ) {
  4842. if ( function_exists( '__' ) ) {
  4843. if ( $parent_class ) {
  4844. trigger_error(
  4845. sprintf(
  4846. /* translators: 1: PHP class name, 2: PHP parent class name, 3: Version number, 4: __construct() method. */
  4847. __( 'The called constructor method for %1$s class in %2$s is <strong>deprecated</strong> since version %3$s! Use %4$s instead.' ),
  4848. $class,
  4849. $parent_class,
  4850. $version,
  4851. '<code>__construct()</code>'
  4852. ),
  4853. E_USER_DEPRECATED
  4854. );
  4855. } else {
  4856. trigger_error(
  4857. sprintf(
  4858. /* translators: 1: PHP class name, 2: Version number, 3: __construct() method. */
  4859. __( 'The called constructor method for %1$s class is <strong>deprecated</strong> since version %2$s! Use %3$s instead.' ),
  4860. $class,
  4861. $version,
  4862. '<code>__construct()</code>'
  4863. ),
  4864. E_USER_DEPRECATED
  4865. );
  4866. }
  4867. } else {
  4868. if ( $parent_class ) {
  4869. trigger_error(
  4870. sprintf(
  4871. 'The called constructor method for %1$s class in %2$s is <strong>deprecated</strong> since version %3$s! Use %4$s instead.',
  4872. $class,
  4873. $parent_class,
  4874. $version,
  4875. '<code>__construct()</code>'
  4876. ),
  4877. E_USER_DEPRECATED
  4878. );
  4879. } else {
  4880. trigger_error(
  4881. sprintf(
  4882. 'The called constructor method for %1$s class is <strong>deprecated</strong> since version %2$s! Use %3$s instead.',
  4883. $class,
  4884. $version,
  4885. '<code>__construct()</code>'
  4886. ),
  4887. E_USER_DEPRECATED
  4888. );
  4889. }
  4890. }
  4891. }
  4892. }
  4893. /**
  4894. * Mark a file as deprecated and inform when it has been used.
  4895. *
  4896. * There is a hook {@see 'deprecated_file_included'} that will be called that can be used
  4897. * to get the backtrace up to what file and function included the deprecated
  4898. * file.
  4899. *
  4900. * The current behavior is to trigger a user error if `WP_DEBUG` is true.
  4901. *
  4902. * This function is to be used in every file that is deprecated.
  4903. *
  4904. * @since 2.5.0
  4905. * @since 5.4.0 This function is no longer marked as "private".
  4906. * @since 5.4.0 The error type is now classified as E_USER_DEPRECATED (used to default to E_USER_NOTICE).
  4907. *
  4908. * @param string $file The file that was included.
  4909. * @param string $version The version of WordPress that deprecated the file.
  4910. * @param string $replacement Optional. The file that should have been included based on ABSPATH.
  4911. * Default empty.
  4912. * @param string $message Optional. A message regarding the change. Default empty.
  4913. */
  4914. function _deprecated_file( $file, $version, $replacement = '', $message = '' ) {
  4915. /**
  4916. * Fires when a deprecated file is called.
  4917. *
  4918. * @since 2.5.0
  4919. *
  4920. * @param string $file The file that was called.
  4921. * @param string $replacement The file that should have been included based on ABSPATH.
  4922. * @param string $version The version of WordPress that deprecated the file.
  4923. * @param string $message A message regarding the change.
  4924. */
  4925. do_action( 'deprecated_file_included', $file, $replacement, $version, $message );
  4926. /**
  4927. * Filters whether to trigger an error for deprecated files.
  4928. *
  4929. * @since 2.5.0
  4930. *
  4931. * @param bool $trigger Whether to trigger the error for deprecated files. Default true.
  4932. */
  4933. if ( WP_DEBUG && apply_filters( 'deprecated_file_trigger_error', true ) ) {
  4934. $message = empty( $message ) ? '' : ' ' . $message;
  4935. if ( function_exists( '__' ) ) {
  4936. if ( $replacement ) {
  4937. trigger_error(
  4938. sprintf(
  4939. /* translators: 1: PHP file name, 2: Version number, 3: Alternative file name. */
  4940. __( 'File %1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.' ),
  4941. $file,
  4942. $version,
  4943. $replacement
  4944. ) . $message,
  4945. E_USER_DEPRECATED
  4946. );
  4947. } else {
  4948. trigger_error(
  4949. sprintf(
  4950. /* translators: 1: PHP file name, 2: Version number. */
  4951. __( 'File %1$s is <strong>deprecated</strong> since version %2$s with no alternative available.' ),
  4952. $file,
  4953. $version
  4954. ) . $message,
  4955. E_USER_DEPRECATED
  4956. );
  4957. }
  4958. } else {
  4959. if ( $replacement ) {
  4960. trigger_error(
  4961. sprintf(
  4962. 'File %1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.',
  4963. $file,
  4964. $version,
  4965. $replacement
  4966. ) . $message,
  4967. E_USER_DEPRECATED
  4968. );
  4969. } else {
  4970. trigger_error(
  4971. sprintf(
  4972. 'File %1$s is <strong>deprecated</strong> since version %2$s with no alternative available.',
  4973. $file,
  4974. $version
  4975. ) . $message,
  4976. E_USER_DEPRECATED
  4977. );
  4978. }
  4979. }
  4980. }
  4981. }
  4982. /**
  4983. * Mark a function argument as deprecated and inform when it has been used.
  4984. *
  4985. * This function is to be used whenever a deprecated function argument is used.
  4986. * Before this function is called, the argument must be checked for whether it was
  4987. * used by comparing it to its default value or evaluating whether it is empty.
  4988. * For example:
  4989. *
  4990. * if ( ! empty( $deprecated ) ) {
  4991. * _deprecated_argument( __FUNCTION__, '3.0.0' );
  4992. * }
  4993. *
  4994. * There is a hook deprecated_argument_run that will be called that can be used
  4995. * to get the backtrace up to what file and function used the deprecated
  4996. * argument.
  4997. *
  4998. * The current behavior is to trigger a user error if WP_DEBUG is true.
  4999. *
  5000. * @since 3.0.0
  5001. * @since 5.4.0 This function is no longer marked as "private".
  5002. * @since 5.4.0 The error type is now classified as E_USER_DEPRECATED (used to default to E_USER_NOTICE).
  5003. *
  5004. * @param string $function The function that was called.
  5005. * @param string $version The version of WordPress that deprecated the argument used.
  5006. * @param string $message Optional. A message regarding the change. Default empty.
  5007. */
  5008. function _deprecated_argument( $function, $version, $message = '' ) {
  5009. /**
  5010. * Fires when a deprecated argument is called.
  5011. *
  5012. * @since 3.0.0
  5013. *
  5014. * @param string $function The function that was called.
  5015. * @param string $message A message regarding the change.
  5016. * @param string $version The version of WordPress that deprecated the argument used.
  5017. */
  5018. do_action( 'deprecated_argument_run', $function, $message, $version );
  5019. /**
  5020. * Filters whether to trigger an error for deprecated arguments.
  5021. *
  5022. * @since 3.0.0
  5023. *
  5024. * @param bool $trigger Whether to trigger the error for deprecated arguments. Default true.
  5025. */
  5026. if ( WP_DEBUG && apply_filters( 'deprecated_argument_trigger_error', true ) ) {
  5027. if ( function_exists( '__' ) ) {
  5028. if ( $message ) {
  5029. trigger_error(
  5030. sprintf(
  5031. /* translators: 1: PHP function name, 2: Version number, 3: Optional message regarding the change. */
  5032. __( 'Function %1$s was called with an argument that is <strong>deprecated</strong> since version %2$s! %3$s' ),
  5033. $function,
  5034. $version,
  5035. $message
  5036. ),
  5037. E_USER_DEPRECATED
  5038. );
  5039. } else {
  5040. trigger_error(
  5041. sprintf(
  5042. /* translators: 1: PHP function name, 2: Version number. */
  5043. __( 'Function %1$s was called with an argument that is <strong>deprecated</strong> since version %2$s with no alternative available.' ),
  5044. $function,
  5045. $version
  5046. ),
  5047. E_USER_DEPRECATED
  5048. );
  5049. }
  5050. } else {
  5051. if ( $message ) {
  5052. trigger_error(
  5053. sprintf(
  5054. 'Function %1$s was called with an argument that is <strong>deprecated</strong> since version %2$s! %3$s',
  5055. $function,
  5056. $version,
  5057. $message
  5058. ),
  5059. E_USER_DEPRECATED
  5060. );
  5061. } else {
  5062. trigger_error(
  5063. sprintf(
  5064. 'Function %1$s was called with an argument that is <strong>deprecated</strong> since version %2$s with no alternative available.',
  5065. $function,
  5066. $version
  5067. ),
  5068. E_USER_DEPRECATED
  5069. );
  5070. }
  5071. }
  5072. }
  5073. }
  5074. /**
  5075. * Marks a deprecated action or filter hook as deprecated and throws a notice.
  5076. *
  5077. * Use the {@see 'deprecated_hook_run'} action to get the backtrace describing where
  5078. * the deprecated hook was called.
  5079. *
  5080. * Default behavior is to trigger a user error if `WP_DEBUG` is true.
  5081. *
  5082. * This function is called by the do_action_deprecated() and apply_filters_deprecated()
  5083. * functions, and so generally does not need to be called directly.
  5084. *
  5085. * @since 4.6.0
  5086. * @since 5.4.0 The error type is now classified as E_USER_DEPRECATED (used to default to E_USER_NOTICE).
  5087. * @access private
  5088. *
  5089. * @param string $hook The hook that was used.
  5090. * @param string $version The version of WordPress that deprecated the hook.
  5091. * @param string $replacement Optional. The hook that should have been used. Default empty.
  5092. * @param string $message Optional. A message regarding the change. Default empty.
  5093. */
  5094. function _deprecated_hook( $hook, $version, $replacement = '', $message = '' ) {
  5095. /**
  5096. * Fires when a deprecated hook is called.
  5097. *
  5098. * @since 4.6.0
  5099. *
  5100. * @param string $hook The hook that was called.
  5101. * @param string $replacement The hook that should be used as a replacement.
  5102. * @param string $version The version of WordPress that deprecated the argument used.
  5103. * @param string $message A message regarding the change.
  5104. */
  5105. do_action( 'deprecated_hook_run', $hook, $replacement, $version, $message );
  5106. /**
  5107. * Filters whether to trigger deprecated hook errors.
  5108. *
  5109. * @since 4.6.0
  5110. *
  5111. * @param bool $trigger Whether to trigger deprecated hook errors. Requires
  5112. * `WP_DEBUG` to be defined true.
  5113. */
  5114. if ( WP_DEBUG && apply_filters( 'deprecated_hook_trigger_error', true ) ) {
  5115. $message = empty( $message ) ? '' : ' ' . $message;
  5116. if ( $replacement ) {
  5117. trigger_error(
  5118. sprintf(
  5119. /* translators: 1: WordPress hook name, 2: Version number, 3: Alternative hook name. */
  5120. __( 'Hook %1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.' ),
  5121. $hook,
  5122. $version,
  5123. $replacement
  5124. ) . $message,
  5125. E_USER_DEPRECATED
  5126. );
  5127. } else {
  5128. trigger_error(
  5129. sprintf(
  5130. /* translators: 1: WordPress hook name, 2: Version number. */
  5131. __( 'Hook %1$s is <strong>deprecated</strong> since version %2$s with no alternative available.' ),
  5132. $hook,
  5133. $version
  5134. ) . $message,
  5135. E_USER_DEPRECATED
  5136. );
  5137. }
  5138. }
  5139. }
  5140. /**
  5141. * Mark something as being incorrectly called.
  5142. *
  5143. * There is a hook {@see 'doing_it_wrong_run'} that will be called that can be used
  5144. * to get the backtrace up to what file and function called the deprecated
  5145. * function.
  5146. *
  5147. * The current behavior is to trigger a user error if `WP_DEBUG` is true.
  5148. *
  5149. * @since 3.1.0
  5150. * @since 5.4.0 This function is no longer marked as "private".
  5151. *
  5152. * @param string $function The function that was called.
  5153. * @param string $message A message explaining what has been done incorrectly.
  5154. * @param string $version The version of WordPress where the message was added.
  5155. */
  5156. function _doing_it_wrong( $function, $message, $version ) {
  5157. /**
  5158. * Fires when the given function is being used incorrectly.
  5159. *
  5160. * @since 3.1.0
  5161. *
  5162. * @param string $function The function that was called.
  5163. * @param string $message A message explaining what has been done incorrectly.
  5164. * @param string $version The version of WordPress where the message was added.
  5165. */
  5166. do_action( 'doing_it_wrong_run', $function, $message, $version );
  5167. /**
  5168. * Filters whether to trigger an error for _doing_it_wrong() calls.
  5169. *
  5170. * @since 3.1.0
  5171. * @since 5.1.0 Added the $function, $message and $version parameters.
  5172. *
  5173. * @param bool $trigger Whether to trigger the error for _doing_it_wrong() calls. Default true.
  5174. * @param string $function The function that was called.
  5175. * @param string $message A message explaining what has been done incorrectly.
  5176. * @param string $version The version of WordPress where the message was added.
  5177. */
  5178. if ( WP_DEBUG && apply_filters( 'doing_it_wrong_trigger_error', true, $function, $message, $version ) ) {
  5179. if ( function_exists( '__' ) ) {
  5180. if ( $version ) {
  5181. /* translators: %s: Version number. */
  5182. $version = sprintf( __( '(This message was added in version %s.)' ), $version );
  5183. }
  5184. $message .= ' ' . sprintf(
  5185. /* translators: %s: Documentation URL. */
  5186. __( 'Please see <a href="%s">Debugging in WordPress</a> for more information.' ),
  5187. __( 'https://wordpress.org/support/article/debugging-in-wordpress/' )
  5188. );
  5189. trigger_error(
  5190. sprintf(
  5191. /* translators: Developer debugging message. 1: PHP function name, 2: Explanatory message, 3: WordPress version number. */
  5192. __( 'Function %1$s was called <strong>incorrectly</strong>. %2$s %3$s' ),
  5193. $function,
  5194. $message,
  5195. $version
  5196. ),
  5197. E_USER_NOTICE
  5198. );
  5199. } else {
  5200. if ( $version ) {
  5201. $version = sprintf( '(This message was added in version %s.)', $version );
  5202. }
  5203. $message .= sprintf(
  5204. ' Please see <a href="%s">Debugging in WordPress</a> for more information.',
  5205. 'https://wordpress.org/support/article/debugging-in-wordpress/'
  5206. );
  5207. trigger_error(
  5208. sprintf(
  5209. 'Function %1$s was called <strong>incorrectly</strong>. %2$s %3$s',
  5210. $function,
  5211. $message,
  5212. $version
  5213. ),
  5214. E_USER_NOTICE
  5215. );
  5216. }
  5217. }
  5218. }
  5219. /**
  5220. * Is the server running earlier than 1.5.0 version of lighttpd?
  5221. *
  5222. * @since 2.5.0
  5223. *
  5224. * @return bool Whether the server is running lighttpd < 1.5.0.
  5225. */
  5226. function is_lighttpd_before_150() {
  5227. $server_parts = explode( '/', isset( $_SERVER['SERVER_SOFTWARE'] ) ? $_SERVER['SERVER_SOFTWARE'] : '' );
  5228. $server_parts[1] = isset( $server_parts[1] ) ? $server_parts[1] : '';
  5229. return ( 'lighttpd' === $server_parts[0] && -1 == version_compare( $server_parts[1], '1.5.0' ) );
  5230. }
  5231. /**
  5232. * Does the specified module exist in the Apache config?
  5233. *
  5234. * @since 2.5.0
  5235. *
  5236. * @global bool $is_apache
  5237. *
  5238. * @param string $mod The module, e.g. mod_rewrite.
  5239. * @param bool $default Optional. The default return value if the module is not found. Default false.
  5240. * @return bool Whether the specified module is loaded.
  5241. */
  5242. function apache_mod_loaded( $mod, $default = false ) {
  5243. global $is_apache;
  5244. if ( ! $is_apache ) {
  5245. return false;
  5246. }
  5247. if ( function_exists( 'apache_get_modules' ) ) {
  5248. $mods = apache_get_modules();
  5249. if ( in_array( $mod, $mods, true ) ) {
  5250. return true;
  5251. }
  5252. } elseif ( function_exists( 'phpinfo' ) && false === strpos( ini_get( 'disable_functions' ), 'phpinfo' ) ) {
  5253. ob_start();
  5254. phpinfo( 8 );
  5255. $phpinfo = ob_get_clean();
  5256. if ( false !== strpos( $phpinfo, $mod ) ) {
  5257. return true;
  5258. }
  5259. }
  5260. return $default;
  5261. }
  5262. /**
  5263. * Check if IIS 7+ supports pretty permalinks.
  5264. *
  5265. * @since 2.8.0
  5266. *
  5267. * @global bool $is_iis7
  5268. *
  5269. * @return bool Whether IIS7 supports permalinks.
  5270. */
  5271. function iis7_supports_permalinks() {
  5272. global $is_iis7;
  5273. $supports_permalinks = false;
  5274. if ( $is_iis7 ) {
  5275. /* First we check if the DOMDocument class exists. If it does not exist, then we cannot
  5276. * easily update the xml configuration file, hence we just bail out and tell user that
  5277. * pretty permalinks cannot be used.
  5278. *
  5279. * Next we check if the URL Rewrite Module 1.1 is loaded and enabled for the web site. When
  5280. * URL Rewrite 1.1 is loaded it always sets a server variable called 'IIS_UrlRewriteModule'.
  5281. * Lastly we make sure that PHP is running via FastCGI. This is important because if it runs
  5282. * via ISAPI then pretty permalinks will not work.
  5283. */
  5284. $supports_permalinks = class_exists( 'DOMDocument', false ) && isset( $_SERVER['IIS_UrlRewriteModule'] ) && ( 'cgi-fcgi' === PHP_SAPI );
  5285. }
  5286. /**
  5287. * Filters whether IIS 7+ supports pretty permalinks.
  5288. *
  5289. * @since 2.8.0
  5290. *
  5291. * @param bool $supports_permalinks Whether IIS7 supports permalinks. Default false.
  5292. */
  5293. return apply_filters( 'iis7_supports_permalinks', $supports_permalinks );
  5294. }
  5295. /**
  5296. * Validates a file name and path against an allowed set of rules.
  5297. *
  5298. * A return value of `1` means the file path contains directory traversal.
  5299. *
  5300. * A return value of `2` means the file path contains a Windows drive path.
  5301. *
  5302. * A return value of `3` means the file is not in the allowed files list.
  5303. *
  5304. * @since 1.2.0
  5305. *
  5306. * @param string $file File path.
  5307. * @param string[] $allowed_files Optional. Array of allowed files.
  5308. * @return int 0 means nothing is wrong, greater than 0 means something was wrong.
  5309. */
  5310. function validate_file( $file, $allowed_files = array() ) {
  5311. if ( ! is_scalar( $file ) || '' === $file ) {
  5312. return 0;
  5313. }
  5314. // `../` on its own is not allowed:
  5315. if ( '../' === $file ) {
  5316. return 1;
  5317. }
  5318. // More than one occurrence of `../` is not allowed:
  5319. if ( preg_match_all( '#\.\./#', $file, $matches, PREG_SET_ORDER ) && ( count( $matches ) > 1 ) ) {
  5320. return 1;
  5321. }
  5322. // `../` which does not occur at the end of the path is not allowed:
  5323. if ( false !== strpos( $file, '../' ) && '../' !== mb_substr( $file, -3, 3 ) ) {
  5324. return 1;
  5325. }
  5326. // Files not in the allowed file list are not allowed:
  5327. if ( ! empty( $allowed_files ) && ! in_array( $file, $allowed_files, true ) ) {
  5328. return 3;
  5329. }
  5330. // Absolute Windows drive paths are not allowed:
  5331. if ( ':' === substr( $file, 1, 1 ) ) {
  5332. return 2;
  5333. }
  5334. return 0;
  5335. }
  5336. /**
  5337. * Whether to force SSL used for the Administration Screens.
  5338. *
  5339. * @since 2.6.0
  5340. *
  5341. * @param string|bool $force Optional. Whether to force SSL in admin screens. Default null.
  5342. * @return bool True if forced, false if not forced.
  5343. */
  5344. function force_ssl_admin( $force = null ) {
  5345. static $forced = false;
  5346. if ( ! is_null( $force ) ) {
  5347. $old_forced = $forced;
  5348. $forced = $force;
  5349. return $old_forced;
  5350. }
  5351. return $forced;
  5352. }
  5353. /**
  5354. * Guess the URL for the site.
  5355. *
  5356. * Will remove wp-admin links to retrieve only return URLs not in the wp-admin
  5357. * directory.
  5358. *
  5359. * @since 2.6.0
  5360. *
  5361. * @return string The guessed URL.
  5362. */
  5363. function wp_guess_url() {
  5364. if ( defined( 'WP_SITEURL' ) && '' !== WP_SITEURL ) {
  5365. $url = WP_SITEURL;
  5366. } else {
  5367. $abspath_fix = str_replace( '\\', '/', ABSPATH );
  5368. $script_filename_dir = dirname( $_SERVER['SCRIPT_FILENAME'] );
  5369. // The request is for the admin.
  5370. if ( strpos( $_SERVER['REQUEST_URI'], 'wp-admin' ) !== false || strpos( $_SERVER['REQUEST_URI'], 'wp-login.php' ) !== false ) {
  5371. $path = preg_replace( '#/(wp-admin/.*|wp-login.php)#i', '', $_SERVER['REQUEST_URI'] );
  5372. // The request is for a file in ABSPATH.
  5373. } elseif ( $script_filename_dir . '/' === $abspath_fix ) {
  5374. // Strip off any file/query params in the path.
  5375. $path = preg_replace( '#/[^/]*$#i', '', $_SERVER['PHP_SELF'] );
  5376. } else {
  5377. if ( false !== strpos( $_SERVER['SCRIPT_FILENAME'], $abspath_fix ) ) {
  5378. // Request is hitting a file inside ABSPATH.
  5379. $directory = str_replace( ABSPATH, '', $script_filename_dir );
  5380. // Strip off the subdirectory, and any file/query params.
  5381. $path = preg_replace( '#/' . preg_quote( $directory, '#' ) . '/[^/]*$#i', '', $_SERVER['REQUEST_URI'] );
  5382. } elseif ( false !== strpos( $abspath_fix, $script_filename_dir ) ) {
  5383. // Request is hitting a file above ABSPATH.
  5384. $subdirectory = substr( $abspath_fix, strpos( $abspath_fix, $script_filename_dir ) + strlen( $script_filename_dir ) );
  5385. // Strip off any file/query params from the path, appending the subdirectory to the installation.
  5386. $path = preg_replace( '#/[^/]*$#i', '', $_SERVER['REQUEST_URI'] ) . $subdirectory;
  5387. } else {
  5388. $path = $_SERVER['REQUEST_URI'];
  5389. }
  5390. }
  5391. $schema = is_ssl() ? 'https://' : 'http://'; // set_url_scheme() is not defined yet.
  5392. $url = $schema . $_SERVER['HTTP_HOST'] . $path;
  5393. }
  5394. return rtrim( $url, '/' );
  5395. }
  5396. /**
  5397. * Temporarily suspend cache additions.
  5398. *
  5399. * Stops more data being added to the cache, but still allows cache retrieval.
  5400. * This is useful for actions, such as imports, when a lot of data would otherwise
  5401. * be almost uselessly added to the cache.
  5402. *
  5403. * Suspension lasts for a single page load at most. Remember to call this
  5404. * function again if you wish to re-enable cache adds earlier.
  5405. *
  5406. * @since 3.3.0
  5407. *
  5408. * @param bool $suspend Optional. Suspends additions if true, re-enables them if false.
  5409. * @return bool The current suspend setting
  5410. */
  5411. function wp_suspend_cache_addition( $suspend = null ) {
  5412. static $_suspend = false;
  5413. if ( is_bool( $suspend ) ) {
  5414. $_suspend = $suspend;
  5415. }
  5416. return $_suspend;
  5417. }
  5418. /**
  5419. * Suspend cache invalidation.
  5420. *
  5421. * Turns cache invalidation on and off. Useful during imports where you don't want to do
  5422. * invalidations every time a post is inserted. Callers must be sure that what they are
  5423. * doing won't lead to an inconsistent cache when invalidation is suspended.
  5424. *
  5425. * @since 2.7.0
  5426. *
  5427. * @global bool $_wp_suspend_cache_invalidation
  5428. *
  5429. * @param bool $suspend Optional. Whether to suspend or enable cache invalidation. Default true.
  5430. * @return bool The current suspend setting.
  5431. */
  5432. function wp_suspend_cache_invalidation( $suspend = true ) {
  5433. global $_wp_suspend_cache_invalidation;
  5434. $current_suspend = $_wp_suspend_cache_invalidation;
  5435. $_wp_suspend_cache_invalidation = $suspend;
  5436. return $current_suspend;
  5437. }
  5438. /**
  5439. * Determine whether a site is the main site of the current network.
  5440. *
  5441. * @since 3.0.0
  5442. * @since 4.9.0 The `$network_id` parameter was added.
  5443. *
  5444. * @param int $site_id Optional. Site ID to test. Defaults to current site.
  5445. * @param int $network_id Optional. Network ID of the network to check for.
  5446. * Defaults to current network.
  5447. * @return bool True if $site_id is the main site of the network, or if not
  5448. * running Multisite.
  5449. */
  5450. function is_main_site( $site_id = null, $network_id = null ) {
  5451. if ( ! is_multisite() ) {
  5452. return true;
  5453. }
  5454. if ( ! $site_id ) {
  5455. $site_id = get_current_blog_id();
  5456. }
  5457. $site_id = (int) $site_id;
  5458. return get_main_site_id( $network_id ) === $site_id;
  5459. }
  5460. /**
  5461. * Gets the main site ID.
  5462. *
  5463. * @since 4.9.0
  5464. *
  5465. * @param int $network_id Optional. The ID of the network for which to get the main site.
  5466. * Defaults to the current network.
  5467. * @return int The ID of the main site.
  5468. */
  5469. function get_main_site_id( $network_id = null ) {
  5470. if ( ! is_multisite() ) {
  5471. return get_current_blog_id();
  5472. }
  5473. $network = get_network( $network_id );
  5474. if ( ! $network ) {
  5475. return 0;
  5476. }
  5477. return $network->site_id;
  5478. }
  5479. /**
  5480. * Determine whether a network is the main network of the Multisite installation.
  5481. *
  5482. * @since 3.7.0
  5483. *
  5484. * @param int $network_id Optional. Network ID to test. Defaults to current network.
  5485. * @return bool True if $network_id is the main network, or if not running Multisite.
  5486. */
  5487. function is_main_network( $network_id = null ) {
  5488. if ( ! is_multisite() ) {
  5489. return true;
  5490. }
  5491. if ( null === $network_id ) {
  5492. $network_id = get_current_network_id();
  5493. }
  5494. $network_id = (int) $network_id;
  5495. return ( get_main_network_id() === $network_id );
  5496. }
  5497. /**
  5498. * Get the main network ID.
  5499. *
  5500. * @since 4.3.0
  5501. *
  5502. * @return int The ID of the main network.
  5503. */
  5504. function get_main_network_id() {
  5505. if ( ! is_multisite() ) {
  5506. return 1;
  5507. }
  5508. $current_network = get_network();
  5509. if ( defined( 'PRIMARY_NETWORK_ID' ) ) {
  5510. $main_network_id = PRIMARY_NETWORK_ID;
  5511. } elseif ( isset( $current_network->id ) && 1 === (int) $current_network->id ) {
  5512. // If the current network has an ID of 1, assume it is the main network.
  5513. $main_network_id = 1;
  5514. } else {
  5515. $_networks = get_networks(
  5516. array(
  5517. 'fields' => 'ids',
  5518. 'number' => 1,
  5519. )
  5520. );
  5521. $main_network_id = array_shift( $_networks );
  5522. }
  5523. /**
  5524. * Filters the main network ID.
  5525. *
  5526. * @since 4.3.0
  5527. *
  5528. * @param int $main_network_id The ID of the main network.
  5529. */
  5530. return (int) apply_filters( 'get_main_network_id', $main_network_id );
  5531. }
  5532. /**
  5533. * Determine whether global terms are enabled.
  5534. *
  5535. * @since 3.0.0
  5536. *
  5537. * @return bool True if multisite and global terms enabled.
  5538. */
  5539. function global_terms_enabled() {
  5540. if ( ! is_multisite() ) {
  5541. return false;
  5542. }
  5543. static $global_terms = null;
  5544. if ( is_null( $global_terms ) ) {
  5545. /**
  5546. * Filters whether global terms are enabled.
  5547. *
  5548. * Returning a non-null value from the filter will effectively short-circuit the function
  5549. * and return the value of the 'global_terms_enabled' site option instead.
  5550. *
  5551. * @since 3.0.0
  5552. *
  5553. * @param null $enabled Whether global terms are enabled.
  5554. */
  5555. $filter = apply_filters( 'global_terms_enabled', null );
  5556. if ( ! is_null( $filter ) ) {
  5557. $global_terms = (bool) $filter;
  5558. } else {
  5559. $global_terms = (bool) get_site_option( 'global_terms_enabled', false );
  5560. }
  5561. }
  5562. return $global_terms;
  5563. }
  5564. /**
  5565. * Determines whether site meta is enabled.
  5566. *
  5567. * This function checks whether the 'blogmeta' database table exists. The result is saved as
  5568. * a setting for the main network, making it essentially a global setting. Subsequent requests
  5569. * will refer to this setting instead of running the query.
  5570. *
  5571. * @since 5.1.0
  5572. *
  5573. * @global wpdb $wpdb WordPress database abstraction object.
  5574. *
  5575. * @return bool True if site meta is supported, false otherwise.
  5576. */
  5577. function is_site_meta_supported() {
  5578. global $wpdb;
  5579. if ( ! is_multisite() ) {
  5580. return false;
  5581. }
  5582. $network_id = get_main_network_id();
  5583. $supported = get_network_option( $network_id, 'site_meta_supported', false );
  5584. if ( false === $supported ) {
  5585. $supported = $wpdb->get_var( "SHOW TABLES LIKE '{$wpdb->blogmeta}'" ) ? 1 : 0;
  5586. update_network_option( $network_id, 'site_meta_supported', $supported );
  5587. }
  5588. return (bool) $supported;
  5589. }
  5590. /**
  5591. * gmt_offset modification for smart timezone handling.
  5592. *
  5593. * Overrides the gmt_offset option if we have a timezone_string available.
  5594. *
  5595. * @since 2.8.0
  5596. *
  5597. * @return float|false Timezone GMT offset, false otherwise.
  5598. */
  5599. function wp_timezone_override_offset() {
  5600. $timezone_string = get_option( 'timezone_string' );
  5601. if ( ! $timezone_string ) {
  5602. return false;
  5603. }
  5604. $timezone_object = timezone_open( $timezone_string );
  5605. $datetime_object = date_create();
  5606. if ( false === $timezone_object || false === $datetime_object ) {
  5607. return false;
  5608. }
  5609. return round( timezone_offset_get( $timezone_object, $datetime_object ) / HOUR_IN_SECONDS, 2 );
  5610. }
  5611. /**
  5612. * Sort-helper for timezones.
  5613. *
  5614. * @since 2.9.0
  5615. * @access private
  5616. *
  5617. * @param array $a
  5618. * @param array $b
  5619. * @return int
  5620. */
  5621. function _wp_timezone_choice_usort_callback( $a, $b ) {
  5622. // Don't use translated versions of Etc.
  5623. if ( 'Etc' === $a['continent'] && 'Etc' === $b['continent'] ) {
  5624. // Make the order of these more like the old dropdown.
  5625. if ( 'GMT+' === substr( $a['city'], 0, 4 ) && 'GMT+' === substr( $b['city'], 0, 4 ) ) {
  5626. return -1 * ( strnatcasecmp( $a['city'], $b['city'] ) );
  5627. }
  5628. if ( 'UTC' === $a['city'] ) {
  5629. if ( 'GMT+' === substr( $b['city'], 0, 4 ) ) {
  5630. return 1;
  5631. }
  5632. return -1;
  5633. }
  5634. if ( 'UTC' === $b['city'] ) {
  5635. if ( 'GMT+' === substr( $a['city'], 0, 4 ) ) {
  5636. return -1;
  5637. }
  5638. return 1;
  5639. }
  5640. return strnatcasecmp( $a['city'], $b['city'] );
  5641. }
  5642. if ( $a['t_continent'] == $b['t_continent'] ) {
  5643. if ( $a['t_city'] == $b['t_city'] ) {
  5644. return strnatcasecmp( $a['t_subcity'], $b['t_subcity'] );
  5645. }
  5646. return strnatcasecmp( $a['t_city'], $b['t_city'] );
  5647. } else {
  5648. // Force Etc to the bottom of the list.
  5649. if ( 'Etc' === $a['continent'] ) {
  5650. return 1;
  5651. }
  5652. if ( 'Etc' === $b['continent'] ) {
  5653. return -1;
  5654. }
  5655. return strnatcasecmp( $a['t_continent'], $b['t_continent'] );
  5656. }
  5657. }
  5658. /**
  5659. * Gives a nicely-formatted list of timezone strings.
  5660. *
  5661. * @since 2.9.0
  5662. * @since 4.7.0 Added the `$locale` parameter.
  5663. *
  5664. * @param string $selected_zone Selected timezone.
  5665. * @param string $locale Optional. Locale to load the timezones in. Default current site locale.
  5666. * @return string
  5667. */
  5668. function wp_timezone_choice( $selected_zone, $locale = null ) {
  5669. static $mo_loaded = false, $locale_loaded = null;
  5670. $continents = array( 'Africa', 'America', 'Antarctica', 'Arctic', 'Asia', 'Atlantic', 'Australia', 'Europe', 'Indian', 'Pacific' );
  5671. // Load translations for continents and cities.
  5672. if ( ! $mo_loaded || $locale !== $locale_loaded ) {
  5673. $locale_loaded = $locale ? $locale : get_locale();
  5674. $mofile = WP_LANG_DIR . '/continents-cities-' . $locale_loaded . '.mo';
  5675. unload_textdomain( 'continents-cities' );
  5676. load_textdomain( 'continents-cities', $mofile );
  5677. $mo_loaded = true;
  5678. }
  5679. $zonen = array();
  5680. foreach ( timezone_identifiers_list() as $zone ) {
  5681. $zone = explode( '/', $zone );
  5682. if ( ! in_array( $zone[0], $continents, true ) ) {
  5683. continue;
  5684. }
  5685. // This determines what gets set and translated - we don't translate Etc/* strings here, they are done later.
  5686. $exists = array(
  5687. 0 => ( isset( $zone[0] ) && $zone[0] ),
  5688. 1 => ( isset( $zone[1] ) && $zone[1] ),
  5689. 2 => ( isset( $zone[2] ) && $zone[2] ),
  5690. );
  5691. $exists[3] = ( $exists[0] && 'Etc' !== $zone[0] );
  5692. $exists[4] = ( $exists[1] && $exists[3] );
  5693. $exists[5] = ( $exists[2] && $exists[3] );
  5694. // phpcs:disable WordPress.WP.I18n.LowLevelTranslationFunction,WordPress.WP.I18n.NonSingularStringLiteralText
  5695. $zonen[] = array(
  5696. 'continent' => ( $exists[0] ? $zone[0] : '' ),
  5697. 'city' => ( $exists[1] ? $zone[1] : '' ),
  5698. 'subcity' => ( $exists[2] ? $zone[2] : '' ),
  5699. 't_continent' => ( $exists[3] ? translate( str_replace( '_', ' ', $zone[0] ), 'continents-cities' ) : '' ),
  5700. 't_city' => ( $exists[4] ? translate( str_replace( '_', ' ', $zone[1] ), 'continents-cities' ) : '' ),
  5701. 't_subcity' => ( $exists[5] ? translate( str_replace( '_', ' ', $zone[2] ), 'continents-cities' ) : '' ),
  5702. );
  5703. // phpcs:enable
  5704. }
  5705. usort( $zonen, '_wp_timezone_choice_usort_callback' );
  5706. $structure = array();
  5707. if ( empty( $selected_zone ) ) {
  5708. $structure[] = '<option selected="selected" value="">' . __( 'Select a city' ) . '</option>';
  5709. }
  5710. foreach ( $zonen as $key => $zone ) {
  5711. // Build value in an array to join later.
  5712. $value = array( $zone['continent'] );
  5713. if ( empty( $zone['city'] ) ) {
  5714. // It's at the continent level (generally won't happen).
  5715. $display = $zone['t_continent'];
  5716. } else {
  5717. // It's inside a continent group.
  5718. // Continent optgroup.
  5719. if ( ! isset( $zonen[ $key - 1 ] ) || $zonen[ $key - 1 ]['continent'] !== $zone['continent'] ) {
  5720. $label = $zone['t_continent'];
  5721. $structure[] = '<optgroup label="' . esc_attr( $label ) . '">';
  5722. }
  5723. // Add the city to the value.
  5724. $value[] = $zone['city'];
  5725. $display = $zone['t_city'];
  5726. if ( ! empty( $zone['subcity'] ) ) {
  5727. // Add the subcity to the value.
  5728. $value[] = $zone['subcity'];
  5729. $display .= ' - ' . $zone['t_subcity'];
  5730. }
  5731. }
  5732. // Build the value.
  5733. $value = implode( '/', $value );
  5734. $selected = '';
  5735. if ( $value === $selected_zone ) {
  5736. $selected = 'selected="selected" ';
  5737. }
  5738. $structure[] = '<option ' . $selected . 'value="' . esc_attr( $value ) . '">' . esc_html( $display ) . '</option>';
  5739. // Close continent optgroup.
  5740. if ( ! empty( $zone['city'] ) && ( ! isset( $zonen[ $key + 1 ] ) || ( isset( $zonen[ $key + 1 ] ) && $zonen[ $key + 1 ]['continent'] !== $zone['continent'] ) ) ) {
  5741. $structure[] = '</optgroup>';
  5742. }
  5743. }
  5744. // Do UTC.
  5745. $structure[] = '<optgroup label="' . esc_attr__( 'UTC' ) . '">';
  5746. $selected = '';
  5747. if ( 'UTC' === $selected_zone ) {
  5748. $selected = 'selected="selected" ';
  5749. }
  5750. $structure[] = '<option ' . $selected . 'value="' . esc_attr( 'UTC' ) . '">' . __( 'UTC' ) . '</option>';
  5751. $structure[] = '</optgroup>';
  5752. // Do manual UTC offsets.
  5753. $structure[] = '<optgroup label="' . esc_attr__( 'Manual Offsets' ) . '">';
  5754. $offset_range = array(
  5755. -12,
  5756. -11.5,
  5757. -11,
  5758. -10.5,
  5759. -10,
  5760. -9.5,
  5761. -9,
  5762. -8.5,
  5763. -8,
  5764. -7.5,
  5765. -7,
  5766. -6.5,
  5767. -6,
  5768. -5.5,
  5769. -5,
  5770. -4.5,
  5771. -4,
  5772. -3.5,
  5773. -3,
  5774. -2.5,
  5775. -2,
  5776. -1.5,
  5777. -1,
  5778. -0.5,
  5779. 0,
  5780. 0.5,
  5781. 1,
  5782. 1.5,
  5783. 2,
  5784. 2.5,
  5785. 3,
  5786. 3.5,
  5787. 4,
  5788. 4.5,
  5789. 5,
  5790. 5.5,
  5791. 5.75,
  5792. 6,
  5793. 6.5,
  5794. 7,
  5795. 7.5,
  5796. 8,
  5797. 8.5,
  5798. 8.75,
  5799. 9,
  5800. 9.5,
  5801. 10,
  5802. 10.5,
  5803. 11,
  5804. 11.5,
  5805. 12,
  5806. 12.75,
  5807. 13,
  5808. 13.75,
  5809. 14,
  5810. );
  5811. foreach ( $offset_range as $offset ) {
  5812. if ( 0 <= $offset ) {
  5813. $offset_name = '+' . $offset;
  5814. } else {
  5815. $offset_name = (string) $offset;
  5816. }
  5817. $offset_value = $offset_name;
  5818. $offset_name = str_replace( array( '.25', '.5', '.75' ), array( ':15', ':30', ':45' ), $offset_name );
  5819. $offset_name = 'UTC' . $offset_name;
  5820. $offset_value = 'UTC' . $offset_value;
  5821. $selected = '';
  5822. if ( $offset_value === $selected_zone ) {
  5823. $selected = 'selected="selected" ';
  5824. }
  5825. $structure[] = '<option ' . $selected . 'value="' . esc_attr( $offset_value ) . '">' . esc_html( $offset_name ) . '</option>';
  5826. }
  5827. $structure[] = '</optgroup>';
  5828. return implode( "\n", $structure );
  5829. }
  5830. /**
  5831. * Strip close comment and close php tags from file headers used by WP.
  5832. *
  5833. * @since 2.8.0
  5834. * @access private
  5835. *
  5836. * @see https://core.trac.wordpress.org/ticket/8497
  5837. *
  5838. * @param string $str Header comment to clean up.
  5839. * @return string
  5840. */
  5841. function _cleanup_header_comment( $str ) {
  5842. return trim( preg_replace( '/\s*(?:\*\/|\?>).*/', '', $str ) );
  5843. }
  5844. /**
  5845. * Permanently delete comments or posts of any type that have held a status
  5846. * of 'trash' for the number of days defined in EMPTY_TRASH_DAYS.
  5847. *
  5848. * The default value of `EMPTY_TRASH_DAYS` is 30 (days).
  5849. *
  5850. * @since 2.9.0
  5851. *
  5852. * @global wpdb $wpdb WordPress database abstraction object.
  5853. */
  5854. function wp_scheduled_delete() {
  5855. global $wpdb;
  5856. $delete_timestamp = time() - ( DAY_IN_SECONDS * EMPTY_TRASH_DAYS );
  5857. $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 );
  5858. foreach ( (array) $posts_to_delete as $post ) {
  5859. $post_id = (int) $post['post_id'];
  5860. if ( ! $post_id ) {
  5861. continue;
  5862. }
  5863. $del_post = get_post( $post_id );
  5864. if ( ! $del_post || 'trash' !== $del_post->post_status ) {
  5865. delete_post_meta( $post_id, '_wp_trash_meta_status' );
  5866. delete_post_meta( $post_id, '_wp_trash_meta_time' );
  5867. } else {
  5868. wp_delete_post( $post_id );
  5869. }
  5870. }
  5871. $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 );
  5872. foreach ( (array) $comments_to_delete as $comment ) {
  5873. $comment_id = (int) $comment['comment_id'];
  5874. if ( ! $comment_id ) {
  5875. continue;
  5876. }
  5877. $del_comment = get_comment( $comment_id );
  5878. if ( ! $del_comment || 'trash' !== $del_comment->comment_approved ) {
  5879. delete_comment_meta( $comment_id, '_wp_trash_meta_time' );
  5880. delete_comment_meta( $comment_id, '_wp_trash_meta_status' );
  5881. } else {
  5882. wp_delete_comment( $del_comment );
  5883. }
  5884. }
  5885. }
  5886. /**
  5887. * Retrieve metadata from a file.
  5888. *
  5889. * Searches for metadata in the first 8 KB of a file, such as a plugin or theme.
  5890. * Each piece of metadata must be on its own line. Fields can not span multiple
  5891. * lines, the value will get cut at the end of the first line.
  5892. *
  5893. * If the file data is not within that first 8 KB, then the author should correct
  5894. * their plugin file and move the data headers to the top.
  5895. *
  5896. * @link https://codex.wordpress.org/File_Header
  5897. *
  5898. * @since 2.9.0
  5899. *
  5900. * @param string $file Absolute path to the file.
  5901. * @param array $default_headers List of headers, in the format `array( 'HeaderKey' => 'Header Name' )`.
  5902. * @param string $context Optional. If specified adds filter hook {@see 'extra_$context_headers'}.
  5903. * Default empty.
  5904. * @return string[] Array of file header values keyed by header name.
  5905. */
  5906. function get_file_data( $file, $default_headers, $context = '' ) {
  5907. // Pull only the first 8 KB of the file in.
  5908. $file_data = file_get_contents( $file, false, null, 0, 8 * KB_IN_BYTES );
  5909. if ( false === $file_data ) {
  5910. $file_data = '';
  5911. }
  5912. // Make sure we catch CR-only line endings.
  5913. $file_data = str_replace( "\r", "\n", $file_data );
  5914. /**
  5915. * Filters extra file headers by context.
  5916. *
  5917. * The dynamic portion of the hook name, `$context`, refers to
  5918. * the context where extra headers might be loaded.
  5919. *
  5920. * @since 2.9.0
  5921. *
  5922. * @param array $extra_context_headers Empty array by default.
  5923. */
  5924. $extra_headers = $context ? apply_filters( "extra_{$context}_headers", array() ) : array();
  5925. if ( $extra_headers ) {
  5926. $extra_headers = array_combine( $extra_headers, $extra_headers ); // Keys equal values.
  5927. $all_headers = array_merge( $extra_headers, (array) $default_headers );
  5928. } else {
  5929. $all_headers = $default_headers;
  5930. }
  5931. foreach ( $all_headers as $field => $regex ) {
  5932. if ( preg_match( '/^(?:[ \t]*<\?php)?[ \t\/*#@]*' . preg_quote( $regex, '/' ) . ':(.*)$/mi', $file_data, $match ) && $match[1] ) {
  5933. $all_headers[ $field ] = _cleanup_header_comment( $match[1] );
  5934. } else {
  5935. $all_headers[ $field ] = '';
  5936. }
  5937. }
  5938. return $all_headers;
  5939. }
  5940. /**
  5941. * Returns true.
  5942. *
  5943. * Useful for returning true to filters easily.
  5944. *
  5945. * @since 3.0.0
  5946. *
  5947. * @see __return_false()
  5948. *
  5949. * @return true True.
  5950. */
  5951. function __return_true() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionDoubleUnderscore,PHPCompatibility.FunctionNameRestrictions.ReservedFunctionNames.FunctionDoubleUnderscore
  5952. return true;
  5953. }
  5954. /**
  5955. * Returns false.
  5956. *
  5957. * Useful for returning false to filters easily.
  5958. *
  5959. * @since 3.0.0
  5960. *
  5961. * @see __return_true()
  5962. *
  5963. * @return false False.
  5964. */
  5965. function __return_false() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionDoubleUnderscore,PHPCompatibility.FunctionNameRestrictions.ReservedFunctionNames.FunctionDoubleUnderscore
  5966. return false;
  5967. }
  5968. /**
  5969. * Returns 0.
  5970. *
  5971. * Useful for returning 0 to filters easily.
  5972. *
  5973. * @since 3.0.0
  5974. *
  5975. * @return int 0.
  5976. */
  5977. function __return_zero() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionDoubleUnderscore,PHPCompatibility.FunctionNameRestrictions.ReservedFunctionNames.FunctionDoubleUnderscore
  5978. return 0;
  5979. }
  5980. /**
  5981. * Returns an empty array.
  5982. *
  5983. * Useful for returning an empty array to filters easily.
  5984. *
  5985. * @since 3.0.0
  5986. *
  5987. * @return array Empty array.
  5988. */
  5989. function __return_empty_array() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionDoubleUnderscore,PHPCompatibility.FunctionNameRestrictions.ReservedFunctionNames.FunctionDoubleUnderscore
  5990. return array();
  5991. }
  5992. /**
  5993. * Returns null.
  5994. *
  5995. * Useful for returning null to filters easily.
  5996. *
  5997. * @since 3.4.0
  5998. *
  5999. * @return null Null value.
  6000. */
  6001. function __return_null() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionDoubleUnderscore,PHPCompatibility.FunctionNameRestrictions.ReservedFunctionNames.FunctionDoubleUnderscore
  6002. return null;
  6003. }
  6004. /**
  6005. * Returns an empty string.
  6006. *
  6007. * Useful for returning an empty string to filters easily.
  6008. *
  6009. * @since 3.7.0
  6010. *
  6011. * @see __return_null()
  6012. *
  6013. * @return string Empty string.
  6014. */
  6015. function __return_empty_string() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionDoubleUnderscore,PHPCompatibility.FunctionNameRestrictions.ReservedFunctionNames.FunctionDoubleUnderscore
  6016. return '';
  6017. }
  6018. /**
  6019. * Send a HTTP header to disable content type sniffing in browsers which support it.
  6020. *
  6021. * @since 3.0.0
  6022. *
  6023. * @see https://blogs.msdn.com/ie/archive/2008/07/02/ie8-security-part-v-comprehensive-protection.aspx
  6024. * @see https://src.chromium.org/viewvc/chrome?view=rev&revision=6985
  6025. */
  6026. function send_nosniff_header() {
  6027. header( 'X-Content-Type-Options: nosniff' );
  6028. }
  6029. /**
  6030. * Return a MySQL expression for selecting the week number based on the start_of_week option.
  6031. *
  6032. * @ignore
  6033. * @since 3.0.0
  6034. *
  6035. * @param string $column Database column.
  6036. * @return string SQL clause.
  6037. */
  6038. function _wp_mysql_week( $column ) {
  6039. $start_of_week = (int) get_option( 'start_of_week' );
  6040. switch ( $start_of_week ) {
  6041. case 1:
  6042. return "WEEK( $column, 1 )";
  6043. case 2:
  6044. case 3:
  6045. case 4:
  6046. case 5:
  6047. case 6:
  6048. return "WEEK( DATE_SUB( $column, INTERVAL $start_of_week DAY ), 0 )";
  6049. case 0:
  6050. default:
  6051. return "WEEK( $column, 0 )";
  6052. }
  6053. }
  6054. /**
  6055. * Find hierarchy loops using a callback function that maps object IDs to parent IDs.
  6056. *
  6057. * @since 3.1.0
  6058. * @access private
  6059. *
  6060. * @param callable $callback Function that accepts ( ID, $callback_args ) and outputs parent_ID.
  6061. * @param int $start The ID to start the loop check at.
  6062. * @param int $start_parent The parent_ID of $start to use instead of calling $callback( $start ).
  6063. * Use null to always use $callback
  6064. * @param array $callback_args Optional. Additional arguments to send to $callback.
  6065. * @return array IDs of all members of loop.
  6066. */
  6067. function wp_find_hierarchy_loop( $callback, $start, $start_parent, $callback_args = array() ) {
  6068. $override = is_null( $start_parent ) ? array() : array( $start => $start_parent );
  6069. $arbitrary_loop_member = wp_find_hierarchy_loop_tortoise_hare( $callback, $start, $override, $callback_args );
  6070. if ( ! $arbitrary_loop_member ) {
  6071. return array();
  6072. }
  6073. return wp_find_hierarchy_loop_tortoise_hare( $callback, $arbitrary_loop_member, $override, $callback_args, true );
  6074. }
  6075. /**
  6076. * Use the "The Tortoise and the Hare" algorithm to detect loops.
  6077. *
  6078. * For every step of the algorithm, the hare takes two steps and the tortoise one.
  6079. * If the hare ever laps the tortoise, there must be a loop.
  6080. *
  6081. * @since 3.1.0
  6082. * @access private
  6083. *
  6084. * @param callable $callback Function that accepts ( ID, callback_arg, ... ) and outputs parent_ID.
  6085. * @param int $start The ID to start the loop check at.
  6086. * @param array $override Optional. An array of ( ID => parent_ID, ... ) to use instead of $callback.
  6087. * Default empty array.
  6088. * @param array $callback_args Optional. Additional arguments to send to $callback. Default empty array.
  6089. * @param bool $_return_loop Optional. Return loop members or just detect presence of loop? Only set
  6090. * to true if you already know the given $start is part of a loop (otherwise
  6091. * the returned array might include branches). Default false.
  6092. * @return mixed Scalar ID of some arbitrary member of the loop, or array of IDs of all members of loop if
  6093. * $_return_loop
  6094. */
  6095. function wp_find_hierarchy_loop_tortoise_hare( $callback, $start, $override = array(), $callback_args = array(), $_return_loop = false ) {
  6096. $tortoise = $start;
  6097. $hare = $start;
  6098. $evanescent_hare = $start;
  6099. $return = array();
  6100. // Set evanescent_hare to one past hare.
  6101. // Increment hare two steps.
  6102. while (
  6103. $tortoise
  6104. &&
  6105. ( $evanescent_hare = isset( $override[ $hare ] ) ? $override[ $hare ] : call_user_func_array( $callback, array_merge( array( $hare ), $callback_args ) ) )
  6106. &&
  6107. ( $hare = isset( $override[ $evanescent_hare ] ) ? $override[ $evanescent_hare ] : call_user_func_array( $callback, array_merge( array( $evanescent_hare ), $callback_args ) ) )
  6108. ) {
  6109. if ( $_return_loop ) {
  6110. $return[ $tortoise ] = true;
  6111. $return[ $evanescent_hare ] = true;
  6112. $return[ $hare ] = true;
  6113. }
  6114. // Tortoise got lapped - must be a loop.
  6115. if ( $tortoise == $evanescent_hare || $tortoise == $hare ) {
  6116. return $_return_loop ? $return : $tortoise;
  6117. }
  6118. // Increment tortoise by one step.
  6119. $tortoise = isset( $override[ $tortoise ] ) ? $override[ $tortoise ] : call_user_func_array( $callback, array_merge( array( $tortoise ), $callback_args ) );
  6120. }
  6121. return false;
  6122. }
  6123. /**
  6124. * Send a HTTP header to limit rendering of pages to same origin iframes.
  6125. *
  6126. * @since 3.1.3
  6127. *
  6128. * @see https://developer.mozilla.org/en/the_x-frame-options_response_header
  6129. */
  6130. function send_frame_options_header() {
  6131. header( 'X-Frame-Options: SAMEORIGIN' );
  6132. }
  6133. /**
  6134. * Retrieve a list of protocols to allow in HTML attributes.
  6135. *
  6136. * @since 3.3.0
  6137. * @since 4.3.0 Added 'webcal' to the protocols array.
  6138. * @since 4.7.0 Added 'urn' to the protocols array.
  6139. * @since 5.3.0 Added 'sms' to the protocols array.
  6140. * @since 5.6.0 Added 'irc6' and 'ircs' to the protocols array.
  6141. *
  6142. * @see wp_kses()
  6143. * @see esc_url()
  6144. *
  6145. * @return string[] Array of allowed protocols. Defaults to an array containing 'http', 'https',
  6146. * 'ftp', 'ftps', 'mailto', 'news', 'irc', 'irc6', 'ircs', 'gopher', 'nntp', 'feed',
  6147. * 'telnet', 'mms', 'rtsp', 'sms', 'svn', 'tel', 'fax', 'xmpp', 'webcal', and 'urn'.
  6148. * This covers all common link protocols, except for 'javascript' which should not
  6149. * be allowed for untrusted users.
  6150. */
  6151. function wp_allowed_protocols() {
  6152. static $protocols = array();
  6153. if ( empty( $protocols ) ) {
  6154. $protocols = array( 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'irc6', 'ircs', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'sms', 'svn', 'tel', 'fax', 'xmpp', 'webcal', 'urn' );
  6155. }
  6156. if ( ! did_action( 'wp_loaded' ) ) {
  6157. /**
  6158. * Filters the list of protocols allowed in HTML attributes.
  6159. *
  6160. * @since 3.0.0
  6161. *
  6162. * @param string[] $protocols Array of allowed protocols e.g. 'http', 'ftp', 'tel', and more.
  6163. */
  6164. $protocols = array_unique( (array) apply_filters( 'kses_allowed_protocols', $protocols ) );
  6165. }
  6166. return $protocols;
  6167. }
  6168. /**
  6169. * Return a comma-separated string of functions that have been called to get
  6170. * to the current point in code.
  6171. *
  6172. * @since 3.4.0
  6173. *
  6174. * @see https://core.trac.wordpress.org/ticket/19589
  6175. *
  6176. * @param string $ignore_class Optional. A class to ignore all function calls within - useful
  6177. * when you want to just give info about the callee. Default null.
  6178. * @param int $skip_frames Optional. A number of stack frames to skip - useful for unwinding
  6179. * back to the source of the issue. Default 0.
  6180. * @param bool $pretty Optional. Whether or not you want a comma separated string or raw
  6181. * array returned. Default true.
  6182. * @return string|array Either a string containing a reversed comma separated trace or an array
  6183. * of individual calls.
  6184. */
  6185. function wp_debug_backtrace_summary( $ignore_class = null, $skip_frames = 0, $pretty = true ) {
  6186. static $truncate_paths;
  6187. $trace = debug_backtrace( false );
  6188. $caller = array();
  6189. $check_class = ! is_null( $ignore_class );
  6190. $skip_frames++; // Skip this function.
  6191. if ( ! isset( $truncate_paths ) ) {
  6192. $truncate_paths = array(
  6193. wp_normalize_path( WP_CONTENT_DIR ),
  6194. wp_normalize_path( ABSPATH ),
  6195. );
  6196. }
  6197. foreach ( $trace as $call ) {
  6198. if ( $skip_frames > 0 ) {
  6199. $skip_frames--;
  6200. } elseif ( isset( $call['class'] ) ) {
  6201. if ( $check_class && $ignore_class == $call['class'] ) {
  6202. continue; // Filter out calls.
  6203. }
  6204. $caller[] = "{$call['class']}{$call['type']}{$call['function']}";
  6205. } else {
  6206. if ( in_array( $call['function'], array( 'do_action', 'apply_filters', 'do_action_ref_array', 'apply_filters_ref_array' ), true ) ) {
  6207. $caller[] = "{$call['function']}('{$call['args'][0]}')";
  6208. } elseif ( in_array( $call['function'], array( 'include', 'include_once', 'require', 'require_once' ), true ) ) {
  6209. $filename = isset( $call['args'][0] ) ? $call['args'][0] : '';
  6210. $caller[] = $call['function'] . "('" . str_replace( $truncate_paths, '', wp_normalize_path( $filename ) ) . "')";
  6211. } else {
  6212. $caller[] = $call['function'];
  6213. }
  6214. }
  6215. }
  6216. if ( $pretty ) {
  6217. return implode( ', ', array_reverse( $caller ) );
  6218. } else {
  6219. return $caller;
  6220. }
  6221. }
  6222. /**
  6223. * Retrieve IDs that are not already present in the cache.
  6224. *
  6225. * @since 3.4.0
  6226. * @access private
  6227. *
  6228. * @param int[] $object_ids Array of IDs.
  6229. * @param string $cache_key The cache bucket to check against.
  6230. * @return int[] Array of IDs not present in the cache.
  6231. */
  6232. function _get_non_cached_ids( $object_ids, $cache_key ) {
  6233. $non_cached_ids = array();
  6234. $cache_values = wp_cache_get_multiple( $object_ids, $cache_key );
  6235. foreach ( $cache_values as $id => $value ) {
  6236. if ( ! $value ) {
  6237. $non_cached_ids[] = (int) $id;
  6238. }
  6239. }
  6240. return $non_cached_ids;
  6241. }
  6242. /**
  6243. * Test if the current device has the capability to upload files.
  6244. *
  6245. * @since 3.4.0
  6246. * @access private
  6247. *
  6248. * @return bool Whether the device is able to upload files.
  6249. */
  6250. function _device_can_upload() {
  6251. if ( ! wp_is_mobile() ) {
  6252. return true;
  6253. }
  6254. $ua = $_SERVER['HTTP_USER_AGENT'];
  6255. if ( strpos( $ua, 'iPhone' ) !== false
  6256. || strpos( $ua, 'iPad' ) !== false
  6257. || strpos( $ua, 'iPod' ) !== false ) {
  6258. return preg_match( '#OS ([\d_]+) like Mac OS X#', $ua, $version ) && version_compare( $version[1], '6', '>=' );
  6259. }
  6260. return true;
  6261. }
  6262. /**
  6263. * Test if a given path is a stream URL
  6264. *
  6265. * @since 3.5.0
  6266. *
  6267. * @param string $path The resource path or URL.
  6268. * @return bool True if the path is a stream URL.
  6269. */
  6270. function wp_is_stream( $path ) {
  6271. $scheme_separator = strpos( $path, '://' );
  6272. if ( false === $scheme_separator ) {
  6273. // $path isn't a stream.
  6274. return false;
  6275. }
  6276. $stream = substr( $path, 0, $scheme_separator );
  6277. return in_array( $stream, stream_get_wrappers(), true );
  6278. }
  6279. /**
  6280. * Test if the supplied date is valid for the Gregorian calendar.
  6281. *
  6282. * @since 3.5.0
  6283. *
  6284. * @link https://www.php.net/manual/en/function.checkdate.php
  6285. *
  6286. * @param int $month Month number.
  6287. * @param int $day Day number.
  6288. * @param int $year Year number.
  6289. * @param string $source_date The date to filter.
  6290. * @return bool True if valid date, false if not valid date.
  6291. */
  6292. function wp_checkdate( $month, $day, $year, $source_date ) {
  6293. /**
  6294. * Filters whether the given date is valid for the Gregorian calendar.
  6295. *
  6296. * @since 3.5.0
  6297. *
  6298. * @param bool $checkdate Whether the given date is valid.
  6299. * @param string $source_date Date to check.
  6300. */
  6301. return apply_filters( 'wp_checkdate', checkdate( $month, $day, $year ), $source_date );
  6302. }
  6303. /**
  6304. * Load the auth check for monitoring whether the user is still logged in.
  6305. *
  6306. * Can be disabled with remove_action( 'admin_enqueue_scripts', 'wp_auth_check_load' );
  6307. *
  6308. * This is disabled for certain screens where a login screen could cause an
  6309. * inconvenient interruption. A filter called {@see 'wp_auth_check_load'} can be used
  6310. * for fine-grained control.
  6311. *
  6312. * @since 3.6.0
  6313. */
  6314. function wp_auth_check_load() {
  6315. if ( ! is_admin() && ! is_user_logged_in() ) {
  6316. return;
  6317. }
  6318. if ( defined( 'IFRAME_REQUEST' ) ) {
  6319. return;
  6320. }
  6321. $screen = get_current_screen();
  6322. $hidden = array( 'update', 'update-network', 'update-core', 'update-core-network', 'upgrade', 'upgrade-network', 'network' );
  6323. $show = ! in_array( $screen->id, $hidden, true );
  6324. /**
  6325. * Filters whether to load the authentication check.
  6326. *
  6327. * Returning a falsey value from the filter will effectively short-circuit
  6328. * loading the authentication check.
  6329. *
  6330. * @since 3.6.0
  6331. *
  6332. * @param bool $show Whether to load the authentication check.
  6333. * @param WP_Screen $screen The current screen object.
  6334. */
  6335. if ( apply_filters( 'wp_auth_check_load', $show, $screen ) ) {
  6336. wp_enqueue_style( 'wp-auth-check' );
  6337. wp_enqueue_script( 'wp-auth-check' );
  6338. add_action( 'admin_print_footer_scripts', 'wp_auth_check_html', 5 );
  6339. add_action( 'wp_print_footer_scripts', 'wp_auth_check_html', 5 );
  6340. }
  6341. }
  6342. /**
  6343. * Output the HTML that shows the wp-login dialog when the user is no longer logged in.
  6344. *
  6345. * @since 3.6.0
  6346. */
  6347. function wp_auth_check_html() {
  6348. $login_url = wp_login_url();
  6349. $current_domain = ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'];
  6350. $same_domain = ( strpos( $login_url, $current_domain ) === 0 );
  6351. /**
  6352. * Filters whether the authentication check originated at the same domain.
  6353. *
  6354. * @since 3.6.0
  6355. *
  6356. * @param bool $same_domain Whether the authentication check originated at the same domain.
  6357. */
  6358. $same_domain = apply_filters( 'wp_auth_check_same_domain', $same_domain );
  6359. $wrap_class = $same_domain ? 'hidden' : 'hidden fallback';
  6360. ?>
  6361. <div id="wp-auth-check-wrap" class="<?php echo $wrap_class; ?>">
  6362. <div id="wp-auth-check-bg"></div>
  6363. <div id="wp-auth-check">
  6364. <button type="button" class="wp-auth-check-close button-link"><span class="screen-reader-text"><?php _e( 'Close dialog' ); ?></span></button>
  6365. <?php
  6366. if ( $same_domain ) {
  6367. $login_src = add_query_arg(
  6368. array(
  6369. 'interim-login' => '1',
  6370. 'wp_lang' => get_user_locale(),
  6371. ),
  6372. $login_url
  6373. );
  6374. ?>
  6375. <div id="wp-auth-check-form" class="loading" data-src="<?php echo esc_url( $login_src ); ?>"></div>
  6376. <?php
  6377. }
  6378. ?>
  6379. <div class="wp-auth-fallback">
  6380. <p><b class="wp-auth-fallback-expired" tabindex="0"><?php _e( 'Session expired' ); ?></b></p>
  6381. <p><a href="<?php echo esc_url( $login_url ); ?>" target="_blank"><?php _e( 'Please log in again.' ); ?></a>
  6382. <?php _e( 'The login page will open in a new tab. After logging in you can close it and return to this page.' ); ?></p>
  6383. </div>
  6384. </div>
  6385. </div>
  6386. <?php
  6387. }
  6388. /**
  6389. * Check whether a user is still logged in, for the heartbeat.
  6390. *
  6391. * Send a result that shows a log-in box if the user is no longer logged in,
  6392. * or if their cookie is within the grace period.
  6393. *
  6394. * @since 3.6.0
  6395. *
  6396. * @global int $login_grace_period
  6397. *
  6398. * @param array $response The Heartbeat response.
  6399. * @return array The Heartbeat response with 'wp-auth-check' value set.
  6400. */
  6401. function wp_auth_check( $response ) {
  6402. $response['wp-auth-check'] = is_user_logged_in() && empty( $GLOBALS['login_grace_period'] );
  6403. return $response;
  6404. }
  6405. /**
  6406. * Return RegEx body to liberally match an opening HTML tag.
  6407. *
  6408. * Matches an opening HTML tag that:
  6409. * 1. Is self-closing or
  6410. * 2. Has no body but has a closing tag of the same name or
  6411. * 3. Contains a body and a closing tag of the same name
  6412. *
  6413. * Note: this RegEx does not balance inner tags and does not attempt
  6414. * to produce valid HTML
  6415. *
  6416. * @since 3.6.0
  6417. *
  6418. * @param string $tag An HTML tag name. Example: 'video'.
  6419. * @return string Tag RegEx.
  6420. */
  6421. function get_tag_regex( $tag ) {
  6422. if ( empty( $tag ) ) {
  6423. return '';
  6424. }
  6425. return sprintf( '<%1$s[^<]*(?:>[\s\S]*<\/%1$s>|\s*\/>)', tag_escape( $tag ) );
  6426. }
  6427. /**
  6428. * Retrieve a canonical form of the provided charset appropriate for passing to PHP
  6429. * functions such as htmlspecialchars() and charset HTML attributes.
  6430. *
  6431. * @since 3.6.0
  6432. * @access private
  6433. *
  6434. * @see https://core.trac.wordpress.org/ticket/23688
  6435. *
  6436. * @param string $charset A charset name.
  6437. * @return string The canonical form of the charset.
  6438. */
  6439. function _canonical_charset( $charset ) {
  6440. if ( 'utf-8' === strtolower( $charset ) || 'utf8' === strtolower( $charset ) ) {
  6441. return 'UTF-8';
  6442. }
  6443. if ( 'iso-8859-1' === strtolower( $charset ) || 'iso8859-1' === strtolower( $charset ) ) {
  6444. return 'ISO-8859-1';
  6445. }
  6446. return $charset;
  6447. }
  6448. /**
  6449. * Set the mbstring internal encoding to a binary safe encoding when func_overload
  6450. * is enabled.
  6451. *
  6452. * When mbstring.func_overload is in use for multi-byte encodings, the results from
  6453. * strlen() and similar functions respect the utf8 characters, causing binary data
  6454. * to return incorrect lengths.
  6455. *
  6456. * This function overrides the mbstring encoding to a binary-safe encoding, and
  6457. * resets it to the users expected encoding afterwards through the
  6458. * `reset_mbstring_encoding` function.
  6459. *
  6460. * It is safe to recursively call this function, however each
  6461. * `mbstring_binary_safe_encoding()` call must be followed up with an equal number
  6462. * of `reset_mbstring_encoding()` calls.
  6463. *
  6464. * @since 3.7.0
  6465. *
  6466. * @see reset_mbstring_encoding()
  6467. *
  6468. * @param bool $reset Optional. Whether to reset the encoding back to a previously-set encoding.
  6469. * Default false.
  6470. */
  6471. function mbstring_binary_safe_encoding( $reset = false ) {
  6472. static $encodings = array();
  6473. static $overloaded = null;
  6474. if ( is_null( $overloaded ) ) {
  6475. if ( function_exists( 'mb_internal_encoding' )
  6476. && ( (int) ini_get( 'mbstring.func_overload' ) & 2 ) // phpcs:ignore PHPCompatibility.IniDirectives.RemovedIniDirectives.mbstring_func_overloadDeprecated
  6477. ) {
  6478. $overloaded = true;
  6479. } else {
  6480. $overloaded = false;
  6481. }
  6482. }
  6483. if ( false === $overloaded ) {
  6484. return;
  6485. }
  6486. if ( ! $reset ) {
  6487. $encoding = mb_internal_encoding();
  6488. array_push( $encodings, $encoding );
  6489. mb_internal_encoding( 'ISO-8859-1' );
  6490. }
  6491. if ( $reset && $encodings ) {
  6492. $encoding = array_pop( $encodings );
  6493. mb_internal_encoding( $encoding );
  6494. }
  6495. }
  6496. /**
  6497. * Reset the mbstring internal encoding to a users previously set encoding.
  6498. *
  6499. * @see mbstring_binary_safe_encoding()
  6500. *
  6501. * @since 3.7.0
  6502. */
  6503. function reset_mbstring_encoding() {
  6504. mbstring_binary_safe_encoding( true );
  6505. }
  6506. /**
  6507. * Filter/validate a variable as a boolean.
  6508. *
  6509. * Alternative to `filter_var( $var, FILTER_VALIDATE_BOOLEAN )`.
  6510. *
  6511. * @since 4.0.0
  6512. *
  6513. * @param mixed $var Boolean value to validate.
  6514. * @return bool Whether the value is validated.
  6515. */
  6516. function wp_validate_boolean( $var ) {
  6517. if ( is_bool( $var ) ) {
  6518. return $var;
  6519. }
  6520. if ( is_string( $var ) && 'false' === strtolower( $var ) ) {
  6521. return false;
  6522. }
  6523. return (bool) $var;
  6524. }
  6525. /**
  6526. * Delete a file
  6527. *
  6528. * @since 4.2.0
  6529. *
  6530. * @param string $file The path to the file to delete.
  6531. */
  6532. function wp_delete_file( $file ) {
  6533. /**
  6534. * Filters the path of the file to delete.
  6535. *
  6536. * @since 2.1.0
  6537. *
  6538. * @param string $file Path to the file to delete.
  6539. */
  6540. $delete = apply_filters( 'wp_delete_file', $file );
  6541. if ( ! empty( $delete ) ) {
  6542. @unlink( $delete );
  6543. }
  6544. }
  6545. /**
  6546. * Deletes a file if its path is within the given directory.
  6547. *
  6548. * @since 4.9.7
  6549. *
  6550. * @param string $file Absolute path to the file to delete.
  6551. * @param string $directory Absolute path to a directory.
  6552. * @return bool True on success, false on failure.
  6553. */
  6554. function wp_delete_file_from_directory( $file, $directory ) {
  6555. if ( wp_is_stream( $file ) ) {
  6556. $real_file = $file;
  6557. $real_directory = $directory;
  6558. } else {
  6559. $real_file = realpath( wp_normalize_path( $file ) );
  6560. $real_directory = realpath( wp_normalize_path( $directory ) );
  6561. }
  6562. if ( false !== $real_file ) {
  6563. $real_file = wp_normalize_path( $real_file );
  6564. }
  6565. if ( false !== $real_directory ) {
  6566. $real_directory = wp_normalize_path( $real_directory );
  6567. }
  6568. if ( false === $real_file || false === $real_directory || strpos( $real_file, trailingslashit( $real_directory ) ) !== 0 ) {
  6569. return false;
  6570. }
  6571. wp_delete_file( $file );
  6572. return true;
  6573. }
  6574. /**
  6575. * Outputs a small JS snippet on preview tabs/windows to remove `window.name` on unload.
  6576. *
  6577. * This prevents reusing the same tab for a preview when the user has navigated away.
  6578. *
  6579. * @since 4.3.0
  6580. *
  6581. * @global WP_Post $post Global post object.
  6582. */
  6583. function wp_post_preview_js() {
  6584. global $post;
  6585. if ( ! is_preview() || empty( $post ) ) {
  6586. return;
  6587. }
  6588. // Has to match the window name used in post_submit_meta_box().
  6589. $name = 'wp-preview-' . (int) $post->ID;
  6590. ?>
  6591. <script>
  6592. ( function() {
  6593. var query = document.location.search;
  6594. if ( query && query.indexOf( 'preview=true' ) !== -1 ) {
  6595. window.name = '<?php echo $name; ?>';
  6596. }
  6597. if ( window.addEventListener ) {
  6598. window.addEventListener( 'unload', function() { window.name = ''; }, false );
  6599. }
  6600. }());
  6601. </script>
  6602. <?php
  6603. }
  6604. /**
  6605. * Parses and formats a MySQL datetime (Y-m-d H:i:s) for ISO8601 (Y-m-d\TH:i:s).
  6606. *
  6607. * Explicitly strips timezones, as datetimes are not saved with any timezone
  6608. * information. Including any information on the offset could be misleading.
  6609. *
  6610. * Despite historical function name, the output does not conform to RFC3339 format,
  6611. * which must contain timezone.
  6612. *
  6613. * @since 4.4.0
  6614. *
  6615. * @param string $date_string Date string to parse and format.
  6616. * @return string Date formatted for ISO8601 without time zone.
  6617. */
  6618. function mysql_to_rfc3339( $date_string ) {
  6619. return mysql2date( 'Y-m-d\TH:i:s', $date_string, false );
  6620. }
  6621. /**
  6622. * Attempts to raise the PHP memory limit for memory intensive processes.
  6623. *
  6624. * Only allows raising the existing limit and prevents lowering it.
  6625. *
  6626. * @since 4.6.0
  6627. *
  6628. * @param string $context Optional. Context in which the function is called. Accepts either 'admin',
  6629. * 'image', or an arbitrary other context. If an arbitrary context is passed,
  6630. * the similarly arbitrary {@see '$context_memory_limit'} filter will be
  6631. * invoked. Default 'admin'.
  6632. * @return int|string|false The limit that was set or false on failure.
  6633. */
  6634. function wp_raise_memory_limit( $context = 'admin' ) {
  6635. // Exit early if the limit cannot be changed.
  6636. if ( false === wp_is_ini_value_changeable( 'memory_limit' ) ) {
  6637. return false;
  6638. }
  6639. $current_limit = ini_get( 'memory_limit' );
  6640. $current_limit_int = wp_convert_hr_to_bytes( $current_limit );
  6641. if ( -1 === $current_limit_int ) {
  6642. return false;
  6643. }
  6644. $wp_max_limit = WP_MAX_MEMORY_LIMIT;
  6645. $wp_max_limit_int = wp_convert_hr_to_bytes( $wp_max_limit );
  6646. $filtered_limit = $wp_max_limit;
  6647. switch ( $context ) {
  6648. case 'admin':
  6649. /**
  6650. * Filters the maximum memory limit available for administration screens.
  6651. *
  6652. * This only applies to administrators, who may require more memory for tasks
  6653. * like updates. Memory limits when processing images (uploaded or edited by
  6654. * users of any role) are handled separately.
  6655. *
  6656. * The `WP_MAX_MEMORY_LIMIT` constant specifically defines the maximum memory
  6657. * limit available when in the administration back end. The default is 256M
  6658. * (256 megabytes of memory) or the original `memory_limit` php.ini value if
  6659. * this is higher.
  6660. *
  6661. * @since 3.0.0
  6662. * @since 4.6.0 The default now takes the original `memory_limit` into account.
  6663. *
  6664. * @param int|string $filtered_limit The maximum WordPress memory limit. Accepts an integer
  6665. * (bytes), or a shorthand string notation, such as '256M'.
  6666. */
  6667. $filtered_limit = apply_filters( 'admin_memory_limit', $filtered_limit );
  6668. break;
  6669. case 'image':
  6670. /**
  6671. * Filters the memory limit allocated for image manipulation.
  6672. *
  6673. * @since 3.5.0
  6674. * @since 4.6.0 The default now takes the original `memory_limit` into account.
  6675. *
  6676. * @param int|string $filtered_limit Maximum memory limit to allocate for images.
  6677. * Default `WP_MAX_MEMORY_LIMIT` or the original
  6678. * php.ini `memory_limit`, whichever is higher.
  6679. * Accepts an integer (bytes), or a shorthand string
  6680. * notation, such as '256M'.
  6681. */
  6682. $filtered_limit = apply_filters( 'image_memory_limit', $filtered_limit );
  6683. break;
  6684. default:
  6685. /**
  6686. * Filters the memory limit allocated for arbitrary contexts.
  6687. *
  6688. * The dynamic portion of the hook name, `$context`, refers to an arbitrary
  6689. * context passed on calling the function. This allows for plugins to define
  6690. * their own contexts for raising the memory limit.
  6691. *
  6692. * @since 4.6.0
  6693. *
  6694. * @param int|string $filtered_limit Maximum memory limit to allocate for images.
  6695. * Default '256M' or the original php.ini `memory_limit`,
  6696. * whichever is higher. Accepts an integer (bytes), or a
  6697. * shorthand string notation, such as '256M'.
  6698. */
  6699. $filtered_limit = apply_filters( "{$context}_memory_limit", $filtered_limit );
  6700. break;
  6701. }
  6702. $filtered_limit_int = wp_convert_hr_to_bytes( $filtered_limit );
  6703. if ( -1 === $filtered_limit_int || ( $filtered_limit_int > $wp_max_limit_int && $filtered_limit_int > $current_limit_int ) ) {
  6704. if ( false !== ini_set( 'memory_limit', $filtered_limit ) ) {
  6705. return $filtered_limit;
  6706. } else {
  6707. return false;
  6708. }
  6709. } elseif ( -1 === $wp_max_limit_int || $wp_max_limit_int > $current_limit_int ) {
  6710. if ( false !== ini_set( 'memory_limit', $wp_max_limit ) ) {
  6711. return $wp_max_limit;
  6712. } else {
  6713. return false;
  6714. }
  6715. }
  6716. return false;
  6717. }
  6718. /**
  6719. * Generate a random UUID (version 4).
  6720. *
  6721. * @since 4.7.0
  6722. *
  6723. * @return string UUID.
  6724. */
  6725. function wp_generate_uuid4() {
  6726. return sprintf(
  6727. '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
  6728. mt_rand( 0, 0xffff ),
  6729. mt_rand( 0, 0xffff ),
  6730. mt_rand( 0, 0xffff ),
  6731. mt_rand( 0, 0x0fff ) | 0x4000,
  6732. mt_rand( 0, 0x3fff ) | 0x8000,
  6733. mt_rand( 0, 0xffff ),
  6734. mt_rand( 0, 0xffff ),
  6735. mt_rand( 0, 0xffff )
  6736. );
  6737. }
  6738. /**
  6739. * Validates that a UUID is valid.
  6740. *
  6741. * @since 4.9.0
  6742. *
  6743. * @param mixed $uuid UUID to check.
  6744. * @param int $version Specify which version of UUID to check against. Default is none,
  6745. * to accept any UUID version. Otherwise, only version allowed is `4`.
  6746. * @return bool The string is a valid UUID or false on failure.
  6747. */
  6748. function wp_is_uuid( $uuid, $version = null ) {
  6749. if ( ! is_string( $uuid ) ) {
  6750. return false;
  6751. }
  6752. if ( is_numeric( $version ) ) {
  6753. if ( 4 !== (int) $version ) {
  6754. _doing_it_wrong( __FUNCTION__, __( 'Only UUID V4 is supported at this time.' ), '4.9.0' );
  6755. return false;
  6756. }
  6757. $regex = '/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/';
  6758. } else {
  6759. $regex = '/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/';
  6760. }
  6761. return (bool) preg_match( $regex, $uuid );
  6762. }
  6763. /**
  6764. * Gets unique ID.
  6765. *
  6766. * This is a PHP implementation of Underscore's uniqueId method. A static variable
  6767. * contains an integer that is incremented with each call. This number is returned
  6768. * with the optional prefix. As such the returned value is not universally unique,
  6769. * but it is unique across the life of the PHP process.
  6770. *
  6771. * @since 5.0.3
  6772. *
  6773. * @param string $prefix Prefix for the returned ID.
  6774. * @return string Unique ID.
  6775. */
  6776. function wp_unique_id( $prefix = '' ) {
  6777. static $id_counter = 0;
  6778. return $prefix . (string) ++$id_counter;
  6779. }
  6780. /**
  6781. * Gets last changed date for the specified cache group.
  6782. *
  6783. * @since 4.7.0
  6784. *
  6785. * @param string $group Where the cache contents are grouped.
  6786. * @return string UNIX timestamp with microseconds representing when the group was last changed.
  6787. */
  6788. function wp_cache_get_last_changed( $group ) {
  6789. $last_changed = wp_cache_get( 'last_changed', $group );
  6790. if ( ! $last_changed ) {
  6791. $last_changed = microtime();
  6792. wp_cache_set( 'last_changed', $last_changed, $group );
  6793. }
  6794. return $last_changed;
  6795. }
  6796. /**
  6797. * Send an email to the old site admin email address when the site admin email address changes.
  6798. *
  6799. * @since 4.9.0
  6800. *
  6801. * @param string $old_email The old site admin email address.
  6802. * @param string $new_email The new site admin email address.
  6803. * @param string $option_name The relevant database option name.
  6804. */
  6805. function wp_site_admin_email_change_notification( $old_email, $new_email, $option_name ) {
  6806. $send = true;
  6807. // Don't send the notification to the default 'admin_email' value.
  6808. if ( 'you@example.com' === $old_email ) {
  6809. $send = false;
  6810. }
  6811. /**
  6812. * Filters whether to send the site admin email change notification email.
  6813. *
  6814. * @since 4.9.0
  6815. *
  6816. * @param bool $send Whether to send the email notification.
  6817. * @param string $old_email The old site admin email address.
  6818. * @param string $new_email The new site admin email address.
  6819. */
  6820. $send = apply_filters( 'send_site_admin_email_change_email', $send, $old_email, $new_email );
  6821. if ( ! $send ) {
  6822. return;
  6823. }
  6824. /* translators: Do not translate OLD_EMAIL, NEW_EMAIL, SITENAME, SITEURL: those are placeholders. */
  6825. $email_change_text = __(
  6826. 'Hi,
  6827. This notice confirms that the admin email address was changed on ###SITENAME###.
  6828. The new admin email address is ###NEW_EMAIL###.
  6829. This email has been sent to ###OLD_EMAIL###
  6830. Regards,
  6831. All at ###SITENAME###
  6832. ###SITEURL###'
  6833. );
  6834. $email_change_email = array(
  6835. 'to' => $old_email,
  6836. /* translators: Site admin email change notification email subject. %s: Site title. */
  6837. 'subject' => __( '[%s] Admin Email Changed' ),
  6838. 'message' => $email_change_text,
  6839. 'headers' => '',
  6840. );
  6841. // Get site name.
  6842. $site_name = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
  6843. /**
  6844. * Filters the contents of the email notification sent when the site admin email address is changed.
  6845. *
  6846. * @since 4.9.0
  6847. *
  6848. * @param array $email_change_email {
  6849. * Used to build wp_mail().
  6850. *
  6851. * @type string $to The intended recipient.
  6852. * @type string $subject The subject of the email.
  6853. * @type string $message The content of the email.
  6854. * The following strings have a special meaning and will get replaced dynamically:
  6855. * - ###OLD_EMAIL### The old site admin email address.
  6856. * - ###NEW_EMAIL### The new site admin email address.
  6857. * - ###SITENAME### The name of the site.
  6858. * - ###SITEURL### The URL to the site.
  6859. * @type string $headers Headers.
  6860. * }
  6861. * @param string $old_email The old site admin email address.
  6862. * @param string $new_email The new site admin email address.
  6863. */
  6864. $email_change_email = apply_filters( 'site_admin_email_change_email', $email_change_email, $old_email, $new_email );
  6865. $email_change_email['message'] = str_replace( '###OLD_EMAIL###', $old_email, $email_change_email['message'] );
  6866. $email_change_email['message'] = str_replace( '###NEW_EMAIL###', $new_email, $email_change_email['message'] );
  6867. $email_change_email['message'] = str_replace( '###SITENAME###', $site_name, $email_change_email['message'] );
  6868. $email_change_email['message'] = str_replace( '###SITEURL###', home_url(), $email_change_email['message'] );
  6869. wp_mail(
  6870. $email_change_email['to'],
  6871. sprintf(
  6872. $email_change_email['subject'],
  6873. $site_name
  6874. ),
  6875. $email_change_email['message'],
  6876. $email_change_email['headers']
  6877. );
  6878. }
  6879. /**
  6880. * Return an anonymized IPv4 or IPv6 address.
  6881. *
  6882. * @since 4.9.6 Abstracted from `WP_Community_Events::get_unsafe_client_ip()`.
  6883. *
  6884. * @param string $ip_addr The IPv4 or IPv6 address to be anonymized.
  6885. * @param bool $ipv6_fallback Optional. Whether to return the original IPv6 address if the needed functions
  6886. * to anonymize it are not present. Default false, return `::` (unspecified address).
  6887. * @return string The anonymized IP address.
  6888. */
  6889. function wp_privacy_anonymize_ip( $ip_addr, $ipv6_fallback = false ) {
  6890. if ( empty( $ip_addr ) ) {
  6891. return '0.0.0.0';
  6892. }
  6893. // Detect what kind of IP address this is.
  6894. $ip_prefix = '';
  6895. $is_ipv6 = substr_count( $ip_addr, ':' ) > 1;
  6896. $is_ipv4 = ( 3 === substr_count( $ip_addr, '.' ) );
  6897. if ( $is_ipv6 && $is_ipv4 ) {
  6898. // IPv6 compatibility mode, temporarily strip the IPv6 part, and treat it like IPv4.
  6899. $ip_prefix = '::ffff:';
  6900. $ip_addr = preg_replace( '/^\[?[0-9a-f:]*:/i', '', $ip_addr );
  6901. $ip_addr = str_replace( ']', '', $ip_addr );
  6902. $is_ipv6 = false;
  6903. }
  6904. if ( $is_ipv6 ) {
  6905. // IPv6 addresses will always be enclosed in [] if there's a port.
  6906. $left_bracket = strpos( $ip_addr, '[' );
  6907. $right_bracket = strpos( $ip_addr, ']' );
  6908. $percent = strpos( $ip_addr, '%' );
  6909. $netmask = 'ffff:ffff:ffff:ffff:0000:0000:0000:0000';
  6910. // Strip the port (and [] from IPv6 addresses), if they exist.
  6911. if ( false !== $left_bracket && false !== $right_bracket ) {
  6912. $ip_addr = substr( $ip_addr, $left_bracket + 1, $right_bracket - $left_bracket - 1 );
  6913. } elseif ( false !== $left_bracket || false !== $right_bracket ) {
  6914. // The IP has one bracket, but not both, so it's malformed.
  6915. return '::';
  6916. }
  6917. // Strip the reachability scope.
  6918. if ( false !== $percent ) {
  6919. $ip_addr = substr( $ip_addr, 0, $percent );
  6920. }
  6921. // No invalid characters should be left.
  6922. if ( preg_match( '/[^0-9a-f:]/i', $ip_addr ) ) {
  6923. return '::';
  6924. }
  6925. // Partially anonymize the IP by reducing it to the corresponding network ID.
  6926. if ( function_exists( 'inet_pton' ) && function_exists( 'inet_ntop' ) ) {
  6927. $ip_addr = inet_ntop( inet_pton( $ip_addr ) & inet_pton( $netmask ) );
  6928. if ( false === $ip_addr ) {
  6929. return '::';
  6930. }
  6931. } elseif ( ! $ipv6_fallback ) {
  6932. return '::';
  6933. }
  6934. } elseif ( $is_ipv4 ) {
  6935. // Strip any port and partially anonymize the IP.
  6936. $last_octet_position = strrpos( $ip_addr, '.' );
  6937. $ip_addr = substr( $ip_addr, 0, $last_octet_position ) . '.0';
  6938. } else {
  6939. return '0.0.0.0';
  6940. }
  6941. // Restore the IPv6 prefix to compatibility mode addresses.
  6942. return $ip_prefix . $ip_addr;
  6943. }
  6944. /**
  6945. * Return uniform "anonymous" data by type.
  6946. *
  6947. * @since 4.9.6
  6948. *
  6949. * @param string $type The type of data to be anonymized.
  6950. * @param string $data Optional The data to be anonymized.
  6951. * @return string The anonymous data for the requested type.
  6952. */
  6953. function wp_privacy_anonymize_data( $type, $data = '' ) {
  6954. switch ( $type ) {
  6955. case 'email':
  6956. $anonymous = 'deleted@site.invalid';
  6957. break;
  6958. case 'url':
  6959. $anonymous = 'https://site.invalid';
  6960. break;
  6961. case 'ip':
  6962. $anonymous = wp_privacy_anonymize_ip( $data );
  6963. break;
  6964. case 'date':
  6965. $anonymous = '0000-00-00 00:00:00';
  6966. break;
  6967. case 'text':
  6968. /* translators: Deleted text. */
  6969. $anonymous = __( '[deleted]' );
  6970. break;
  6971. case 'longtext':
  6972. /* translators: Deleted long text. */
  6973. $anonymous = __( 'This content was deleted by the author.' );
  6974. break;
  6975. default:
  6976. $anonymous = '';
  6977. break;
  6978. }
  6979. /**
  6980. * Filters the anonymous data for each type.
  6981. *
  6982. * @since 4.9.6
  6983. *
  6984. * @param string $anonymous Anonymized data.
  6985. * @param string $type Type of the data.
  6986. * @param string $data Original data.
  6987. */
  6988. return apply_filters( 'wp_privacy_anonymize_data', $anonymous, $type, $data );
  6989. }
  6990. /**
  6991. * Returns the directory used to store personal data export files.
  6992. *
  6993. * @since 4.9.6
  6994. *
  6995. * @see wp_privacy_exports_url
  6996. *
  6997. * @return string Exports directory.
  6998. */
  6999. function wp_privacy_exports_dir() {
  7000. $upload_dir = wp_upload_dir();
  7001. $exports_dir = trailingslashit( $upload_dir['basedir'] ) . 'wp-personal-data-exports/';
  7002. /**
  7003. * Filters the directory used to store personal data export files.
  7004. *
  7005. * @since 4.9.6
  7006. * @since 5.5.0 Exports now use relative paths, so changes to the directory
  7007. * via this filter should be reflected on the server.
  7008. *
  7009. * @param string $exports_dir Exports directory.
  7010. */
  7011. return apply_filters( 'wp_privacy_exports_dir', $exports_dir );
  7012. }
  7013. /**
  7014. * Returns the URL of the directory used to store personal data export files.
  7015. *
  7016. * @since 4.9.6
  7017. *
  7018. * @see wp_privacy_exports_dir
  7019. *
  7020. * @return string Exports directory URL.
  7021. */
  7022. function wp_privacy_exports_url() {
  7023. $upload_dir = wp_upload_dir();
  7024. $exports_url = trailingslashit( $upload_dir['baseurl'] ) . 'wp-personal-data-exports/';
  7025. /**
  7026. * Filters the URL of the directory used to store personal data export files.
  7027. *
  7028. * @since 4.9.6
  7029. * @since 5.5.0 Exports now use relative paths, so changes to the directory URL
  7030. * via this filter should be reflected on the server.
  7031. *
  7032. * @param string $exports_url Exports directory URL.
  7033. */
  7034. return apply_filters( 'wp_privacy_exports_url', $exports_url );
  7035. }
  7036. /**
  7037. * Schedule a `WP_Cron` job to delete expired export files.
  7038. *
  7039. * @since 4.9.6
  7040. */
  7041. function wp_schedule_delete_old_privacy_export_files() {
  7042. if ( wp_installing() ) {
  7043. return;
  7044. }
  7045. if ( ! wp_next_scheduled( 'wp_privacy_delete_old_export_files' ) ) {
  7046. wp_schedule_event( time(), 'hourly', 'wp_privacy_delete_old_export_files' );
  7047. }
  7048. }
  7049. /**
  7050. * Cleans up export files older than three days old.
  7051. *
  7052. * The export files are stored in `wp-content/uploads`, and are therefore publicly
  7053. * accessible. A CSPRN is appended to the filename to mitigate the risk of an
  7054. * unauthorized person downloading the file, but it is still possible. Deleting
  7055. * the file after the data subject has had a chance to delete it adds an additional
  7056. * layer of protection.
  7057. *
  7058. * @since 4.9.6
  7059. */
  7060. function wp_privacy_delete_old_export_files() {
  7061. $exports_dir = wp_privacy_exports_dir();
  7062. if ( ! is_dir( $exports_dir ) ) {
  7063. return;
  7064. }
  7065. require_once ABSPATH . 'wp-admin/includes/file.php';
  7066. $export_files = list_files( $exports_dir, 100, array( 'index.php' ) );
  7067. /**
  7068. * Filters the lifetime, in seconds, of a personal data export file.
  7069. *
  7070. * By default, the lifetime is 3 days. Once the file reaches that age, it will automatically
  7071. * be deleted by a cron job.
  7072. *
  7073. * @since 4.9.6
  7074. *
  7075. * @param int $expiration The expiration age of the export, in seconds.
  7076. */
  7077. $expiration = apply_filters( 'wp_privacy_export_expiration', 3 * DAY_IN_SECONDS );
  7078. foreach ( (array) $export_files as $export_file ) {
  7079. $file_age_in_seconds = time() - filemtime( $export_file );
  7080. if ( $expiration < $file_age_in_seconds ) {
  7081. unlink( $export_file );
  7082. }
  7083. }
  7084. }
  7085. /**
  7086. * Gets the URL to learn more about updating the PHP version the site is running on.
  7087. *
  7088. * This URL can be overridden by specifying an environment variable `WP_UPDATE_PHP_URL` or by using the
  7089. * {@see 'wp_update_php_url'} filter. Providing an empty string is not allowed and will result in the
  7090. * default URL being used. Furthermore the page the URL links to should preferably be localized in the
  7091. * site language.
  7092. *
  7093. * @since 5.1.0
  7094. *
  7095. * @return string URL to learn more about updating PHP.
  7096. */
  7097. function wp_get_update_php_url() {
  7098. $default_url = wp_get_default_update_php_url();
  7099. $update_url = $default_url;
  7100. if ( false !== getenv( 'WP_UPDATE_PHP_URL' ) ) {
  7101. $update_url = getenv( 'WP_UPDATE_PHP_URL' );
  7102. }
  7103. /**
  7104. * Filters the URL to learn more about updating the PHP version the site is running on.
  7105. *
  7106. * Providing an empty string is not allowed and will result in the default URL being used. Furthermore
  7107. * the page the URL links to should preferably be localized in the site language.
  7108. *
  7109. * @since 5.1.0
  7110. *
  7111. * @param string $update_url URL to learn more about updating PHP.
  7112. */
  7113. $update_url = apply_filters( 'wp_update_php_url', $update_url );
  7114. if ( empty( $update_url ) ) {
  7115. $update_url = $default_url;
  7116. }
  7117. return $update_url;
  7118. }
  7119. /**
  7120. * Gets the default URL to learn more about updating the PHP version the site is running on.
  7121. *
  7122. * Do not use this function to retrieve this URL. Instead, use {@see wp_get_update_php_url()} when relying on the URL.
  7123. * This function does not allow modifying the returned URL, and is only used to compare the actually used URL with the
  7124. * default one.
  7125. *
  7126. * @since 5.1.0
  7127. * @access private
  7128. *
  7129. * @return string Default URL to learn more about updating PHP.
  7130. */
  7131. function wp_get_default_update_php_url() {
  7132. return _x( 'https://wordpress.org/support/update-php/', 'localized PHP upgrade information page' );
  7133. }
  7134. /**
  7135. * Prints the default annotation for the web host altering the "Update PHP" page URL.
  7136. *
  7137. * This function is to be used after {@see wp_get_update_php_url()} to display a consistent
  7138. * annotation if the web host has altered the default "Update PHP" page URL.
  7139. *
  7140. * @since 5.1.0
  7141. * @since 5.2.0 Added the `$before` and `$after` parameters.
  7142. *
  7143. * @param string $before Markup to output before the annotation. Default `<p class="description">`.
  7144. * @param string $after Markup to output after the annotation. Default `</p>`.
  7145. */
  7146. function wp_update_php_annotation( $before = '<p class="description">', $after = '</p>' ) {
  7147. $annotation = wp_get_update_php_annotation();
  7148. if ( $annotation ) {
  7149. echo $before . $annotation . $after;
  7150. }
  7151. }
  7152. /**
  7153. * Returns the default annotation for the web hosting altering the "Update PHP" page URL.
  7154. *
  7155. * This function is to be used after {@see wp_get_update_php_url()} to return a consistent
  7156. * annotation if the web host has altered the default "Update PHP" page URL.
  7157. *
  7158. * @since 5.2.0
  7159. *
  7160. * @return string Update PHP page annotation. An empty string if no custom URLs are provided.
  7161. */
  7162. function wp_get_update_php_annotation() {
  7163. $update_url = wp_get_update_php_url();
  7164. $default_url = wp_get_default_update_php_url();
  7165. if ( $update_url === $default_url ) {
  7166. return '';
  7167. }
  7168. $annotation = sprintf(
  7169. /* translators: %s: Default Update PHP page URL. */
  7170. __( '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>.' ),
  7171. esc_url( $default_url )
  7172. );
  7173. return $annotation;
  7174. }
  7175. /**
  7176. * Gets the URL for directly updating the PHP version the site is running on.
  7177. *
  7178. * A URL will only be returned if the `WP_DIRECT_UPDATE_PHP_URL` environment variable is specified or
  7179. * by using the {@see 'wp_direct_php_update_url'} filter. This allows hosts to send users directly to
  7180. * the page where they can update PHP to a newer version.
  7181. *
  7182. * @since 5.1.1
  7183. *
  7184. * @return string URL for directly updating PHP or empty string.
  7185. */
  7186. function wp_get_direct_php_update_url() {
  7187. $direct_update_url = '';
  7188. if ( false !== getenv( 'WP_DIRECT_UPDATE_PHP_URL' ) ) {
  7189. $direct_update_url = getenv( 'WP_DIRECT_UPDATE_PHP_URL' );
  7190. }
  7191. /**
  7192. * Filters the URL for directly updating the PHP version the site is running on from the host.
  7193. *
  7194. * @since 5.1.1
  7195. *
  7196. * @param string $direct_update_url URL for directly updating PHP.
  7197. */
  7198. $direct_update_url = apply_filters( 'wp_direct_php_update_url', $direct_update_url );
  7199. return $direct_update_url;
  7200. }
  7201. /**
  7202. * Display a button directly linking to a PHP update process.
  7203. *
  7204. * This provides hosts with a way for users to be sent directly to their PHP update process.
  7205. *
  7206. * The button is only displayed if a URL is returned by `wp_get_direct_php_update_url()`.
  7207. *
  7208. * @since 5.1.1
  7209. */
  7210. function wp_direct_php_update_button() {
  7211. $direct_update_url = wp_get_direct_php_update_url();
  7212. if ( empty( $direct_update_url ) ) {
  7213. return;
  7214. }
  7215. echo '<p class="button-container">';
  7216. printf(
  7217. '<a class="button button-primary" href="%1$s" target="_blank" rel="noopener">%2$s <span class="screen-reader-text">%3$s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a>',
  7218. esc_url( $direct_update_url ),
  7219. __( 'Update PHP' ),
  7220. /* translators: Accessibility text. */
  7221. __( '(opens in a new tab)' )
  7222. );
  7223. echo '</p>';
  7224. }
  7225. /**
  7226. * Gets the URL to learn more about updating the site to use HTTPS.
  7227. *
  7228. * This URL can be overridden by specifying an environment variable `WP_UPDATE_HTTPS_URL` or by using the
  7229. * {@see 'wp_update_https_url'} filter. Providing an empty string is not allowed and will result in the
  7230. * default URL being used. Furthermore the page the URL links to should preferably be localized in the
  7231. * site language.
  7232. *
  7233. * @since 5.7.0
  7234. *
  7235. * @return string URL to learn more about updating to HTTPS.
  7236. */
  7237. function wp_get_update_https_url() {
  7238. $default_url = wp_get_default_update_https_url();
  7239. $update_url = $default_url;
  7240. if ( false !== getenv( 'WP_UPDATE_HTTPS_URL' ) ) {
  7241. $update_url = getenv( 'WP_UPDATE_HTTPS_URL' );
  7242. }
  7243. /**
  7244. * Filters the URL to learn more about updating the HTTPS version the site is running on.
  7245. *
  7246. * Providing an empty string is not allowed and will result in the default URL being used. Furthermore
  7247. * the page the URL links to should preferably be localized in the site language.
  7248. *
  7249. * @since 5.7.0
  7250. *
  7251. * @param string $update_url URL to learn more about updating HTTPS.
  7252. */
  7253. $update_url = apply_filters( 'wp_update_https_url', $update_url );
  7254. if ( empty( $update_url ) ) {
  7255. $update_url = $default_url;
  7256. }
  7257. return $update_url;
  7258. }
  7259. /**
  7260. * Gets the default URL to learn more about updating the site to use HTTPS.
  7261. *
  7262. * Do not use this function to retrieve this URL. Instead, use {@see wp_get_update_https_url()} when relying on the URL.
  7263. * This function does not allow modifying the returned URL, and is only used to compare the actually used URL with the
  7264. * default one.
  7265. *
  7266. * @since 5.7.0
  7267. * @access private
  7268. *
  7269. * @return string Default URL to learn more about updating to HTTPS.
  7270. */
  7271. function wp_get_default_update_https_url() {
  7272. /* translators: Documentation explaining HTTPS and why it should be used. */
  7273. return __( 'https://wordpress.org/support/article/why-should-i-use-https/' );
  7274. }
  7275. /**
  7276. * Gets the URL for directly updating the site to use HTTPS.
  7277. *
  7278. * A URL will only be returned if the `WP_DIRECT_UPDATE_HTTPS_URL` environment variable is specified or
  7279. * by using the {@see 'wp_direct_update_https_url'} filter. This allows hosts to send users directly to
  7280. * the page where they can update their site to use HTTPS.
  7281. *
  7282. * @since 5.7.0
  7283. *
  7284. * @return string URL for directly updating to HTTPS or empty string.
  7285. */
  7286. function wp_get_direct_update_https_url() {
  7287. $direct_update_url = '';
  7288. if ( false !== getenv( 'WP_DIRECT_UPDATE_HTTPS_URL' ) ) {
  7289. $direct_update_url = getenv( 'WP_DIRECT_UPDATE_HTTPS_URL' );
  7290. }
  7291. /**
  7292. * Filters the URL for directly updating the PHP version the site is running on from the host.
  7293. *
  7294. * @since 5.7.0
  7295. *
  7296. * @param string $direct_update_url URL for directly updating PHP.
  7297. */
  7298. $direct_update_url = apply_filters( 'wp_direct_update_https_url', $direct_update_url );
  7299. return $direct_update_url;
  7300. }
  7301. /**
  7302. * Get the size of a directory.
  7303. *
  7304. * A helper function that is used primarily to check whether
  7305. * a blog has exceeded its allowed upload space.
  7306. *
  7307. * @since MU (3.0.0)
  7308. * @since 5.2.0 $max_execution_time parameter added.
  7309. *
  7310. * @param string $directory Full path of a directory.
  7311. * @param int $max_execution_time Maximum time to run before giving up. In seconds.
  7312. * The timeout is global and is measured from the moment WordPress started to load.
  7313. * @return int|false|null Size in bytes if a valid directory. False if not. Null if timeout.
  7314. */
  7315. function get_dirsize( $directory, $max_execution_time = null ) {
  7316. // Exclude individual site directories from the total when checking the main site of a network,
  7317. // as they are subdirectories and should not be counted.
  7318. if ( is_multisite() && is_main_site() ) {
  7319. $size = recurse_dirsize( $directory, $directory . '/sites', $max_execution_time );
  7320. } else {
  7321. $size = recurse_dirsize( $directory, null, $max_execution_time );
  7322. }
  7323. return $size;
  7324. }
  7325. /**
  7326. * Get the size of a directory recursively.
  7327. *
  7328. * Used by get_dirsize() to get a directory size when it contains other directories.
  7329. *
  7330. * @since MU (3.0.0)
  7331. * @since 4.3.0 The `$exclude` parameter was added.
  7332. * @since 5.2.0 The `$max_execution_time` parameter was added.
  7333. * @since 5.6.0 The `$directory_cache` parameter was added.
  7334. *
  7335. * @param string $directory Full path of a directory.
  7336. * @param string|string[] $exclude Optional. Full path of a subdirectory to exclude from the total,
  7337. * or array of paths. Expected without trailing slash(es).
  7338. * @param int $max_execution_time Optional. Maximum time to run before giving up. In seconds.
  7339. * The timeout is global and is measured from the moment
  7340. * WordPress started to load.
  7341. * @param array $directory_cache Optional. Array of cached directory paths.
  7342. *
  7343. * @return int|false|null Size in bytes if a valid directory. False if not. Null if timeout.
  7344. */
  7345. function recurse_dirsize( $directory, $exclude = null, $max_execution_time = null, &$directory_cache = null ) {
  7346. $directory = untrailingslashit( $directory );
  7347. $save_cache = false;
  7348. if ( ! isset( $directory_cache ) ) {
  7349. $directory_cache = get_transient( 'dirsize_cache' );
  7350. $save_cache = true;
  7351. }
  7352. if ( isset( $directory_cache[ $directory ] ) && is_int( $directory_cache[ $directory ] ) ) {
  7353. return $directory_cache[ $directory ];
  7354. }
  7355. if ( ! file_exists( $directory ) || ! is_dir( $directory ) || ! is_readable( $directory ) ) {
  7356. return false;
  7357. }
  7358. if (
  7359. ( is_string( $exclude ) && $directory === $exclude ) ||
  7360. ( is_array( $exclude ) && in_array( $directory, $exclude, true ) )
  7361. ) {
  7362. return false;
  7363. }
  7364. if ( null === $max_execution_time ) {
  7365. // Keep the previous behavior but attempt to prevent fatal errors from timeout if possible.
  7366. if ( function_exists( 'ini_get' ) ) {
  7367. $max_execution_time = ini_get( 'max_execution_time' );
  7368. } else {
  7369. // Disable...
  7370. $max_execution_time = 0;
  7371. }
  7372. // Leave 1 second "buffer" for other operations if $max_execution_time has reasonable value.
  7373. if ( $max_execution_time > 10 ) {
  7374. $max_execution_time -= 1;
  7375. }
  7376. }
  7377. /**
  7378. * Filters the amount of storage space used by one directory and all its children, in megabytes.
  7379. *
  7380. * Return the actual used space to short-circuit the recursive PHP file size calculation
  7381. * and use something else, like a CDN API or native operating system tools for better performance.
  7382. *
  7383. * @since 5.6.0
  7384. *
  7385. * @param int|false $space_used The amount of used space, in bytes. Default false.
  7386. * @param string $directory Full path of a directory.
  7387. * @param string|string[]|null $exclude Full path of a subdirectory to exclude from the total,
  7388. * or array of paths.
  7389. * @param int $max_execution_time Maximum time to run before giving up. In seconds.
  7390. * @param array $directory_cache Array of cached directory paths.
  7391. */
  7392. $size = apply_filters( 'pre_recurse_dirsize', false, $directory, $exclude, $max_execution_time, $directory_cache );
  7393. if ( false === $size ) {
  7394. $size = 0;
  7395. $handle = opendir( $directory );
  7396. if ( $handle ) {
  7397. while ( ( $file = readdir( $handle ) ) !== false ) {
  7398. $path = $directory . '/' . $file;
  7399. if ( '.' !== $file && '..' !== $file ) {
  7400. if ( is_file( $path ) ) {
  7401. $size += filesize( $path );
  7402. } elseif ( is_dir( $path ) ) {
  7403. $handlesize = recurse_dirsize( $path, $exclude, $max_execution_time, $directory_cache );
  7404. if ( $handlesize > 0 ) {
  7405. $size += $handlesize;
  7406. }
  7407. }
  7408. if ( $max_execution_time > 0 &&
  7409. ( microtime( true ) - WP_START_TIMESTAMP ) > $max_execution_time
  7410. ) {
  7411. // Time exceeded. Give up instead of risking a fatal timeout.
  7412. $size = null;
  7413. break;
  7414. }
  7415. }
  7416. }
  7417. closedir( $handle );
  7418. }
  7419. }
  7420. if ( ! is_array( $directory_cache ) ) {
  7421. $directory_cache = array();
  7422. }
  7423. $directory_cache[ $directory ] = $size;
  7424. // Only write the transient on the top level call and not on recursive calls.
  7425. if ( $save_cache ) {
  7426. set_transient( 'dirsize_cache', $directory_cache );
  7427. }
  7428. return $size;
  7429. }
  7430. /**
  7431. * Cleans directory size cache used by recurse_dirsize().
  7432. *
  7433. * Removes the current directory and all parent directories from the `dirsize_cache` transient.
  7434. *
  7435. * @since 5.6.0
  7436. * @since 5.9.0 Added input validation with a notice for invalid input.
  7437. *
  7438. * @param string $path Full path of a directory or file.
  7439. */
  7440. function clean_dirsize_cache( $path ) {
  7441. if ( ! is_string( $path ) || empty( $path ) ) {
  7442. trigger_error(
  7443. sprintf(
  7444. /* translators: 1: Function name, 2: A variable type, like "boolean" or "integer". */
  7445. __( '%1$s only accepts a non-empty path string, received %2$s.' ),
  7446. '<code>clean_dirsize_cache()</code>',
  7447. '<code>' . gettype( $path ) . '</code>'
  7448. )
  7449. );
  7450. return;
  7451. }
  7452. $directory_cache = get_transient( 'dirsize_cache' );
  7453. if ( empty( $directory_cache ) ) {
  7454. return;
  7455. }
  7456. if (
  7457. strpos( $path, '/' ) === false &&
  7458. strpos( $path, '\\' ) === false
  7459. ) {
  7460. unset( $directory_cache[ $path ] );
  7461. set_transient( 'dirsize_cache', $directory_cache );
  7462. return;
  7463. }
  7464. $last_path = null;
  7465. $path = untrailingslashit( $path );
  7466. unset( $directory_cache[ $path ] );
  7467. while (
  7468. $last_path !== $path &&
  7469. DIRECTORY_SEPARATOR !== $path &&
  7470. '.' !== $path &&
  7471. '..' !== $path
  7472. ) {
  7473. $last_path = $path;
  7474. $path = dirname( $path );
  7475. unset( $directory_cache[ $path ] );
  7476. }
  7477. set_transient( 'dirsize_cache', $directory_cache );
  7478. }
  7479. /**
  7480. * Checks compatibility with the current WordPress version.
  7481. *
  7482. * @since 5.2.0
  7483. *
  7484. * @global string $wp_version WordPress version.
  7485. *
  7486. * @param string $required Minimum required WordPress version.
  7487. * @return bool True if required version is compatible or empty, false if not.
  7488. */
  7489. function is_wp_version_compatible( $required ) {
  7490. global $wp_version;
  7491. // Strip off any -alpha, -RC, -beta, -src suffixes.
  7492. list( $version ) = explode( '-', $wp_version );
  7493. return empty( $required ) || version_compare( $version, $required, '>=' );
  7494. }
  7495. /**
  7496. * Checks compatibility with the current PHP version.
  7497. *
  7498. * @since 5.2.0
  7499. *
  7500. * @param string $required Minimum required PHP version.
  7501. * @return bool True if required version is compatible or empty, false if not.
  7502. */
  7503. function is_php_version_compatible( $required ) {
  7504. return empty( $required ) || version_compare( phpversion(), $required, '>=' );
  7505. }
  7506. /**
  7507. * Check if two numbers are nearly the same.
  7508. *
  7509. * This is similar to using `round()` but the precision is more fine-grained.
  7510. *
  7511. * @since 5.3.0
  7512. *
  7513. * @param int|float $expected The expected value.
  7514. * @param int|float $actual The actual number.
  7515. * @param int|float $precision The allowed variation.
  7516. * @return bool Whether the numbers match whithin the specified precision.
  7517. */
  7518. function wp_fuzzy_number_match( $expected, $actual, $precision = 1 ) {
  7519. return abs( (float) $expected - (float) $actual ) <= $precision;
  7520. }