| [ Index ] |
PHP Cross Reference of WordPress Trunk (Updated Daily) |
[Summary view] [Print] [Text view]
1 <?php 2 /** 3 * Main WordPress API 4 * 5 * @package WordPress 6 */ 7 8 // Don't load directly. 9 if ( ! defined( 'ABSPATH' ) ) { 10 exit; 11 } 12 13 require ABSPATH . WPINC . '/option.php'; 14 15 /** 16 * Converts given MySQL date string into a different format. 17 * 18 * - `$format` should be a PHP date format string. 19 * - 'U' and 'G' formats will return an integer sum of timestamp with timezone offset. 20 * - `$date` is expected to be local time in MySQL format (`Y-m-d H:i:s`). 21 * 22 * Historically UTC time could be passed to the function to produce Unix timestamp. 23 * 24 * If `$translate` is true then the given date and format string will 25 * be passed to `wp_date()` for translation. 26 * 27 * @since 0.71 28 * 29 * @param string $format Format of the date to return. 30 * @param string $date Date string to convert. 31 * @param bool $translate Whether the return date should be translated. Default true. 32 * @return string|int|false Integer if `$format` is 'U' or 'G', string otherwise. 33 * False on failure. 34 * 35 * @phpstan-return ( $format is 'U'|'G' ? int|false : string|false ) 36 */ 37 function mysql2date( $format, $date, $translate = true ) { 38 if ( empty( $date ) ) { 39 return false; 40 } 41 42 $timezone = wp_timezone(); 43 $datetime = date_create( $date, $timezone ); 44 45 if ( false === $datetime ) { 46 return false; 47 } 48 49 // Returns a sum of timestamp with timezone offset. Ideally should never be used. 50 if ( 'G' === $format || 'U' === $format ) { 51 return $datetime->getTimestamp() + $datetime->getOffset(); 52 } 53 54 if ( $translate ) { 55 return wp_date( $format, $datetime->getTimestamp(), $timezone ); 56 } 57 58 return $datetime->format( $format ); 59 } 60 61 /** 62 * Retrieves the current time based on specified type. 63 * 64 * - The 'mysql' type will return the time in the format for MySQL DATETIME field. 65 * - The 'timestamp' or 'U' types will return the current timestamp or a sum of timestamp 66 * and timezone offset, depending on `$gmt`. 67 * - Other strings will be interpreted as PHP date formats (e.g. 'Y-m-d'). 68 * 69 * If `$gmt` is a truthy value then both types will use GMT time, otherwise the 70 * output is adjusted with the GMT offset for the site. 71 * 72 * @since 1.0.0 73 * @since 5.3.0 Now returns an integer if `$type` is 'U'. Previously a string was returned. 74 * 75 * @param string $type Type of time to retrieve. Accepts 'mysql', 'timestamp', 'U', 76 * or PHP date format string (e.g. 'Y-m-d'). 77 * @param bool $gmt Optional. Whether to use GMT timezone. Default false. 78 * @return int|string Integer if `$type` is 'timestamp' or 'U', string otherwise. 79 * 80 * @phpstan-return ( $type is 'timestamp'|'U' ? int : string ) 81 */ 82 function current_time( $type, $gmt = false ) { 83 // Don't use non-GMT timestamp, unless you know the difference and really need to. 84 if ( 'timestamp' === $type || 'U' === $type ) { 85 return $gmt ? time() : time() + (int) ( (float) get_option( 'gmt_offset' ) * HOUR_IN_SECONDS ); 86 } 87 88 if ( 'mysql' === $type ) { 89 $type = 'Y-m-d H:i:s'; 90 } 91 92 $timezone = $gmt ? new DateTimeZone( 'UTC' ) : wp_timezone(); 93 $datetime = new DateTime( 'now', $timezone ); 94 95 return $datetime->format( $type ); 96 } 97 98 /** 99 * Retrieves the current time as an object using the site's timezone. 100 * 101 * @since 5.3.0 102 * 103 * @return DateTimeImmutable Date and time object. 104 */ 105 function current_datetime() { 106 return new DateTimeImmutable( 'now', wp_timezone() ); 107 } 108 109 /** 110 * Retrieves the timezone of the site as a string. 111 * 112 * Uses the `timezone_string` option to get a proper timezone name if available, 113 * otherwise falls back to a manual UTC ± offset. 114 * 115 * Example return values: 116 * 117 * - 'Europe/Rome' 118 * - 'America/North_Dakota/New_Salem' 119 * - 'UTC' 120 * - '-06:30' 121 * - '+00:00' 122 * - '+08:45' 123 * 124 * @since 5.3.0 125 * 126 * @return string PHP timezone name or a ±HH:MM offset. 127 */ 128 function wp_timezone_string() { 129 $timezone_string = get_option( 'timezone_string' ); 130 131 if ( $timezone_string ) { 132 return $timezone_string; 133 } 134 135 $offset = (float) get_option( 'gmt_offset' ); 136 $hours = (int) $offset; 137 $minutes = ( $offset - $hours ); 138 139 $sign = ( $offset < 0 ) ? '-' : '+'; 140 $abs_hour = abs( $hours ); 141 $abs_mins = abs( $minutes * 60 ); 142 $tz_offset = sprintf( '%s%02d:%02d', $sign, $abs_hour, $abs_mins ); 143 144 return $tz_offset; 145 } 146 147 /** 148 * Retrieves the timezone of the site as a `DateTimeZone` object. 149 * 150 * Timezone can be based on a PHP timezone string or a ±HH:MM offset. 151 * 152 * @since 5.3.0 153 * 154 * @return DateTimeZone Timezone object. 155 */ 156 function wp_timezone() { 157 return new DateTimeZone( wp_timezone_string() ); 158 } 159 160 /** 161 * Retrieves the date in localized format, based on a sum of Unix timestamp and 162 * timezone offset in seconds. 163 * 164 * If the locale specifies the locale month and weekday, then the locale will 165 * take over the format for the date. If it isn't, then the date format string 166 * will be used instead. 167 * 168 * Note that due to the way WP typically generates a sum of timestamp and offset 169 * with `strtotime()`, it implies offset added at a _current_ time, not at the time 170 * the timestamp represents. Storing such timestamps or calculating them differently 171 * will lead to invalid output. 172 * 173 * @since 0.71 174 * @since 5.3.0 Converted into a wrapper for wp_date(). 175 * 176 * @param string $format Format to display the date. 177 * @param int|bool $timestamp_with_offset Optional. A sum of Unix timestamp and timezone offset 178 * in seconds. Default false. 179 * @param bool $gmt Optional. Whether to use GMT timezone. Only applies 180 * if timestamp is not provided. Default false. 181 * @return string The date, translated if locale specifies it. 182 */ 183 function date_i18n( $format, $timestamp_with_offset = false, $gmt = false ) { 184 $timestamp = $timestamp_with_offset; 185 186 // If timestamp is omitted it should be current time (summed with offset, unless `$gmt` is true). 187 if ( ! is_numeric( $timestamp ) ) { 188 // phpcs:ignore WordPress.DateTime.CurrentTimeTimestamp.Requested 189 $timestamp = current_time( 'timestamp', $gmt ); 190 } 191 192 /* 193 * This is a legacy implementation quirk that the returned timestamp is also with offset. 194 * Ideally this function should never be used to produce a timestamp. 195 */ 196 if ( 'U' === $format ) { 197 $date = $timestamp; 198 } elseif ( $gmt && false === $timestamp_with_offset ) { // Current time in UTC. 199 $date = wp_date( $format, null, new DateTimeZone( 'UTC' ) ); 200 } elseif ( false === $timestamp_with_offset ) { // Current time in site's timezone. 201 $date = wp_date( $format ); 202 } else { 203 /* 204 * Timestamp with offset is typically produced by a UTC `strtotime()` call on an input without timezone. 205 * This is the best attempt to reverse that operation into a local time to use. 206 */ 207 $local_time = gmdate( 'Y-m-d H:i:s', $timestamp ); 208 $timezone = wp_timezone(); 209 $datetime = date_create( $local_time, $timezone ); 210 $date = wp_date( $format, $datetime->getTimestamp(), $timezone ); 211 } 212 213 /** 214 * Filters the date formatted based on the locale. 215 * 216 * @since 2.8.0 217 * 218 * @param string $date Formatted date string. 219 * @param string $format Format to display the date. 220 * @param int $timestamp A sum of Unix timestamp and timezone offset in seconds. 221 * Might be without offset if input omitted timestamp but requested GMT. 222 * @param bool $gmt Whether to use GMT timezone. Only applies if timestamp was not provided. 223 */ 224 $date = apply_filters( 'date_i18n', $date, $format, $timestamp, $gmt ); 225 226 return $date; 227 } 228 229 /** 230 * Retrieves the date, in localized format. 231 * 232 * This is a newer function, intended to replace `date_i18n()` without legacy quirks in it. 233 * 234 * Note that, unlike `date_i18n()`, this function accepts a true Unix timestamp, not summed 235 * with timezone offset. 236 * 237 * @since 5.3.0 238 * 239 * @global WP_Locale $wp_locale WordPress date and time locale object. 240 * 241 * @param string $format PHP date format. 242 * @param int|null $timestamp Optional. Unix timestamp. Defaults to current time. 243 * @param DateTimeZone|null $timezone Optional. Timezone to output result in. Defaults to timezone 244 * from site settings. 245 * @return string|false The date, translated if locale specifies it. False on invalid timestamp input. 246 */ 247 function wp_date( $format, $timestamp = null, $timezone = null ) { 248 global $wp_locale; 249 250 if ( null === $timestamp ) { 251 $timestamp = time(); 252 } elseif ( ! is_numeric( $timestamp ) ) { 253 return false; 254 } 255 256 if ( ! $timezone ) { 257 $timezone = wp_timezone(); 258 } 259 260 $datetime = date_create( '@' . $timestamp ); 261 262 if ( false === $datetime ) { 263 return false; 264 } 265 266 $datetime->setTimezone( $timezone ); 267 268 if ( empty( $wp_locale->month ) || empty( $wp_locale->weekday ) ) { 269 $date = $datetime->format( $format ); 270 } else { 271 // We need to unpack shorthand `r` format because it has parts that might be localized. 272 $format = preg_replace( '/(?<!\\\\)r/', DATE_RFC2822, $format ); 273 274 $new_format = ''; 275 $format_length = strlen( $format ); 276 $month = $wp_locale->get_month( $datetime->format( 'm' ) ); 277 $weekday = $wp_locale->get_weekday( (int) $datetime->format( 'w' ) ); 278 279 for ( $i = 0; $i < $format_length; $i++ ) { 280 switch ( $format[ $i ] ) { 281 case 'D': 282 $new_format .= addcslashes( $wp_locale->get_weekday_abbrev( $weekday ), '\\A..Za..z' ); 283 break; 284 case 'F': 285 $new_format .= addcslashes( $month, '\\A..Za..z' ); 286 break; 287 case 'l': 288 $new_format .= addcslashes( $weekday, '\\A..Za..z' ); 289 break; 290 case 'M': 291 $new_format .= addcslashes( $wp_locale->get_month_abbrev( $month ), '\\A..Za..z' ); 292 break; 293 case 'a': 294 $new_format .= addcslashes( $wp_locale->get_meridiem( $datetime->format( 'a' ) ), '\\A..Za..z' ); 295 break; 296 case 'A': 297 $new_format .= addcslashes( $wp_locale->get_meridiem( $datetime->format( 'A' ) ), '\\A..Za..z' ); 298 break; 299 case '\\': 300 $new_format .= $format[ $i ]; 301 302 // If character follows a slash, we add it without translating. 303 if ( $i < $format_length ) { 304 $new_format .= $format[ ++$i ]; 305 } 306 break; 307 default: 308 $new_format .= $format[ $i ]; 309 break; 310 } 311 } 312 313 $date = $datetime->format( $new_format ); 314 $date = wp_maybe_decline_date( $date, $format ); 315 } 316 317 /** 318 * Filters the date formatted based on the locale. 319 * 320 * @since 5.3.0 321 * 322 * @param string $date Formatted date string. 323 * @param string $format Format to display the date. 324 * @param int $timestamp Unix timestamp. 325 * @param DateTimeZone $timezone Timezone. 326 */ 327 $date = apply_filters( 'wp_date', $date, $format, $timestamp, $timezone ); 328 329 return $date; 330 } 331 332 /** 333 * Determines if the date should be declined. 334 * 335 * If the locale specifies that month names require a genitive case in certain 336 * formats (like 'j F Y'), the month name will be replaced with a correct form. 337 * 338 * @since 4.4.0 339 * @since 5.4.0 The `$format` parameter was added. 340 * 341 * @global WP_Locale $wp_locale WordPress date and time locale object. 342 * 343 * @param string $date Formatted date string. 344 * @param string $format Optional. Date format to check. Default empty string. 345 * @return string The date, declined if locale specifies it. 346 */ 347 function wp_maybe_decline_date( $date, $format = '' ) { 348 global $wp_locale; 349 350 // i18n functions are not available in SHORTINIT mode. 351 if ( ! function_exists( '_x' ) ) { 352 return $date; 353 } 354 355 /* 356 * translators: If months in your language require a genitive case, 357 * translate this to 'on'. Do not translate into your own language. 358 */ 359 if ( 'on' === _x( 'off', 'decline months names: on or off' ) ) { 360 361 $months = $wp_locale->month; 362 $months_genitive = $wp_locale->month_genitive; 363 364 /* 365 * Match a format like 'j F Y' or 'j. F' (day of the month, followed by month name) 366 * and decline the month. 367 */ 368 if ( $format ) { 369 $decline = preg_match( '#[dj]\.? F#', $format ); 370 } else { 371 // If the format is not passed, try to guess it from the date string. 372 $decline = preg_match( '#\b\d{1,2}\.? [^\d ]+\b#u', $date ); 373 } 374 375 if ( $decline ) { 376 foreach ( $months as $key => $month ) { 377 $months[ $key ] = '# ' . preg_quote( $month, '#' ) . '\b#u'; 378 } 379 380 foreach ( $months_genitive as $key => $month ) { 381 $months_genitive[ $key ] = ' ' . $month; 382 } 383 384 $date = preg_replace( $months, $months_genitive, $date ); 385 } 386 387 /* 388 * Match a format like 'F jS' or 'F j' (month name, followed by day with an optional ordinal suffix) 389 * and change it to declined 'j F'. 390 */ 391 if ( $format ) { 392 $decline = preg_match( '#F [dj]#', $format ); 393 } else { 394 // If the format is not passed, try to guess it from the date string. 395 $decline = preg_match( '#\b[^\d ]+ \d{1,2}(st|nd|rd|th)?\b#u', trim( $date ) ); 396 } 397 398 if ( $decline ) { 399 foreach ( $months as $key => $month ) { 400 $months[ $key ] = '#\b' . preg_quote( $month, '#' ) . ' (\d{1,2})(st|nd|rd|th)?([-–]\d{1,2})?(st|nd|rd|th)?\b#u'; 401 } 402 403 foreach ( $months_genitive as $key => $month ) { 404 $months_genitive[ $key ] = '$1$3 ' . $month; 405 } 406 407 $date = preg_replace( $months, $months_genitive, $date ); 408 } 409 } 410 411 // Used for locale-specific rules. 412 $locale = get_locale(); 413 414 if ( 'ca' === $locale ) { 415 // " de abril| de agost| de octubre..." -> " d'abril| d'agost| d'octubre..." 416 $date = preg_replace( '# de ([ao])#i', " d'\\1", $date ); 417 } 418 419 return $date; 420 } 421 422 /** 423 * Converts float number to format based on the locale. 424 * 425 * @since 2.3.0 426 * 427 * @global WP_Locale $wp_locale WordPress date and time locale object. 428 * 429 * @param float $number The number to convert based on locale. 430 * @param int $decimals Optional. Precision of the number of decimal places. Default 0. 431 * @return string Converted number in string format. 432 */ 433 function number_format_i18n( $number, $decimals = 0 ) { 434 global $wp_locale; 435 436 if ( isset( $wp_locale ) ) { 437 $formatted = number_format( $number, absint( $decimals ), $wp_locale->number_format['decimal_point'], $wp_locale->number_format['thousands_sep'] ); 438 } else { 439 $formatted = number_format( $number, absint( $decimals ) ); 440 } 441 442 /** 443 * Filters the number formatted based on the locale. 444 * 445 * @since 2.8.0 446 * @since 4.9.0 The `$number` and `$decimals` parameters were added. 447 * 448 * @param string $formatted Converted number in string format. 449 * @param float $number The number to convert based on locale. 450 * @param int $decimals Precision of the number of decimal places. 451 */ 452 return apply_filters( 'number_format_i18n', $formatted, $number, $decimals ); 453 } 454 455 /** 456 * Converts a number of bytes to the largest unit the bytes will fit into. 457 * 458 * It is easier to read 1 KB than 1024 bytes and 1 MB than 1048576 bytes. Converts 459 * number of bytes to human readable number by taking the number of that unit 460 * that the bytes will go into it. Supports YB value. 461 * 462 * Please note that integers in PHP are limited to 32 bits, unless they are on 463 * 64 bit architecture, then they have 64 bit size. If you need to place the 464 * larger size then what PHP integer type will hold, then use a string. It will 465 * be converted to a double, which should always have 64 bit length. 466 * 467 * Technically the correct unit names for powers of 1024 are KiB, MiB etc. 468 * 469 * @since 2.3.0 470 * @since 6.0.0 Support for PB, EB, ZB, and YB was added. 471 * 472 * @param int|float|string $bytes Number of bytes. Note max integer size for integers. 473 * @param int $decimals Optional. Precision of number of decimal places. Default 0. 474 * @return string|false Number string on success, false on failure. 475 * 476 * @phpstan-param int|float|numeric-string $bytes 477 * 478 * @phpstan-return ( $bytes is int<0, max> ? string : string|false ) 479 */ 480 function size_format( $bytes, $decimals = 0 ) { 481 if ( ! is_numeric( $bytes ) ) { 482 return false; 483 } 484 485 $bytes = (float) $bytes; 486 487 $quant = array( 488 /* translators: Unit symbol for yottabyte. */ 489 _x( 'YB', 'unit symbol' ) => YB_IN_BYTES, 490 /* translators: Unit symbol for zettabyte. */ 491 _x( 'ZB', 'unit symbol' ) => ZB_IN_BYTES, 492 /* translators: Unit symbol for exabyte. */ 493 _x( 'EB', 'unit symbol' ) => EB_IN_BYTES, 494 /* translators: Unit symbol for petabyte. */ 495 _x( 'PB', 'unit symbol' ) => PB_IN_BYTES, 496 /* translators: Unit symbol for terabyte. */ 497 _x( 'TB', 'unit symbol' ) => TB_IN_BYTES, 498 /* translators: Unit symbol for gigabyte. */ 499 _x( 'GB', 'unit symbol' ) => GB_IN_BYTES, 500 /* translators: Unit symbol for megabyte. */ 501 _x( 'MB', 'unit symbol' ) => MB_IN_BYTES, 502 /* translators: Unit symbol for kilobyte. */ 503 _x( 'KB', 'unit symbol' ) => KB_IN_BYTES, 504 /* translators: Unit symbol for byte. */ 505 _x( 'B', 'unit symbol' ) => 1, 506 ); 507 508 if ( 0.0 === $bytes ) { 509 /* translators: Unit symbol for byte. */ 510 return number_format_i18n( 0, $decimals ) . ' ' . _x( 'B', 'unit symbol' ); 511 } 512 513 foreach ( $quant as $unit => $mag ) { 514 if ( $bytes >= $mag ) { 515 return number_format_i18n( $bytes / $mag, $decimals ) . ' ' . $unit; 516 } 517 } 518 519 return false; 520 } 521 522 /** 523 * Converts a duration to human readable format. 524 * 525 * @since 5.1.0 526 * 527 * @param string $duration Duration will be in string format (HH:ii:ss) OR (ii:ss), 528 * with a possible prepended negative sign (-). 529 * @return string|false A human readable duration string, false on failure. 530 */ 531 function human_readable_duration( $duration = '' ) { 532 if ( ( empty( $duration ) || ! is_string( $duration ) ) ) { 533 return false; 534 } 535 536 $duration = trim( $duration ); 537 538 // Remove prepended negative sign. 539 if ( str_starts_with( $duration, '-' ) ) { 540 $duration = substr( $duration, 1 ); 541 } 542 543 // Extract duration parts. 544 $duration_parts = array_reverse( explode( ':', $duration ) ); 545 $duration_count = count( $duration_parts ); 546 547 $hour = null; 548 $minute = null; 549 $second = null; 550 551 if ( 3 === $duration_count ) { 552 // Validate HH:ii:ss duration format. 553 if ( ! ( (bool) preg_match( '/^([0-9]+):([0-5]?[0-9]):([0-5]?[0-9])$/', $duration ) ) ) { 554 return false; 555 } 556 // Three parts: hours, minutes & seconds. 557 list( $second, $minute, $hour ) = $duration_parts; 558 } elseif ( 2 === $duration_count ) { 559 // Validate ii:ss duration format. 560 if ( ! ( (bool) preg_match( '/^([0-5]?[0-9]):([0-5]?[0-9])$/', $duration ) ) ) { 561 return false; 562 } 563 // Two parts: minutes & seconds. 564 list( $second, $minute ) = $duration_parts; 565 } else { 566 return false; 567 } 568 569 $human_readable_duration = array(); 570 571 // Add the hour part to the string. 572 if ( is_numeric( $hour ) ) { 573 /* translators: %s: Time duration in hour or hours. */ 574 $human_readable_duration[] = sprintf( _n( '%s hour', '%s hours', $hour ), (int) $hour ); 575 } 576 577 // Add the minute part to the string. 578 if ( is_numeric( $minute ) ) { 579 /* translators: %s: Time duration in minute or minutes. */ 580 $human_readable_duration[] = sprintf( _n( '%s minute', '%s minutes', $minute ), (int) $minute ); 581 } 582 583 // Add the second part to the string. 584 if ( is_numeric( $second ) ) { 585 /* translators: %s: Time duration in second or seconds. */ 586 $human_readable_duration[] = sprintf( _n( '%s second', '%s seconds', $second ), (int) $second ); 587 } 588 589 return implode( ', ', $human_readable_duration ); 590 } 591 592 /** 593 * Gets the week start and end from the datetime or date string from MySQL. 594 * 595 * @since 0.71 596 * 597 * @param string $mysqlstring Date or datetime field type from MySQL. 598 * @param int|string $start_of_week Optional. Start of the week as an integer. Default empty string. 599 * @return int[] { 600 * Week start and end dates as Unix timestamps. 601 * 602 * @type int $start The week start date as a Unix timestamp. 603 * @type int $end The week end date as a Unix timestamp. 604 * } 605 */ 606 function get_weekstartend( $mysqlstring, $start_of_week = '' ) { 607 // MySQL string year. 608 $mysql_year = substr( $mysqlstring, 0, 4 ); 609 610 // MySQL string month. 611 $mysql_month = substr( $mysqlstring, 5, 2 ); 612 613 // MySQL string day. 614 $mysql_day = substr( $mysqlstring, 8, 2 ); 615 616 // The timestamp for MySQL string day. 617 $day = mktime( 0, 0, 0, $mysql_month, $mysql_day, $mysql_year ); 618 619 // The day of the week from the timestamp. 620 $weekday = (int) gmdate( 'w', $day ); 621 622 if ( ! is_numeric( $start_of_week ) ) { 623 $start_of_week = (int) get_option( 'start_of_week' ); 624 } 625 626 if ( $weekday < $start_of_week ) { 627 $weekday += 7; 628 } 629 630 // The most recent week start day on or before $day. 631 $start = $day - DAY_IN_SECONDS * ( $weekday - $start_of_week ); 632 633 // $start + 1 week - 1 second. 634 $end = $start + WEEK_IN_SECONDS - 1; 635 636 return compact( 'start', 'end' ); 637 } 638 639 /** 640 * Serializes data, if needed. 641 * 642 * @since 2.0.5 643 * 644 * @param string|array|object $data Data that might be serialized. 645 * @return mixed A scalar data. 646 * 647 * @phpstan-template T of mixed 648 * @phpstan-param T $data 649 * @phpstan-return ( T is array|object|string ? string : T ) 650 */ 651 function maybe_serialize( $data ) { 652 if ( is_array( $data ) || is_object( $data ) ) { 653 return serialize( $data ); 654 } 655 656 /* 657 * Double serialization is required for backward compatibility. 658 * See https://core.trac.wordpress.org/ticket/12930 659 * Also the world will end. See WP 3.6.1. 660 */ 661 if ( is_serialized( $data, false ) ) { 662 return serialize( $data ); 663 } 664 665 return $data; 666 } 667 668 /** 669 * Unserializes data only if it was serialized. 670 * 671 * @since 2.0.0 672 * 673 * @param string $data Data that might be unserialized. 674 * @return mixed Unserialized data can be any type. 675 */ 676 function maybe_unserialize( $data ) { 677 if ( is_serialized( $data ) ) { // Don't attempt to unserialize data that wasn't serialized going in. 678 return @unserialize( trim( $data ) ); 679 } 680 681 return $data; 682 } 683 684 /** 685 * Checks value to find if it was serialized. 686 * 687 * If $data is not a string, then returned value will always be false. 688 * Serialized data is always a string. 689 * 690 * @since 2.0.5 691 * @since 6.1.0 Added Enum support. 692 * 693 * @param string $data Value to check to see if was serialized. 694 * @param bool $strict Optional. Whether to be strict about the end of the string. Default true. 695 * @return bool False if not serialized and true if it was. 696 */ 697 function is_serialized( $data, $strict = true ) { 698 // If it isn't a string, it isn't serialized. 699 if ( ! is_string( $data ) ) { 700 return false; 701 } 702 $data = trim( $data ); 703 if ( 'N;' === $data ) { 704 return true; 705 } 706 if ( strlen( $data ) < 4 ) { 707 return false; 708 } 709 if ( ':' !== $data[1] ) { 710 return false; 711 } 712 if ( $strict ) { 713 $lastc = substr( $data, -1 ); 714 if ( ';' !== $lastc && '}' !== $lastc ) { 715 return false; 716 } 717 } else { 718 $semicolon = strpos( $data, ';' ); 719 $brace = strpos( $data, '}' ); 720 // Either ; or } must exist. 721 if ( false === $semicolon && false === $brace ) { 722 return false; 723 } 724 // But neither must be in the first X characters. 725 if ( false !== $semicolon && $semicolon < 3 ) { 726 return false; 727 } 728 if ( false !== $brace && $brace < 4 ) { 729 return false; 730 } 731 } 732 $token = $data[0]; 733 switch ( $token ) { 734 case 's': 735 if ( $strict ) { 736 if ( '"' !== substr( $data, -2, 1 ) ) { 737 return false; 738 } 739 } elseif ( ! str_contains( $data, '"' ) ) { 740 return false; 741 } 742 // Or else fall through. 743 case 'a': 744 case 'O': 745 case 'E': 746 return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data ); 747 case 'b': 748 case 'i': 749 case 'd': 750 $end = $strict ? '$' : ''; 751 return (bool) preg_match( "/^{$token}:[0-9.E+-]+;$end/", $data ); 752 } 753 return false; 754 } 755 756 /** 757 * Checks whether serialized data is of string type. 758 * 759 * @since 2.0.5 760 * 761 * @param string $data Serialized data. 762 * @return bool False if not a serialized string, true if it is. 763 */ 764 function is_serialized_string( $data ) { 765 // if it isn't a string, it isn't a serialized string. 766 if ( ! is_string( $data ) ) { 767 return false; 768 } 769 $data = trim( $data ); 770 if ( strlen( $data ) < 4 ) { 771 return false; 772 } elseif ( ':' !== $data[1] ) { 773 return false; 774 } elseif ( ! str_ends_with( $data, ';' ) ) { 775 return false; 776 } elseif ( 's' !== $data[0] ) { 777 return false; 778 } elseif ( '"' !== substr( $data, -2, 1 ) ) { 779 return false; 780 } else { 781 return true; 782 } 783 } 784 785 /** 786 * Retrieves post title from XML-RPC XML. 787 * 788 * If the `title` element is not found in the XML, the default post title 789 * from the `$post_default_title` global will be used instead. 790 * 791 * @since 0.71 792 * 793 * @global string $post_default_title Default XML-RPC post title. 794 * 795 * @param string $content XML-RPC XML Request content. 796 * @return string Post title. 797 */ 798 function xmlrpc_getposttitle( $content ) { 799 global $post_default_title; 800 if ( preg_match( '/<title>(.+?)<\/title>/is', $content, $matchtitle ) ) { 801 $post_title = $matchtitle[1]; 802 } else { 803 $post_title = $post_default_title; 804 } 805 return $post_title; 806 } 807 808 /** 809 * Retrieves the post category or categories from XML-RPC XML. 810 * 811 * If the `category` element is not found in the XML, the default post category 812 * from the `$post_default_category` global will be used instead. 813 * The return type will then be a string. 814 * 815 * If the `category` element is found, the return type will be an array. 816 * 817 * @since 0.71 818 * 819 * @global string $post_default_category Default XML-RPC post category. 820 * 821 * @param string $content XML-RPC XML Request content. 822 * @return string[]|string An array of category names or default category name. 823 */ 824 function xmlrpc_getpostcategory( $content ) { 825 global $post_default_category; 826 if ( preg_match( '/<category>(.+?)<\/category>/is', $content, $matchcat ) ) { 827 $post_category = trim( $matchcat[1], ',' ); 828 $post_category = explode( ',', $post_category ); 829 } else { 830 $post_category = $post_default_category; 831 } 832 return $post_category; 833 } 834 835 /** 836 * XML-RPC XML content without title and category elements. 837 * 838 * @since 0.71 839 * 840 * @param string $content XML-RPC XML Request content. 841 * @return string XML-RPC XML Request content without title and category elements. 842 */ 843 function xmlrpc_removepostdata( $content ) { 844 $content = preg_replace( '/<title>(.+?)<\/title>/si', '', $content ); 845 $content = preg_replace( '/<category>(.+?)<\/category>/si', '', $content ); 846 $content = trim( $content ); 847 return $content; 848 } 849 850 /** 851 * Uses RegEx to extract URLs from arbitrary content. 852 * 853 * @since 3.7.0 854 * @since 6.0.0 Fixes support for HTML entities (Trac 30580). 855 * 856 * @param string $content Content to extract URLs from. 857 * @return string[] Array of URLs found in passed string. 858 * 859 * @phpstan-return ( $content is empty ? array{} : list<string> ) 860 */ 861 function wp_extract_urls( $content ) { 862 preg_match_all( 863 "#([\"']?)(" 864 . '(?:([\w-]+:)?//?)' 865 . '[^\s()<>]+' 866 . '[.]' 867 . '(?:' 868 . '\([\w\d]+\)|' 869 . '(?:' 870 . "[^`!()\[\]{}:'\".,<>«»“”‘’\s]|" 871 . '(?:[:]\d+)?/?' 872 . ')+' 873 . ')' 874 . ")\\1#", 875 $content, 876 $post_links 877 ); 878 879 $post_links = array_unique( 880 array_map( 881 static function ( $link ) { 882 // Decode to replace valid entities, like &. 883 $link = html_entity_decode( $link ); 884 // Maintain backward compatibility by removing extraneous semi-colons (`;`). 885 return str_replace( ';', '', $link ); 886 }, 887 $post_links[2] 888 ) 889 ); 890 891 return array_values( $post_links ); 892 } 893 894 /** 895 * Checks content for video and audio links to add as enclosures. 896 * 897 * Will not add enclosures that have already been added and will 898 * remove enclosures that are no longer in the post. This is called as 899 * pingbacks and trackbacks. 900 * 901 * @since 1.5.0 902 * @since 5.3.0 The `$content` parameter was made optional, and the `$post` parameter was 903 * updated to accept a post ID or a WP_Post object. 904 * @since 5.6.0 The `$content` parameter is no longer optional, but passing `null` to skip it 905 * is still supported. 906 * 907 * @global wpdb $wpdb WordPress database abstraction object. 908 * 909 * @param string|null $content Post content. If `null`, the `post_content` field from `$post` is used. 910 * @param int|WP_Post $post Post ID or post object. 911 * @return void|false Void on success, false if the post is not found. 912 */ 913 function do_enclose( $content, $post ) { 914 global $wpdb; 915 916 // @todo Tidy this code and make the debug code optional. 917 require_once ABSPATH . WPINC . '/class-IXR.php'; 918 919 $post = get_post( $post ); 920 if ( ! $post ) { 921 return false; 922 } 923 924 if ( null === $content ) { 925 $content = $post->post_content; 926 } 927 928 $post_links = array(); 929 930 $pung = get_enclosed( $post->ID ); 931 932 $post_links_temp = wp_extract_urls( $content ); 933 934 foreach ( $pung as $link_test ) { 935 // Link is no longer in post. 936 if ( ! in_array( $link_test, $post_links_temp, true ) ) { 937 $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 ) . '%' ) ); 938 foreach ( $mids as $mid ) { 939 delete_metadata_by_mid( 'post', $mid ); 940 } 941 } 942 } 943 944 foreach ( (array) $post_links_temp as $link_test ) { 945 // If we haven't pung it already. 946 if ( ! in_array( $link_test, $pung, true ) ) { 947 $test = parse_url( $link_test ); 948 if ( false === $test ) { 949 continue; 950 } 951 if ( isset( $test['query'] ) ) { 952 $post_links[] = $link_test; 953 } elseif ( isset( $test['path'] ) && ( '/' !== $test['path'] ) && ( '' !== $test['path'] ) ) { 954 $post_links[] = $link_test; 955 } 956 } 957 } 958 959 /** 960 * Filters the list of enclosure links before querying the database. 961 * 962 * Allows for the addition and/or removal of potential enclosures to save 963 * to postmeta before checking the database for existing enclosures. 964 * 965 * @since 4.4.0 966 * 967 * @param string[] $post_links An array of enclosure links. 968 * @param int $post_id Post ID. 969 */ 970 $post_links = apply_filters( 'enclosure_links', $post_links, $post->ID ); 971 972 foreach ( (array) $post_links as $url ) { 973 $url = strip_fragment_from_url( $url ); 974 975 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 ) . '%' ) ) ) { 976 977 $headers = wp_get_http_headers( $url ); 978 if ( $headers ) { 979 $len = (int) ( $headers['Content-Length'] ?? 0 ); 980 $type = $headers['Content-Type'] ?? ''; 981 $allowed_types = array( 'video', 'audio' ); 982 983 // Check to see if we can figure out the mime type from the extension. 984 $url_parts = parse_url( $url ); 985 if ( false !== $url_parts && ! empty( $url_parts['path'] ) ) { 986 $extension = pathinfo( $url_parts['path'], PATHINFO_EXTENSION ); 987 if ( ! empty( $extension ) ) { 988 foreach ( wp_get_mime_types() as $exts => $mime ) { 989 if ( preg_match( '!^(' . $exts . ')$!i', $extension ) ) { 990 $type = $mime; 991 break; 992 } 993 } 994 } 995 } 996 997 if ( in_array( substr( $type, 0, strpos( $type, '/' ) ), $allowed_types, true ) ) { 998 add_post_meta( $post->ID, 'enclosure', "$url\n$len\n$mime\n" ); 999 } 1000 } 1001 } 1002 } 1003 } 1004 1005 /** 1006 * Retrieves HTTP Headers from URL. 1007 * 1008 * @since 1.5.1 1009 * 1010 * @param string $url URL to retrieve HTTP headers from. 1011 * @param bool $deprecated Not Used. 1012 * @return \WpOrg\Requests\Utility\CaseInsensitiveDictionary|false Headers on success, false on failure. 1013 * 1014 * @phpstan-param false $deprecated 1015 */ 1016 function wp_get_http_headers( $url, $deprecated = false ) { 1017 if ( ! empty( $deprecated ) ) { 1018 _deprecated_argument( __FUNCTION__, '2.7.0' ); 1019 } 1020 1021 $response = wp_safe_remote_head( $url ); 1022 1023 if ( is_wp_error( $response ) ) { 1024 return false; 1025 } 1026 1027 return wp_remote_retrieve_headers( $response ); 1028 } 1029 1030 /** 1031 * Determines whether the publish date of the current post in the loop is different 1032 * from the publish date of the previous post in the loop. 1033 * 1034 * For more information on this and similar theme functions, check out 1035 * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/ 1036 * Conditional Tags} article in the Theme Developer Handbook. 1037 * 1038 * @since 0.71 1039 * 1040 * @global string $currentday The day of the current post in the loop. 1041 * @global string $previousday The day of the previous post in the loop. 1042 * 1043 * @return int 1 when new day, 0 if not a new day. 1044 * 1045 * @phpstan-return 0|1 1046 */ 1047 function is_new_day() { 1048 global $currentday, $previousday; 1049 1050 if ( $currentday !== $previousday ) { 1051 return 1; 1052 } else { 1053 return 0; 1054 } 1055 } 1056 1057 /** 1058 * Builds a URL query based on an associative or indexed array. 1059 * 1060 * This is a convenient function for easily building URL queries. 1061 * It sets the separator to '&' and uses the _http_build_query() function. 1062 * 1063 * Unlike PHP's native http_build_query(), this function does NOT URL-encode 1064 * the keys or values. Callers are responsible for encoding values beforehand 1065 * with urlencode() or rawurlencode(), or late-escaping the output with 1066 * esc_url() before use. 1067 * 1068 * @since 2.3.0 1069 * 1070 * @see _http_build_query() Used to build the query. 1071 * @link https://www.php.net/manual/en/function.http-build-query.php for more on what 1072 * http_build_query() does. 1073 * 1074 * @param array $data Array of key/value pairs to build the query from. 1075 * @return string Query string, without URL encoding applied. 1076 */ 1077 function build_query( $data ) { 1078 return _http_build_query( $data, null, '&', '', false ); 1079 } 1080 1081 /** 1082 * From php.net (modified by Mark Jaquith to behave like the native PHP5 function). 1083 * 1084 * @since 3.2.0 1085 * @access private 1086 * 1087 * @link https://www.php.net/manual/en/function.http-build-query.php 1088 * 1089 * @param array|object $data An array or object of data. Converted to array. 1090 * @param string $prefix Optional. Numeric index. If set, start parameter numbering with it. 1091 * Default null. 1092 * @param string $sep Optional. Argument separator; defaults to 'arg_separator.output'. 1093 * Default null. 1094 * @param string $key Optional. Used to prefix key name. Default empty string. 1095 * @param bool $urlencode Optional. Whether to use urlencode() in the result. Default true. 1096 * @return string The query string. 1097 */ 1098 function _http_build_query( $data, $prefix = null, $sep = null, $key = '', $urlencode = true ) { 1099 $ret = array(); 1100 1101 foreach ( (array) $data as $k => $v ) { 1102 if ( $urlencode ) { 1103 $k = urlencode( $k ); 1104 } 1105 1106 if ( is_int( $k ) && null !== $prefix ) { 1107 $k = $prefix . $k; 1108 } 1109 1110 if ( ! empty( $key ) ) { 1111 $k = $key . '%5B' . $k . '%5D'; 1112 } 1113 1114 if ( null === $v ) { 1115 continue; 1116 } elseif ( false === $v ) { 1117 $v = '0'; 1118 } 1119 1120 if ( is_array( $v ) || is_object( $v ) ) { 1121 array_push( $ret, _http_build_query( $v, '', $sep, $k, $urlencode ) ); 1122 } elseif ( $urlencode ) { 1123 array_push( $ret, $k . '=' . urlencode( $v ) ); 1124 } else { 1125 array_push( $ret, $k . '=' . $v ); 1126 } 1127 } 1128 1129 if ( null === $sep ) { 1130 $sep = ini_get( 'arg_separator.output' ); 1131 } 1132 1133 return implode( $sep, $ret ); 1134 } 1135 1136 /** 1137 * Retrieves a modified URL query string. 1138 * 1139 * You can rebuild the URL and append query variables to the URL query by using this function. 1140 * There are two ways to use this function; either a single key and value, or an associative array. 1141 * 1142 * Using a single key and value: 1143 * 1144 * add_query_arg( 'key', 'value', 'http://example.com' ); 1145 * 1146 * Using an associative array: 1147 * 1148 * add_query_arg( array( 1149 * 'key1' => 'value1', 1150 * 'key2' => 'value2', 1151 * ), 'http://example.com' ); 1152 * 1153 * Omitting the URL from either use results in the current URL being used 1154 * (the value of `$_SERVER['REQUEST_URI']`). 1155 * 1156 * Values are expected to be encoded appropriately with urlencode() or rawurlencode(). 1157 * 1158 * Setting any query variable's value to boolean false removes the key (see remove_query_arg()). 1159 * 1160 * Important: The return value of add_query_arg() is not escaped by default. Output should be 1161 * late-escaped with esc_url() or similar to help prevent vulnerability to cross-site scripting 1162 * (XSS) attacks. 1163 * 1164 * @since 1.5.0 1165 * @since 5.3.0 Formalized the existing and already documented parameters 1166 * by adding `...$args` to the function signature. 1167 * 1168 * @param mixed ...$args Either a query variable key (string), its value (required; false removes 1169 * the key), and an optional URL (string), or an associative array of query 1170 * variables and an optional URL (string). If the URL is omitted or false, 1171 * the current URL (`$_SERVER['REQUEST_URI']`) is used. 1172 * @return string New URL query string (unescaped). 1173 */ 1174 function add_query_arg( ...$args ) { 1175 if ( is_array( $args[0] ) ) { 1176 if ( count( $args ) < 2 || false === $args[1] ) { 1177 $uri = $_SERVER['REQUEST_URI']; 1178 } else { 1179 $uri = $args[1]; 1180 } 1181 } else { 1182 if ( count( $args ) < 3 || false === $args[2] ) { 1183 $uri = $_SERVER['REQUEST_URI']; 1184 } else { 1185 $uri = $args[2]; 1186 } 1187 } 1188 1189 $frag = strstr( $uri, '#' ); 1190 if ( $frag ) { 1191 $uri = substr( $uri, 0, -strlen( $frag ) ); 1192 } else { 1193 $frag = ''; 1194 } 1195 1196 if ( 0 === stripos( $uri, 'http://' ) ) { 1197 $protocol = 'http://'; 1198 $uri = substr( $uri, 7 ); 1199 } elseif ( 0 === stripos( $uri, 'https://' ) ) { 1200 $protocol = 'https://'; 1201 $uri = substr( $uri, 8 ); 1202 } else { 1203 $protocol = ''; 1204 } 1205 1206 if ( str_contains( $uri, '?' ) ) { 1207 list( $base, $query ) = explode( '?', $uri, 2 ); 1208 $base .= '?'; 1209 } elseif ( $protocol || ! str_contains( $uri, '=' ) ) { 1210 $base = $uri . '?'; 1211 $query = ''; 1212 } else { 1213 $base = ''; 1214 $query = $uri; 1215 } 1216 1217 wp_parse_str( $query, $qs ); 1218 $qs = urlencode_deep( $qs ); // This re-URL-encodes things that were already in the query string. 1219 if ( is_array( $args[0] ) ) { 1220 foreach ( $args[0] as $k => $v ) { 1221 $qs[ $k ] = $v; 1222 } 1223 } else { 1224 $qs[ $args[0] ] = $args[1]; 1225 } 1226 1227 foreach ( $qs as $k => $v ) { 1228 if ( false === $v ) { 1229 unset( $qs[ $k ] ); 1230 } 1231 } 1232 1233 $ret = build_query( $qs ); 1234 $ret = trim( $ret, '?' ); 1235 $ret = preg_replace( '#=(&|$)#', '$1', $ret ); 1236 $ret = $protocol . $base . $ret . $frag; 1237 $ret = rtrim( $ret, '?' ); 1238 $ret = str_replace( '?#', '#', $ret ); 1239 return $ret; 1240 } 1241 1242 /** 1243 * Removes an item or items from a query string. 1244 * 1245 * Important: The return value of remove_query_arg() is not escaped by default. Output should be 1246 * late-escaped with esc_url() or similar to help prevent vulnerability to cross-site scripting 1247 * (XSS) attacks. 1248 * 1249 * @since 1.5.0 1250 * 1251 * @param string|string[] $key Query key or keys to remove. 1252 * @param false|string $query Optional. When false uses the current URL. Default false. 1253 * @return string New URL query string. 1254 */ 1255 function remove_query_arg( $key, $query = false ) { 1256 if ( is_array( $key ) ) { // Removing multiple keys. 1257 foreach ( $key as $k ) { 1258 $query = add_query_arg( $k, false, $query ); 1259 } 1260 return $query; 1261 } 1262 return add_query_arg( $key, false, $query ); 1263 } 1264 1265 /** 1266 * Returns an array of single-use query variable names that can be removed from a URL. 1267 * 1268 * @since 4.4.0 1269 * 1270 * @return string[] An array of query variable names to remove from the URL. 1271 */ 1272 function wp_removable_query_args() { 1273 $removable_query_args = array( 1274 'activate', 1275 'activated', 1276 'admin_email_remind_later', 1277 'admin_email_updated', 1278 'approved', 1279 'core-major-auto-updates-saved', 1280 'deactivate', 1281 'delete_count', 1282 'deleted', 1283 'disabled', 1284 'doing_wp_cron', 1285 'enabled', 1286 'error', 1287 'hotkeys_highlight_first', 1288 'hotkeys_highlight_last', 1289 'ids', 1290 'locked', 1291 'message', 1292 'network_admin_email_updated', 1293 'same', 1294 'saved', 1295 'settings-updated', 1296 'skipped', 1297 'spammed', 1298 'trashed', 1299 'translation_updates', 1300 'unspammed', 1301 'untrashed', 1302 'update', 1303 'updated', 1304 'wp-post-new-reload', 1305 ); 1306 1307 /** 1308 * Filters the list of query variable names to remove. 1309 * 1310 * @since 4.2.0 1311 * 1312 * @param string[] $removable_query_args An array of query variable names to remove from a URL. 1313 */ 1314 return apply_filters( 'removable_query_args', $removable_query_args ); 1315 } 1316 1317 /** 1318 * Walks the array while sanitizing the contents. 1319 * 1320 * @since 0.71 1321 * @since 5.5.0 Non-string values are left untouched. 1322 * 1323 * @param array $input_array Array to walk while sanitizing contents. 1324 * @return array Sanitized $input_array. 1325 * 1326 * @phpstan-template T of array 1327 * @phpstan-param T $input_array 1328 * @phpstan-return array<key-of<T>, ( value-of<T> is string ? string : value-of<T> )> 1329 */ 1330 function add_magic_quotes( $input_array ) { 1331 foreach ( (array) $input_array as $k => $v ) { 1332 if ( is_array( $v ) ) { 1333 $input_array[ $k ] = add_magic_quotes( $v ); 1334 } elseif ( is_string( $v ) ) { 1335 $input_array[ $k ] = addslashes( $v ); 1336 } 1337 } 1338 1339 return $input_array; 1340 } 1341 1342 /** 1343 * HTTP request for URI to retrieve content. 1344 * 1345 * @since 1.5.1 1346 * 1347 * @see wp_safe_remote_get() 1348 * 1349 * @param string $uri URI/URL of web page to retrieve. 1350 * @return string|false HTTP content. False on failure. 1351 */ 1352 function wp_remote_fopen( $uri ) { 1353 $parsed_url = parse_url( $uri ); 1354 1355 if ( ! $parsed_url || ! is_array( $parsed_url ) ) { 1356 return false; 1357 } 1358 1359 $options = array(); 1360 $options['timeout'] = 10; 1361 1362 $response = wp_safe_remote_get( $uri, $options ); 1363 1364 if ( is_wp_error( $response ) ) { 1365 return false; 1366 } 1367 1368 return wp_remote_retrieve_body( $response ); 1369 } 1370 1371 /** 1372 * Sets up the WordPress query. 1373 * 1374 * @since 2.0.0 1375 * 1376 * @global WP $wp Current WordPress environment instance. 1377 * @global WP_Query $wp_query WordPress Query object. 1378 * @global WP_Query $wp_the_query Copy of the WordPress Query object. 1379 * 1380 * @param string|array $query_vars Default WP_Query arguments. 1381 */ 1382 function wp( $query_vars = '' ) { 1383 global $wp, $wp_query, $wp_the_query; 1384 1385 $wp->main( $query_vars ); 1386 1387 if ( ! isset( $wp_the_query ) ) { 1388 $wp_the_query = $wp_query; 1389 } 1390 } 1391 1392 /** 1393 * Retrieves the description for the HTTP status. 1394 * 1395 * @since 2.3.0 1396 * @since 3.9.0 Added status codes 418, 428, 429, 431, and 511. 1397 * @since 4.5.0 Added status codes 308, 421, and 451. 1398 * @since 5.1.0 Added status code 103. 1399 * @since 6.6.0 Added status code 425. 1400 * 1401 * @global array $wp_header_to_desc 1402 * 1403 * @param int $code HTTP status code. 1404 * @return string Status description if found, an empty string otherwise. 1405 */ 1406 function get_status_header_desc( $code ) { 1407 global $wp_header_to_desc; 1408 1409 $code = absint( $code ); 1410 1411 if ( ! isset( $wp_header_to_desc ) ) { 1412 $wp_header_to_desc = array( 1413 100 => 'Continue', 1414 101 => 'Switching Protocols', 1415 102 => 'Processing', 1416 103 => 'Early Hints', 1417 1418 200 => 'OK', 1419 201 => 'Created', 1420 202 => 'Accepted', 1421 203 => 'Non-Authoritative Information', 1422 204 => 'No Content', 1423 205 => 'Reset Content', 1424 206 => 'Partial Content', 1425 207 => 'Multi-Status', 1426 226 => 'IM Used', 1427 1428 300 => 'Multiple Choices', 1429 301 => 'Moved Permanently', 1430 302 => 'Found', 1431 303 => 'See Other', 1432 304 => 'Not Modified', 1433 305 => 'Use Proxy', 1434 306 => 'Reserved', 1435 307 => 'Temporary Redirect', 1436 308 => 'Permanent Redirect', 1437 1438 400 => 'Bad Request', 1439 401 => 'Unauthorized', 1440 402 => 'Payment Required', 1441 403 => 'Forbidden', 1442 404 => 'Not Found', 1443 405 => 'Method Not Allowed', 1444 406 => 'Not Acceptable', 1445 407 => 'Proxy Authentication Required', 1446 408 => 'Request Timeout', 1447 409 => 'Conflict', 1448 410 => 'Gone', 1449 411 => 'Length Required', 1450 412 => 'Precondition Failed', 1451 413 => 'Request Entity Too Large', 1452 414 => 'Request-URI Too Long', 1453 415 => 'Unsupported Media Type', 1454 416 => 'Requested Range Not Satisfiable', 1455 417 => 'Expectation Failed', 1456 418 => 'I\'m a teapot', 1457 421 => 'Misdirected Request', 1458 422 => 'Unprocessable Entity', 1459 423 => 'Locked', 1460 424 => 'Failed Dependency', 1461 425 => 'Too Early', 1462 426 => 'Upgrade Required', 1463 428 => 'Precondition Required', 1464 429 => 'Too Many Requests', 1465 431 => 'Request Header Fields Too Large', 1466 451 => 'Unavailable For Legal Reasons', 1467 1468 500 => 'Internal Server Error', 1469 501 => 'Not Implemented', 1470 502 => 'Bad Gateway', 1471 503 => 'Service Unavailable', 1472 504 => 'Gateway Timeout', 1473 505 => 'HTTP Version Not Supported', 1474 506 => 'Variant Also Negotiates', 1475 507 => 'Insufficient Storage', 1476 510 => 'Not Extended', 1477 511 => 'Network Authentication Required', 1478 ); 1479 } 1480 1481 return $wp_header_to_desc[ $code ] ?? ''; 1482 } 1483 1484 /** 1485 * Sets HTTP status header. 1486 * 1487 * @since 2.0.0 1488 * @since 4.4.0 Added the `$description` parameter. 1489 * 1490 * @see get_status_header_desc() 1491 * 1492 * @param int $code HTTP status code. 1493 * @param string $description Optional. A custom description for the HTTP status. 1494 * Defaults to the result of get_status_header_desc() for the given code. 1495 */ 1496 function status_header( $code, $description = '' ) { 1497 if ( ! $description ) { 1498 $description = get_status_header_desc( $code ); 1499 } 1500 1501 if ( empty( $description ) ) { 1502 return; 1503 } 1504 1505 $protocol = wp_get_server_protocol(); 1506 $status_header = "$protocol $code $description"; 1507 if ( function_exists( 'apply_filters' ) ) { 1508 1509 /** 1510 * Filters an HTTP status header. 1511 * 1512 * @since 2.2.0 1513 * 1514 * @param string $status_header HTTP status header. 1515 * @param int $code HTTP status code. 1516 * @param string $description Description for the status code. 1517 * @param string $protocol Server protocol. 1518 */ 1519 $status_header = apply_filters( 'status_header', $status_header, $code, $description, $protocol ); 1520 } 1521 1522 if ( ! headers_sent() ) { 1523 header( $status_header, true, $code ); 1524 } 1525 } 1526 1527 /** 1528 * Gets the HTTP header information to prevent caching. 1529 * 1530 * The several different headers cover the different ways cache prevention 1531 * is handled by different browsers or intermediate caches such as proxy servers. 1532 * 1533 * @since 2.8.0 1534 * @since 6.3.0 The `Cache-Control` header for logged in users now includes the 1535 * `no-store` and `private` directives. 1536 * @since 6.8.0 The `Cache-Control` header now includes the `no-store` and `private` 1537 * directives regardless of whether a user is logged in. 1538 * 1539 * @return array The associative array of header names and field values. 1540 */ 1541 function wp_get_nocache_headers() { 1542 $cache_control = 'no-cache, must-revalidate, max-age=0, no-store, private'; 1543 1544 $headers = array( 1545 'Expires' => 'Wed, 11 Jan 1984 05:00:00 GMT', 1546 'Cache-Control' => $cache_control, 1547 ); 1548 1549 if ( function_exists( 'apply_filters' ) ) { 1550 /** 1551 * Filters the cache-controlling HTTP headers that are used to prevent caching. 1552 * 1553 * @since 2.8.0 1554 * 1555 * @see wp_get_nocache_headers() 1556 * 1557 * @param array $headers Header names and field values. 1558 */ 1559 $headers = (array) apply_filters( 'nocache_headers', $headers ); 1560 } 1561 $headers['Last-Modified'] = false; 1562 return $headers; 1563 } 1564 1565 /** 1566 * Sets the HTTP headers to prevent caching for the different browsers. 1567 * 1568 * Different browsers support different nocache headers, so several 1569 * headers must be sent so that all of them get the point that no 1570 * caching should occur. 1571 * 1572 * @since 2.0.0 1573 * 1574 * @see wp_get_nocache_headers() 1575 */ 1576 function nocache_headers() { 1577 if ( headers_sent() ) { 1578 return; 1579 } 1580 1581 $headers = wp_get_nocache_headers(); 1582 1583 unset( $headers['Last-Modified'] ); 1584 1585 header_remove( 'Last-Modified' ); 1586 1587 foreach ( $headers as $name => $field_value ) { 1588 header( "{$name}: {$field_value}" ); 1589 } 1590 } 1591 1592 /** 1593 * Sets the HTTP headers for caching for 10 days with JavaScript content type. 1594 * 1595 * @since 2.1.0 1596 */ 1597 function cache_javascript_headers() { 1598 $expires_offset = 10 * DAY_IN_SECONDS; 1599 1600 header( 'Content-Type: text/javascript; charset=' . get_bloginfo( 'charset' ) ); 1601 header( 'Vary: Accept-Encoding' ); // Handle proxies. 1602 header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', time() + $expires_offset ) . ' GMT' ); 1603 } 1604 1605 /** 1606 * Retrieves the number of database queries during the WordPress execution. 1607 * 1608 * @since 2.0.0 1609 * 1610 * @global wpdb $wpdb WordPress database abstraction object. 1611 * 1612 * @return int Number of database queries. 1613 */ 1614 function get_num_queries() { 1615 global $wpdb; 1616 return $wpdb->num_queries; 1617 } 1618 1619 /** 1620 * Determines whether input is yes or no. 1621 * 1622 * Must be 'y' to be true. 1623 * 1624 * @since 1.0.0 1625 * 1626 * @param string $yn Character string containing either 'y' (yes) or 'n' (no). 1627 * @return bool True if 'y', false on anything else. 1628 * 1629 * @phpstan-return ( $yn is 'y'|'Y' ? true : false ) 1630 */ 1631 function bool_from_yn( $yn ) { 1632 return ( 'y' === strtolower( $yn ) ); 1633 } 1634 1635 /** 1636 * Loads the feed template from the use of an action hook. 1637 * 1638 * If the feed action does not have a hook, then the function will die with a 1639 * message telling the visitor that the feed is not valid. 1640 * 1641 * It is better to only have one hook for each feed. 1642 * 1643 * @since 2.1.0 1644 * 1645 * @global WP_Query $wp_query WordPress Query object. 1646 */ 1647 function do_feed() { 1648 global $wp_query; 1649 1650 $feed = get_query_var( 'feed' ); 1651 1652 // Remove the pad, if present. 1653 $feed = preg_replace( '/^_+/', '', $feed ); 1654 1655 if ( '' === $feed || 'feed' === $feed ) { 1656 $feed = get_default_feed(); 1657 } 1658 1659 if ( ! has_action( "do_feed_{$feed}" ) ) { 1660 wp_die( __( '<strong>Error:</strong> This is not a valid feed template.' ), '', array( 'response' => 404 ) ); 1661 } 1662 1663 /** 1664 * Fires once the given feed is loaded. 1665 * 1666 * The dynamic portion of the hook name, `$feed`, refers to the feed template name. 1667 * 1668 * Possible hook names include: 1669 * 1670 * - `do_feed_atom` 1671 * - `do_feed_rdf` 1672 * - `do_feed_rss` 1673 * - `do_feed_rss2` 1674 * 1675 * @since 2.1.0 1676 * @since 4.4.0 The `$feed` parameter was added. 1677 * 1678 * @param bool $is_comment_feed Whether the feed is a comment feed. 1679 * @param string $feed The feed name. 1680 */ 1681 do_action( "do_feed_{$feed}", $wp_query->is_comment_feed, $feed ); 1682 } 1683 1684 /** 1685 * Loads the RDF RSS 0.91 Feed template. 1686 * 1687 * @since 2.1.0 1688 * 1689 * @see load_template() 1690 */ 1691 function do_feed_rdf() { 1692 load_template( ABSPATH . WPINC . '/feed-rdf.php' ); 1693 } 1694 1695 /** 1696 * Loads the RSS 1.0 Feed Template. 1697 * 1698 * @since 2.1.0 1699 * 1700 * @see load_template() 1701 */ 1702 function do_feed_rss() { 1703 load_template( ABSPATH . WPINC . '/feed-rss.php' ); 1704 } 1705 1706 /** 1707 * Loads either the RSS2 comment feed or the RSS2 posts feed. 1708 * 1709 * @since 2.1.0 1710 * 1711 * @see load_template() 1712 * 1713 * @param bool $for_comments True for the comment feed, false for normal feed. 1714 */ 1715 function do_feed_rss2( $for_comments ) { 1716 if ( $for_comments ) { 1717 load_template( ABSPATH . WPINC . '/feed-rss2-comments.php' ); 1718 } else { 1719 load_template( ABSPATH . WPINC . '/feed-rss2.php' ); 1720 } 1721 } 1722 1723 /** 1724 * Loads either Atom comment feed or Atom posts feed. 1725 * 1726 * @since 2.1.0 1727 * 1728 * @see load_template() 1729 * 1730 * @param bool $for_comments True for the comment feed, false for normal feed. 1731 */ 1732 function do_feed_atom( $for_comments ) { 1733 if ( $for_comments ) { 1734 load_template( ABSPATH . WPINC . '/feed-atom-comments.php' ); 1735 } else { 1736 load_template( ABSPATH . WPINC . '/feed-atom.php' ); 1737 } 1738 } 1739 1740 /** 1741 * Displays the default robots.txt file content. 1742 * 1743 * @since 2.1.0 1744 * @since 5.3.0 Remove the "Disallow: /" output if search engine visibility is 1745 * discouraged in favor of robots meta HTML tag via wp_robots_no_robots() 1746 * filter callback. 1747 */ 1748 function do_robots() { 1749 if ( ! headers_sent() ) { 1750 header( 'Content-Type: text/plain; charset=utf-8' ); 1751 } 1752 1753 /** 1754 * Fires when displaying the robots.txt file. 1755 * 1756 * @since 2.1.0 1757 */ 1758 do_action( 'do_robotstxt' ); 1759 1760 $output = "User-agent: *\n"; 1761 $public = (bool) get_option( 'blog_public' ); 1762 1763 $output .= 'Disallow: ' . wp_parse_url( admin_url(), PHP_URL_PATH ) . "\n"; 1764 $output .= 'Allow: ' . wp_parse_url( admin_url( 'admin-ajax.php' ), PHP_URL_PATH ) . "\n"; 1765 1766 /** 1767 * Filters the robots.txt output. 1768 * 1769 * @since 3.0.0 1770 * 1771 * @param string $output The robots.txt output. 1772 * @param bool $public Whether the site is considered "public". 1773 */ 1774 echo apply_filters( 'robots_txt', $output, $public ); 1775 } 1776 1777 /** 1778 * Displays the favicon.ico file content. 1779 * 1780 * @since 5.4.0 1781 * 1782 * @return never 1783 */ 1784 function do_favicon() { 1785 /** 1786 * Fires when serving the favicon.ico file. 1787 * 1788 * @since 5.4.0 1789 */ 1790 do_action( 'do_faviconico' ); 1791 1792 wp_redirect( get_site_icon_url( 32, includes_url( 'images/w-logo-gray-white-bg.png' ) ) ); 1793 exit; 1794 } 1795 1796 /** 1797 * Determines whether WordPress is already installed. 1798 * 1799 * The cache will be checked first. If you have a cache plugin, which saves 1800 * the cache values, then this will work. If you use the default WordPress 1801 * cache, and the database goes away, then you might have problems. 1802 * 1803 * Checks for the 'siteurl' option for whether WordPress is installed. 1804 * 1805 * For more information on this and similar theme functions, check out 1806 * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/ 1807 * Conditional Tags} article in the Theme Developer Handbook. 1808 * 1809 * @since 2.1.0 1810 * 1811 * @global wpdb $wpdb WordPress database abstraction object. 1812 * 1813 * @return bool Whether the site is already installed. 1814 */ 1815 function is_blog_installed() { 1816 global $wpdb; 1817 1818 /* 1819 * Check cache first. If options table goes away and we have true 1820 * cached, oh well. 1821 */ 1822 if ( wp_cache_get( 'is_blog_installed' ) ) { 1823 return true; 1824 } 1825 1826 $suppress = $wpdb->suppress_errors(); 1827 1828 if ( ! wp_installing() ) { 1829 $alloptions = wp_load_alloptions(); 1830 } 1831 1832 // If siteurl is not set to autoload, check it specifically. 1833 if ( ! isset( $alloptions['siteurl'] ) ) { 1834 $installed = $wpdb->get_var( "SELECT option_value FROM $wpdb->options WHERE option_name = 'siteurl'" ); 1835 } else { 1836 $installed = $alloptions['siteurl']; 1837 } 1838 1839 $wpdb->suppress_errors( $suppress ); 1840 1841 $installed = ! empty( $installed ); 1842 wp_cache_set( 'is_blog_installed', $installed ); 1843 1844 if ( $installed ) { 1845 return true; 1846 } 1847 1848 // If visiting repair.php, return true and let it take over. 1849 if ( defined( 'WP_REPAIRING' ) ) { 1850 return true; 1851 } 1852 1853 $suppress = $wpdb->suppress_errors(); 1854 1855 /* 1856 * Loop over the WP tables. If none exist, then scratch installation is allowed. 1857 * If one or more exist, suggest table repair since we got here because the 1858 * options table could not be accessed. 1859 */ 1860 $wp_tables = $wpdb->tables(); 1861 foreach ( $wp_tables as $table ) { 1862 // The existence of custom user tables shouldn't suggest an unwise state or prevent a clean installation. 1863 if ( defined( 'CUSTOM_USER_TABLE' ) && CUSTOM_USER_TABLE === $table ) { 1864 continue; 1865 } 1866 1867 if ( defined( 'CUSTOM_USER_META_TABLE' ) && CUSTOM_USER_META_TABLE === $table ) { 1868 continue; 1869 } 1870 1871 $described_table = $wpdb->get_results( "DESCRIBE $table;" ); 1872 if ( 1873 ( ! $described_table && empty( $wpdb->last_error ) ) || 1874 ( is_array( $described_table ) && 0 === count( $described_table ) ) 1875 ) { 1876 continue; 1877 } 1878 1879 // One or more tables exist. This is not good. 1880 1881 wp_load_translations_early(); 1882 1883 // Die with a DB error. 1884 $wpdb->error = sprintf( 1885 /* translators: %s: Database repair URL. */ 1886 __( 'One or more database tables are unavailable. The database may need to be <a href="%s">repaired</a>.' ), 1887 'maint/repair.php?referrer=is_blog_installed' 1888 ); 1889 1890 dead_db(); 1891 } 1892 1893 $wpdb->suppress_errors( $suppress ); 1894 1895 wp_cache_set( 'is_blog_installed', false ); 1896 1897 return false; 1898 } 1899 1900 /** 1901 * Retrieves URL with nonce added to URL query. 1902 * 1903 * @since 2.0.4 1904 * 1905 * @param string $actionurl URL to add nonce action. 1906 * @param int|string $action Optional. Nonce action name. Default -1. 1907 * @param string $name Optional. Nonce name. Default '_wpnonce'. 1908 * @return string Escaped URL with nonce action added. 1909 */ 1910 function wp_nonce_url( $actionurl, $action = -1, $name = '_wpnonce' ) { 1911 $actionurl = str_replace( '&', '&', $actionurl ); 1912 return esc_html( add_query_arg( $name, wp_create_nonce( $action ), $actionurl ) ); 1913 } 1914 1915 /** 1916 * Retrieves or display nonce hidden field for forms. 1917 * 1918 * The nonce field is used to validate that the contents of the form came from 1919 * the location on the current site and not somewhere else. The nonce does not 1920 * offer absolute protection, but should protect against most cases. It is very 1921 * important to use nonce field in forms. 1922 * 1923 * The $action and $name are optional, but if you want to have better security, 1924 * it is strongly suggested to set those two parameters. It is easier to just 1925 * call the function without any parameters, because validation of the nonce 1926 * doesn't require any parameters, but since crackers know what the default is 1927 * it won't be difficult for them to find a way around your nonce and cause 1928 * damage. 1929 * 1930 * The input name will be whatever $name value you gave. The input value will be 1931 * the nonce creation value. 1932 * 1933 * @since 2.0.4 1934 * 1935 * @param int|string $action Optional. Action name. Default -1. 1936 * @param string $name Optional. Nonce name. Default '_wpnonce'. 1937 * @param bool $referer Optional. Whether to set the referer field for validation. Default true. 1938 * @param bool $display Optional. Whether to display or return hidden form field. Default true. 1939 * @return string Nonce field HTML markup. 1940 */ 1941 function wp_nonce_field( $action = -1, $name = '_wpnonce', $referer = true, $display = true ) { 1942 $name = esc_attr( $name ); 1943 $nonce_field = '<input type="hidden" id="' . $name . '" name="' . $name . '" value="' . wp_create_nonce( $action ) . '" />'; 1944 1945 if ( $referer ) { 1946 $nonce_field .= wp_referer_field( false ); 1947 } 1948 1949 if ( $display ) { 1950 echo $nonce_field; 1951 } 1952 1953 return $nonce_field; 1954 } 1955 1956 /** 1957 * Retrieves or displays referer hidden field for forms. 1958 * 1959 * The referer link is the current Request URI from the server super global. The 1960 * input name is '_wp_http_referer', in case you wanted to check manually. 1961 * 1962 * @since 2.0.4 1963 * 1964 * @param bool $display Optional. Whether to echo or return the referer field. Default true. 1965 * @return string Referer field HTML markup. 1966 */ 1967 function wp_referer_field( $display = true ) { 1968 $request_url = remove_query_arg( '_wp_http_referer' ); 1969 $referer_field = '<input type="hidden" name="_wp_http_referer" value="' . esc_url( $request_url ) . '" />'; 1970 1971 if ( $display ) { 1972 echo $referer_field; 1973 } 1974 1975 return $referer_field; 1976 } 1977 1978 /** 1979 * Retrieves or displays original referer hidden field for forms. 1980 * 1981 * The input name is '_wp_original_http_referer' and will be either the same 1982 * value of wp_referer_field(), if that was posted already or it will be the 1983 * current page, if it doesn't exist. 1984 * 1985 * @since 2.0.4 1986 * 1987 * @param bool $display Optional. Whether to echo the original http referer. Default true. 1988 * @param string $jump_back_to Optional. Can be 'previous' or page you want to jump back to. 1989 * Default 'current'. 1990 * @return string Original referer field. 1991 */ 1992 function wp_original_referer_field( $display = true, $jump_back_to = 'current' ) { 1993 $ref = wp_get_original_referer(); 1994 1995 if ( ! $ref ) { 1996 $ref = ( 'previous' === $jump_back_to ) ? wp_get_referer() : wp_unslash( $_SERVER['REQUEST_URI'] ); 1997 } 1998 1999 $orig_referer_field = '<input type="hidden" name="_wp_original_http_referer" value="' . esc_attr( $ref ) . '" />'; 2000 2001 if ( $display ) { 2002 echo $orig_referer_field; 2003 } 2004 2005 return $orig_referer_field; 2006 } 2007 2008 /** 2009 * Retrieves referer from '_wp_http_referer' or HTTP referer. 2010 * 2011 * If it's the same as the current request URL, will return false. 2012 * 2013 * @since 2.0.4 2014 * 2015 * @return string|false Referer URL on success, false on failure. 2016 */ 2017 function wp_get_referer() { 2018 // Return early if called before wp_validate_redirect() is defined. 2019 if ( ! function_exists( 'wp_validate_redirect' ) ) { 2020 return false; 2021 } 2022 2023 $ref = wp_get_raw_referer(); 2024 2025 if ( $ref && wp_unslash( $_SERVER['REQUEST_URI'] ) !== $ref 2026 && home_url() . wp_unslash( $_SERVER['REQUEST_URI'] ) !== $ref 2027 ) { 2028 return wp_validate_redirect( $ref, false ); 2029 } 2030 2031 return false; 2032 } 2033 2034 /** 2035 * Retrieves unvalidated referer from the '_wp_http_referer' URL query variable or the HTTP referer. 2036 * 2037 * If the value of the '_wp_http_referer' URL query variable is not a string then it will be ignored. 2038 * 2039 * Do not use for redirects, use wp_get_referer() instead. 2040 * 2041 * @since 4.5.0 2042 * 2043 * @return string|false Referer URL on success, false on failure. 2044 */ 2045 function wp_get_raw_referer() { 2046 if ( ! empty( $_REQUEST['_wp_http_referer'] ) && is_string( $_REQUEST['_wp_http_referer'] ) ) { 2047 return wp_unslash( $_REQUEST['_wp_http_referer'] ); 2048 } elseif ( ! empty( $_SERVER['HTTP_REFERER'] ) ) { 2049 return wp_unslash( $_SERVER['HTTP_REFERER'] ); 2050 } 2051 2052 return false; 2053 } 2054 2055 /** 2056 * Retrieves original referer that was posted, if it exists. 2057 * 2058 * @since 2.0.4 2059 * 2060 * @return string|false Original referer URL on success, false on failure. 2061 */ 2062 function wp_get_original_referer() { 2063 // Return early if called before wp_validate_redirect() is defined. 2064 if ( ! function_exists( 'wp_validate_redirect' ) ) { 2065 return false; 2066 } 2067 2068 if ( ! empty( $_REQUEST['_wp_original_http_referer'] ) ) { 2069 return wp_validate_redirect( wp_unslash( $_REQUEST['_wp_original_http_referer'] ), false ); 2070 } 2071 2072 return false; 2073 } 2074 2075 /** 2076 * Recursive directory creation based on full path. 2077 * 2078 * Will attempt to set permissions on folders. 2079 * 2080 * @since 2.0.1 2081 * 2082 * @param string $target Full path to attempt to create. 2083 * @return bool Whether the path was created. True if path already exists. 2084 */ 2085 function wp_mkdir_p( $target ) { 2086 $wrapper = null; 2087 2088 // Strip the protocol. 2089 if ( wp_is_stream( $target ) ) { 2090 list( $wrapper, $target ) = explode( '://', $target, 2 ); 2091 } 2092 2093 // From php.net/mkdir user contributed notes. 2094 $target = str_replace( '//', '/', $target ); 2095 2096 // Put the wrapper back on the target. 2097 if ( null !== $wrapper ) { 2098 $target = $wrapper . '://' . $target; 2099 } 2100 2101 /* 2102 * Safe mode fails with a trailing slash under certain PHP versions. 2103 * Use rtrim() instead of untrailingslashit to avoid formatting.php dependency. 2104 */ 2105 $target = rtrim( $target, '/' ); 2106 if ( empty( $target ) ) { 2107 $target = '/'; 2108 } 2109 2110 if ( file_exists( $target ) ) { 2111 return @is_dir( $target ); 2112 } 2113 2114 // Do not allow path traversals. 2115 if ( str_contains( $target, '../' ) || str_contains( $target, '..' . DIRECTORY_SEPARATOR ) ) { 2116 return false; 2117 } 2118 2119 // We need to find the permissions of the parent folder that exists and inherit that. 2120 $target_parent = dirname( $target ); 2121 while ( '.' !== $target_parent && ! is_dir( $target_parent ) && dirname( $target_parent ) !== $target_parent ) { 2122 $target_parent = dirname( $target_parent ); 2123 } 2124 2125 // Get the permission bits. 2126 $stat = @stat( $target_parent ); 2127 if ( $stat ) { 2128 $dir_perms = $stat['mode'] & 0007777; 2129 } else { 2130 $dir_perms = 0777; 2131 } 2132 2133 if ( @mkdir( $target, $dir_perms, true ) ) { 2134 2135 /* 2136 * If a umask is set that modifies $dir_perms, we'll have to re-set 2137 * the $dir_perms correctly with chmod() 2138 */ 2139 if ( ( $dir_perms & ~umask() ) !== $dir_perms ) { 2140 $folder_parts = explode( '/', substr( $target, strlen( $target_parent ) + 1 ) ); 2141 for ( $i = 1, $c = count( $folder_parts ); $i <= $c; $i++ ) { 2142 chmod( $target_parent . '/' . implode( '/', array_slice( $folder_parts, 0, $i ) ), $dir_perms ); 2143 } 2144 } 2145 2146 return true; 2147 } 2148 2149 /* 2150 * Another process may have created the directory since the check above. Accept 2151 * it, with the permissions that process set: this call did not create it. 2152 */ 2153 return is_dir( $target ); 2154 } 2155 2156 /** 2157 * Tests if a given filesystem path is absolute. 2158 * 2159 * For example, '/foo/bar', or 'c:\windows'. 2160 * 2161 * @since 2.5.0 2162 * 2163 * @param string $path File path. 2164 * @return bool True if path is absolute, false is not absolute. 2165 * 2166 * @phpstan-assert-if-true =non-falsy-string $path 2167 * @phpstan-return ( $path is non-falsy-string ? bool : false ) 2168 */ 2169 function path_is_absolute( $path ) { 2170 /* 2171 * Check to see if the path is a stream and check to see if its an actual 2172 * path or file as realpath() does not support stream wrappers. 2173 */ 2174 if ( wp_is_stream( $path ) && ( is_dir( $path ) || is_file( $path ) ) ) { 2175 return true; 2176 } 2177 2178 /* 2179 * This is definitive if true but fails if $path does not exist or contains 2180 * a symbolic link. 2181 */ 2182 if ( realpath( $path ) === $path ) { 2183 return true; 2184 } 2185 2186 if ( strlen( $path ) === 0 || '.' === $path[0] ) { 2187 return false; 2188 } 2189 2190 // Windows allows absolute paths like this. 2191 if ( preg_match( '#^[a-zA-Z]:\\\\#', $path ) ) { 2192 return true; 2193 } 2194 2195 // A path starting with / or \ is absolute; anything else is relative. 2196 return ( '/' === $path[0] || '\\' === $path[0] ); 2197 } 2198 2199 /** 2200 * Joins two filesystem paths together. 2201 * 2202 * For example, 'give me $path relative to $base'. If the $path is absolute, 2203 * then it the full path is returned. 2204 * 2205 * @since 2.5.0 2206 * 2207 * @param string $base Base path. 2208 * @param string $path Path relative to $base. 2209 * @return string The path with the base or absolute path. 2210 * 2211 * @phpstan-return non-falsy-string 2212 */ 2213 function path_join( $base, $path ) { 2214 if ( path_is_absolute( $path ) ) { 2215 return $path; 2216 } 2217 2218 return rtrim( $base, '/' ) . '/' . $path; 2219 } 2220 2221 /** 2222 * Normalizes a filesystem path. 2223 * 2224 * On windows systems, replaces backslashes with forward slashes 2225 * and forces upper-case drive letters. 2226 * Allows for two leading slashes for Windows network shares, but 2227 * ensures that all other duplicate slashes are reduced to a single. 2228 * 2229 * @since 3.9.0 2230 * @since 4.4.0 Ensures upper-case drive letters on Windows systems. 2231 * @since 4.5.0 Allows for Windows network shares. 2232 * @since 4.9.7 Allows for PHP file wrappers. 2233 * @since 7.0.0 Uses a static cache to store normalized paths. 2234 * 2235 * @param string $path Path to normalize. 2236 * @return string Normalized path. 2237 */ 2238 function wp_normalize_path( $path ): string { 2239 $path = (string) $path; 2240 2241 static $cache = array(); 2242 if ( isset( $cache[ $path ] ) ) { 2243 return $cache[ $path ]; 2244 } 2245 2246 $original_path = $path; 2247 $wrapper = ''; 2248 2249 if ( wp_is_stream( $path ) ) { 2250 list( $wrapper, $path ) = explode( '://', $path, 2 ); 2251 2252 $wrapper .= '://'; 2253 } 2254 2255 // Standardize all paths to use '/'. 2256 $path = str_replace( '\\', '/', $path ); 2257 2258 // Replace multiple slashes down to a singular, allowing for network shares having two slashes. 2259 $path = (string) preg_replace( '|(?<=.)/+|', '/', $path ); 2260 2261 // Windows paths should uppercase the drive letter. 2262 if ( ':' === substr( $path, 1, 1 ) ) { 2263 $path = ucfirst( $path ); 2264 } 2265 2266 $cache[ $original_path ] = $wrapper . $path; 2267 return $cache[ $original_path ]; 2268 } 2269 2270 /** 2271 * Determines a writable directory for temporary files. 2272 * 2273 * Function's preference is the return value of `sys_get_temp_dir()`, 2274 * followed by the `upload_tmp_dir` value from `php.ini`, followed by `WP_CONTENT_DIR`, 2275 * before finally defaulting to `/tmp/`. 2276 * 2277 * Note that `sys_get_temp_dir()` honors the `TMPDIR` environment variable. 2278 * 2279 * In the event that this function does not find a writable location, 2280 * it may be overridden by the `WP_TEMP_DIR` constant in your `wp-config.php` file. 2281 * 2282 * @since 2.5.0 2283 * 2284 * @return string Writable temporary directory. 2285 */ 2286 function get_temp_dir() { 2287 static $temp = ''; 2288 if ( defined( 'WP_TEMP_DIR' ) ) { 2289 return trailingslashit( WP_TEMP_DIR ); 2290 } 2291 2292 if ( $temp ) { 2293 return trailingslashit( $temp ); 2294 } 2295 2296 if ( function_exists( 'sys_get_temp_dir' ) ) { 2297 $temp = sys_get_temp_dir(); 2298 if ( @is_dir( $temp ) && wp_is_writable( $temp ) ) { 2299 return trailingslashit( $temp ); 2300 } 2301 } 2302 2303 $temp = ini_get( 'upload_tmp_dir' ); 2304 if ( @is_dir( $temp ) && wp_is_writable( $temp ) ) { 2305 return trailingslashit( $temp ); 2306 } 2307 2308 $temp = WP_CONTENT_DIR . '/'; 2309 if ( is_dir( $temp ) && wp_is_writable( $temp ) ) { 2310 return $temp; 2311 } 2312 2313 return '/tmp/'; 2314 } 2315 2316 /** 2317 * Determines if a directory is writable. 2318 * 2319 * This function is used to work around certain ACL issues in PHP primarily 2320 * affecting Windows Servers. 2321 * 2322 * @since 3.6.0 2323 * 2324 * @see win_is_writable() 2325 * 2326 * @param string $path Path to check for write-ability. 2327 * @return bool Whether the path is writable. 2328 */ 2329 function wp_is_writable( $path ) { 2330 if ( 'Windows' === PHP_OS_FAMILY ) { 2331 return win_is_writable( $path ); 2332 } 2333 2334 return @is_writable( $path ); 2335 } 2336 2337 /** 2338 * Workaround for Windows bug in is_writable() function 2339 * 2340 * PHP has issues with Windows ACL's for determine if a 2341 * directory is writable or not, this works around them by 2342 * checking the ability to open files rather than relying 2343 * upon PHP to interpret the OS ACL. 2344 * 2345 * @since 2.8.0 2346 * 2347 * @link https://bugs.php.net/bug.php?id=27609 2348 * @link https://bugs.php.net/bug.php?id=30931 2349 * 2350 * @param string $path Windows path to check for write-ability. 2351 * @return bool Whether the path is writable. 2352 */ 2353 function win_is_writable( $path ) { 2354 if ( '/' === $path[ strlen( $path ) - 1 ] ) { 2355 // If it looks like a directory, check a random file within the directory. 2356 return win_is_writable( $path . uniqid( mt_rand() ) . '.tmp' ); 2357 } elseif ( is_dir( $path ) ) { 2358 // If it's a directory (and not a file), check a random file within the directory. 2359 return win_is_writable( $path . '/' . uniqid( mt_rand() ) . '.tmp' ); 2360 } 2361 2362 // Check tmp file for read/write capabilities. 2363 $should_delete_tmp_file = ! file_exists( $path ); 2364 2365 $f = @fopen( $path, 'a' ); 2366 if ( false === $f ) { 2367 return false; 2368 } 2369 fclose( $f ); 2370 2371 if ( $should_delete_tmp_file ) { 2372 unlink( $path ); 2373 } 2374 2375 return true; 2376 } 2377 2378 /** 2379 * Retrieves uploads directory information. 2380 * 2381 * Same as wp_upload_dir() but "light weight" as it doesn't attempt to create the uploads directory. 2382 * Intended for use in themes, when only 'basedir' and 'baseurl' are needed, generally in all cases 2383 * when not uploading files. 2384 * 2385 * @since 4.5.0 2386 * 2387 * @see wp_upload_dir() 2388 * 2389 * @return array See wp_upload_dir() for description. 2390 * @phpstan-return array{ 2391 * path: non-empty-string, 2392 * url: non-empty-string, 2393 * subdir: string, 2394 * basedir: non-empty-string, 2395 * baseurl: non-empty-string, 2396 * error: non-empty-string|false, 2397 * } 2398 */ 2399 function wp_get_upload_dir() { 2400 return wp_upload_dir( null, false ); 2401 } 2402 2403 /** 2404 * Returns an array containing the current upload directory's path and URL. 2405 * 2406 * Checks the 'upload_path' option, which should be from the web root folder, 2407 * and if it isn't empty it will be used. If it is empty, then the path will be 2408 * 'WP_CONTENT_DIR/uploads'. If the 'UPLOADS' constant is defined, then it will 2409 * override the 'upload_path' option and 'WP_CONTENT_DIR/uploads' path. 2410 * 2411 * The upload URL path is set either by the 'upload_url_path' option or by using 2412 * the 'WP_CONTENT_URL' constant and appending '/uploads' to the path. 2413 * 2414 * If the 'uploads_use_yearmonth_folders' is set to true (checkbox if checked in 2415 * the administration settings panel), then the time will be used. The format 2416 * will be year first and then month. 2417 * 2418 * If the path couldn't be created, then an error will be returned with the key 2419 * 'error' containing the error message. The error suggests that the parent 2420 * directory is not writable by the server. 2421 * 2422 * @since 2.0.0 2423 * @uses _wp_upload_dir() 2424 * 2425 * @param string|null $time Optional. Time formatted in 'yyyy/mm'. Default null. 2426 * @param bool $create_dir Optional. Whether to check and create the uploads directory. 2427 * Default true for backward compatibility. 2428 * @param bool $refresh_cache Optional. Whether to refresh the cache. Default false. 2429 * @return array { 2430 * Array of information about the upload directory. 2431 * 2432 * @type string $path Base directory and subdirectory or full path to upload directory. 2433 * @type string $url Base URL and subdirectory or absolute URL to upload directory. 2434 * @type string $subdir Subdirectory if uploads use year/month folders option is on. 2435 * @type string $basedir Path without subdir. 2436 * @type string $baseurl URL path without subdir. 2437 * @type string|false $error False or error message. 2438 * } 2439 * @phpstan-return array{ 2440 * path: non-empty-string, 2441 * url: non-empty-string, 2442 * subdir: string, 2443 * basedir: non-empty-string, 2444 * baseurl: non-empty-string, 2445 * error: non-empty-string|false, 2446 * } 2447 */ 2448 function wp_upload_dir( $time = null, $create_dir = true, $refresh_cache = false ) { 2449 static $cache = array(), $tested_paths = array(); 2450 2451 $key = sprintf( '%d-%s', get_current_blog_id(), (string) $time ); 2452 2453 if ( $refresh_cache || empty( $cache[ $key ] ) ) { 2454 $cache[ $key ] = _wp_upload_dir( $time ); 2455 } 2456 2457 /** 2458 * Filters the uploads directory data. 2459 * 2460 * @since 2.0.0 2461 * 2462 * @param array $uploads { 2463 * Array of information about the upload directory. 2464 * 2465 * @type string $path Base directory and subdirectory or full path to upload directory. 2466 * @type string $url Base URL and subdirectory or absolute URL to upload directory. 2467 * @type string $subdir Subdirectory if uploads use year/month folders option is on. 2468 * @type string $basedir Path without subdir. 2469 * @type string $baseurl URL path without subdir. 2470 * @type string|false $error False or error message. 2471 * } 2472 */ 2473 $uploads = apply_filters( 'upload_dir', $cache[ $key ] ); 2474 2475 if ( $create_dir ) { 2476 $path = $uploads['path']; 2477 2478 if ( array_key_exists( $path, $tested_paths ) ) { 2479 $uploads['error'] = $tested_paths[ $path ]; 2480 } else { 2481 if ( ! wp_mkdir_p( $path ) ) { 2482 if ( str_starts_with( $uploads['basedir'], ABSPATH ) ) { 2483 $error_path = str_replace( ABSPATH, '', $uploads['basedir'] ) . $uploads['subdir']; 2484 } else { 2485 $error_path = wp_basename( $uploads['basedir'] ) . $uploads['subdir']; 2486 } 2487 2488 $uploads['error'] = sprintf( 2489 /* translators: %s: Directory path. */ 2490 __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), 2491 esc_html( $error_path ) 2492 ); 2493 } 2494 2495 $tested_paths[ $path ] = $uploads['error']; 2496 } 2497 } 2498 2499 return $uploads; 2500 } 2501 2502 /** 2503 * A non-filtered, non-cached version of wp_upload_dir() that doesn't check the path. 2504 * 2505 * @since 4.5.0 2506 * @access private 2507 * 2508 * @param string|null $time Optional. Time formatted in 'yyyy/mm'. Default null. 2509 * @return array See wp_upload_dir() 2510 * @phpstan-return array{ 2511 * path: non-empty-string, 2512 * url: non-empty-string, 2513 * subdir: string, 2514 * basedir: non-empty-string, 2515 * baseurl: non-empty-string, 2516 * error: false, 2517 * } 2518 */ 2519 function _wp_upload_dir( $time = null ) { 2520 $siteurl = get_option( 'siteurl' ); 2521 $upload_path = trim( get_option( 'upload_path' ) ); 2522 2523 if ( empty( $upload_path ) || 'wp-content/uploads' === $upload_path ) { 2524 $dir = WP_CONTENT_DIR . '/uploads'; 2525 } elseif ( ! str_starts_with( $upload_path, ABSPATH ) ) { 2526 // $dir is absolute, $upload_path is (maybe) relative to ABSPATH. 2527 $dir = path_join( ABSPATH, $upload_path ); 2528 } else { 2529 $dir = $upload_path; 2530 } 2531 2532 $url = get_option( 'upload_url_path' ); 2533 if ( ! $url ) { 2534 if ( empty( $upload_path ) || ( 'wp-content/uploads' === $upload_path ) || ( $upload_path === $dir ) ) { 2535 $url = WP_CONTENT_URL . '/uploads'; 2536 } else { 2537 $url = trailingslashit( $siteurl ) . $upload_path; 2538 } 2539 } 2540 2541 /* 2542 * Honor the value of UPLOADS. This happens as long as ms-files rewriting is disabled. 2543 * We also sometimes obey UPLOADS when rewriting is enabled -- see the next block. 2544 */ 2545 if ( defined( 'UPLOADS' ) && ! ( is_multisite() && get_site_option( 'ms_files_rewriting' ) ) ) { 2546 $dir = ABSPATH . UPLOADS; 2547 $url = trailingslashit( $siteurl ) . UPLOADS; 2548 } 2549 2550 // If multisite (and if not the main site in a post-MU network). 2551 if ( is_multisite() && ! ( is_main_network() && is_main_site() && defined( 'MULTISITE' ) ) ) { 2552 2553 if ( ! get_site_option( 'ms_files_rewriting' ) ) { 2554 /* 2555 * If ms-files rewriting is disabled (networks created post-3.5), it is fairly 2556 * straightforward: Append sites/%d if we're not on the main site (for post-MU 2557 * networks). (The extra directory prevents a four-digit ID from conflicting with 2558 * a year-based directory for the main site. But if a MU-era network has disabled 2559 * ms-files rewriting manually, they don't need the extra directory, as they never 2560 * had wp-content/uploads for the main site.) 2561 */ 2562 2563 if ( defined( 'MULTISITE' ) ) { 2564 $ms_dir = '/sites/' . get_current_blog_id(); 2565 } else { 2566 $ms_dir = '/' . get_current_blog_id(); 2567 } 2568 2569 $dir .= $ms_dir; 2570 $url .= $ms_dir; 2571 2572 } elseif ( defined( 'UPLOADS' ) && ! ms_is_switched() ) { 2573 /* 2574 * Handle the old-form ms-files.php rewriting if the network still has that enabled. 2575 * When ms-files rewriting is enabled, then we only listen to UPLOADS when: 2576 * 1) We are not on the main site in a post-MU network, as wp-content/uploads is used 2577 * there, and 2578 * 2) We are not switched, as ms_upload_constants() hardcodes these constants to reflect 2579 * the original blog ID. 2580 * 2581 * Rather than UPLOADS, we actually use BLOGUPLOADDIR if it is set, as it is absolute. 2582 * (And it will be set, see ms_upload_constants().) Otherwise, UPLOADS can be used, as 2583 * it is relative to ABSPATH. For the final piece: when UPLOADS is used with ms-files 2584 * rewriting in multisite, the resulting URL is /files. (#WP22702 for background.) 2585 */ 2586 2587 if ( defined( 'BLOGUPLOADDIR' ) ) { 2588 $dir = untrailingslashit( BLOGUPLOADDIR ); 2589 } else { 2590 $dir = ABSPATH . UPLOADS; 2591 } 2592 $url = trailingslashit( $siteurl ) . 'files'; 2593 } 2594 } 2595 2596 $basedir = $dir; 2597 $baseurl = $url; 2598 2599 $subdir = ''; 2600 if ( get_option( 'uploads_use_yearmonth_folders' ) ) { 2601 // Generate the yearly and monthly directories. 2602 if ( ! $time ) { 2603 $time = current_time( 'mysql' ); 2604 } 2605 $y = substr( $time, 0, 4 ); 2606 $m = substr( $time, 5, 2 ); 2607 $subdir = "/$y/$m"; 2608 } 2609 2610 $dir .= $subdir; 2611 $url .= $subdir; 2612 2613 return array( 2614 'path' => $dir, 2615 'url' => $url, 2616 'subdir' => $subdir, 2617 'basedir' => $basedir, 2618 'baseurl' => $baseurl, 2619 'error' => false, 2620 ); 2621 } 2622 2623 /** 2624 * Gets a filename that is sanitized and unique for the given directory. 2625 * 2626 * If the filename is not unique, then a number will be added to the filename 2627 * before the extension, and will continue adding numbers until the filename 2628 * is unique. 2629 * 2630 * The callback function allows the caller to use their own method to create 2631 * unique file names. If defined, the callback should take three arguments: 2632 * - directory, base filename, and extension - and return a unique filename. 2633 * 2634 * @since 2.5.0 2635 * 2636 * @param string $dir Directory. 2637 * @param string $filename File name. 2638 * @param callable $unique_filename_callback Callback. Default null. 2639 * @return string New filename, if given wasn't unique. 2640 */ 2641 function wp_unique_filename( $dir, $filename, $unique_filename_callback = null ) { 2642 // Sanitize the file name before we begin processing. 2643 $filename = sanitize_file_name( $filename ); 2644 2645 // Initialize vars used in the wp_unique_filename filter. 2646 $number = ''; 2647 $alt_filenames = array(); 2648 2649 // Separate the filename into a name and extension. 2650 $ext = pathinfo( $filename, PATHINFO_EXTENSION ); 2651 $name = pathinfo( $filename, PATHINFO_BASENAME ); 2652 2653 if ( $ext ) { 2654 $ext = '.' . $ext; 2655 } 2656 2657 // Edge case: if file is named '.ext', treat as an empty name. 2658 if ( $name === $ext ) { 2659 $name = ''; 2660 } 2661 2662 /* 2663 * Increment the file number until we have a unique file to save in $dir. 2664 * Use callback if supplied. 2665 */ 2666 if ( $unique_filename_callback && is_callable( $unique_filename_callback ) ) { 2667 $filename = call_user_func( $unique_filename_callback, $dir, $name, $ext ); 2668 } else { 2669 $fname = pathinfo( $filename, PATHINFO_FILENAME ); 2670 2671 // Always append a number to file names that can potentially match image sub-size file names. 2672 if ( $fname && preg_match( '/-(?:\d+x\d+|scaled|rotated)$/', $fname ) ) { 2673 $number = 1; 2674 2675 // At this point the file name may not be unique. This is tested below and the $number is incremented. 2676 $filename = str_replace( "{$fname}{$ext}", "{$fname}-{$number}{$ext}", $filename ); 2677 } 2678 2679 /* 2680 * Get the mime type. Uploaded files were already checked with wp_check_filetype_and_ext() 2681 * in _wp_handle_upload(). Using wp_check_filetype() would be sufficient here. 2682 */ 2683 $file_type = wp_check_filetype( $filename ); 2684 $mime_type = $file_type['type']; 2685 2686 $is_image = ( ! empty( $mime_type ) && str_starts_with( $mime_type, 'image/' ) ); 2687 $upload_dir = wp_get_upload_dir(); 2688 $lc_filename = null; 2689 2690 $lc_ext = strtolower( $ext ); 2691 $_dir = trailingslashit( $dir ); 2692 2693 /* 2694 * If the extension is uppercase add an alternate file name with lowercase extension. 2695 * Both need to be tested for uniqueness as the extension will be changed to lowercase 2696 * for better compatibility with different filesystems. Fixes an inconsistency in WP < 2.9 2697 * where uppercase extensions were allowed but image sub-sizes were created with 2698 * lowercase extensions. 2699 */ 2700 if ( $ext && $lc_ext !== $ext ) { 2701 $lc_filename = preg_replace( '|' . preg_quote( $ext ) . '$|', $lc_ext, $filename ); 2702 } 2703 2704 /* 2705 * Increment the number added to the file name if there are any files in $dir 2706 * whose names match one of the possible name variations. 2707 */ 2708 while ( file_exists( $_dir . $filename ) || ( $lc_filename && file_exists( $_dir . $lc_filename ) ) ) { 2709 $new_number = (int) $number + 1; 2710 2711 if ( $lc_filename ) { 2712 $lc_filename = str_replace( 2713 array( "-{$number}{$lc_ext}", "{$number}{$lc_ext}" ), 2714 "-{$new_number}{$lc_ext}", 2715 $lc_filename 2716 ); 2717 } 2718 2719 if ( '' === "{$number}{$ext}" ) { 2720 $filename = "{$filename}-{$new_number}"; 2721 } else { 2722 $filename = str_replace( 2723 array( "-{$number}{$ext}", "{$number}{$ext}" ), 2724 "-{$new_number}{$ext}", 2725 $filename 2726 ); 2727 } 2728 2729 $number = $new_number; 2730 } 2731 2732 // Change the extension to lowercase if needed. 2733 if ( $lc_filename ) { 2734 $filename = $lc_filename; 2735 } 2736 2737 /* 2738 * Prevent collisions with existing file names that contain dimension-like strings 2739 * (whether they are subsizes or originals uploaded prior to #42437). 2740 */ 2741 2742 $files = array(); 2743 $count = 10000; 2744 2745 // The (resized) image files would have name and extension, and will be in the uploads dir. 2746 if ( $name && $ext && @is_dir( $dir ) && str_contains( $dir, $upload_dir['basedir'] ) ) { 2747 /** 2748 * Filters the file list used for calculating a unique filename for a newly added file. 2749 * 2750 * Returning an array from the filter will effectively short-circuit retrieval 2751 * from the filesystem and return the passed value instead. 2752 * 2753 * @since 5.5.0 2754 * 2755 * @param array|null $files The list of files to use for filename comparisons. 2756 * Default null (to retrieve the list from the filesystem). 2757 * @param string $dir The directory for the new file. 2758 * @param string $filename The proposed filename for the new file. 2759 */ 2760 $files = apply_filters( 'pre_wp_unique_filename_file_list', null, $dir, $filename ); 2761 2762 if ( null === $files ) { 2763 // List of all files and directories contained in $dir. 2764 $files = @scandir( $dir ); 2765 } 2766 2767 if ( ! empty( $files ) ) { 2768 // Remove "dot" dirs. 2769 $files = array_diff( $files, array( '.', '..' ) ); 2770 } 2771 2772 if ( ! empty( $files ) ) { 2773 $count = count( $files ); 2774 2775 /* 2776 * Ensure this never goes into infinite loop as it uses pathinfo() and regex in the check, 2777 * but string replacement for the changes. 2778 */ 2779 $i = 0; 2780 2781 while ( $i <= $count && _wp_check_existing_file_names( $filename, $files ) ) { 2782 $new_number = (int) $number + 1; 2783 2784 // If $ext is uppercase it was replaced with the lowercase version after the previous loop. 2785 $filename = str_replace( 2786 array( "-{$number}{$lc_ext}", "{$number}{$lc_ext}" ), 2787 "-{$new_number}{$lc_ext}", 2788 $filename 2789 ); 2790 2791 $number = $new_number; 2792 ++$i; 2793 } 2794 } 2795 } 2796 2797 /* 2798 * Check if an image will be converted after uploading or some existing image sub-size file names may conflict 2799 * when regenerated. If yes, ensure the new file name will be unique and will produce unique sub-sizes. 2800 */ 2801 if ( $is_image ) { 2802 $output_formats = wp_get_image_editor_output_format( $_dir . $filename, $mime_type ); 2803 $alt_types = array(); 2804 2805 if ( ! empty( $output_formats[ $mime_type ] ) ) { 2806 // The image will be converted to this format/mime type. 2807 $alt_mime_type = $output_formats[ $mime_type ]; 2808 2809 // Other types of images whose names may conflict if their sub-sizes are regenerated. 2810 $alt_types = array_keys( array_intersect( $output_formats, array( $mime_type, $alt_mime_type ) ) ); 2811 $alt_types[] = $alt_mime_type; 2812 } elseif ( ! empty( $output_formats ) ) { 2813 $alt_types = array_keys( array_intersect( $output_formats, array( $mime_type ) ) ); 2814 } 2815 2816 // Remove duplicates and the original mime type. It will be added later if needed. 2817 $alt_types = array_unique( array_diff( $alt_types, array( $mime_type ) ) ); 2818 2819 foreach ( $alt_types as $alt_type ) { 2820 $alt_ext = wp_get_default_extension_for_mime_type( $alt_type ); 2821 2822 if ( ! $alt_ext ) { 2823 continue; 2824 } 2825 2826 $alt_ext = ".{$alt_ext}"; 2827 $alt_filename = preg_replace( '|' . preg_quote( $lc_ext ) . '$|', $alt_ext, $filename ); 2828 2829 $alt_filenames[ $alt_ext ] = $alt_filename; 2830 } 2831 2832 if ( ! empty( $alt_filenames ) ) { 2833 /* 2834 * Add the original filename. It needs to be checked again 2835 * together with the alternate filenames when $number is incremented. 2836 */ 2837 $alt_filenames[ $lc_ext ] = $filename; 2838 2839 // Ensure no infinite loop. 2840 $i = 0; 2841 2842 while ( $i <= $count && _wp_check_alternate_file_names( $alt_filenames, $_dir, $files ) ) { 2843 $new_number = (int) $number + 1; 2844 2845 foreach ( $alt_filenames as $alt_ext => $alt_filename ) { 2846 $alt_filenames[ $alt_ext ] = str_replace( 2847 array( "-{$number}{$alt_ext}", "{$number}{$alt_ext}" ), 2848 "-{$new_number}{$alt_ext}", 2849 $alt_filename 2850 ); 2851 } 2852 2853 /* 2854 * Also update the $number in (the output) $filename. 2855 * If the extension was uppercase it was already replaced with the lowercase version. 2856 */ 2857 $filename = str_replace( 2858 array( "-{$number}{$lc_ext}", "{$number}{$lc_ext}" ), 2859 "-{$new_number}{$lc_ext}", 2860 $filename 2861 ); 2862 2863 $number = $new_number; 2864 ++$i; 2865 } 2866 } 2867 } 2868 } 2869 2870 /** 2871 * Filters the result when generating a unique file name. 2872 * 2873 * @since 4.5.0 2874 * @since 5.8.1 The `$alt_filenames` and `$number` parameters were added. 2875 * 2876 * @param string $filename Unique file name. 2877 * @param string $ext File extension. Example: ".png". 2878 * @param string $dir Directory path. 2879 * @param callable|null $unique_filename_callback Callback function that generates the unique file name. 2880 * @param string[] $alt_filenames Array of alternate file names that were checked for collisions. 2881 * @param int|string $number The highest number that was used to make the file name unique 2882 * or an empty string if unused. 2883 */ 2884 return apply_filters( 'wp_unique_filename', $filename, $ext, $dir, $unique_filename_callback, $alt_filenames, $number ); 2885 } 2886 2887 /** 2888 * Helper function to test if each of an array of file names could conflict with existing files. 2889 * 2890 * @since 5.8.1 2891 * @access private 2892 * 2893 * @param string[] $filenames Array of file names to check. 2894 * @param string $dir The directory containing the files. 2895 * @param array $files An array of existing files in the directory. May be empty. 2896 * @return bool True if the tested file name could match an existing file, false otherwise. 2897 */ 2898 function _wp_check_alternate_file_names( $filenames, $dir, $files ) { 2899 foreach ( $filenames as $filename ) { 2900 if ( file_exists( $dir . $filename ) ) { 2901 return true; 2902 } 2903 2904 if ( ! empty( $files ) && _wp_check_existing_file_names( $filename, $files ) ) { 2905 return true; 2906 } 2907 } 2908 2909 return false; 2910 } 2911 2912 /** 2913 * Helper function to check if a file name could match an existing image sub-size file name. 2914 * 2915 * @since 5.3.1 2916 * @access private 2917 * 2918 * @param string $filename The file name to check. 2919 * @param array $files An array of existing files in the directory. 2920 * @return bool True if the tested file name could match an existing file, false otherwise. 2921 */ 2922 function _wp_check_existing_file_names( $filename, $files ) { 2923 $fname = pathinfo( $filename, PATHINFO_FILENAME ); 2924 $ext = pathinfo( $filename, PATHINFO_EXTENSION ); 2925 2926 // Edge case, file names like `.ext`. 2927 if ( empty( $fname ) ) { 2928 2929 return false; 2930 } 2931 2932 if ( $ext ) { 2933 $ext = ".$ext"; 2934 } 2935 2936 $regex = '/^' . preg_quote( $fname ) . '-(?:\d+x\d+|scaled|rotated)' . preg_quote( $ext ) . '$/i'; 2937 2938 foreach ( $files as $file ) { 2939 if ( preg_match( $regex, $file ) ) { 2940 return true; 2941 } 2942 } 2943 2944 return false; 2945 } 2946 2947 /** 2948 * Creates a file in the upload folder with given content. 2949 * 2950 * If there is an error, then the key 'error' will exist with the error message. 2951 * If success, then the key 'file' will have the unique file path, the 'url' key 2952 * will have the link to the new file. and the 'error' key will be set to false. 2953 * 2954 * This function will not move an uploaded file to the upload folder. It will 2955 * create a new file with the content in $bits parameter. If you move the upload 2956 * file, read the content of the uploaded file, and then you can give the 2957 * filename and content to this function, which will add it to the upload 2958 * folder. 2959 * 2960 * The permissions will be set on the new file automatically by this function. 2961 * 2962 * @since 2.0.0 2963 * 2964 * @param string $name Filename. 2965 * @param null|string $deprecated Not used. Set to null. 2966 * @param string $bits File content 2967 * @param string|null $time Optional. Time formatted in 'yyyy/mm'. Default null. 2968 * @return array { 2969 * Information about the newly-uploaded file. 2970 * 2971 * @type string $file Optional. Filename of the newly-uploaded file. Not set if there has been an error. 2972 * @type string $url Optional. URL of the uploaded file. Not set if there has been an error. 2973 * @type string|false $type Optional. File type, or false if the file doesn't match a mime type. 2974 * Not set if there has been an error. 2975 * @type string|false $error Error message, if there has been an error. 2976 * } 2977 * 2978 * @phpstan-param non-empty-string $name 2979 * @phpstan-param null $deprecated 2980 * @phpstan-return array{ file: non-empty-string, url: non-empty-string, type: string|false, error: false } 2981 * |array{ error: string, ... } 2982 */ 2983 function wp_upload_bits( $name, $deprecated, $bits, $time = null ) { 2984 if ( ! empty( $deprecated ) ) { 2985 _deprecated_argument( __FUNCTION__, '2.0.0' ); 2986 } 2987 2988 if ( empty( $name ) ) { 2989 return array( 'error' => __( 'Empty filename' ) ); 2990 } 2991 2992 $wp_filetype = wp_check_filetype( $name ); 2993 if ( ! $wp_filetype['ext'] && ! current_user_can( 'unfiltered_upload' ) ) { 2994 return array( 'error' => __( 'Sorry, you are not allowed to upload this file type.' ) ); 2995 } 2996 2997 $upload = wp_upload_dir( $time ); 2998 2999 if ( false !== $upload['error'] ) { 3000 return $upload; 3001 } 3002 3003 /** 3004 * Filters whether to treat the upload bits as an error. 3005 * 3006 * Returning a non-array from the filter will effectively short-circuit preparing the upload bits 3007 * and return that value instead. An error message should be returned as a string. 3008 * 3009 * @since 3.0.0 3010 * 3011 * @param array|string $upload_bits_error An array of upload bits data, or error message to return. 3012 */ 3013 $upload_bits_error = apply_filters( 3014 'wp_upload_bits', 3015 array( 3016 'name' => $name, 3017 'bits' => $bits, 3018 'time' => $time, 3019 ) 3020 ); 3021 if ( ! is_array( $upload_bits_error ) ) { 3022 $upload['error'] = $upload_bits_error; 3023 return $upload; 3024 } 3025 3026 $filename = wp_unique_filename( $upload['path'], $name ); 3027 3028 $new_file = $upload['path'] . "/$filename"; 3029 if ( ! wp_mkdir_p( dirname( $new_file ) ) ) { 3030 if ( str_starts_with( $upload['basedir'], ABSPATH ) ) { 3031 $error_path = str_replace( ABSPATH, '', $upload['basedir'] ) . $upload['subdir']; 3032 } else { 3033 $error_path = wp_basename( $upload['basedir'] ) . $upload['subdir']; 3034 } 3035 3036 $message = sprintf( 3037 /* translators: %s: Directory path. */ 3038 __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), 3039 $error_path 3040 ); 3041 return array( 'error' => $message ); 3042 } 3043 3044 $ifp = @fopen( $new_file, 'wb' ); 3045 if ( ! $ifp ) { 3046 return array( 3047 /* translators: %s: File name. */ 3048 'error' => sprintf( __( 'Could not write file %s' ), $new_file ), 3049 ); 3050 } 3051 3052 fwrite( $ifp, $bits ); 3053 fclose( $ifp ); 3054 clearstatcache(); 3055 3056 // Set correct file permissions. 3057 $stat = @ stat( dirname( $new_file ) ); 3058 $perms = $stat['mode'] & 0007777; 3059 $perms = $perms & 0000666; 3060 chmod( $new_file, $perms ); 3061 clearstatcache(); 3062 3063 // Compute the URL. 3064 $url = $upload['url'] . "/$filename"; 3065 3066 if ( is_multisite() ) { 3067 clean_dirsize_cache( $new_file ); 3068 } 3069 3070 /** This filter is documented in wp-admin/includes/file.php */ 3071 return apply_filters( 3072 'wp_handle_upload', 3073 array( 3074 'file' => $new_file, 3075 'url' => $url, 3076 'type' => $wp_filetype['type'], 3077 'error' => false, 3078 ), 3079 'sideload' 3080 ); 3081 } 3082 3083 /** 3084 * Retrieves the file type based on the extension name. 3085 * 3086 * @since 2.5.0 3087 * 3088 * @param string $ext The extension to search. 3089 * @return string|null The file type, example: audio, video, document, spreadsheet, etc. 3090 */ 3091 function wp_ext2type( $ext ) { 3092 $ext = strtolower( $ext ); 3093 3094 $ext2type = wp_get_ext_types(); 3095 3096 return array_find_key( 3097 $ext2type, 3098 fn( $exts ) => in_array( $ext, $exts, true ) 3099 ); 3100 } 3101 3102 /** 3103 * Returns the first matched extension for the mime type, as mapped from wp_get_mime_types(). 3104 * 3105 * @since 5.8.1 3106 * 3107 * @param string $mime_type The mime type to search. 3108 * @return string|false The first matching file extension, or false if no extensions are found 3109 * for the given mime type. 3110 */ 3111 function wp_get_default_extension_for_mime_type( $mime_type ) { 3112 $extensions = explode( '|', array_search( $mime_type, wp_get_mime_types(), true ) ); 3113 3114 if ( empty( $extensions[0] ) ) { 3115 return false; 3116 } 3117 3118 return $extensions[0]; 3119 } 3120 3121 /** 3122 * Retrieves the file type from the file name. 3123 * 3124 * You can optionally define the mime array, if needed. 3125 * 3126 * @since 2.0.4 3127 * 3128 * @param string $filename File name or path. 3129 * @param string[]|null $mimes Optional. Array of allowed mime types keyed by their file extension regex. 3130 * Defaults to the result of get_allowed_mime_types(). 3131 * @return array { 3132 * Values for the extension and mime type. 3133 * 3134 * @type string|false $ext File extension, or false if the file doesn't match a mime type. 3135 * @type string|false $type File mime type, or false if the file doesn't match a mime type. 3136 * } 3137 */ 3138 function wp_check_filetype( $filename, $mimes = null ) { 3139 if ( empty( $mimes ) ) { 3140 $mimes = get_allowed_mime_types(); 3141 } 3142 $type = false; 3143 $ext = false; 3144 3145 foreach ( $mimes as $ext_preg => $mime_match ) { 3146 $ext_preg = '!\.(' . $ext_preg . ')$!i'; 3147 if ( preg_match( $ext_preg, $filename, $ext_matches ) ) { 3148 $type = $mime_match; 3149 $ext = $ext_matches[1]; 3150 break; 3151 } 3152 } 3153 3154 return compact( 'ext', 'type' ); 3155 } 3156 3157 /** 3158 * Attempts to determine the real file type of a file. 3159 * 3160 * If unable to, the file name extension will be used to determine type. 3161 * 3162 * If it's determined that the extension does not match the file's real type, 3163 * then the "proper_filename" value will be set with a proper filename and extension. 3164 * 3165 * Currently this function only supports renaming images validated via wp_get_image_mime(). 3166 * 3167 * @since 3.0.0 3168 * 3169 * @param string $file Full path to the file. 3170 * @param string $filename The name of the file (may differ from $file due to $file being 3171 * in a tmp directory). 3172 * @param string[]|null $mimes Optional. Array of allowed mime types keyed by their file extension regex. 3173 * Defaults to the result of get_allowed_mime_types(). 3174 * @return array { 3175 * Values for the extension, mime type, and corrected filename. 3176 * 3177 * @type string|false $ext File extension, or false if the file doesn't match a mime type. 3178 * @type string|false $type File mime type, or false if the file doesn't match a mime type. 3179 * @type string|false $proper_filename File name with its correct extension, or false if it cannot be determined. 3180 * } 3181 */ 3182 function wp_check_filetype_and_ext( $file, $filename, $mimes = null ) { 3183 $proper_filename = false; 3184 3185 // Do basic extension validation and MIME mapping. 3186 $wp_filetype = wp_check_filetype( $filename, $mimes ); 3187 $ext = $wp_filetype['ext']; 3188 $type = $wp_filetype['type']; 3189 3190 // We can't do any further validation without a file to work with. 3191 if ( ! file_exists( $file ) ) { 3192 return compact( 'ext', 'type', 'proper_filename' ); 3193 } 3194 3195 $real_mime = false; 3196 3197 // Validate image types. 3198 if ( $type && str_starts_with( $type, 'image/' ) ) { 3199 3200 // Attempt to figure out what type of image it actually is. 3201 $real_mime = wp_get_image_mime( $file ); 3202 3203 $heic_images_extensions = array( 3204 'heif', 3205 'heics', 3206 'heifs', 3207 ); 3208 3209 if ( $real_mime && ( $real_mime !== $type || in_array( $ext, $heic_images_extensions, true ) ) ) { 3210 /** 3211 * Filters the list mapping image mime types to their respective extensions. 3212 * 3213 * @since 3.0.0 3214 * 3215 * @param array $mime_to_ext Array of image mime types and their matching extensions. 3216 */ 3217 $mime_to_ext = apply_filters( 3218 'getimagesize_mimes_to_exts', 3219 array( 3220 'image/jpeg' => 'jpg', 3221 'image/png' => 'png', 3222 'image/gif' => 'gif', 3223 'image/bmp' => 'bmp', 3224 'image/tiff' => 'tif', 3225 'image/webp' => 'webp', 3226 'image/avif' => 'avif', 3227 3228 /* 3229 * In theory there are/should be file extensions that correspond to the 3230 * mime types: .heif, .heics and .heifs. However it seems that HEIC images 3231 * with any of the mime types commonly have a .heic file extension. 3232 * Seems keeping the status quo here is best for compatibility. 3233 */ 3234 'image/heic' => 'heic', 3235 'image/heif' => 'heic', 3236 'image/heic-sequence' => 'heic', 3237 'image/heif-sequence' => 'heic', 3238 ) 3239 ); 3240 3241 // Replace whatever is after the last period in the filename with the correct extension. 3242 if ( ! empty( $mime_to_ext[ $real_mime ] ) ) { 3243 $filename_parts = explode( '.', $filename ); 3244 3245 array_pop( $filename_parts ); 3246 $filename_parts[] = $mime_to_ext[ $real_mime ]; 3247 $new_filename = implode( '.', $filename_parts ); 3248 3249 if ( $new_filename !== $filename ) { 3250 $proper_filename = $new_filename; // Mark that it changed. 3251 } 3252 3253 // Redefine the extension / MIME. 3254 $wp_filetype = wp_check_filetype( $new_filename, $mimes ); 3255 $ext = $wp_filetype['ext']; 3256 $type = $wp_filetype['type']; 3257 } else { 3258 // Reset $real_mime and try validating again. 3259 $real_mime = false; 3260 } 3261 } 3262 } 3263 3264 // Validate files that didn't get validated during previous checks. 3265 if ( $type && ! $real_mime && extension_loaded( 'fileinfo' ) ) { 3266 $finfo = finfo_open( FILEINFO_MIME_TYPE ); 3267 $real_mime = finfo_file( $finfo, $file ); 3268 3269 if ( PHP_VERSION_ID < 80100 ) { // finfo_close() has no effect as of PHP 8.1. 3270 finfo_close( $finfo ); 3271 } 3272 3273 $google_docs_types = array( 3274 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 3275 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 3276 ); 3277 3278 foreach ( $google_docs_types as $google_docs_type ) { 3279 /* 3280 * finfo_file() can return duplicate mime type for Google docs, 3281 * this conditional reduces it to a single instance. 3282 * 3283 * @link https://bugs.php.net/bug.php?id=77784 3284 * @link https://core.trac.wordpress.org/ticket/57898 3285 */ 3286 if ( 2 === substr_count( $real_mime, $google_docs_type ) ) { 3287 $real_mime = $google_docs_type; 3288 } 3289 } 3290 3291 // fileinfo often misidentifies obscure files as one of these types. 3292 $nonspecific_types = array( 3293 'application/octet-stream', 3294 'application/encrypted', 3295 'application/CDFV2-encrypted', 3296 'application/zip', 3297 ); 3298 3299 /* 3300 * If $real_mime doesn't match the content type we're expecting from the file's extension, 3301 * we need to do some additional vetting. Media types and those listed in $nonspecific_types are 3302 * allowed some leeway, but anything else must exactly match the real content type. 3303 */ 3304 if ( in_array( $real_mime, $nonspecific_types, true ) ) { 3305 // File is a non-specific binary type. That's ok if it's a type that generally tends to be binary. 3306 if ( ! in_array( substr( $type, 0, strcspn( $type, '/' ) ), array( 'application', 'video', 'audio' ), true ) ) { 3307 $type = false; 3308 $ext = false; 3309 } 3310 } elseif ( str_starts_with( $real_mime, 'video/' ) || str_starts_with( $real_mime, 'audio/' ) ) { 3311 /* 3312 * For these types, only the major type must match the real value. 3313 * This means that common mismatches are forgiven: application/vnd.apple.numbers is often misidentified as application/zip, 3314 * and some media files are commonly named with the wrong extension (.mov instead of .mp4) 3315 */ 3316 if ( substr( $real_mime, 0, strcspn( $real_mime, '/' ) ) !== substr( $type, 0, strcspn( $type, '/' ) ) ) { 3317 /* 3318 * Audio stored in an MP4/ISO-BMFF container (such as .m4a and .m4b, and 3319 * some .mp3 files produced by mobile recorders) is frequently detected as 3320 * video/mp4. Allow these known audio-in-video-container confusions rather 3321 * than rejecting a legitimate audio file whose major types don't match. 3322 * Also allow `video/3gpp`, as a RFC 3839 specification-compliant container 3323 * for audio-only content. 3324 */ 3325 $cross_container_types = array( 3326 'audio/mpeg' => array( 'video/mp4', 'video/3gpp' ), 3327 ); 3328 3329 if ( empty( $cross_container_types[ $type ] ) 3330 || ! in_array( $real_mime, $cross_container_types[ $type ], true ) 3331 ) { 3332 $type = false; 3333 $ext = false; 3334 } 3335 } 3336 } elseif ( 'text/plain' === $real_mime ) { 3337 // A few common file types are occasionally detected as text/plain; allow those. 3338 if ( ! in_array( 3339 $type, 3340 array( 3341 'text/plain', 3342 'text/csv', 3343 'application/csv', 3344 'text/richtext', 3345 'text/tsv', 3346 'text/vtt', 3347 ), 3348 true 3349 ) 3350 ) { 3351 $type = false; 3352 $ext = false; 3353 } 3354 } elseif ( 'application/csv' === $real_mime ) { 3355 // Special casing for CSV files. 3356 if ( ! in_array( 3357 $type, 3358 array( 3359 'text/csv', 3360 'text/plain', 3361 'application/csv', 3362 ), 3363 true 3364 ) 3365 ) { 3366 $type = false; 3367 $ext = false; 3368 } 3369 } elseif ( 'text/rtf' === $real_mime ) { 3370 // Special casing for RTF files. 3371 if ( ! in_array( 3372 $type, 3373 array( 3374 'text/rtf', 3375 'text/plain', 3376 'application/rtf', 3377 ), 3378 true 3379 ) 3380 ) { 3381 $type = false; 3382 $ext = false; 3383 } 3384 } elseif ( in_array( $real_mime, array( 'font/ttf', 'font/sfnt' ), true ) ) { 3385 /* 3386 * libmagic 5.47 changed the type reported for TrueType fonts from font/sfnt to the 3387 * canonical font/ttf. PHP 8.6 bundles a libmagic version with this change, but PHP 3388 * builds that use the system libmagic can report either type, so both are accepted 3389 * for TrueType fonts. 3390 * 3391 * @link https://github.com/file/file/commit/6481672a8eb64c2758bf6429d9a76ee5a22174e9 3392 */ 3393 if ( ! in_array( $type, array( 'font/ttf', 'font/sfnt' ), true ) ) { 3394 $type = false; 3395 $ext = false; 3396 } 3397 } else { 3398 if ( $type !== $real_mime ) { 3399 /* 3400 * Everything else including image/* and application/*: 3401 * If the real content type doesn't match the file extension, assume it's dangerous. 3402 */ 3403 $type = false; 3404 $ext = false; 3405 } 3406 } 3407 } 3408 3409 // The mime type must be allowed. 3410 if ( $type ) { 3411 $allowed = get_allowed_mime_types(); 3412 3413 if ( ! in_array( $type, $allowed, true ) ) { 3414 $type = false; 3415 $ext = false; 3416 } 3417 } 3418 3419 /** 3420 * Filters the "real" file type of the given file. 3421 * 3422 * @since 3.0.0 3423 * @since 5.1.0 The `$real_mime` parameter was added. 3424 * 3425 * @param array $wp_check_filetype_and_ext { 3426 * Values for the extension, mime type, and corrected filename. 3427 * 3428 * @type string|false $ext File extension, or false if the file doesn't match a mime type. 3429 * @type string|false $type File mime type, or false if the file doesn't match a mime type. 3430 * @type string|false $proper_filename File name with its correct extension, or false if it cannot be determined. 3431 * } 3432 * @param string $file Full path to the file. 3433 * @param string $filename The name of the file (may differ from $file due to 3434 * $file being in a tmp directory). 3435 * @param string[]|null $mimes Array of mime types keyed by their file extension regex, or null if 3436 * none were provided. 3437 * @param string|false $real_mime The actual mime type or false if the type cannot be determined. 3438 */ 3439 return apply_filters( 'wp_check_filetype_and_ext', compact( 'ext', 'type', 'proper_filename' ), $file, $filename, $mimes, $real_mime ); 3440 } 3441 3442 /** 3443 * Returns the real mime type of an image file. 3444 * 3445 * This depends on exif_imagetype() or getimagesize() to determine real mime types. 3446 * 3447 * @since 4.7.1 3448 * @since 5.8.0 Added support for WebP images. 3449 * @since 6.5.0 Added support for AVIF images. 3450 * @since 6.7.0 Added support for HEIC images. 3451 * 3452 * @param string $file Full path to the file. 3453 * @return string|false The actual mime type or false if the type cannot be determined. 3454 */ 3455 function wp_get_image_mime( $file ) { 3456 /* 3457 * Use exif_imagetype() to check the mimetype if available or fall back to 3458 * getimagesize() if exif isn't available. If either function throws an Exception 3459 * we assume the file could not be validated. 3460 */ 3461 try { 3462 if ( is_callable( 'exif_imagetype' ) ) { 3463 $imagetype = exif_imagetype( $file ); 3464 $mime = ( $imagetype ) ? image_type_to_mime_type( $imagetype ) : false; 3465 } elseif ( function_exists( 'getimagesize' ) ) { 3466 // Don't silence errors when in debug mode, unless running unit tests. 3467 if ( defined( 'WP_DEBUG' ) && WP_DEBUG && ! defined( 'WP_RUN_CORE_TESTS' ) ) { 3468 // Not using wp_getimagesize() here to avoid an infinite loop. 3469 $imagesize = getimagesize( $file ); 3470 } else { 3471 $imagesize = @getimagesize( $file ); 3472 } 3473 3474 $mime = $imagesize['mime'] ?? false; 3475 } else { 3476 $mime = false; 3477 } 3478 3479 if ( false !== $mime ) { 3480 return $mime; 3481 } 3482 3483 $magic = file_get_contents( $file, false, null, 0, 12 ); 3484 3485 if ( false === $magic ) { 3486 return false; 3487 } 3488 3489 /* 3490 * Add WebP fallback detection when image library doesn't support WebP. 3491 * Note: detection values come from LibWebP, see 3492 * https://github.com/webmproject/libwebp/blob/master/imageio/image_dec.c#L30 3493 */ 3494 $magic = bin2hex( $magic ); 3495 if ( 3496 // RIFF. 3497 ( str_starts_with( $magic, '52494646' ) ) && 3498 // WEBP. 3499 ( 16 === strpos( $magic, '57454250' ) ) 3500 ) { 3501 $mime = 'image/webp'; 3502 } 3503 3504 /** 3505 * Add AVIF fallback detection when image library doesn't support AVIF. 3506 * 3507 * Detection based on section 4.3.1 File-type box definition of the ISO/IEC 14496-12 3508 * specification and the AV1-AVIF spec, see https://aomediacodec.github.io/av1-avif/v1.1.0.html#brands. 3509 */ 3510 3511 // Divide the header string into 4 byte groups. 3512 $magic = str_split( $magic, 8 ); 3513 3514 if ( isset( $magic[1] ) && isset( $magic[2] ) && 'ftyp' === hex2bin( $magic[1] ) ) { 3515 if ( 'avif' === hex2bin( $magic[2] ) || 'avis' === hex2bin( $magic[2] ) ) { 3516 $mime = 'image/avif'; 3517 } elseif ( 'heic' === hex2bin( $magic[2] ) ) { 3518 $mime = 'image/heic'; 3519 } elseif ( 'heif' === hex2bin( $magic[2] ) ) { 3520 $mime = 'image/heif'; 3521 } else { 3522 /* 3523 * HEIC/HEIF images and image sequences/animations may have other strings here 3524 * like mif1, msf1, etc. For now fall back to using finfo_file() to detect these. 3525 */ 3526 if ( extension_loaded( 'fileinfo' ) ) { 3527 $fileinfo = finfo_open( FILEINFO_MIME_TYPE ); 3528 $mime_type = finfo_file( $fileinfo, $file ); 3529 3530 if ( PHP_VERSION_ID < 80100 ) { // finfo_close() has no effect as of PHP 8.1. 3531 finfo_close( $fileinfo ); 3532 } 3533 3534 if ( wp_is_heic_image_mime_type( $mime_type ) ) { 3535 $mime = $mime_type; 3536 } 3537 } 3538 } 3539 } 3540 } catch ( Exception $e ) { 3541 $mime = false; 3542 } 3543 3544 return $mime; 3545 } 3546 3547 /** 3548 * Retrieves the list of mime types and file extensions. 3549 * 3550 * @since 3.5.0 3551 * @since 4.2.0 Support was added for GIMP (.xcf) files. 3552 * @since 4.9.2 Support was added for Flac (.flac) files. 3553 * @since 4.9.6 Support was added for AAC (.aac) files. 3554 * @since 6.8.0 Support was added for `audio/x-wav`. 3555 * 3556 * @return array<string, string> Array of mime types keyed by the file extension regex corresponding to those types. 3557 */ 3558 function wp_get_mime_types() { 3559 /** 3560 * Filters the list of mime types and file extensions. 3561 * 3562 * This filter should be used to add, not remove, mime types. To remove 3563 * mime types, use the {@see 'upload_mimes'} filter. 3564 * 3565 * @since 3.5.0 3566 * 3567 * @param array<string, string> $wp_get_mime_types Mime types keyed by the file extension regex 3568 * corresponding to those types. 3569 */ 3570 return apply_filters( 3571 'mime_types', 3572 array( 3573 // Image formats. 3574 'jpg|jpeg|jpe' => 'image/jpeg', 3575 'gif' => 'image/gif', 3576 'png' => 'image/png', 3577 'bmp' => 'image/bmp', 3578 'tiff|tif' => 'image/tiff', 3579 'webp' => 'image/webp', 3580 'avif' => 'image/avif', 3581 'ico' => 'image/x-icon', 3582 3583 // TODO: Needs improvement. All images with the following mime types seem to have .heic file extension. 3584 'heic' => 'image/heic', 3585 'heif' => 'image/heif', 3586 'heics' => 'image/heic-sequence', 3587 'heifs' => 'image/heif-sequence', 3588 3589 // Video formats. 3590 'asf|asx' => 'video/x-ms-asf', 3591 'wmv' => 'video/x-ms-wmv', 3592 'wmx' => 'video/x-ms-wmx', 3593 'wm' => 'video/x-ms-wm', 3594 'avi' => 'video/avi', 3595 'divx' => 'video/divx', 3596 'flv' => 'video/x-flv', 3597 'mov|qt' => 'video/quicktime', 3598 'mpeg|mpg|mpe' => 'video/mpeg', 3599 'mp4|m4v' => 'video/mp4', 3600 'ogv' => 'video/ogg', 3601 'webm' => 'video/webm', 3602 'mkv' => 'video/x-matroska', 3603 '3gp|3gpp' => 'video/3gpp', // Can also be audio. 3604 '3g2|3gp2' => 'video/3gpp2', // Can also be audio. 3605 // Text formats. 3606 'txt|asc|c|cc|h|srt' => 'text/plain', 3607 'csv' => 'text/csv', 3608 'tsv' => 'text/tab-separated-values', 3609 'ics' => 'text/calendar', 3610 'rtx' => 'text/richtext', 3611 'css' => 'text/css', 3612 'htm|html' => 'text/html', 3613 'vtt' => 'text/vtt', 3614 'dfxp' => 'application/ttaf+xml', 3615 // Audio formats. 3616 'mp3|m4a|m4b' => 'audio/mpeg', 3617 'aac' => 'audio/aac', 3618 'ra|ram' => 'audio/x-realaudio', 3619 'wav|x-wav' => 'audio/wav', 3620 'ogg|oga' => 'audio/ogg', 3621 'flac' => 'audio/flac', 3622 'mid|midi' => 'audio/midi', 3623 'wma' => 'audio/x-ms-wma', 3624 'wax' => 'audio/x-ms-wax', 3625 'mka' => 'audio/x-matroska', 3626 // Misc application formats. 3627 'rtf' => 'application/rtf', 3628 'js' => 'application/javascript', 3629 'pdf' => 'application/pdf', 3630 'swf' => 'application/x-shockwave-flash', 3631 'class' => 'application/java', 3632 'tar' => 'application/x-tar', 3633 'zip' => 'application/zip', 3634 'gz|gzip' => 'application/x-gzip', 3635 'rar' => 'application/rar', 3636 '7z' => 'application/x-7z-compressed', 3637 'exe' => 'application/x-msdownload', 3638 'psd' => 'application/octet-stream', 3639 'xcf' => 'application/octet-stream', 3640 // MS Office formats. 3641 'doc' => 'application/msword', 3642 'pot|pps|ppt' => 'application/vnd.ms-powerpoint', 3643 'wri' => 'application/vnd.ms-write', 3644 'xla|xls|xlt|xlw' => 'application/vnd.ms-excel', 3645 'mdb' => 'application/vnd.ms-access', 3646 'mpp' => 'application/vnd.ms-project', 3647 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 3648 'docm' => 'application/vnd.ms-word.document.macroEnabled.12', 3649 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 3650 'dotm' => 'application/vnd.ms-word.template.macroEnabled.12', 3651 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 3652 'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12', 3653 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 3654 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 3655 'xltm' => 'application/vnd.ms-excel.template.macroEnabled.12', 3656 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12', 3657 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 3658 'pptm' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12', 3659 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 3660 'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', 3661 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template', 3662 'potm' => 'application/vnd.ms-powerpoint.template.macroEnabled.12', 3663 'ppam' => 'application/vnd.ms-powerpoint.addin.macroEnabled.12', 3664 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide', 3665 'sldm' => 'application/vnd.ms-powerpoint.slide.macroEnabled.12', 3666 'onetoc|onetoc2|onetmp|onepkg' => 'application/onenote', 3667 'oxps' => 'application/oxps', 3668 'xps' => 'application/vnd.ms-xpsdocument', 3669 // OpenOffice formats. 3670 'odt' => 'application/vnd.oasis.opendocument.text', 3671 'odp' => 'application/vnd.oasis.opendocument.presentation', 3672 'ods' => 'application/vnd.oasis.opendocument.spreadsheet', 3673 'odg' => 'application/vnd.oasis.opendocument.graphics', 3674 'odc' => 'application/vnd.oasis.opendocument.chart', 3675 'odb' => 'application/vnd.oasis.opendocument.database', 3676 'odf' => 'application/vnd.oasis.opendocument.formula', 3677 // WordPerfect formats. 3678 'wp|wpd' => 'application/wordperfect', 3679 // iWork formats. 3680 'key' => 'application/vnd.apple.keynote', 3681 'numbers' => 'application/vnd.apple.numbers', 3682 'pages' => 'application/vnd.apple.pages', 3683 ) 3684 ); 3685 } 3686 3687 /** 3688 * Retrieves the list of common file extensions and their types. 3689 * 3690 * @since 4.6.0 3691 * 3692 * @return array<string, string[]> Multi-dimensional array of file extensions types keyed by the type of file. 3693 */ 3694 function wp_get_ext_types() { 3695 3696 /** 3697 * Filters file type based on the extension name. 3698 * 3699 * @since 2.5.0 3700 * 3701 * @see wp_ext2type() 3702 * 3703 * @param array<string, string[]> $ext2type Multi-dimensional array of file extensions types keyed by the type of file. 3704 */ 3705 return apply_filters( 3706 'ext2type', 3707 array( 3708 'image' => array( 'jpg', 'jpeg', 'jpe', 'gif', 'png', 'bmp', 'tif', 'tiff', 'ico', 'heic', 'heif', 'webp', 'avif' ), 3709 'audio' => array( 'aac', 'ac3', 'aif', 'aiff', 'flac', 'm3a', 'm4a', 'm4b', 'mka', 'mp1', 'mp2', 'mp3', 'ogg', 'oga', 'ram', 'wav', 'wma' ), 3710 'video' => array( '3g2', '3gp', '3gpp', 'asf', 'avi', 'divx', 'dv', 'flv', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'mpv', 'ogm', 'ogv', 'qt', 'rm', 'vob', 'wmv' ), 3711 'document' => array( 'doc', 'docx', 'docm', 'dotm', 'odt', 'pages', 'pdf', 'xps', 'oxps', 'rtf', 'wp', 'wpd', 'psd', 'xcf' ), 3712 'spreadsheet' => array( 'numbers', 'ods', 'xls', 'xlsx', 'xlsm', 'xlsb' ), 3713 'interactive' => array( 'swf', 'key', 'ppt', 'pptx', 'pptm', 'pps', 'ppsx', 'ppsm', 'sldx', 'sldm', 'odp' ), 3714 'text' => array( 'asc', 'csv', 'tsv', 'txt' ), 3715 'archive' => array( 'bz2', 'cab', 'dmg', 'gz', 'rar', 'sea', 'sit', 'sqx', 'tar', 'tgz', 'zip', '7z' ), 3716 'code' => array( 'css', 'htm', 'html', 'php', 'js' ), 3717 ) 3718 ); 3719 } 3720 3721 /** 3722 * Wrapper for PHP filesize with filters and casting the result as an integer. 3723 * 3724 * @since 6.0.0 3725 * @since 7.1.0 The return value is now ensured to always be greater than or equal to zero. 3726 * 3727 * @link https://www.php.net/manual/en/function.filesize.php 3728 * 3729 * @param string $path Path to the file. 3730 * @return int The size of the file in bytes, or 0 in the event of an error. 3731 * @phpstan-return non-negative-int 3732 */ 3733 function wp_filesize( $path ): int { 3734 /** 3735 * Filters the result of wp_filesize() before the file_exists() PHP function is run. 3736 * 3737 * @since 6.0.0 3738 * @since 7.1.0 Negative values are now ignored, being treated the same as null. Numeric values are cast to integers. 3739 * 3740 * @param null|int $size The unfiltered value. Returning a non-negative number from the callback bypasses the filesize call. 3741 * @param string $path Path to the file. 3742 */ 3743 $size = apply_filters( 'pre_wp_filesize', null, $path ); 3744 if ( is_numeric( $size ) ) { 3745 $size = (int) $size; 3746 } 3747 if ( is_int( $size ) && $size >= 0 ) { 3748 return $size; 3749 } 3750 3751 $size = file_exists( $path ) ? (int) filesize( $path ) : 0; 3752 3753 /** 3754 * Filters the size of the file. 3755 * 3756 * @since 6.0.0 3757 * @since 7.1.0 The return value is now always zero or greater. Numeric values are cast to integers. 3758 * 3759 * @param int $size The result of PHP filesize on the file. 3760 * @param string $path Path to the file. 3761 */ 3762 $size = apply_filters( 'wp_filesize', $size, $path ); 3763 if ( is_numeric( $size ) ) { 3764 $size = (int) $size; 3765 } else { 3766 $size = 0; 3767 } 3768 return max( 0, $size ); 3769 } 3770 3771 /** 3772 * Retrieves the list of allowed mime types and file extensions. 3773 * 3774 * @since 2.8.6 3775 * 3776 * @param int|WP_User $user Optional. User to check. Defaults to current user. 3777 * @return array<string, string> Array of mime types keyed by the file extension regex corresponding to those types. 3778 */ 3779 function get_allowed_mime_types( $user = null ) { 3780 $t = wp_get_mime_types(); 3781 3782 unset( $t['swf'], $t['exe'] ); 3783 if ( function_exists( 'current_user_can' ) ) { 3784 $unfiltered = $user ? user_can( $user, 'unfiltered_html' ) : current_user_can( 'unfiltered_html' ); 3785 } 3786 3787 if ( empty( $unfiltered ) ) { 3788 unset( $t['htm|html'], $t['js'] ); 3789 } 3790 3791 /** 3792 * Filters the list of allowed mime types and file extensions. 3793 * 3794 * @since 2.0.0 3795 * 3796 * @param array<string, string> $t Mime types keyed by the file extension regex corresponding to those types. 3797 * @param int|WP_User|null $user User ID, User object or null if not provided (indicates current user). 3798 */ 3799 return apply_filters( 'upload_mimes', $t, $user ); 3800 } 3801 3802 /** 3803 * Displays "Are You Sure" message to confirm the action being taken. 3804 * 3805 * If the action has the nonce explain message, then it will be displayed 3806 * along with the "Are you sure?" message. 3807 * 3808 * @since 2.0.4 3809 * 3810 * @param string $action The nonce action. 3811 * @return never 3812 */ 3813 function wp_nonce_ays( $action ) { 3814 // Default title and response code. 3815 $title = __( 'An error occurred.' ); 3816 $response_code = 403; 3817 3818 if ( 'log-out' === $action ) { 3819 $title = sprintf( 3820 /* translators: %s: Site title. */ 3821 __( 'You are attempting to log out of %s' ), 3822 get_bloginfo( 'name' ) 3823 ); 3824 3825 $redirect_to = $_REQUEST['redirect_to'] ?? ''; 3826 3827 $html = $title; 3828 $html .= '</p><p>'; 3829 $html .= sprintf( 3830 /* translators: %s: Logout URL. */ 3831 __( 'Do you really want to <a href="%s">log out</a>?' ), 3832 wp_logout_url( $redirect_to ) 3833 ); 3834 } else { 3835 $html = __( 'The link you followed has expired.' ); 3836 3837 if ( wp_get_referer() ) { 3838 $wp_http_referer = remove_query_arg( 'updated', wp_get_referer() ); 3839 $wp_http_referer = wp_validate_redirect( sanitize_url( $wp_http_referer ) ); 3840 3841 $html .= '</p><p>'; 3842 $html .= sprintf( 3843 '<a href="%s">%s</a>', 3844 esc_url( $wp_http_referer ), 3845 __( 'Please try again.' ) 3846 ); 3847 } 3848 } 3849 3850 wp_die( $html, $title, $response_code ); 3851 } 3852 3853 /** 3854 * Kills WordPress execution and displays HTML page with an error message. 3855 * 3856 * This function complements the `die()` PHP function. The difference is that 3857 * HTML will be displayed to the user. It is recommended to use this function 3858 * only when the execution should not continue any further. It is not recommended 3859 * to call this function very often, and try to handle as many errors as possible 3860 * silently or more gracefully. 3861 * 3862 * As a shorthand, the desired HTTP response code may be passed as an integer to 3863 * the `$title` parameter (the default title would apply) or the `$args` parameter. 3864 * 3865 * @since 2.0.4 3866 * @since 4.1.0 The `$title` and `$args` parameters were changed to optionally accept 3867 * an integer to be used as the response code. 3868 * @since 5.1.0 The `$link_url`, `$link_text`, and `$exit` arguments were added. 3869 * @since 5.3.0 The `$charset` argument was added. 3870 * @since 5.5.0 The `$text_direction` argument has a priority over get_language_attributes() 3871 * in the default handler. 3872 * 3873 * @global WP_Query $wp_query WordPress Query object. 3874 * 3875 * @param string|WP_Error|int $message Optional. Error message. If this is a WP_Error object, 3876 * and not an Ajax or XML-RPC request, the error's messages are used. 3877 * An integer is echoed as the entire response body by legacy Ajax 3878 * handlers, which use -1 for a failed nonce or capability check, 3879 * 0 for failure, and 1 for success. Default empty string. 3880 * @param string|int $title Optional. Error title. If `$message` is a `WP_Error` object, 3881 * error data with the key 'title' may be used to specify the title. 3882 * If `$title` is an integer, then it is treated as the response code. 3883 * Default empty string. 3884 * @param string|array|int $args { 3885 * Optional. Arguments to control behavior. If `$args` is an integer, then it is treated 3886 * as the response code. Default empty array. 3887 * 3888 * @type int|null $response The HTTP response code, or null to send no status header. The Ajax, JSON, 3889 * JSONP and XML handlers all accept null, for backward compatibility. 3890 * Default 200 for Ajax requests, 500 otherwise. 3891 * @type string $link_url A URL to include a link to. Only works in combination with $link_text. 3892 * Default empty string. 3893 * @type string $link_text A label for the link to include. Only works in combination with $link_url. 3894 * Default empty string. 3895 * @type bool $back_link Whether to include a link to go back. Default false. 3896 * @type string $text_direction The text direction. This is only useful internally, when WordPress is still 3897 * loading and the site's locale is not set up yet. Accepts 'rtl' and 'ltr'. 3898 * Default is the value of is_rtl(). 3899 * @type string $charset Character set of the HTML output. Default 'utf-8'. 3900 * @type string $code Error code to use. Default is 'wp_die', or the main error code if $message 3901 * is a WP_Error. 3902 * @type bool $exit Whether to exit the process after completion. Default true. 3903 * } 3904 * @return void Never returns if `$args['exit']` is true (the default), otherwise returns void. 3905 * @phpstan-param string|WP_Error|int<-1, max> $message 3906 * @phpstan-return ( $args is array{exit: false} ? void : never ) 3907 */ 3908 function wp_die( $message = '', $title = '', $args = array() ) { 3909 global $wp_query; 3910 3911 if ( is_int( $args ) ) { 3912 $args = array( 'response' => $args ); 3913 } elseif ( is_int( $title ) ) { 3914 $args = array( 'response' => $title ); 3915 $title = ''; 3916 } 3917 3918 if ( wp_doing_ajax() ) { 3919 /** 3920 * Filters the callback for killing WordPress execution for Ajax requests. 3921 * 3922 * @since 3.4.0 3923 * 3924 * @param callable $callback Callback function name. 3925 */ 3926 $callback = apply_filters( 'wp_die_ajax_handler', '_ajax_wp_die_handler' ); 3927 } elseif ( wp_is_json_request() ) { 3928 /** 3929 * Filters the callback for killing WordPress execution for JSON requests. 3930 * 3931 * @since 5.1.0 3932 * 3933 * @param callable $callback Callback function name. 3934 */ 3935 $callback = apply_filters( 'wp_die_json_handler', '_json_wp_die_handler' ); 3936 } elseif ( wp_is_serving_rest_request() && wp_is_jsonp_request() ) { 3937 /** 3938 * Filters the callback for killing WordPress execution for JSONP REST requests. 3939 * 3940 * @since 5.2.0 3941 * 3942 * @param callable $callback Callback function name. 3943 */ 3944 $callback = apply_filters( 'wp_die_jsonp_handler', '_jsonp_wp_die_handler' ); 3945 } elseif ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) { 3946 /** 3947 * Filters the callback for killing WordPress execution for XML-RPC requests. 3948 * 3949 * @since 3.4.0 3950 * 3951 * @param callable $callback Callback function name. 3952 */ 3953 $callback = apply_filters( 'wp_die_xmlrpc_handler', '_xmlrpc_wp_die_handler' ); 3954 } elseif ( wp_is_xml_request() 3955 || isset( $wp_query ) && 3956 ( function_exists( 'is_feed' ) && is_feed() 3957 || function_exists( 'is_comment_feed' ) && is_comment_feed() 3958 || function_exists( 'is_trackback' ) && is_trackback() ) ) { 3959 /** 3960 * Filters the callback for killing WordPress execution for XML requests. 3961 * 3962 * @since 5.2.0 3963 * 3964 * @param callable $callback Callback function name. 3965 */ 3966 $callback = apply_filters( 'wp_die_xml_handler', '_xml_wp_die_handler' ); 3967 } else { 3968 /** 3969 * Filters the callback for killing WordPress execution for all non-Ajax, non-JSON, non-XML requests. 3970 * 3971 * @since 3.0.0 3972 * 3973 * @param callable $callback Callback function name. 3974 */ 3975 $callback = apply_filters( 'wp_die_handler', '_default_wp_die_handler' ); 3976 } 3977 3978 call_user_func( $callback, $message, $title, $args ); 3979 } 3980 3981 /** 3982 * Kills WordPress execution and displays HTML page with an error message. 3983 * 3984 * This is the default handler for wp_die(). If you want a custom one, 3985 * you can override this using the {@see 'wp_die_handler'} filter in wp_die(). 3986 * 3987 * @since 3.0.0 3988 * @access private 3989 * 3990 * @param string|WP_Error $message Error message or WP_Error object. 3991 * @param string $title Optional. Error title. Default empty string. 3992 * @param string|array $args Optional. Arguments to control behavior. Default empty array. 3993 * @phpstan-return ( $args is array{exit: false} ? void : never ) 3994 */ 3995 function _default_wp_die_handler( $message, $title = '', $args = array() ) { 3996 list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args ); 3997 3998 if ( is_string( $message ) ) { 3999 if ( ! empty( $parsed_args['additional_errors'] ) ) { 4000 $message = array_merge( 4001 array( $message ), 4002 wp_list_pluck( $parsed_args['additional_errors'], 'message' ) 4003 ); 4004 $message = "<ul>\n\t\t<li>" . implode( "</li>\n\t\t<li>", $message ) . "</li>\n\t</ul>"; 4005 } 4006 4007 $message = sprintf( 4008 '<div class="wp-die-message">%s</div>', 4009 $message 4010 ); 4011 } 4012 4013 $have_gettext = function_exists( '__' ); 4014 4015 if ( ! empty( $parsed_args['link_url'] ) && ! empty( $parsed_args['link_text'] ) ) { 4016 $link_url = $parsed_args['link_url']; 4017 if ( function_exists( 'esc_url' ) ) { 4018 $link_url = esc_url( $link_url ); 4019 } 4020 $link_text = $parsed_args['link_text']; 4021 $message .= "\n<p><a href='{$link_url}'>{$link_text}</a></p>"; 4022 } 4023 4024 if ( isset( $parsed_args['back_link'] ) && $parsed_args['back_link'] ) { 4025 $back_text = $have_gettext ? __( '« Back' ) : '« Back'; 4026 $message .= "\n<p><a href='javascript:history.back()'>$back_text</a></p>"; 4027 } 4028 4029 if ( ! did_action( 'admin_head' ) ) : 4030 if ( ! headers_sent() ) { 4031 header( "Content-Type: text/html; charset={$parsed_args['charset']}" ); 4032 status_header( $parsed_args['response'] ); 4033 nocache_headers(); 4034 } 4035 4036 $text_direction = $parsed_args['text_direction']; 4037 $dir_attr = "dir='$text_direction'"; 4038 4039 /* 4040 * If `text_direction` was not explicitly passed, 4041 * use get_language_attributes() if available. 4042 */ 4043 if ( empty( $args['text_direction'] ) 4044 && function_exists( 'language_attributes' ) && function_exists( 'is_rtl' ) 4045 ) { 4046 $dir_attr = get_language_attributes(); 4047 } 4048 ?> 4049 <!DOCTYPE html> 4050 <html <?php echo $dir_attr; ?>> 4051 <head> 4052 <meta http-equiv="Content-Type" content="text/html; charset=<?php echo $parsed_args['charset']; ?>" /> 4053 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 4054 <?php 4055 if ( function_exists( 'wp_robots' ) && function_exists( 'wp_robots_no_robots' ) && function_exists( 'add_filter' ) ) { 4056 add_filter( 'wp_robots', 'wp_robots_no_robots' ); 4057 // Prevent warnings because of $wp_query not existing. 4058 remove_filter( 'wp_robots', 'wp_robots_noindex_embeds' ); 4059 remove_filter( 'wp_robots', 'wp_robots_noindex_search' ); 4060 wp_robots(); 4061 } 4062 ?> 4063 <title><?php echo $title; ?></title> 4064 <style> 4065 html { 4066 background: #f1f1f1; 4067 } 4068 body { 4069 background: #fff; 4070 border: 1px solid #ccd0d4; 4071 color: #444; 4072 font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif; 4073 margin: 2em auto; 4074 padding: 1em 2em; 4075 max-width: 700px; 4076 -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .04); 4077 box-shadow: 0 1px 1px rgba(0, 0, 0, .04); 4078 } 4079 h1 { 4080 border-bottom: 1px solid #dadada; 4081 clear: both; 4082 color: #666; 4083 font-size: 24px; 4084 margin: 30px 0 0 0; 4085 padding: 0; 4086 padding-bottom: 7px; 4087 } 4088 #error-page { 4089 margin-top: 50px; 4090 } 4091 #error-page p, 4092 #error-page .wp-die-message { 4093 font-size: 14px; 4094 line-height: 1.5; 4095 margin: 25px 0 20px; 4096 } 4097 #error-page code { 4098 font-family: Consolas, Monaco, monospace; 4099 } 4100 ul li { 4101 margin-bottom: 10px; 4102 font-size: 14px ; 4103 } 4104 a { 4105 color: #3858e9; 4106 } 4107 a:hover, 4108 a:active { 4109 color: #183ad6; 4110 } 4111 a:focus { 4112 color: #183ad6; 4113 box-shadow: 0 0 0 var(--wp-admin-border-width-focus, 1.5px) var(--wp-admin-theme-color, #3858e9); 4114 outline: 2px solid transparent; 4115 } 4116 .button { 4117 background: #f3f5f6; 4118 border: 1px solid #016087; 4119 color: #016087; 4120 display: inline-block; 4121 text-decoration: none; 4122 font-size: 13px; 4123 line-height: 2; 4124 height: 28px; 4125 margin: 0; 4126 padding: 0 10px 1px; 4127 cursor: pointer; 4128 -webkit-border-radius: 3px; 4129 -webkit-appearance: none; 4130 border-radius: 3px; 4131 white-space: nowrap; 4132 -webkit-box-sizing: border-box; 4133 -moz-box-sizing: border-box; 4134 box-sizing: border-box; 4135 4136 vertical-align: top; 4137 } 4138 4139 .button.button-large { 4140 line-height: 2.30769231; 4141 min-height: 32px; 4142 padding: 0 12px; 4143 } 4144 4145 .button:hover, 4146 .button:focus { 4147 background: #f1f1f1; 4148 } 4149 4150 .button:focus { 4151 background: #f3f5f6; 4152 border-color: #007cba; 4153 -webkit-box-shadow: 0 0 0 1px #007cba; 4154 box-shadow: 0 0 0 1px #007cba; 4155 color: #016087; 4156 outline: 2px solid transparent; 4157 outline-offset: 0; 4158 } 4159 4160 .button:active { 4161 background: #f3f5f6; 4162 border-color: #7e8993; 4163 -webkit-box-shadow: none; 4164 box-shadow: none; 4165 } 4166 4167 <?php 4168 if ( 'rtl' === $text_direction ) { 4169 echo 'body { font-family: Tahoma, Arial; }'; 4170 } 4171 ?> 4172 </style> 4173 </head> 4174 <body id="error-page"> 4175 <?php endif; // ! did_action( 'admin_head' ) ?> 4176 <?php echo $message; ?> 4177 </body> 4178 </html> 4179 <?php 4180 if ( $parsed_args['exit'] ) { 4181 die(); 4182 } 4183 } 4184 4185 /** 4186 * Kills WordPress execution and displays Ajax response with an error message. 4187 * 4188 * This is the handler for wp_die() when processing Ajax requests. 4189 * 4190 * @since 3.4.0 4191 * @access private 4192 * 4193 * @param string $message Error message. 4194 * @param string $title Optional. Error title (unused). Default empty string. 4195 * @param string|array $args Optional. Arguments to control behavior. Default empty array. 4196 * @phpstan-return ( $args is array{exit: false} ? void : never ) 4197 */ 4198 function _ajax_wp_die_handler( $message, $title = '', $args = array() ) { 4199 // Set default 'response' to 200 for Ajax requests. 4200 $args = wp_parse_args( 4201 $args, 4202 array( 'response' => 200 ) 4203 ); 4204 4205 list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args ); 4206 4207 if ( ! headers_sent() ) { 4208 // This is intentional. For backward-compatibility, support passing null here. 4209 if ( null !== $args['response'] ) { 4210 status_header( $parsed_args['response'] ); 4211 } 4212 nocache_headers(); 4213 } 4214 4215 if ( is_scalar( $message ) ) { 4216 $message = (string) $message; 4217 } else { 4218 $message = '0'; 4219 } 4220 4221 if ( $parsed_args['exit'] ) { 4222 die( $message ); 4223 } 4224 4225 echo $message; 4226 } 4227 4228 /** 4229 * Kills WordPress execution and displays JSON response with an error message. 4230 * 4231 * This is the handler for wp_die() when processing JSON requests. 4232 * 4233 * @since 5.1.0 4234 * @access private 4235 * 4236 * @param string $message Error message. 4237 * @param string $title Optional. Error title. Default empty string. 4238 * @param string|array $args Optional. Arguments to control behavior. Default empty array. 4239 * @phpstan-return ( $args is array{exit: false} ? void : never ) 4240 */ 4241 function _json_wp_die_handler( $message, $title = '', $args = array() ) { 4242 list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args ); 4243 4244 $data = array( 4245 'code' => $parsed_args['code'], 4246 'message' => $message, 4247 'data' => array( 4248 'status' => $parsed_args['response'], 4249 ), 4250 'additional_errors' => $parsed_args['additional_errors'], 4251 ); 4252 4253 if ( isset( $parsed_args['error_data'] ) ) { 4254 $data['data']['error'] = $parsed_args['error_data']; 4255 } 4256 4257 if ( ! headers_sent() ) { 4258 header( "Content-Type: application/json; charset={$parsed_args['charset']}" ); 4259 if ( null !== $parsed_args['response'] ) { 4260 status_header( $parsed_args['response'] ); 4261 } 4262 nocache_headers(); 4263 } 4264 4265 echo wp_json_encode( $data ); 4266 if ( $parsed_args['exit'] ) { 4267 die(); 4268 } 4269 } 4270 4271 /** 4272 * Kills WordPress execution and displays JSONP response with an error message. 4273 * 4274 * This is the handler for wp_die() when processing JSONP requests. 4275 * 4276 * @since 5.2.0 4277 * @access private 4278 * 4279 * @param string $message Error message. 4280 * @param string $title Optional. Error title. Default empty string. 4281 * @param string|array $args Optional. Arguments to control behavior. Default empty array. 4282 * @phpstan-return ( $args is array{exit: false} ? void : never ) 4283 */ 4284 function _jsonp_wp_die_handler( $message, $title = '', $args = array() ) { 4285 list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args ); 4286 4287 $data = array( 4288 'code' => $parsed_args['code'], 4289 'message' => $message, 4290 'data' => array( 4291 'status' => $parsed_args['response'], 4292 ), 4293 'additional_errors' => $parsed_args['additional_errors'], 4294 ); 4295 4296 if ( isset( $parsed_args['error_data'] ) ) { 4297 $data['data']['error'] = $parsed_args['error_data']; 4298 } 4299 4300 if ( ! headers_sent() ) { 4301 header( "Content-Type: application/javascript; charset={$parsed_args['charset']}" ); 4302 header( 'X-Content-Type-Options: nosniff' ); 4303 header( 'X-Robots-Tag: noindex' ); 4304 if ( null !== $parsed_args['response'] ) { 4305 status_header( $parsed_args['response'] ); 4306 } 4307 nocache_headers(); 4308 } 4309 4310 $result = wp_json_encode( $data ); 4311 $jsonp_callback = $_GET['_jsonp']; 4312 echo '/**/' . $jsonp_callback . '(' . $result . ')'; 4313 if ( $parsed_args['exit'] ) { 4314 die(); 4315 } 4316 } 4317 4318 /** 4319 * Kills WordPress execution and displays XML response with an error message. 4320 * 4321 * This is the handler for wp_die() when processing XML-RPC requests. 4322 * 4323 * @since 3.2.0 4324 * @access private 4325 * 4326 * @global wp_xmlrpc_server $wp_xmlrpc_server 4327 * 4328 * @param string $message Error message. 4329 * @param string $title Optional. Error title. Default empty string. 4330 * @param string|array $args Optional. Arguments to control behavior. Default empty array. 4331 * @phpstan-return ( $args is array{exit: false} ? void : never ) 4332 */ 4333 function _xmlrpc_wp_die_handler( $message, $title = '', $args = array() ) { 4334 global $wp_xmlrpc_server; 4335 4336 list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args ); 4337 4338 if ( ! headers_sent() ) { 4339 nocache_headers(); 4340 } 4341 4342 if ( $wp_xmlrpc_server ) { 4343 $error = new IXR_Error( $parsed_args['response'], $message ); 4344 $wp_xmlrpc_server->output( $error->getXml() ); 4345 } 4346 if ( $parsed_args['exit'] ) { 4347 die(); 4348 } 4349 } 4350 4351 /** 4352 * Kills WordPress execution and displays XML response with an error message. 4353 * 4354 * This is the handler for wp_die() when processing XML requests. 4355 * 4356 * @since 5.2.0 4357 * @access private 4358 * 4359 * @param string $message Error message. 4360 * @param string $title Optional. Error title. Default empty string. 4361 * @param string|array $args Optional. Arguments to control behavior. Default empty array. 4362 * @phpstan-return ( $args is array{exit: false} ? void : never ) 4363 */ 4364 function _xml_wp_die_handler( $message, $title = '', $args = array() ) { 4365 list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args ); 4366 4367 $message = htmlspecialchars( $message ); 4368 $title = htmlspecialchars( $title ); 4369 4370 $xml = <<<EOD 4371 <error> 4372 <code>{$parsed_args['code']}</code> 4373 <title><![CDATA[{$title}]]></title> 4374 <message><![CDATA[{$message}]]></message> 4375 <data> 4376 <status>{$parsed_args['response']}</status> 4377 </data> 4378 </error> 4379 4380 EOD; 4381 4382 if ( ! headers_sent() ) { 4383 header( "Content-Type: text/xml; charset={$parsed_args['charset']}" ); 4384 if ( null !== $parsed_args['response'] ) { 4385 status_header( $parsed_args['response'] ); 4386 } 4387 nocache_headers(); 4388 } 4389 4390 echo $xml; 4391 if ( $parsed_args['exit'] ) { 4392 die(); 4393 } 4394 } 4395 4396 /** 4397 * Kills WordPress execution and displays an error message. 4398 * 4399 * This is the handler for wp_die() when processing APP requests. 4400 * 4401 * @since 3.4.0 4402 * @since 5.1.0 Added the $title and $args parameters. 4403 * @access private 4404 * 4405 * @param string $message Optional. Response to print. Default empty string. 4406 * @param string $title Optional. Error title (unused). Default empty string. 4407 * @param string|array $args Optional. Arguments to control behavior. Default empty array. 4408 * @phpstan-return ( $args is array{exit: false} ? void : never ) 4409 */ 4410 function _scalar_wp_die_handler( $message = '', $title = '', $args = array() ) { 4411 list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args ); 4412 4413 if ( $parsed_args['exit'] ) { 4414 if ( is_scalar( $message ) ) { 4415 die( (string) $message ); 4416 } 4417 die(); 4418 } 4419 4420 if ( is_scalar( $message ) ) { 4421 echo (string) $message; 4422 } 4423 } 4424 4425 /** 4426 * Processes arguments passed to wp_die() consistently for its handlers. 4427 * 4428 * @since 5.1.0 4429 * @access private 4430 * 4431 * @param string|WP_Error|int $message Error message, WP_Error object, or integer response. 4432 * @param string $title Optional. Error title. Default empty string. 4433 * @param string|array $args Optional. Arguments to control behavior. Default empty array. 4434 * @return array { 4435 * Processed arguments. 4436 * 4437 * @type string|int $0 Error message, or integer response. 4438 * @type string $1 Error title. 4439 * @type array $2 Arguments to control behavior. 4440 * } 4441 */ 4442 function _wp_die_process_input( $message, $title = '', $args = array() ) { 4443 $defaults = array( 4444 'response' => 0, 4445 'code' => '', 4446 'exit' => true, 4447 'back_link' => false, 4448 'link_url' => '', 4449 'link_text' => '', 4450 'text_direction' => '', 4451 'charset' => 'utf-8', 4452 'additional_errors' => array(), 4453 ); 4454 4455 $args = wp_parse_args( $args, $defaults ); 4456 4457 if ( function_exists( 'is_wp_error' ) && is_wp_error( $message ) ) { 4458 if ( ! empty( $message->errors ) ) { 4459 $errors = array(); 4460 foreach ( (array) $message->errors as $error_code => $error_messages ) { 4461 foreach ( (array) $error_messages as $error_message ) { 4462 $errors[] = array( 4463 'code' => $error_code, 4464 'message' => $error_message, 4465 'data' => $message->get_error_data( $error_code ), 4466 ); 4467 } 4468 } 4469 4470 $message = $errors[0]['message']; 4471 if ( empty( $args['code'] ) ) { 4472 $args['code'] = $errors[0]['code']; 4473 } 4474 if ( empty( $args['response'] ) && is_array( $errors[0]['data'] ) && ! empty( $errors[0]['data']['status'] ) ) { 4475 $args['response'] = $errors[0]['data']['status']; 4476 } 4477 if ( empty( $title ) && is_array( $errors[0]['data'] ) && ! empty( $errors[0]['data']['title'] ) ) { 4478 $title = $errors[0]['data']['title']; 4479 } 4480 if ( WP_DEBUG_DISPLAY && is_array( $errors[0]['data'] ) && ! empty( $errors[0]['data']['error'] ) ) { 4481 $args['error_data'] = $errors[0]['data']['error']; 4482 } 4483 4484 unset( $errors[0] ); 4485 $args['additional_errors'] = array_values( $errors ); 4486 } else { 4487 $message = ''; 4488 } 4489 } 4490 4491 $have_gettext = function_exists( '__' ); 4492 4493 // The $title and these specific $args must always have a non-empty value. 4494 if ( empty( $args['code'] ) ) { 4495 $args['code'] = 'wp_die'; 4496 } 4497 if ( empty( $args['response'] ) ) { 4498 $args['response'] = 500; 4499 } 4500 if ( empty( $title ) ) { 4501 $title = $have_gettext ? __( 'WordPress › Error' ) : 'WordPress › Error'; 4502 } 4503 if ( empty( $args['text_direction'] ) || ! in_array( $args['text_direction'], array( 'ltr', 'rtl' ), true ) ) { 4504 $args['text_direction'] = 'ltr'; 4505 if ( function_exists( 'is_rtl' ) && is_rtl() ) { 4506 $args['text_direction'] = 'rtl'; 4507 } 4508 } 4509 4510 if ( ! empty( $args['charset'] ) ) { 4511 $args['charset'] = _canonical_charset( $args['charset'] ); 4512 } 4513 4514 return array( $message, $title, $args ); 4515 } 4516 4517 /** 4518 * Encodes a variable into JSON, with some confidence checks. 4519 * 4520 * @since 4.1.0 4521 * @since 5.3.0 No longer handles support for PHP < 5.6. 4522 * @since 6.5.0 The `$data` parameter has been renamed to `$value` and 4523 * the `$options` parameter to `$flags` for parity with PHP. 4524 * 4525 * @param mixed $value Variable (usually an array or object) to encode as JSON. 4526 * @param int $flags Optional. Options to be passed to json_encode(). Default 0. 4527 * @param int $depth Optional. Maximum depth to walk through $value. Must be 4528 * greater than 0. Default 512. 4529 * @return string|false The JSON encoded string, or false if it cannot be encoded. 4530 * 4531 * @phpstan-param positive-int $depth 4532 * @phpstan-return non-empty-string|false 4533 */ 4534 function wp_json_encode( $value, $flags = 0, $depth = 512 ) { 4535 $json = json_encode( $value, $flags, $depth ); 4536 4537 // If json_encode() was successful, no need to do more confidence checking. 4538 if ( false !== $json ) { 4539 return $json; 4540 } 4541 4542 try { 4543 $value = _wp_json_sanity_check( $value, $depth ); 4544 } catch ( Exception $e ) { 4545 return false; 4546 } 4547 4548 return json_encode( $value, $flags, $depth ); 4549 } 4550 4551 /** 4552 * Performs confidence checks on data that shall be encoded to JSON. 4553 * 4554 * @ignore 4555 * @since 4.1.0 4556 * @access private 4557 * 4558 * @see wp_json_encode() 4559 * 4560 * @throws Exception If depth limit is reached. 4561 * 4562 * @param mixed $value Variable (usually an array or object) to encode as JSON. 4563 * @param int $depth Maximum depth to walk through $value. Must be greater than 0. 4564 * @return mixed The sanitized data that shall be encoded to JSON. 4565 */ 4566 function _wp_json_sanity_check( $value, $depth ) { 4567 if ( $depth < 0 ) { 4568 throw new Exception( 'Reached depth limit' ); 4569 } 4570 4571 if ( is_array( $value ) ) { 4572 $output = array(); 4573 foreach ( $value as $id => $el ) { 4574 // Don't forget to sanitize the ID! 4575 if ( is_string( $id ) ) { 4576 $clean_id = _wp_json_convert_string( $id ); 4577 } else { 4578 $clean_id = $id; 4579 } 4580 4581 // Check the element type, so that we're only recursing if we really have to. 4582 if ( is_array( $el ) || is_object( $el ) ) { 4583 $output[ $clean_id ] = _wp_json_sanity_check( $el, $depth - 1 ); 4584 } elseif ( is_string( $el ) ) { 4585 $output[ $clean_id ] = _wp_json_convert_string( $el ); 4586 } else { 4587 $output[ $clean_id ] = $el; 4588 } 4589 } 4590 } elseif ( is_object( $value ) ) { 4591 $output = new stdClass(); 4592 foreach ( $value as $id => $el ) { 4593 if ( is_string( $id ) ) { 4594 $clean_id = _wp_json_convert_string( $id ); 4595 } else { 4596 $clean_id = $id; 4597 } 4598 4599 if ( is_array( $el ) || is_object( $el ) ) { 4600 $output->$clean_id = _wp_json_sanity_check( $el, $depth - 1 ); 4601 } elseif ( is_string( $el ) ) { 4602 $output->$clean_id = _wp_json_convert_string( $el ); 4603 } else { 4604 $output->$clean_id = $el; 4605 } 4606 } 4607 } elseif ( is_string( $value ) ) { 4608 return _wp_json_convert_string( $value ); 4609 } else { 4610 return $value; 4611 } 4612 4613 return $output; 4614 } 4615 4616 /** 4617 * Converts a string to UTF-8, so that it can be safely encoded to JSON. 4618 * 4619 * @ignore 4620 * @since 4.1.0 4621 * @access private 4622 * 4623 * @see _wp_json_sanity_check() 4624 * 4625 * @param string $input_string The string which is to be converted. 4626 * @return string The checked string. 4627 */ 4628 function _wp_json_convert_string( $input_string ) { 4629 static $use_mb = null; 4630 if ( is_null( $use_mb ) ) { 4631 $use_mb = function_exists( 'mb_convert_encoding' ); 4632 } 4633 4634 if ( $use_mb ) { 4635 $encoding = mb_detect_encoding( $input_string, mb_detect_order(), true ); 4636 if ( $encoding ) { 4637 return mb_convert_encoding( $input_string, 'UTF-8', $encoding ); 4638 } else { 4639 return mb_convert_encoding( $input_string, 'UTF-8', 'UTF-8' ); 4640 } 4641 } else { 4642 return wp_check_invalid_utf8( $input_string, true ); 4643 } 4644 } 4645 4646 /** 4647 * Prepares response data to be serialized to JSON. 4648 * 4649 * This supports the JsonSerializable interface for PHP 5.2-5.3 as well. 4650 * 4651 * @ignore 4652 * @since 4.4.0 4653 * @deprecated 5.3.0 This function is no longer needed as support for PHP 5.2-5.3 4654 * has been dropped. 4655 * @access private 4656 * 4657 * @param mixed $value Native representation. 4658 * @return bool|int|float|null|string|array Data ready for `json_encode()`. 4659 */ 4660 function _wp_json_prepare_data( $value ) { 4661 _deprecated_function( __FUNCTION__, '5.3.0' ); 4662 return $value; 4663 } 4664 4665 /** 4666 * Sends a JSON response back to an Ajax request. 4667 * 4668 * @since 3.5.0 4669 * @since 4.7.0 The `$status_code` parameter was added. 4670 * @since 5.6.0 The `$flags` parameter was added. 4671 * 4672 * @param mixed $response Variable (usually an array or object) to encode as JSON, 4673 * then print and die. 4674 * @param int $status_code Optional. The HTTP status code to output. Default null. 4675 * @param int $flags Optional. Options to be passed to json_encode(). Default 0. 4676 * @return never 4677 */ 4678 function wp_send_json( $response, $status_code = null, $flags = 0 ) { 4679 if ( wp_is_serving_rest_request() ) { 4680 _doing_it_wrong( 4681 __FUNCTION__, 4682 sprintf( 4683 /* translators: 1: WP_REST_Response, 2: WP_Error */ 4684 __( 'Return a %1$s or %2$s object from your callback when using the REST API.' ), 4685 'WP_REST_Response', 4686 'WP_Error' 4687 ), 4688 '5.5.0' 4689 ); 4690 } 4691 4692 if ( ! headers_sent() ) { 4693 header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) ); 4694 if ( null !== $status_code ) { 4695 status_header( $status_code ); 4696 } 4697 } 4698 4699 echo wp_json_encode( $response, $flags ); 4700 4701 if ( wp_doing_ajax() ) { 4702 wp_die( 4703 '', 4704 '', 4705 array( 4706 'response' => null, 4707 ) 4708 ); 4709 } else { 4710 die; 4711 } 4712 } 4713 4714 /** 4715 * Sends a JSON response back to an Ajax request, indicating success. 4716 * 4717 * @since 3.5.0 4718 * @since 4.7.0 The `$status_code` parameter was added. 4719 * @since 5.6.0 The `$flags` parameter was added. 4720 * 4721 * @param mixed $value Optional. Data to encode as JSON, then print and die. Default null. 4722 * @param int $status_code Optional. The HTTP status code to output. Default null. 4723 * @param int $flags Optional. Options to be passed to json_encode(). Default 0. 4724 * @return never 4725 */ 4726 function wp_send_json_success( $value = null, $status_code = null, $flags = 0 ) { 4727 $response = array( 'success' => true ); 4728 4729 if ( isset( $value ) ) { 4730 $response['data'] = $value; 4731 } 4732 4733 wp_send_json( $response, $status_code, $flags ); 4734 } 4735 4736 /** 4737 * Sends a JSON response back to an Ajax request, indicating failure. 4738 * 4739 * If the `$value` parameter is a WP_Error object, the errors 4740 * within the object are processed and output as an array of error 4741 * codes and corresponding messages. All other types are output 4742 * without further processing. 4743 * 4744 * @since 3.5.0 4745 * @since 4.1.0 The `$value` parameter is now processed if a WP_Error object is passed in. 4746 * @since 4.7.0 The `$status_code` parameter was added. 4747 * @since 5.6.0 The `$flags` parameter was added. 4748 * 4749 * @param mixed $value Optional. Data to encode as JSON, then print and die. Default null. 4750 * @param int $status_code Optional. The HTTP status code to output. Default null. 4751 * @param int $flags Optional. Options to be passed to json_encode(). Default 0. 4752 * @return never 4753 */ 4754 function wp_send_json_error( $value = null, $status_code = null, $flags = 0 ) { 4755 $response = array( 'success' => false ); 4756 4757 if ( isset( $value ) ) { 4758 if ( is_wp_error( $value ) ) { 4759 $result = array(); 4760 foreach ( $value->errors as $code => $messages ) { 4761 foreach ( $messages as $message ) { 4762 $result[] = array( 4763 'code' => $code, 4764 'message' => $message, 4765 ); 4766 } 4767 } 4768 4769 $response['data'] = $result; 4770 } else { 4771 $response['data'] = $value; 4772 } 4773 } 4774 4775 wp_send_json( $response, $status_code, $flags ); 4776 } 4777 4778 /** 4779 * Checks that a JSONP callback is a valid JavaScript callback name. 4780 * 4781 * Only allows alphanumeric characters and the dot character in callback 4782 * function names. This helps to mitigate XSS attacks caused by directly 4783 * outputting user input. 4784 * 4785 * @since 4.6.0 4786 * 4787 * @param string $callback Supplied JSONP callback function name. 4788 * @return bool Whether the callback function name is valid. 4789 */ 4790 function wp_check_jsonp_callback( $callback ) { 4791 if ( ! is_string( $callback ) ) { 4792 return false; 4793 } 4794 4795 preg_replace( '/[^\w\.]/', '', $callback, -1, $illegal_char_count ); 4796 4797 return 0 === $illegal_char_count; 4798 } 4799 4800 /** 4801 * Reads and decodes a JSON file. 4802 * 4803 * @since 5.9.0 4804 * 4805 * @param string $filename Path to the JSON file. 4806 * @param array $options { 4807 * Optional. Options to be used with `json_decode()`. 4808 * 4809 * @type bool $associative Optional. When `true`, JSON objects will be returned as associative arrays. 4810 * When `false`, JSON objects will be returned as objects. Default false. 4811 * } 4812 * 4813 * @return mixed Returns the value encoded in JSON in appropriate PHP type. 4814 * `null` is returned if the file is not found, is not a readable file, 4815 * or its content can't be decoded. 4816 */ 4817 function wp_json_file_decode( $filename, $options = array() ) { 4818 $normalized_filename = wp_normalize_path( realpath( $filename ) ); 4819 4820 if ( ! $normalized_filename ) { 4821 wp_trigger_error( 4822 __FUNCTION__, 4823 sprintf( 4824 /* translators: %s: Path to the JSON file. */ 4825 __( "File %s doesn't exist!" ), 4826 $filename 4827 ) 4828 ); 4829 return null; 4830 } 4831 if ( ! is_file( $normalized_filename ) || ! is_readable( $normalized_filename ) ) { 4832 wp_trigger_error( 4833 __FUNCTION__, 4834 sprintf( 4835 /* translators: %s: Path to the JSON file. */ 4836 __( '%s is not a readable file.' ), 4837 $filename 4838 ) 4839 ); 4840 return null; 4841 } 4842 4843 $options = wp_parse_args( $options, array( 'associative' => false ) ); 4844 $decoded_file = json_decode( file_get_contents( $normalized_filename ), $options['associative'] ); 4845 4846 if ( JSON_ERROR_NONE !== json_last_error() ) { 4847 wp_trigger_error( 4848 __FUNCTION__, 4849 sprintf( 4850 /* translators: 1: Path to the JSON file, 2: Error message. */ 4851 __( 'Error when decoding a JSON file at path %1$s: %2$s' ), 4852 $filename, 4853 json_last_error_msg() 4854 ) 4855 ); 4856 return null; 4857 } 4858 4859 return $decoded_file; 4860 } 4861 4862 /** 4863 * Retrieves the WordPress home page URL. 4864 * 4865 * If the constant named 'WP_HOME' exists, then it will be used and returned 4866 * by the function. This can be used to counter the redirection on your local 4867 * development environment. 4868 * 4869 * @since 2.2.0 4870 * @access private 4871 * 4872 * @see WP_HOME 4873 * 4874 * @param string $url URL for the home location. 4875 * @return string Homepage location. 4876 */ 4877 function _config_wp_home( $url = '' ) { 4878 if ( defined( 'WP_HOME' ) ) { 4879 return untrailingslashit( WP_HOME ); 4880 } 4881 return $url; 4882 } 4883 4884 /** 4885 * Retrieves the WordPress site URL. 4886 * 4887 * If the constant named 'WP_SITEURL' is defined, then the value in that 4888 * constant will always be returned. This can be used for debugging a site 4889 * on your localhost while not having to change the database to your URL. 4890 * 4891 * @since 2.2.0 4892 * @access private 4893 * 4894 * @see WP_SITEURL 4895 * 4896 * @param string $url URL to set the WordPress site location. 4897 * @return string The WordPress site URL. 4898 */ 4899 function _config_wp_siteurl( $url = '' ) { 4900 if ( defined( 'WP_SITEURL' ) ) { 4901 return untrailingslashit( WP_SITEURL ); 4902 } 4903 return $url; 4904 } 4905 4906 /** 4907 * Deletes the fresh site option. 4908 * 4909 * @since 4.7.0 4910 * @access private 4911 */ 4912 function _delete_option_fresh_site() { 4913 update_option( 'fresh_site', '0', false ); 4914 } 4915 4916 /** 4917 * Sets the localized direction for MCE plugin. 4918 * 4919 * Will only set the direction to 'rtl', if the WordPress locale has 4920 * the text direction set to 'rtl'. 4921 * 4922 * Fills in the 'directionality' setting, enables the 'directionality' 4923 * plugin, and adds the 'ltr' button to 'toolbar1', formerly 4924 * 'theme_advanced_buttons1' array keys. These keys are then returned 4925 * in the $mce_init (TinyMCE settings) array. 4926 * 4927 * @since 2.1.0 4928 * @access private 4929 * 4930 * @param array $mce_init MCE settings array. 4931 * @return array Direction set for 'rtl', if needed by locale. 4932 */ 4933 function _mce_set_direction( $mce_init ) { 4934 if ( is_rtl() ) { 4935 $mce_init['directionality'] = 'rtl'; 4936 $mce_init['rtl_ui'] = true; 4937 4938 if ( ! empty( $mce_init['plugins'] ) && ! str_contains( $mce_init['plugins'], 'directionality' ) ) { 4939 $mce_init['plugins'] .= ',directionality'; 4940 } 4941 4942 if ( ! empty( $mce_init['toolbar1'] ) && ! preg_match( '/\bltr\b/', $mce_init['toolbar1'] ) ) { 4943 $mce_init['toolbar1'] .= ',ltr'; 4944 } 4945 } 4946 4947 return $mce_init; 4948 } 4949 4950 /** 4951 * Determines whether WordPress is currently serving a REST API request. 4952 * 4953 * The function relies on the 'REST_REQUEST' global. As such, it only returns true when an actual REST _request_ is 4954 * being made. It does not return true when a REST endpoint is hit as part of another request, e.g. for preloading a 4955 * REST response. See {@see wp_is_rest_endpoint()} for that purpose. 4956 * 4957 * This function should not be called until the {@see 'parse_request'} action, as the constant is only defined then, 4958 * even for an actual REST request. 4959 * 4960 * @since 6.5.0 4961 * 4962 * @return bool True if it's a WordPress REST API request, false otherwise. 4963 */ 4964 function wp_is_serving_rest_request() { 4965 return defined( 'REST_REQUEST' ) && REST_REQUEST; 4966 } 4967 4968 /** 4969 * Converts smiley code to the icon graphic file equivalent. 4970 * 4971 * You can turn off smilies, by going to the write setting screen and unchecking 4972 * the box, or by setting 'use_smilies' option to false or removing the option. 4973 * 4974 * Plugins may override the default smiley list by setting the $wpsmiliestrans 4975 * to an array, with the key the code the blogger types in and the value the 4976 * image file. 4977 * 4978 * The $wp_smiliessearch global is for the regular expression and is set each 4979 * time the function is called. 4980 * 4981 * The full list of smilies can be found in the function and won't be listed in 4982 * the description. Probably should create a Codex page for it, so that it is 4983 * available. 4984 * 4985 * @since 2.2.0 4986 * 4987 * @global array $wpsmiliestrans 4988 * @global array $wp_smiliessearch 4989 */ 4990 function smilies_init() { 4991 global $wpsmiliestrans, $wp_smiliessearch; 4992 4993 // Don't bother setting up smilies if they are disabled. 4994 if ( ! get_option( 'use_smilies' ) ) { 4995 return; 4996 } 4997 4998 if ( ! isset( $wpsmiliestrans ) ) { 4999 $wpsmiliestrans = array( 5000 ':mrgreen:' => 'mrgreen.png', 5001 ':neutral:' => "\xf0\x9f\x98\x90", 5002 ':twisted:' => "\xf0\x9f\x98\x88", 5003 ':arrow:' => "\xe2\x9e\xa1", 5004 ':shock:' => "\xf0\x9f\x98\xaf", 5005 ':smile:' => "\xf0\x9f\x99\x82", 5006 ':???:' => "\xf0\x9f\x98\x95", 5007 ':cool:' => "\xf0\x9f\x98\x8e", 5008 ':evil:' => "\xf0\x9f\x91\xbf", 5009 ':grin:' => "\xf0\x9f\x98\x80", 5010 ':idea:' => "\xf0\x9f\x92\xa1", 5011 ':oops:' => "\xf0\x9f\x98\xb3", 5012 ':razz:' => "\xf0\x9f\x98\x9b", 5013 ':roll:' => "\xf0\x9f\x99\x84", 5014 ':wink:' => "\xf0\x9f\x98\x89", 5015 ':cry:' => "\xf0\x9f\x98\xa5", 5016 ':eek:' => "\xf0\x9f\x98\xae", 5017 ':lol:' => "\xf0\x9f\x98\x86", 5018 ':mad:' => "\xf0\x9f\x98\xa1", 5019 ':sad:' => "\xf0\x9f\x99\x81", 5020 '8-)' => "\xf0\x9f\x98\x8e", 5021 '8-O' => "\xf0\x9f\x98\xaf", 5022 ':-(' => "\xf0\x9f\x99\x81", 5023 ':-)' => "\xf0\x9f\x99\x82", 5024 ':-?' => "\xf0\x9f\x98\x95", 5025 ':-D' => "\xf0\x9f\x98\x80", 5026 ':-P' => "\xf0\x9f\x98\x9b", 5027 ':-o' => "\xf0\x9f\x98\xae", 5028 ':-x' => "\xf0\x9f\x98\xa1", 5029 ':-|' => "\xf0\x9f\x98\x90", 5030 ';-)' => "\xf0\x9f\x98\x89", 5031 // This one transformation breaks regular text with frequency. 5032 // '8)' => "\xf0\x9f\x98\x8e", 5033 '8O' => "\xf0\x9f\x98\xaf", 5034 ':(' => "\xf0\x9f\x99\x81", 5035 ':)' => "\xf0\x9f\x99\x82", 5036 ':?' => "\xf0\x9f\x98\x95", 5037 ':D' => "\xf0\x9f\x98\x80", 5038 ':P' => "\xf0\x9f\x98\x9b", 5039 ':o' => "\xf0\x9f\x98\xae", 5040 ':x' => "\xf0\x9f\x98\xa1", 5041 ':|' => "\xf0\x9f\x98\x90", 5042 ';)' => "\xf0\x9f\x98\x89", 5043 ':!:' => "\xe2\x9d\x97", 5044 ':?:' => "\xe2\x9d\x93", 5045 ); 5046 } 5047 5048 /** 5049 * Filters all the smilies. 5050 * 5051 * This filter must be added before `smilies_init` is run, as 5052 * it is normally only run once to setup the smilies regex. 5053 * 5054 * @since 4.7.0 5055 * 5056 * @param string[] $wpsmiliestrans List of the smilies' hexadecimal representations, keyed by their smily code. 5057 */ 5058 $wpsmiliestrans = apply_filters( 'smilies', $wpsmiliestrans ); 5059 5060 if ( count( $wpsmiliestrans ) === 0 ) { 5061 return; 5062 } 5063 5064 /* 5065 * NOTE: we sort the smilies in reverse key order. This is to make sure 5066 * we match the longest possible smilie (:???: vs :?) as the regular 5067 * expression used below is first-match 5068 */ 5069 krsort( $wpsmiliestrans ); 5070 5071 $spaces = wp_spaces_regexp(); 5072 5073 // Begin first "subpattern". 5074 $wp_smiliessearch = '/(?<=' . $spaces . '|^)'; 5075 5076 $subchar = ''; 5077 foreach ( (array) $wpsmiliestrans as $smiley => $img ) { 5078 $firstchar = substr( $smiley, 0, 1 ); 5079 $rest = substr( $smiley, 1 ); 5080 5081 // New subpattern? 5082 if ( $firstchar !== $subchar ) { 5083 if ( '' !== $subchar ) { 5084 $wp_smiliessearch .= ')(?=' . $spaces . '|$)'; // End previous "subpattern". 5085 $wp_smiliessearch .= '|(?<=' . $spaces . '|^)'; // Begin another "subpattern". 5086 } 5087 5088 $subchar = $firstchar; 5089 $wp_smiliessearch .= preg_quote( $firstchar, '/' ) . '(?:'; 5090 } else { 5091 $wp_smiliessearch .= '|'; 5092 } 5093 5094 $wp_smiliessearch .= preg_quote( $rest, '/' ); 5095 } 5096 5097 $wp_smiliessearch .= ')(?=' . $spaces . '|$)/m'; 5098 } 5099 5100 /** 5101 * Merges user defined arguments into defaults array. 5102 * 5103 * This function is used throughout WordPress to allow for both string or array 5104 * to be merged into another array. 5105 * 5106 * The keys of the returned array are documented as strings, since that is what 5107 * callers mean by them, but they are not promised as such to static analysis. 5108 * Integer keys remain reachable through arguments that are perfectly valid: 5109 * `json_decode( '{"0":"a"}' )` is an object whose properties `get_object_vars()` 5110 * reports under an integer key, and `parse_str()` reads `0=a` as one as well. 5111 * 5112 * @since 2.2.0 5113 * @since 2.3.0 `$args` can now also be an object. 5114 * 5115 * @param string|array<string, mixed>|object $args Value to merge with $defaults. 5116 * @param array<string, mixed> $defaults Optional. Array that serves as the defaults. 5117 * Default empty array. 5118 * @return array<string, mixed> Merged user defined values with defaults. 5119 * @phpstan-return array<array-key, mixed> 5120 */ 5121 function wp_parse_args( $args, $defaults = array() ): array { 5122 if ( is_object( $args ) ) { 5123 $parsed_args = get_object_vars( $args ); 5124 } elseif ( is_array( $args ) ) { 5125 $parsed_args =& $args; 5126 } else { 5127 wp_parse_str( $args, $parsed_args ); 5128 } 5129 5130 if ( is_array( $defaults ) && $defaults ) { 5131 return array_merge( $defaults, $parsed_args ); 5132 } 5133 return $parsed_args; 5134 } 5135 5136 /** 5137 * Converts a comma- or space-separated list of scalar values to an array. 5138 * 5139 * @since 5.1.0 5140 * @since 7.2.0 Added explicit support for passing an integer. 5141 * 5142 * @param mixed[]|string|int $input_list List of values. 5143 * @return array Array of scalar values. A string is split into a list, while an array 5144 * keeps its keys, so the result is not necessarily a list. 5145 * @phpstan-return ( 5146 * $input_list is string|int ? list<string> : ( 5147 * $input_list is array<string> ? array<string> : array<scalar> 5148 * ) 5149 * ) 5150 */ 5151 function wp_parse_list( $input_list ): array { 5152 if ( is_int( $input_list ) ) { 5153 $input_list = array( (string) $input_list ); 5154 } elseif ( ! is_array( $input_list ) ) { 5155 $parsed_list = preg_split( '/[\s,]+/', $input_list, -1, PREG_SPLIT_NO_EMPTY ); 5156 return is_array( $parsed_list ) ? $parsed_list : array(); 5157 } 5158 5159 // Validate all entries of the list are scalar. 5160 $input_list = array_filter( $input_list, 'is_scalar' ); 5161 5162 return $input_list; 5163 } 5164 5165 /** 5166 * Cleans up an array, comma- or space-separated list of IDs. 5167 * 5168 * @since 3.0.0 5169 * @since 5.1.0 Refactored to use {@see wp_parse_list()}. 5170 * @since 7.2.0 Added explicit support for passing an integer. 5171 * 5172 * @param mixed[]|string|int $input_list List of IDs. 5173 * @return int[] Sanitized array of IDs. May include zero. Keys are preserved 5174 * from the input and `array_unique()` may leave gaps, so the 5175 * result is not necessarily a list. 5176 * @phpstan-return array<non-negative-int> 5177 */ 5178 function wp_parse_id_list( $input_list ): array { 5179 $input_list = wp_parse_list( $input_list ); 5180 5181 return array_unique( array_map( 'absint', $input_list ) ); 5182 } 5183 5184 /** 5185 * Cleans up an array, comma- or space-separated list of slugs. 5186 * 5187 * @since 4.7.0 5188 * @since 5.1.0 Refactored to use {@see wp_parse_list()}. 5189 * @since 7.2.0 Added explicit support for passing an integer. 5190 * 5191 * @param mixed[]|string|int $input_list List of slugs. 5192 * @return string[] Sanitized array of slugs. May include an empty string. Keys 5193 * are preserved from the input and `array_unique()` may leave 5194 * gaps, so the result is not necessarily a list. 5195 */ 5196 function wp_parse_slug_list( $input_list ): array { 5197 $input_list = wp_parse_list( $input_list ); 5198 5199 return array_unique( 5200 array_map( 5201 'sanitize_title', 5202 array_map( 5203 /* 5204 * Cast booleans, integers, and floats to strings. Non-scalar types 5205 * (including null) have already been filtered out by wp_parse_list(). 5206 */ 5207 'strval', 5208 $input_list 5209 ) 5210 ) 5211 ); 5212 } 5213 5214 /** 5215 * Extracts a slice of an array, given a list of keys. 5216 * 5217 * @since 3.1.0 5218 * 5219 * @param array<string, mixed> $input_array The original array. 5220 * @param string[] $keys The list of keys. 5221 * @return array<string, mixed> The array slice. 5222 * 5223 * @phpstan-template TKey of string 5224 * @phpstan-template TValue 5225 * @phpstan-param array<string, TValue> $input_array 5226 * @phpstan-param array<TKey> $keys 5227 * @phpstan-return array<TKey, TValue> 5228 */ 5229 function wp_array_slice_assoc( $input_array, $keys ): array { 5230 $slice = array(); 5231 5232 foreach ( $keys as $key ) { 5233 if ( isset( $input_array[ $key ] ) ) { 5234 $slice[ $key ] = $input_array[ $key ]; 5235 } 5236 } 5237 5238 return $slice; 5239 } 5240 5241 /** 5242 * Sorts the keys of an array alphabetically. 5243 * 5244 * The array is passed by reference so it doesn't get returned 5245 * which mimics the behavior of `ksort()`. 5246 * 5247 * @since 6.0.0 5248 * 5249 * @param array $input_array The array to sort, passed by reference. 5250 */ 5251 function wp_recursive_ksort( &$input_array ) { 5252 foreach ( $input_array as &$value ) { 5253 if ( is_array( $value ) ) { 5254 wp_recursive_ksort( $value ); 5255 } 5256 } 5257 5258 ksort( $input_array ); 5259 } 5260 5261 /** 5262 * Accesses an array in depth based on a path of keys. 5263 * 5264 * It is the PHP equivalent of JavaScript's `lodash.get()` and mirroring it may help other components 5265 * retain some symmetry between client and server implementations. 5266 * 5267 * Example usage: 5268 * 5269 * $input_array = array( 5270 * 'a' => array( 5271 * 'b' => array( 5272 * 'c' => 1, 5273 * ), 5274 * ), 5275 * ); 5276 * _wp_array_get( $input_array, array( 'a', 'b', 'c' ) ); 5277 * 5278 * @internal 5279 * 5280 * @since 5.6.0 5281 * @access private 5282 * 5283 * @param array $input_array An array from which we want to retrieve some information. 5284 * @param array $path An array of keys describing the path with which to retrieve information. 5285 * @param mixed $default_value Optional. The return value if the path does not exist within the array, 5286 * or if `$input_array` or `$path` are not arrays. Default null. 5287 * @return mixed The value from the path specified. 5288 */ 5289 function _wp_array_get( $input_array, $path, $default_value = null ) { 5290 // Confirm $path is valid. 5291 if ( ! is_array( $path ) || 0 === count( $path ) ) { 5292 return $default_value; 5293 } 5294 5295 foreach ( $path as $path_element ) { 5296 if ( ! is_array( $input_array ) ) { 5297 return $default_value; 5298 } 5299 5300 if ( is_string( $path_element ) 5301 || is_int( $path_element ) 5302 || null === $path_element 5303 ) { 5304 /* 5305 * Check if the path element exists in the input array. 5306 * We check with `isset()` first, as it is a lot faster 5307 * than `array_key_exists()`. 5308 */ 5309 if ( isset( $path_element, $input_array[ $path_element ] ) ) { 5310 $input_array = $input_array[ $path_element ]; 5311 continue; 5312 } 5313 5314 /* 5315 * If `isset()` returns false, we check with `array_key_exists()`, 5316 * which also checks for `null` values. 5317 */ 5318 if ( isset( $path_element ) && array_key_exists( $path_element, $input_array ) ) { 5319 $input_array = $input_array[ $path_element ]; 5320 continue; 5321 } 5322 } 5323 5324 return $default_value; 5325 } 5326 5327 return $input_array; 5328 } 5329 5330 /** 5331 * Sets an array in depth based on a path of keys. 5332 * 5333 * It is the PHP equivalent of JavaScript's `lodash.set()` and mirroring it may help other components 5334 * retain some symmetry between client and server implementations. 5335 * 5336 * Example usage: 5337 * 5338 * $input_array = array(); 5339 * _wp_array_set( $input_array, array( 'a', 'b', 'c', 1 ) ); 5340 * 5341 * $input_array becomes: 5342 * array( 5343 * 'a' => array( 5344 * 'b' => array( 5345 * 'c' => 1, 5346 * ), 5347 * ), 5348 * ); 5349 * 5350 * @internal 5351 * 5352 * @since 5.8.0 5353 * @access private 5354 * 5355 * @param array $input_array An array that we want to mutate to include a specific value in a path. 5356 * @param array $path An array of keys describing the path that we want to mutate. 5357 * @param mixed $value The value that will be set. 5358 */ 5359 function _wp_array_set( &$input_array, $path, $value = null ) { 5360 // Confirm $input_array is valid. 5361 if ( ! is_array( $input_array ) ) { 5362 return; 5363 } 5364 5365 // Confirm $path is valid. 5366 if ( ! is_array( $path ) ) { 5367 return; 5368 } 5369 5370 $path_length = count( $path ); 5371 5372 if ( 0 === $path_length ) { 5373 return; 5374 } 5375 5376 foreach ( $path as $path_element ) { 5377 if ( 5378 ! is_string( $path_element ) && ! is_int( $path_element ) && 5379 ! is_null( $path_element ) 5380 ) { 5381 return; 5382 } 5383 } 5384 5385 for ( $i = 0; $i < $path_length - 1; ++$i ) { 5386 $path_element = $path[ $i ]; 5387 if ( 5388 ! array_key_exists( $path_element, $input_array ) || 5389 ! is_array( $input_array[ $path_element ] ) 5390 ) { 5391 $input_array[ $path_element ] = array(); 5392 } 5393 $input_array = &$input_array[ $path_element ]; 5394 } 5395 5396 $input_array[ $path[ $i ] ] = $value; 5397 } 5398 5399 /** 5400 * This function is trying to replicate what 5401 * lodash's kebabCase (JS library) does in the client. 5402 * 5403 * The reason we need this function is that we do some processing 5404 * in both the client and the server (e.g.: we generate 5405 * preset classes from preset slugs) that needs to 5406 * create the same output. 5407 * 5408 * We can't remove or update the client's library due to backward compatibility 5409 * (some of the output of lodash's kebabCase is saved in the post content). 5410 * We have to make the server behave like the client. 5411 * 5412 * Changes to this function should follow updates in the client 5413 * with the same logic. 5414 * 5415 * @since 5.8.0 5416 * 5417 * @link https://github.com/lodash/lodash/blob/4.17/dist/lodash.js#L14369 5418 * @link https://github.com/lodash/lodash/blob/4.17/dist/lodash.js#L278 5419 * @link https://github.com/lodash-php/lodash-php/blob/master/src/String/kebabCase.php 5420 * @link https://github.com/lodash-php/lodash-php/blob/master/src/internal/unicodeWords.php 5421 * 5422 * @param string $input_string The string to kebab-case. 5423 * @return string kebab-cased-string. 5424 */ 5425 function _wp_to_kebab_case( $input_string ) { 5426 // Ignore the camelCase names for variables so the names are the same as lodash so comparing and porting new changes is easier. 5427 // phpcs:disable WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase 5428 5429 /* 5430 * Some notable things we've removed compared to the lodash version are: 5431 * 5432 * - non-alphanumeric characters: rsAstralRange, rsEmoji, etc 5433 * - the groups that processed the apostrophe, as it's removed before passing the string to preg_match: rsApos, rsOptContrLower, and rsOptContrUpper 5434 * 5435 */ 5436 5437 /** Used to compose unicode character classes. */ 5438 $rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff'; 5439 $rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf'; 5440 $rsPunctuationRange = '\\x{2000}-\\x{206f}'; 5441 $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}'; 5442 $rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde'; 5443 $rsBreakRange = $rsNonCharRange . $rsPunctuationRange . $rsSpaceRange; 5444 5445 /** Used to compose unicode capture groups. */ 5446 $rsBreak = '[' . $rsBreakRange . ']'; 5447 $rsDigits = '\\d+'; // The last lodash version in GitHub uses a single digit here and expands it when in use. 5448 $rsLower = '[' . $rsLowerRange . ']'; 5449 $rsMisc = '[^' . $rsBreakRange . $rsDigits . $rsLowerRange . $rsUpperRange . ']'; 5450 $rsUpper = '[' . $rsUpperRange . ']'; 5451 5452 /** Used to compose unicode regexes. */ 5453 $rsMiscLower = '(?:' . $rsLower . '|' . $rsMisc . ')'; 5454 $rsMiscUpper = '(?:' . $rsUpper . '|' . $rsMisc . ')'; 5455 $rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])'; 5456 $rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])'; 5457 5458 $regexp = '/' . implode( 5459 '|', 5460 array( 5461 $rsUpper . '?' . $rsLower . '+' . '(?=' . implode( '|', array( $rsBreak, $rsUpper, '$' ) ) . ')', 5462 $rsMiscUpper . '+' . '(?=' . implode( '|', array( $rsBreak, $rsUpper . $rsMiscLower, '$' ) ) . ')', 5463 $rsUpper . '?' . $rsMiscLower . '+', 5464 $rsUpper . '+', 5465 $rsOrdUpper, 5466 $rsOrdLower, 5467 $rsDigits, 5468 ) 5469 ) . '/u'; 5470 5471 preg_match_all( $regexp, str_replace( "'", '', $input_string ), $matches ); 5472 return strtolower( implode( '-', $matches[0] ) ); 5473 // phpcs:enable WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase 5474 } 5475 5476 /** 5477 * Determines if the variable is a numeric-indexed array. 5478 * 5479 * Note! This answers a different question than {@see array_is_list()} and is 5480 * more flexible to handle situations where some numeric array indices 5481 * have been removed. A numeric-indexed array is only a “list” when the 5482 * array keys form a contiguous range from zero to the highest key. 5483 * 5484 * Example: 5485 * 5486 * true === wp_is_numeric_array( array( 1, 2, 3, 4 ) ); 5487 * false === wp_is_numeric_array( array( 'name' => 'WordPress' ) ); 5488 * 5489 * // All-numeric keys vs. list. 5490 * $above_two = array_filter( array( 1, 2, 8, 9 ), fn ( $v ) => $v > 2 ); 5491 * $above_two === array( '2' => 8, '3' => 9 ); 5492 * true === wp_is_numeric_array( $above_two ); 5493 * false === array_is_list( $above_two ); 5494 * 5495 * @since 4.4.0 5496 * 5497 * @param mixed $data Variable to check. 5498 * @return bool Whether the variable is a list. 5499 * 5500 * @phpstan-assert-if-true array<int, mixed> $data 5501 * 5502 * @phpstan-return ( $data is array<int, mixed> ? true : false ) 5503 */ 5504 function wp_is_numeric_array( $data ): bool { 5505 if ( ! is_array( $data ) ) { 5506 return false; 5507 } 5508 5509 return array_all( $data, fn( $value, $key ) => ! is_string( $key ) ); 5510 } 5511 5512 /** 5513 * Filters a list of objects, based on a set of key => value arguments. 5514 * 5515 * Retrieves the objects from the list that match the given arguments. 5516 * Key represents property name, and value represents property value. 5517 * 5518 * If an object has more properties than those specified in arguments, 5519 * that will not disqualify it. When using the 'and' operator, 5520 * any missing properties will disqualify it. 5521 * 5522 * When using the `$field` argument, this function can also retrieve 5523 * a particular field from all matching objects, whereas wp_list_filter() 5524 * only does the filtering. 5525 * 5526 * @since 3.0.0 5527 * @since 4.7.0 Uses `WP_List_Util` class. 5528 * 5529 * @param array $input_list An array of objects to filter. 5530 * @param array $args Optional. An array of key => value arguments to match 5531 * against each object. Default empty array. 5532 * @param string $operator Optional. The logical operation to perform. 'and' means 5533 * all elements from the array must match. 'or' means only 5534 * one element needs to match. 'not' means no elements may 5535 * match. The value is case-insensitive. Default 'and'. 5536 * @param bool|string $field Optional. A field from the object to place instead 5537 * of the entire object. Default false. 5538 * @return array A list of objects or object fields. 5539 * 5540 * @phpstan-param 'and'|'AND'|'or'|'OR'|'not'|'NOT' $operator 5541 */ 5542 function wp_filter_object_list( $input_list, $args = array(), $operator = 'and', $field = false ) { 5543 if ( ! is_array( $input_list ) ) { 5544 return array(); 5545 } 5546 5547 $util = new WP_List_Util( $input_list ); 5548 5549 $util->filter( $args, $operator ); 5550 5551 if ( $field ) { 5552 $util->pluck( $field ); 5553 } 5554 5555 return $util->get_output(); 5556 } 5557 5558 /** 5559 * Filters a list of objects, based on a set of key => value arguments. 5560 * 5561 * Retrieves the objects from the list that match the given arguments. 5562 * Key represents property name, and value represents property value. 5563 * 5564 * If an object has more properties than those specified in arguments, 5565 * that will not disqualify it. When using the 'and' operator, 5566 * any missing properties will disqualify it. 5567 * 5568 * If you want to retrieve a particular field from all matching objects, 5569 * use wp_filter_object_list() instead. 5570 * 5571 * @since 3.1.0 5572 * @since 4.7.0 Uses `WP_List_Util` class. 5573 * @since 5.9.0 Converted into a wrapper for `wp_filter_object_list()`. 5574 * 5575 * @param array $input_list An array of objects to filter. 5576 * @param array $args Optional. An array of key => value arguments to match 5577 * against each object. Default empty array. 5578 * @param string $operator Optional. The logical operation to perform. 'and' means 5579 * all elements from the array must match. 'or' means only 5580 * one element needs to match. 'not' means no elements may 5581 * match. The value is case-insensitive. Default 'and'. 5582 * @return array Array of found values. 5583 * 5584 * @phpstan-param 'and'|'AND'|'or'|'OR'|'not'|'NOT' $operator 5585 */ 5586 function wp_list_filter( $input_list, $args = array(), $operator = 'and' ) { 5587 return wp_filter_object_list( $input_list, $args, $operator ); 5588 } 5589 5590 /** 5591 * Plucks a certain field out of each object or array in an array. 5592 * 5593 * This has the same functionality and prototype of 5594 * array_column() (PHP 5.5) but also supports objects. 5595 * 5596 * @since 3.1.0 5597 * @since 4.0.0 $index_key parameter added. 5598 * @since 4.7.0 Uses `WP_List_Util` class. 5599 * 5600 * @param array $input_list List of objects or arrays. 5601 * @param int|string $field Field from the object to place instead of the entire object. 5602 * @param int|string $index_key Optional. Field from the object to use as keys for the new array. 5603 * Default null. 5604 * @return array Array of found values. If `$index_key` is set, an array of found values with keys 5605 * corresponding to `$index_key`. If `$index_key` is null, array keys from the original 5606 * `$input_list` will be preserved in the results. 5607 */ 5608 function wp_list_pluck( $input_list, $field, $index_key = null ) { 5609 if ( ! is_array( $input_list ) ) { 5610 return array(); 5611 } 5612 5613 $util = new WP_List_Util( $input_list ); 5614 5615 return $util->pluck( $field, $index_key ); 5616 } 5617 5618 /** 5619 * Sorts an array of objects or arrays based on one or more orderby arguments. 5620 * 5621 * @since 4.7.0 5622 * 5623 * @param array $input_list An array of objects or arrays to sort. 5624 * @param string|array $orderby Optional. Either the field name to order by or an array 5625 * of multiple orderby fields as `$orderby => $order`. 5626 * Default empty array. 5627 * @param string $order Optional. Either 'ASC' or 'DESC'. Only used if `$orderby` 5628 * is a string. Default 'ASC'. 5629 * @param bool $preserve_keys Optional. Whether to preserve keys. Default false. 5630 * @return array The sorted array. 5631 */ 5632 function wp_list_sort( $input_list, $orderby = array(), $order = 'ASC', $preserve_keys = false ) { 5633 if ( ! is_array( $input_list ) ) { 5634 return array(); 5635 } 5636 5637 $util = new WP_List_Util( $input_list ); 5638 5639 return $util->sort( $orderby, $order, $preserve_keys ); 5640 } 5641 5642 /** 5643 * Determines if Widgets library should be loaded. 5644 * 5645 * Checks to make sure that the widgets library hasn't already been loaded. 5646 * If it hasn't, then it will load the widgets library and run an action hook. 5647 * 5648 * @since 2.2.0 5649 */ 5650 function wp_maybe_load_widgets() { 5651 /** 5652 * Filters whether to load the Widgets library. 5653 * 5654 * Returning a falsey value from the filter will effectively short-circuit 5655 * the Widgets library from loading. 5656 * 5657 * @since 2.8.0 5658 * 5659 * @param bool $wp_maybe_load_widgets Whether to load the Widgets library. 5660 * Default true. 5661 */ 5662 if ( ! apply_filters( 'load_default_widgets', true ) ) { 5663 return; 5664 } 5665 5666 require_once ABSPATH . WPINC . '/default-widgets.php'; 5667 5668 add_action( '_admin_menu', 'wp_widgets_add_menu' ); 5669 } 5670 5671 /** 5672 * Appends the Widgets menu to the themes main menu. 5673 * 5674 * @since 2.2.0 5675 * @since 5.9.3 Don't specify menu order when the active theme is a block theme. 5676 * 5677 * @global array $submenu 5678 */ 5679 function wp_widgets_add_menu() { 5680 global $submenu; 5681 5682 if ( ! current_theme_supports( 'widgets' ) ) { 5683 return; 5684 } 5685 5686 $menu_name = __( 'Widgets' ); 5687 if ( wp_is_block_theme() ) { 5688 $submenu['themes.php'][] = array( $menu_name, 'edit_theme_options', 'widgets.php' ); 5689 } else { 5690 $submenu['themes.php'][9] = array( $menu_name, 'edit_theme_options', 'widgets.php' ); 5691 } 5692 5693 ksort( $submenu['themes.php'], SORT_NUMERIC ); 5694 } 5695 5696 /** 5697 * Flushes all output buffers for PHP 5.2. 5698 * 5699 * Make sure all output buffers are flushed before our singletons are destroyed. 5700 * 5701 * @since 2.2.0 5702 */ 5703 function wp_ob_end_flush_all() { 5704 $levels = ob_get_level(); 5705 for ( $i = 0; $i < $levels; $i++ ) { 5706 ob_end_flush(); 5707 } 5708 } 5709 5710 /** 5711 * Loads custom DB error or display WordPress DB error. 5712 * 5713 * If a file exists in the wp-content directory named db-error.php, then it will 5714 * be loaded instead of displaying the WordPress DB error. If it is not found, 5715 * then the WordPress DB error will be displayed instead. 5716 * 5717 * The WordPress DB error sets the HTTP status header to 500 to try to prevent 5718 * search engines from caching the message. Custom DB messages should do the 5719 * same. 5720 * 5721 * This function was backported to WordPress 2.3.2, but originally was added 5722 * in WordPress 2.5.0. 5723 * 5724 * @since 2.3.2 5725 * @since 7.2.0 Added status and no-cache headers before loading a custom `db-error.php` drop-in. 5726 * 5727 * @global wpdb $wpdb WordPress database abstraction object. 5728 * 5729 * @return never 5730 */ 5731 function dead_db() { 5732 global $wpdb; 5733 5734 wp_load_translations_early(); 5735 5736 // Load custom DB error template, if present. 5737 if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) { 5738 status_header( 500 ); 5739 nocache_headers(); 5740 require_once WP_CONTENT_DIR . '/db-error.php'; 5741 die(); 5742 } 5743 5744 // If installing or in the admin, provide the verbose message. 5745 if ( wp_installing() || defined( 'WP_ADMIN' ) ) { 5746 wp_die( $wpdb->error ); 5747 } 5748 5749 // Otherwise, be terse. 5750 wp_die( '<h1>' . __( 'Error establishing a database connection' ) . '</h1>', __( 'Database Error' ) ); 5751 } 5752 5753 /** 5754 * Marks a function as deprecated and inform when it has been used. 5755 * 5756 * There is a {@see 'deprecated_function_run'} hook that will be called that can be used 5757 * to get the backtrace up to what file and function called the deprecated function. 5758 * 5759 * The current behavior is to trigger a user error if `WP_DEBUG` is true. 5760 * 5761 * This function is to be used in every function that is deprecated. 5762 * 5763 * @since 2.5.0 5764 * @since 5.4.0 This function is no longer marked as "private". 5765 * @since 5.4.0 The error type is now classified as E_USER_DEPRECATED (used to default to E_USER_NOTICE). 5766 * 5767 * @param string $function_name The function that was called. 5768 * @param string $version The version of WordPress that deprecated the function. 5769 * @param string $replacement Optional. The function that should have been called. Default empty string. 5770 */ 5771 function _deprecated_function( $function_name, $version, $replacement = '' ) { 5772 5773 /** 5774 * Fires when a deprecated function is called. 5775 * 5776 * @since 2.5.0 5777 * 5778 * @param string $function_name The function that was called. 5779 * @param string $replacement The function that should have been called. 5780 * @param string $version The version of WordPress that deprecated the function. 5781 */ 5782 do_action( 'deprecated_function_run', $function_name, $replacement, $version ); 5783 5784 /** 5785 * Filters whether to trigger an error for deprecated functions. 5786 * 5787 * @since 2.5.0 5788 * 5789 * @param bool $trigger Whether to trigger the error for deprecated functions. Default true. 5790 */ 5791 if ( WP_DEBUG && apply_filters( 'deprecated_function_trigger_error', true ) ) { 5792 if ( function_exists( '__' ) ) { 5793 if ( $replacement ) { 5794 $message = sprintf( 5795 /* translators: 1: PHP function name, 2: Version number, 3: Alternative function name. */ 5796 __( 'Function %1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.' ), 5797 $function_name, 5798 $version, 5799 $replacement 5800 ); 5801 } else { 5802 $message = sprintf( 5803 /* translators: 1: PHP function name, 2: Version number. */ 5804 __( 'Function %1$s is <strong>deprecated</strong> since version %2$s with no alternative available.' ), 5805 $function_name, 5806 $version 5807 ); 5808 } 5809 } else { 5810 if ( $replacement ) { 5811 $message = sprintf( 5812 'Function %1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.', 5813 $function_name, 5814 $version, 5815 $replacement 5816 ); 5817 } else { 5818 $message = sprintf( 5819 'Function %1$s is <strong>deprecated</strong> since version %2$s with no alternative available.', 5820 $function_name, 5821 $version 5822 ); 5823 } 5824 } 5825 5826 wp_trigger_error( '', $message, E_USER_DEPRECATED ); 5827 } 5828 } 5829 5830 /** 5831 * Marks a constructor as deprecated and informs when it has been used. 5832 * 5833 * Similar to _deprecated_function(), but with different strings. Used to 5834 * remove PHP4-style constructors. 5835 * 5836 * The current behavior is to trigger a user error if `WP_DEBUG` is true. 5837 * 5838 * This function is to be used in every PHP4-style constructor method that is deprecated. 5839 * 5840 * @since 4.3.0 5841 * @since 4.5.0 Added the `$parent_class` parameter. 5842 * @since 5.4.0 This function is no longer marked as "private". 5843 * @since 5.4.0 The error type is now classified as E_USER_DEPRECATED (used to default to E_USER_NOTICE). 5844 * 5845 * @param string $class_name The class containing the deprecated constructor. 5846 * @param string $version The version of WordPress that deprecated the function. 5847 * @param string $parent_class Optional. The parent class calling the deprecated constructor. 5848 * Default empty string. 5849 */ 5850 function _deprecated_constructor( $class_name, $version, $parent_class = '' ) { 5851 5852 /** 5853 * Fires when a deprecated constructor is called. 5854 * 5855 * @since 4.3.0 5856 * @since 4.5.0 Added the `$parent_class` parameter. 5857 * 5858 * @param string $class_name The class containing the deprecated constructor. 5859 * @param string $version The version of WordPress that deprecated the function. 5860 * @param string $parent_class The parent class calling the deprecated constructor. 5861 */ 5862 do_action( 'deprecated_constructor_run', $class_name, $version, $parent_class ); 5863 5864 /** 5865 * Filters whether to trigger an error for deprecated functions. 5866 * 5867 * `WP_DEBUG` must be true in addition to the filter evaluating to true. 5868 * 5869 * @since 4.3.0 5870 * 5871 * @param bool $trigger Whether to trigger the error for deprecated functions. Default true. 5872 */ 5873 if ( WP_DEBUG && apply_filters( 'deprecated_constructor_trigger_error', true ) ) { 5874 if ( function_exists( '__' ) ) { 5875 if ( $parent_class ) { 5876 $message = sprintf( 5877 /* translators: 1: PHP class name, 2: PHP parent class name, 3: Version number, 4: __construct() method. */ 5878 __( 'The called constructor method for %1$s class in %2$s is <strong>deprecated</strong> since version %3$s! Use %4$s instead.' ), 5879 $class_name, 5880 $parent_class, 5881 $version, 5882 '<code>__construct()</code>' 5883 ); 5884 } else { 5885 $message = sprintf( 5886 /* translators: 1: PHP class name, 2: Version number, 3: __construct() method. */ 5887 __( 'The called constructor method for %1$s class is <strong>deprecated</strong> since version %2$s! Use %3$s instead.' ), 5888 $class_name, 5889 $version, 5890 '<code>__construct()</code>' 5891 ); 5892 } 5893 } else { 5894 if ( $parent_class ) { 5895 $message = sprintf( 5896 'The called constructor method for %1$s class in %2$s is <strong>deprecated</strong> since version %3$s! Use %4$s instead.', 5897 $class_name, 5898 $parent_class, 5899 $version, 5900 '<code>__construct()</code>' 5901 ); 5902 } else { 5903 $message = sprintf( 5904 'The called constructor method for %1$s class is <strong>deprecated</strong> since version %2$s! Use %3$s instead.', 5905 $class_name, 5906 $version, 5907 '<code>__construct()</code>' 5908 ); 5909 } 5910 } 5911 5912 wp_trigger_error( '', $message, E_USER_DEPRECATED ); 5913 } 5914 } 5915 5916 /** 5917 * Marks a class as deprecated and informs when it has been used. 5918 * 5919 * There is a {@see 'deprecated_class_run'} hook that will be called that can be used 5920 * to get the backtrace up to what file and function called the deprecated class. 5921 * 5922 * The current behavior is to trigger a user error if `WP_DEBUG` is true. 5923 * 5924 * This function is to be used in the class constructor for every deprecated class. 5925 * See {@see _deprecated_constructor()} for deprecating PHP4-style constructors. 5926 * 5927 * @since 6.4.0 5928 * 5929 * @param string $class_name The name of the class being instantiated. 5930 * @param string $version The version of WordPress that deprecated the class. 5931 * @param string $replacement Optional. The class or function that should have been called. 5932 * Default empty string. 5933 */ 5934 function _deprecated_class( $class_name, $version, $replacement = '' ) { 5935 5936 /** 5937 * Fires when a deprecated class is called. 5938 * 5939 * @since 6.4.0 5940 * 5941 * @param string $class_name The name of the class being instantiated. 5942 * @param string $replacement The class or function that should have been called. 5943 * @param string $version The version of WordPress that deprecated the class. 5944 */ 5945 do_action( 'deprecated_class_run', $class_name, $replacement, $version ); 5946 5947 /** 5948 * Filters whether to trigger an error for a deprecated class. 5949 * 5950 * @since 6.4.0 5951 * 5952 * @param bool $trigger Whether to trigger an error for a deprecated class. Default true. 5953 */ 5954 if ( WP_DEBUG && apply_filters( 'deprecated_class_trigger_error', true ) ) { 5955 if ( function_exists( '__' ) ) { 5956 if ( $replacement ) { 5957 $message = sprintf( 5958 /* translators: 1: PHP class name, 2: Version number, 3: Alternative class or function name. */ 5959 __( 'Class %1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.' ), 5960 $class_name, 5961 $version, 5962 $replacement 5963 ); 5964 } else { 5965 $message = sprintf( 5966 /* translators: 1: PHP class name, 2: Version number. */ 5967 __( 'Class %1$s is <strong>deprecated</strong> since version %2$s with no alternative available.' ), 5968 $class_name, 5969 $version 5970 ); 5971 } 5972 } else { 5973 if ( $replacement ) { 5974 $message = sprintf( 5975 'Class %1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.', 5976 $class_name, 5977 $version, 5978 $replacement 5979 ); 5980 } else { 5981 $message = sprintf( 5982 'Class %1$s is <strong>deprecated</strong> since version %2$s with no alternative available.', 5983 $class_name, 5984 $version 5985 ); 5986 } 5987 } 5988 5989 wp_trigger_error( '', $message, E_USER_DEPRECATED ); 5990 } 5991 } 5992 5993 /** 5994 * Marks a file as deprecated and inform when it has been used. 5995 * 5996 * There is a {@see 'deprecated_file_included'} hook that will be called that can be used 5997 * to get the backtrace up to what file and function included the deprecated file. 5998 * 5999 * The current behavior is to trigger a user error if `WP_DEBUG` is true. 6000 * 6001 * This function is to be used in every file that is deprecated. 6002 * 6003 * @since 2.5.0 6004 * @since 5.4.0 This function is no longer marked as "private". 6005 * @since 5.4.0 The error type is now classified as E_USER_DEPRECATED (used to default to E_USER_NOTICE). 6006 * 6007 * @param string $file The file that was included. 6008 * @param string $version The version of WordPress that deprecated the file. 6009 * @param string $replacement Optional. The file that should have been included based on ABSPATH. 6010 * Default empty string. 6011 * @param string $message Optional. A message regarding the change. Default empty string. 6012 */ 6013 function _deprecated_file( $file, $version, $replacement = '', $message = '' ) { 6014 6015 /** 6016 * Fires when a deprecated file is called. 6017 * 6018 * @since 2.5.0 6019 * 6020 * @param string $file The file that was called. 6021 * @param string $replacement The file that should have been included based on ABSPATH. 6022 * @param string $version The version of WordPress that deprecated the file. 6023 * @param string $message A message regarding the change. 6024 */ 6025 do_action( 'deprecated_file_included', $file, $replacement, $version, $message ); 6026 6027 /** 6028 * Filters whether to trigger an error for deprecated files. 6029 * 6030 * @since 2.5.0 6031 * 6032 * @param bool $trigger Whether to trigger the error for deprecated files. Default true. 6033 */ 6034 if ( WP_DEBUG && apply_filters( 'deprecated_file_trigger_error', true ) ) { 6035 $message = empty( $message ) ? '' : ' ' . $message; 6036 6037 if ( function_exists( '__' ) ) { 6038 if ( $replacement ) { 6039 $message = sprintf( 6040 /* translators: 1: PHP file name, 2: Version number, 3: Alternative file name. */ 6041 __( 'File %1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.' ), 6042 $file, 6043 $version, 6044 $replacement 6045 ) . $message; 6046 } else { 6047 $message = sprintf( 6048 /* translators: 1: PHP file name, 2: Version number. */ 6049 __( 'File %1$s is <strong>deprecated</strong> since version %2$s with no alternative available.' ), 6050 $file, 6051 $version 6052 ) . $message; 6053 } 6054 } else { 6055 if ( $replacement ) { 6056 $message = sprintf( 6057 'File %1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.', 6058 $file, 6059 $version, 6060 $replacement 6061 ); 6062 } else { 6063 $message = sprintf( 6064 'File %1$s is <strong>deprecated</strong> since version %2$s with no alternative available.', 6065 $file, 6066 $version 6067 ) . $message; 6068 } 6069 } 6070 6071 wp_trigger_error( '', $message, E_USER_DEPRECATED ); 6072 } 6073 } 6074 6075 /** 6076 * Marks a function argument as deprecated and inform when it has been used. 6077 * 6078 * This function is to be used whenever a deprecated function argument is used. 6079 * Before this function is called, the argument must be checked for whether it was 6080 * used by comparing it to its default value or evaluating whether it is empty. 6081 * 6082 * For example: 6083 * 6084 * if ( ! empty( $deprecated ) ) { 6085 * _deprecated_argument( __FUNCTION__, '3.0.0' ); 6086 * } 6087 * 6088 * There is a {@see 'deprecated_argument_run'} hook that will be called that can be used 6089 * to get the backtrace up to what file and function used the deprecated argument. 6090 * 6091 * The current behavior is to trigger a user error if WP_DEBUG is true. 6092 * 6093 * @since 3.0.0 6094 * @since 5.4.0 This function is no longer marked as "private". 6095 * @since 5.4.0 The error type is now classified as E_USER_DEPRECATED (used to default to E_USER_NOTICE). 6096 * 6097 * @param string $function_name The function that was called. 6098 * @param string $version The version of WordPress that deprecated the argument used. 6099 * @param string $message Optional. A message regarding the change. Default empty string. 6100 */ 6101 function _deprecated_argument( $function_name, $version, $message = '' ) { 6102 6103 /** 6104 * Fires when a deprecated argument is called. 6105 * 6106 * @since 3.0.0 6107 * 6108 * @param string $function_name The function that was called. 6109 * @param string $message A message regarding the change. 6110 * @param string $version The version of WordPress that deprecated the argument used. 6111 */ 6112 do_action( 'deprecated_argument_run', $function_name, $message, $version ); 6113 6114 /** 6115 * Filters whether to trigger an error for deprecated arguments. 6116 * 6117 * @since 3.0.0 6118 * 6119 * @param bool $trigger Whether to trigger the error for deprecated arguments. Default true. 6120 */ 6121 if ( WP_DEBUG && apply_filters( 'deprecated_argument_trigger_error', true ) ) { 6122 if ( function_exists( '__' ) ) { 6123 if ( $message ) { 6124 $message = sprintf( 6125 /* translators: 1: PHP function name, 2: Version number, 3: Optional message regarding the change. */ 6126 __( 'Function %1$s was called with an argument that is <strong>deprecated</strong> since version %2$s! %3$s' ), 6127 $function_name, 6128 $version, 6129 $message 6130 ); 6131 } else { 6132 $message = sprintf( 6133 /* translators: 1: PHP function name, 2: Version number. */ 6134 __( 'Function %1$s was called with an argument that is <strong>deprecated</strong> since version %2$s with no alternative available.' ), 6135 $function_name, 6136 $version 6137 ); 6138 } 6139 } else { 6140 if ( $message ) { 6141 $message = sprintf( 6142 'Function %1$s was called with an argument that is <strong>deprecated</strong> since version %2$s! %3$s', 6143 $function_name, 6144 $version, 6145 $message 6146 ); 6147 } else { 6148 $message = sprintf( 6149 'Function %1$s was called with an argument that is <strong>deprecated</strong> since version %2$s with no alternative available.', 6150 $function_name, 6151 $version 6152 ); 6153 } 6154 } 6155 6156 wp_trigger_error( '', $message, E_USER_DEPRECATED ); 6157 } 6158 } 6159 6160 /** 6161 * Marks a deprecated action or filter hook as deprecated and throws a notice. 6162 * 6163 * Use the {@see 'deprecated_hook_run'} action to get the backtrace describing where 6164 * the deprecated hook was called. 6165 * 6166 * Default behavior is to trigger a user error if `WP_DEBUG` is true. 6167 * 6168 * This function is called by the do_action_deprecated() and apply_filters_deprecated() 6169 * functions, and so generally does not need to be called directly. 6170 * 6171 * @since 4.6.0 6172 * @since 5.4.0 The error type is now classified as E_USER_DEPRECATED (used to default to E_USER_NOTICE). 6173 * @access private 6174 * 6175 * @param string $hook The hook that was used. 6176 * @param string $version The version of WordPress that deprecated the hook. 6177 * @param string $replacement Optional. The hook that should have been used. Default empty string. 6178 * @param string $message Optional. A message regarding the change. Default empty. 6179 */ 6180 function _deprecated_hook( $hook, $version, $replacement = '', $message = '' ) { 6181 /** 6182 * Fires when a deprecated hook is called. 6183 * 6184 * @since 4.6.0 6185 * 6186 * @param string $hook The hook that was called. 6187 * @param string $replacement The hook that should be used as a replacement. 6188 * @param string $version The version of WordPress that deprecated the argument used. 6189 * @param string $message A message regarding the change. 6190 */ 6191 do_action( 'deprecated_hook_run', $hook, $replacement, $version, $message ); 6192 6193 /** 6194 * Filters whether to trigger deprecated hook errors. 6195 * 6196 * @since 4.6.0 6197 * 6198 * @param bool $trigger Whether to trigger deprecated hook errors. Requires 6199 * `WP_DEBUG` to be defined true. 6200 */ 6201 if ( WP_DEBUG && apply_filters( 'deprecated_hook_trigger_error', true ) ) { 6202 $message = empty( $message ) ? '' : ' ' . $message; 6203 6204 if ( $replacement ) { 6205 $message = sprintf( 6206 /* translators: 1: WordPress hook name, 2: Version number, 3: Alternative hook name. */ 6207 __( 'Hook %1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.' ), 6208 $hook, 6209 $version, 6210 $replacement 6211 ) . $message; 6212 } else { 6213 $message = sprintf( 6214 /* translators: 1: WordPress hook name, 2: Version number. */ 6215 __( 'Hook %1$s is <strong>deprecated</strong> since version %2$s with no alternative available.' ), 6216 $hook, 6217 $version 6218 ) . $message; 6219 } 6220 6221 wp_trigger_error( '', $message, E_USER_DEPRECATED ); 6222 } 6223 } 6224 6225 /** 6226 * Marks something as being incorrectly called. 6227 * 6228 * There is a {@see 'doing_it_wrong_run'} hook that will be called that can be used 6229 * to get the backtrace up to what file and function called the deprecated function. 6230 * 6231 * The current behavior is to trigger a user error if `WP_DEBUG` is true. 6232 * 6233 * @since 3.1.0 6234 * @since 5.4.0 This function is no longer marked as "private". 6235 * 6236 * @param string $function_name The function that was called. 6237 * @param string $message A message explaining what has been done incorrectly. 6238 * @param string $version The version of WordPress where the message was added. 6239 */ 6240 function _doing_it_wrong( $function_name, $message, $version ) { 6241 6242 /** 6243 * Fires when the given function is being used incorrectly. 6244 * 6245 * @since 3.1.0 6246 * 6247 * @param string $function_name The function that was called. 6248 * @param string $message A message explaining what has been done incorrectly. 6249 * @param string $version The version of WordPress where the message was added. 6250 */ 6251 do_action( 'doing_it_wrong_run', $function_name, $message, $version ); 6252 6253 /** 6254 * Filters whether to trigger an error for _doing_it_wrong() calls. 6255 * 6256 * @since 3.1.0 6257 * @since 5.1.0 Added the `$function_name`, `$message`, and `$version` parameters. 6258 * 6259 * @param bool $trigger Whether to trigger the error for _doing_it_wrong() calls. Default true. 6260 * @param string $function_name The function that was called. 6261 * @param string $message A message explaining what has been done incorrectly. 6262 * @param string $version The version of WordPress where the message was added. 6263 */ 6264 if ( WP_DEBUG && apply_filters( 'doing_it_wrong_trigger_error', true, $function_name, $message, $version ) ) { 6265 if ( function_exists( '__' ) ) { 6266 if ( $version ) { 6267 /* translators: %s: Version number. */ 6268 $version = sprintf( __( '(This message was added in version %s.)' ), $version ); 6269 } 6270 6271 $message .= ' ' . sprintf( 6272 /* translators: %s: Documentation URL. */ 6273 __( 'Please see <a href="%s">Debugging in WordPress</a> for more information.' ), 6274 __( 'https://developer.wordpress.org/advanced-administration/debug/debug-wordpress/' ) 6275 ); 6276 6277 $message = sprintf( 6278 /* translators: Developer debugging message. 1: PHP function name, 2: Explanatory message, 3: WordPress version number. */ 6279 __( 'Function %1$s was called <strong>incorrectly</strong>. %2$s %3$s' ), 6280 $function_name, 6281 $message, 6282 $version 6283 ); 6284 } else { 6285 if ( $version ) { 6286 $version = sprintf( '(This message was added in version %s.)', $version ); 6287 } 6288 6289 $message .= sprintf( 6290 ' Please see <a href="%s">Debugging in WordPress</a> for more information.', 6291 'https://developer.wordpress.org/advanced-administration/debug/debug-wordpress/' 6292 ); 6293 6294 $message = sprintf( 6295 'Function %1$s was called <strong>incorrectly</strong>. %2$s %3$s', 6296 $function_name, 6297 $message, 6298 $version 6299 ); 6300 } 6301 6302 wp_trigger_error( '', $message ); 6303 } 6304 } 6305 6306 /** 6307 * Generates a user-level error/warning/notice/deprecation message. 6308 * 6309 * Generates the message when `WP_DEBUG` is true. 6310 * 6311 * @since 6.4.0 6312 * 6313 * @param string $function_name The function that triggered the error. 6314 * @param string $message The message explaining the error. 6315 * The message can contain allowed HTML 'a' (with href), 'code', 6316 * 'br', 'em', and 'strong' tags and http or https protocols. 6317 * If it contains other HTML tags or protocols, the message should be escaped 6318 * before passing to this function to avoid being stripped {@see wp_kses()}. 6319 * @param int $error_level Optional. The designated error type for this error. 6320 * Only works with E_USER family of constants. Default E_USER_NOTICE. 6321 * 6322 * @phpstan-param E_USER_ERROR|E_USER_WARNING|E_USER_NOTICE|E_USER_DEPRECATED $error_level 6323 */ 6324 function wp_trigger_error( $function_name, $message, $error_level = E_USER_NOTICE ) { 6325 /** 6326 * Always fires when the given function triggers a user-level error/warning/notice/deprecation message. 6327 * 6328 * Can be used to attach custom error handlers even if WP_DEBUG is not truthy. 6329 * 6330 * @since 7.0.0 6331 * 6332 * @param string $function_name The function that triggered the error. 6333 * @param string $message The message explaining the error. 6334 * @param int $error_level The designated error type for this error. 6335 */ 6336 do_action( 'wp_trigger_error_always_run', $function_name, $message, $error_level ); 6337 6338 /** 6339 * Filters whether to trigger an error. 6340 * 6341 * @since 7.0.0 6342 * 6343 * @param bool $trigger Whether to trigger the error. Default true. 6344 * @param string $function_name The function that triggered the error. 6345 * @param string $message The message explaining the error. 6346 * @param int $error_level The designated error type for this error. 6347 */ 6348 if ( ! apply_filters( 'wp_trigger_error_trigger_error', true, $function_name, $message, $error_level ) ) { 6349 return; 6350 } 6351 6352 // Bail out if WP_DEBUG is not turned on. 6353 if ( ! WP_DEBUG ) { 6354 return; 6355 } 6356 6357 /** 6358 * Fires when the given function triggers a user-level error/warning/notice/deprecation message. 6359 * 6360 * Can be used for debug backtracking. 6361 * 6362 * @since 6.4.0 6363 * 6364 * @param string $function_name The function that triggered the error. 6365 * @param string $message The message explaining the error. 6366 * @param int $error_level The designated error type for this error. 6367 */ 6368 do_action( 'wp_trigger_error_run', $function_name, $message, $error_level ); 6369 6370 if ( ! empty( $function_name ) ) { 6371 $message = sprintf( '%s(): %s', $function_name, $message ); 6372 } 6373 6374 $message = wp_kses( 6375 $message, 6376 array( 6377 'a' => array( 'href' => true ), 6378 'br' => array(), 6379 'code' => array(), 6380 'em' => array(), 6381 'strong' => array(), 6382 ), 6383 array( 'http', 'https' ) 6384 ); 6385 6386 if ( E_USER_ERROR === $error_level ) { 6387 throw new WP_Exception( $message ); 6388 } 6389 6390 trigger_error( $message, $error_level ); 6391 } 6392 6393 /** 6394 * Determines whether the server is running an earlier than 1.5.0 version of lighttpd. 6395 * 6396 * @since 2.5.0 6397 * 6398 * @return bool Whether the server is running lighttpd < 1.5.0. 6399 */ 6400 function is_lighttpd_before_150() { 6401 $server_parts = explode( '/', $_SERVER['SERVER_SOFTWARE'] ?? '' ); 6402 $server_parts[1] ??= ''; 6403 6404 return ( 'lighttpd' === $server_parts[0] && -1 === version_compare( $server_parts[1], '1.5.0' ) ); 6405 } 6406 6407 /** 6408 * Determines whether the specified module exist in the Apache config. 6409 * 6410 * @since 2.5.0 6411 * 6412 * @global bool $is_apache 6413 * 6414 * @param string $mod The module, e.g. mod_rewrite. 6415 * @param bool $default_value Optional. The default return value if the module is not found. Default false. 6416 * @return bool Whether the specified module is loaded. 6417 */ 6418 function apache_mod_loaded( $mod, $default_value = false ) { 6419 global $is_apache; 6420 6421 if ( ! $is_apache ) { 6422 return false; 6423 } 6424 6425 $loaded_mods = array(); 6426 6427 if ( function_exists( 'apache_get_modules' ) ) { 6428 $loaded_mods = apache_get_modules(); 6429 6430 if ( in_array( $mod, $loaded_mods, true ) ) { 6431 return true; 6432 } 6433 } 6434 6435 if ( empty( $loaded_mods ) 6436 && function_exists( 'phpinfo' ) 6437 && ! str_contains( ini_get( 'disable_functions' ), 'phpinfo' ) 6438 ) { 6439 ob_start(); 6440 phpinfo( INFO_MODULES ); 6441 $phpinfo = ob_get_clean(); 6442 6443 if ( str_contains( $phpinfo, $mod ) ) { 6444 return true; 6445 } 6446 } 6447 6448 return $default_value; 6449 } 6450 6451 /** 6452 * Checks if IIS 7+ supports pretty permalinks. 6453 * 6454 * @since 2.8.0 6455 * 6456 * @global bool $is_iis7 6457 * 6458 * @return bool Whether IIS7 supports permalinks. 6459 */ 6460 function iis7_supports_permalinks() { 6461 global $is_iis7; 6462 6463 $supports_permalinks = false; 6464 if ( $is_iis7 ) { 6465 /* First we check if the DOMDocument class exists. If it does not exist, then we cannot 6466 * easily update the xml configuration file, hence we just bail out and tell user that 6467 * pretty permalinks cannot be used. 6468 * 6469 * Next we check if the URL Rewrite Module 1.1 is loaded and enabled for the website. When 6470 * URL Rewrite 1.1 is loaded it always sets a server variable called 'IIS_UrlRewriteModule'. 6471 * Lastly we make sure that PHP is running via FastCGI. This is important because if it runs 6472 * via ISAPI then pretty permalinks will not work. 6473 */ 6474 $supports_permalinks = class_exists( 'DOMDocument', false ) && isset( $_SERVER['IIS_UrlRewriteModule'] ) && ( 'cgi-fcgi' === PHP_SAPI ); 6475 } 6476 6477 /** 6478 * Filters whether IIS 7+ supports pretty permalinks. 6479 * 6480 * @since 2.8.0 6481 * 6482 * @param bool $supports_permalinks Whether IIS7 supports permalinks. Default false. 6483 */ 6484 return apply_filters( 'iis7_supports_permalinks', $supports_permalinks ); 6485 } 6486 6487 /** 6488 * Validates a file name and path against an allowed set of rules. 6489 * 6490 * A return value of `1` means the file path contains directory traversal. 6491 * 6492 * A return value of `2` means the file path contains an absolute Windows path. 6493 * This covers drive paths such as `C:/WINDOWS`, UNC network share paths such as 6494 * `//server/share`, and the Windows device namespaces `//./` and `//?/`. 6495 * 6496 * A return value of `3` means the file is not in the allowed files list. 6497 * 6498 * A return value of `0` means no file was provided or processed. 6499 * 6500 * Note that absolute POSIX paths such as `/etc/passwd` are *not* rejected, and 6501 * never have been. Callers that must reject them are responsible for their own 6502 * check. The convention in core is to concatenate the validated value onto a 6503 * trusted base directory and then confirm the result exists, rather than to 6504 * treat this function as an absolute-path guard. 6505 * 6506 * @since 1.2.0 6507 * @since 7.2.0 A return value of `2` also covers UNC and Windows device paths. 6508 * 6509 * @param string $file File path. 6510 * @param string[] $allowed_files Optional. Array of allowed files. Default empty array. 6511 * @return int 0 means nothing is wrong, greater than 0 means something was wrong. 6512 * 6513 * @phpstan-return ( $file is '' ? 0 : ( $allowed_files is empty ? 0|1|2 : 0|1|2|3 ) ) 6514 */ 6515 function validate_file( $file, $allowed_files = array() ) { 6516 if ( ! is_scalar( $file ) || '' === $file ) { 6517 return 0; 6518 } 6519 6520 // Normalize path for Windows servers. 6521 $file = wp_normalize_path( $file ); 6522 // Normalize path for $allowed_files as well so it's an apples to apples comparison. 6523 $allowed_files = array_map( 'wp_normalize_path', $allowed_files ); 6524 6525 // `../` on its own is not allowed: 6526 if ( '../' === $file ) { 6527 return 1; 6528 } 6529 6530 // More than one occurrence of `../` is not allowed: 6531 if ( preg_match_all( '#\.\./#', $file, $matches, PREG_SET_ORDER ) && ( count( $matches ) > 1 ) ) { 6532 return 1; 6533 } 6534 6535 // `../` which does not occur at the end of the path is not allowed: 6536 if ( str_contains( $file, '../' ) && '../' !== mb_substr( $file, -3, 3 ) ) { 6537 return 1; 6538 } 6539 6540 // Files not in the allowed file list are not allowed: 6541 if ( ! empty( $allowed_files ) && ! in_array( $file, $allowed_files, true ) ) { 6542 return 3; 6543 } 6544 6545 /* 6546 * Absolute Windows paths are not allowed. 6547 * 6548 * The drive-letter test predates validate_file() itself, arriving from 6549 * b2/cafelog by way of a long series of moves. It only ever matched the 6550 * `X:` form, which left UNC and device paths accepted: wp_normalize_path() 6551 * above has already folded backslashes to forward slashes, and it 6552 * deliberately preserves a leading `//` for network shares, so those 6553 * paths arrive with no colon in the second byte. 6554 * 6555 * Anchoring the second test to the start of the string is what keeps 6556 * stream wrappers working. A registered wrapper keeps its `://` through 6557 * wp_normalize_path(), placing those slashes past the second byte. 6558 */ 6559 if ( ':' === substr( $file, 1, 1 ) || str_starts_with( $file, '//' ) ) { 6560 return 2; 6561 } 6562 6563 return 0; 6564 } 6565 6566 /** 6567 * Determines whether to force SSL used for the Administration Screens. 6568 * 6569 * @since 2.6.0 6570 * 6571 * @param string|bool|null $force Optional. Whether to force SSL in admin screens. Default null. 6572 * @return bool True if forced, false if not forced. 6573 */ 6574 function force_ssl_admin( $force = null ) { 6575 static $forced = false; 6576 6577 if ( ! is_null( $force ) ) { 6578 $old_forced = $forced; 6579 $forced = (bool) $force; 6580 return $old_forced; 6581 } 6582 6583 return $forced; 6584 } 6585 6586 /** 6587 * Guesses the URL for the site. 6588 * 6589 * Will remove wp-admin links to retrieve only return URLs not in the wp-admin 6590 * directory. 6591 * 6592 * @since 2.6.0 6593 * 6594 * @return string The guessed URL. 6595 */ 6596 function wp_guess_url() { 6597 if ( defined( 'WP_SITEURL' ) && '' !== WP_SITEURL ) { 6598 $url = WP_SITEURL; 6599 } else { 6600 $abspath_fix = str_replace( '\\', '/', ABSPATH ); 6601 $script_filename_dir = dirname( $_SERVER['SCRIPT_FILENAME'] ); 6602 6603 // The request is for the admin. 6604 if ( str_contains( $_SERVER['REQUEST_URI'], 'wp-admin' ) || str_contains( $_SERVER['REQUEST_URI'], 'wp-login.php' ) ) { 6605 $path = preg_replace( '#/(wp-admin/?.*|wp-login\.php.*)#i', '', $_SERVER['REQUEST_URI'] ); 6606 6607 // The request is for a file in ABSPATH. 6608 } elseif ( $script_filename_dir . '/' === $abspath_fix ) { 6609 // Strip off any file/query params in the path. 6610 $path = preg_replace( '#/[^/]*$#i', '', $_SERVER['PHP_SELF'] ); 6611 6612 } else { 6613 if ( str_contains( $_SERVER['SCRIPT_FILENAME'], $abspath_fix ) ) { 6614 // Request is hitting a file inside ABSPATH. 6615 $directory = str_replace( ABSPATH, '', $script_filename_dir ); 6616 // Strip off the subdirectory, and any file/query params. 6617 $path = preg_replace( '#/' . preg_quote( $directory, '#' ) . '/[^/]*$#i', '', $_SERVER['REQUEST_URI'] ); 6618 } elseif ( str_contains( $abspath_fix, $script_filename_dir ) ) { 6619 // Request is hitting a file above ABSPATH. 6620 $subdirectory = substr( $abspath_fix, strpos( $abspath_fix, $script_filename_dir ) + strlen( $script_filename_dir ) ); 6621 // Strip off any file/query params from the path, appending the subdirectory to the installation. 6622 $path = preg_replace( '#/[^/]*$#i', '', $_SERVER['REQUEST_URI'] ) . $subdirectory; 6623 } else { 6624 $path = $_SERVER['REQUEST_URI']; 6625 } 6626 } 6627 6628 $schema = is_ssl() ? 'https://' : 'http://'; // set_url_scheme() is not defined yet. 6629 $url = $schema . $_SERVER['HTTP_HOST'] . $path; 6630 } 6631 6632 return rtrim( $url, '/' ); 6633 } 6634 6635 /** 6636 * Temporarily suspends cache additions. 6637 * 6638 * Stops more data being added to the cache, but still allows cache retrieval. 6639 * This is useful for actions, such as imports, when a lot of data would otherwise 6640 * be almost uselessly added to the cache. 6641 * 6642 * Suspension lasts for a single page load at most. Remember to call this 6643 * function again if you wish to re-enable cache adds earlier. 6644 * 6645 * @since 3.3.0 6646 * 6647 * @param bool $suspend Optional. Suspends additions if true, re-enables them if false. 6648 * Defaults to not changing the current setting. 6649 * @return bool The current suspend setting. 6650 */ 6651 function wp_suspend_cache_addition( $suspend = null ) { 6652 static $_suspend = false; 6653 6654 if ( is_bool( $suspend ) ) { 6655 $_suspend = $suspend; 6656 } 6657 6658 return $_suspend; 6659 } 6660 6661 /** 6662 * Suspends cache invalidation. 6663 * 6664 * Turns cache invalidation on and off. Useful during imports where you don't want to do 6665 * invalidations every time a post is inserted. Callers must be sure that what they are 6666 * doing won't lead to an inconsistent cache when invalidation is suspended. 6667 * 6668 * @since 2.7.0 6669 * 6670 * @global bool $_wp_suspend_cache_invalidation 6671 * 6672 * @param bool $suspend Optional. Whether to suspend or enable cache invalidation. Default true. 6673 * @return bool The current suspend setting. 6674 */ 6675 function wp_suspend_cache_invalidation( $suspend = true ) { 6676 global $_wp_suspend_cache_invalidation; 6677 6678 $current_suspend = $_wp_suspend_cache_invalidation; 6679 $_wp_suspend_cache_invalidation = $suspend; 6680 return $current_suspend; 6681 } 6682 6683 /** 6684 * Determines whether a site is the main site of the current network. 6685 * 6686 * @since 3.0.0 6687 * @since 4.9.0 The `$network_id` parameter was added. 6688 * 6689 * @param int $site_id Optional. Site ID to test. Defaults to current site. 6690 * @param int $network_id Optional. Network ID of the network to check for. 6691 * Defaults to current network. 6692 * @return bool True if $site_id is the main site of the network, or if not 6693 * running Multisite. 6694 */ 6695 function is_main_site( $site_id = null, $network_id = null ) { 6696 if ( ! is_multisite() ) { 6697 return true; 6698 } 6699 6700 if ( ! $site_id ) { 6701 $site_id = get_current_blog_id(); 6702 } 6703 6704 $site_id = (int) $site_id; 6705 6706 return get_main_site_id( $network_id ) === $site_id; 6707 } 6708 6709 /** 6710 * Gets the main site ID. 6711 * 6712 * @since 4.9.0 6713 * 6714 * @param int $network_id Optional. The ID of the network for which to get the main site. 6715 * Defaults to the current network. 6716 * @return int The ID of the main site. 6717 */ 6718 function get_main_site_id( $network_id = null ) { 6719 if ( ! is_multisite() ) { 6720 return get_current_blog_id(); 6721 } 6722 6723 $network = get_network( $network_id ); 6724 if ( ! $network ) { 6725 return 0; 6726 } 6727 6728 return $network->site_id; 6729 } 6730 6731 /** 6732 * Determines whether a network is the main network of the Multisite installation. 6733 * 6734 * @since 3.7.0 6735 * 6736 * @param int $network_id Optional. Network ID to test. Defaults to current network. 6737 * @return bool True if $network_id is the main network, or if not running Multisite. 6738 */ 6739 function is_main_network( $network_id = null ) { 6740 if ( ! is_multisite() ) { 6741 return true; 6742 } 6743 6744 if ( null === $network_id ) { 6745 $network_id = get_current_network_id(); 6746 } 6747 6748 $network_id = (int) $network_id; 6749 6750 return ( get_main_network_id() === $network_id ); 6751 } 6752 6753 /** 6754 * Gets the main network ID. 6755 * 6756 * @since 4.3.0 6757 * 6758 * @return int The ID of the main network. 6759 * 6760 * @phpstan-return non-negative-int 6761 */ 6762 function get_main_network_id() { 6763 if ( ! is_multisite() ) { 6764 return 1; 6765 } 6766 6767 $current_network = get_network(); 6768 6769 if ( defined( 'PRIMARY_NETWORK_ID' ) ) { 6770 $main_network_id = PRIMARY_NETWORK_ID; 6771 } elseif ( isset( $current_network->id ) && 1 === (int) $current_network->id ) { 6772 // If the current network has an ID of 1, assume it is the main network. 6773 $main_network_id = 1; 6774 } else { 6775 $_networks = get_networks( 6776 array( 6777 'fields' => 'ids', 6778 'number' => 1, 6779 ) 6780 ); 6781 $main_network_id = array_shift( $_networks ); 6782 } 6783 6784 /** 6785 * Filters the main network ID. 6786 * 6787 * @since 4.3.0 6788 * 6789 * @param int $main_network_id The ID of the main network. 6790 * 6791 * @phpstan-param non-negative-int $main_network_id 6792 */ 6793 return (int) apply_filters( 'get_main_network_id', $main_network_id ); 6794 } 6795 6796 /** 6797 * Determines whether site meta is enabled. 6798 * 6799 * This function checks whether the 'blogmeta' database table exists. The result is saved as 6800 * a setting for the main network, making it essentially a global setting. Subsequent requests 6801 * will refer to this setting instead of running the query. 6802 * 6803 * @since 5.1.0 6804 * 6805 * @global wpdb $wpdb WordPress database abstraction object. 6806 * 6807 * @return bool True if site meta is supported, false otherwise. 6808 */ 6809 function is_site_meta_supported() { 6810 global $wpdb; 6811 6812 if ( ! is_multisite() ) { 6813 return false; 6814 } 6815 6816 $network_id = get_main_network_id(); 6817 6818 $supported = get_network_option( $network_id, 'site_meta_supported', false ); 6819 if ( false === $supported ) { 6820 $supported = $wpdb->get_var( "SHOW TABLES LIKE '{$wpdb->blogmeta}'" ) ? 1 : 0; 6821 6822 update_network_option( $network_id, 'site_meta_supported', $supported ); 6823 } 6824 6825 return (bool) $supported; 6826 } 6827 6828 /** 6829 * Modifies gmt_offset for smart timezone handling. 6830 * 6831 * Overrides the gmt_offset option if we have a timezone_string available. 6832 * 6833 * @since 2.8.0 6834 * 6835 * @return float|false Timezone GMT offset, false otherwise. 6836 */ 6837 function wp_timezone_override_offset() { 6838 $timezone_string = get_option( 'timezone_string' ); 6839 if ( ! $timezone_string ) { 6840 return false; 6841 } 6842 6843 $timezone_object = timezone_open( $timezone_string ); 6844 $datetime_object = date_create(); 6845 if ( false === $timezone_object || false === $datetime_object ) { 6846 return false; 6847 } 6848 6849 return round( timezone_offset_get( $timezone_object, $datetime_object ) / HOUR_IN_SECONDS, 2 ); 6850 } 6851 6852 /** 6853 * Sort-helper for timezones. 6854 * 6855 * @since 2.9.0 6856 * @access private 6857 * 6858 * @param array $a 6859 * @param array $b 6860 * @return int Comparison result. 6861 */ 6862 function _wp_timezone_choice_usort_callback( $a, $b ) { 6863 // Don't use translated versions of Etc. 6864 if ( 'Etc' === $a['continent'] && 'Etc' === $b['continent'] ) { 6865 // Make the order of these more like the old dropdown. 6866 if ( str_starts_with( $a['city'], 'GMT+' ) && str_starts_with( $b['city'], 'GMT+' ) ) { 6867 return -1 * ( strnatcasecmp( $a['city'], $b['city'] ) ); 6868 } 6869 6870 if ( 'UTC' === $a['city'] ) { 6871 if ( str_starts_with( $b['city'], 'GMT+' ) ) { 6872 return 1; 6873 } 6874 6875 return -1; 6876 } 6877 6878 if ( 'UTC' === $b['city'] ) { 6879 if ( str_starts_with( $a['city'], 'GMT+' ) ) { 6880 return -1; 6881 } 6882 6883 return 1; 6884 } 6885 6886 return strnatcasecmp( $a['city'], $b['city'] ); 6887 } 6888 6889 if ( $a['t_continent'] === $b['t_continent'] ) { 6890 if ( $a['t_city'] === $b['t_city'] ) { 6891 return strnatcasecmp( $a['t_subcity'], $b['t_subcity'] ); 6892 } 6893 6894 return strnatcasecmp( $a['t_city'], $b['t_city'] ); 6895 } else { 6896 // Force Etc to the bottom of the list. 6897 if ( 'Etc' === $a['continent'] ) { 6898 return 1; 6899 } 6900 6901 if ( 'Etc' === $b['continent'] ) { 6902 return -1; 6903 } 6904 6905 return strnatcasecmp( $a['t_continent'], $b['t_continent'] ); 6906 } 6907 } 6908 6909 /** 6910 * Gives a nicely-formatted list of timezone strings. 6911 * 6912 * @since 2.9.0 6913 * @since 4.7.0 Added the `$locale` parameter. 6914 * 6915 * @param string $selected_zone Selected timezone. 6916 * @param string $locale Optional. Locale to load the timezones in. Default current site locale. 6917 * @return string HTML select element for timezones. 6918 */ 6919 function wp_timezone_choice( $selected_zone, $locale = null ) { 6920 static $mo_loaded = false, $locale_loaded = null; 6921 6922 $continents = array( 'Africa', 'America', 'Antarctica', 'Arctic', 'Asia', 'Atlantic', 'Australia', 'Europe', 'Indian', 'Pacific' ); 6923 6924 // Load translations for continents and cities. 6925 if ( ! $mo_loaded || $locale !== $locale_loaded ) { 6926 $locale_loaded = $locale ? $locale : get_locale(); 6927 $mofile = WP_LANG_DIR . '/continents-cities-' . $locale_loaded . '.mo'; 6928 unload_textdomain( 'continents-cities', true ); 6929 load_textdomain( 'continents-cities', $mofile, $locale_loaded ); 6930 $mo_loaded = true; 6931 } 6932 6933 $tz_identifiers = timezone_identifiers_list(); 6934 $zonen = array(); 6935 6936 foreach ( $tz_identifiers as $zone ) { 6937 $zone = explode( '/', $zone ); 6938 if ( ! in_array( $zone[0], $continents, true ) ) { 6939 continue; 6940 } 6941 6942 // This determines what gets set and translated - we don't translate Etc/* strings here, they are done later. 6943 $exists = array( 6944 0 => ! empty( $zone[0] ), 6945 1 => ! empty( $zone[1] ), 6946 2 => ! empty( $zone[2] ), 6947 ); 6948 $exists[3] = $exists[0]; 6949 $exists[4] = ( $exists[1] && $exists[3] ); 6950 $exists[5] = ( $exists[2] && $exists[3] ); 6951 6952 // phpcs:disable WordPress.WP.I18n.LowLevelTranslationFunction,WordPress.WP.I18n.NonSingularStringLiteralText 6953 $zonen[] = array( 6954 'continent' => ( $exists[0] ? $zone[0] : '' ), 6955 'city' => ( $exists[1] ? $zone[1] : '' ), 6956 'subcity' => ( $exists[2] ? $zone[2] : '' ), 6957 't_continent' => ( $exists[3] ? translate( str_replace( '_', ' ', $zone[0] ), 'continents-cities' ) : '' ), 6958 't_city' => ( $exists[4] ? translate( str_replace( '_', ' ', $zone[1] ), 'continents-cities' ) : '' ), 6959 't_subcity' => ( $exists[5] ? translate( str_replace( '_', ' ', $zone[2] ), 'continents-cities' ) : '' ), 6960 ); 6961 // phpcs:enable 6962 } 6963 usort( $zonen, '_wp_timezone_choice_usort_callback' ); 6964 6965 $structure = array(); 6966 6967 if ( empty( $selected_zone ) ) { 6968 $structure[] = '<option selected="selected" value="">' . __( 'Select a city' ) . '</option>'; 6969 } 6970 6971 // If this is a deprecated, but valid, timezone string, display it at the top of the list as-is. 6972 if ( in_array( $selected_zone, $tz_identifiers, true ) === false 6973 && in_array( $selected_zone, timezone_identifiers_list( DateTimeZone::ALL_WITH_BC ), true ) 6974 ) { 6975 $structure[] = '<option selected="selected" value="' . esc_attr( $selected_zone ) . '" dir="auto">' . esc_html( $selected_zone ) . '</option>'; 6976 } 6977 6978 foreach ( $zonen as $key => $zone ) { 6979 // Build value in an array to join later. 6980 $value = array( $zone['continent'] ); 6981 6982 if ( empty( $zone['city'] ) ) { 6983 // It's at the continent level (generally won't happen). 6984 $display = $zone['t_continent']; 6985 } else { 6986 // It's inside a continent group. 6987 6988 // Continent optgroup. 6989 if ( ! isset( $zonen[ $key - 1 ] ) || $zonen[ $key - 1 ]['continent'] !== $zone['continent'] ) { 6990 $label = $zone['t_continent']; 6991 $structure[] = '<optgroup label="' . esc_attr( $label ) . '" dir="auto">'; 6992 } 6993 6994 // Add the city to the value. 6995 $value[] = $zone['city']; 6996 6997 $display = $zone['t_city']; 6998 if ( ! empty( $zone['subcity'] ) ) { 6999 // Add the subcity to the value. 7000 $value[] = $zone['subcity']; 7001 $display .= ' - ' . $zone['t_subcity']; 7002 } 7003 } 7004 7005 // Build the value. 7006 $value = implode( '/', $value ); 7007 $selected = ''; 7008 if ( $value === $selected_zone ) { 7009 $selected = 'selected="selected" '; 7010 } 7011 $structure[] = '<option ' . $selected . 'value="' . esc_attr( $value ) . '" dir="auto">' . esc_html( $display ) . '</option>'; 7012 7013 // Close continent optgroup. 7014 if ( ! empty( $zone['city'] ) && ( ! isset( $zonen[ $key + 1 ] ) || $zonen[ $key + 1 ]['continent'] !== $zone['continent'] ) ) { 7015 $structure[] = '</optgroup>'; 7016 } 7017 } 7018 7019 // Do UTC. 7020 $structure[] = '<optgroup label="' . esc_attr__( 'UTC' ) . '" dir="auto">'; 7021 $selected = ''; 7022 if ( 'UTC' === $selected_zone ) { 7023 $selected = 'selected="selected" '; 7024 } 7025 $structure[] = '<option ' . $selected . 'value="' . esc_attr( 'UTC' ) . '" dir="auto">' . __( 'UTC' ) . '</option>'; 7026 $structure[] = '</optgroup>'; 7027 7028 // Do manual UTC offsets. 7029 $structure[] = '<optgroup label="' . esc_attr__( 'Manual Offsets' ) . '" dir="auto">'; 7030 $offset_range = array( 7031 -12, 7032 -11.5, 7033 -11, 7034 -10.5, 7035 -10, 7036 -9.5, 7037 -9, 7038 -8.5, 7039 -8, 7040 -7.5, 7041 -7, 7042 -6.5, 7043 -6, 7044 -5.5, 7045 -5, 7046 -4.5, 7047 -4, 7048 -3.5, 7049 -3, 7050 -2.5, 7051 -2, 7052 -1.5, 7053 -1, 7054 -0.5, 7055 0, 7056 0.5, 7057 1, 7058 1.5, 7059 2, 7060 2.5, 7061 3, 7062 3.5, 7063 4, 7064 4.5, 7065 5, 7066 5.5, 7067 5.75, 7068 6, 7069 6.5, 7070 7, 7071 7.5, 7072 8, 7073 8.5, 7074 8.75, 7075 9, 7076 9.5, 7077 10, 7078 10.5, 7079 11, 7080 11.5, 7081 12, 7082 12.75, 7083 13, 7084 13.75, 7085 14, 7086 ); 7087 foreach ( $offset_range as $offset ) { 7088 if ( 0 <= $offset ) { 7089 $offset_name = '+' . $offset; 7090 } else { 7091 $offset_name = (string) $offset; 7092 } 7093 7094 $offset_value = $offset_name; 7095 $offset_name = str_replace( array( '.25', '.5', '.75' ), array( ':15', ':30', ':45' ), $offset_name ); 7096 $offset_name = 'UTC' . $offset_name; 7097 $offset_value = 'UTC' . $offset_value; 7098 $selected = ''; 7099 if ( $offset_value === $selected_zone ) { 7100 $selected = 'selected="selected" '; 7101 } 7102 $structure[] = '<option ' . $selected . 'value="' . esc_attr( $offset_value ) . '" dir="auto">' . esc_html( $offset_name ) . '</option>'; 7103 } 7104 $structure[] = '</optgroup>'; 7105 7106 return implode( "\n", $structure ); 7107 } 7108 7109 /** 7110 * Strips close comment and close php tags from file headers used by WP. 7111 * 7112 * @since 2.8.0 7113 * @access private 7114 * 7115 * @link https://core.trac.wordpress.org/ticket/8497 7116 * 7117 * @param string $str Header comment to clean up. 7118 * @return string Cleaned header comment. 7119 */ 7120 function _cleanup_header_comment( $str ) { 7121 return trim( preg_replace( '/\s*(?:\*\/|\?>).*/', '', $str ) ); 7122 } 7123 7124 /** 7125 * Permanently deletes comments or posts of any type that have held a status 7126 * of 'trash' for the number of days defined in EMPTY_TRASH_DAYS. 7127 * 7128 * The default value of `EMPTY_TRASH_DAYS` is 30 (days). 7129 * 7130 * @since 2.9.0 7131 * 7132 * @global wpdb $wpdb WordPress database abstraction object. 7133 */ 7134 function wp_scheduled_delete() { 7135 global $wpdb; 7136 7137 $delete_timestamp = time() - ( DAY_IN_SECONDS * EMPTY_TRASH_DAYS ); 7138 7139 $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 ); 7140 7141 foreach ( (array) $posts_to_delete as $post ) { 7142 $post_id = (int) $post['post_id']; 7143 if ( ! $post_id ) { 7144 continue; 7145 } 7146 7147 $del_post = get_post( $post_id ); 7148 7149 if ( ! $del_post || 'trash' !== $del_post->post_status ) { 7150 delete_post_meta( $post_id, '_wp_trash_meta_status' ); 7151 delete_post_meta( $post_id, '_wp_trash_meta_time' ); 7152 } else { 7153 wp_delete_post( $post_id ); 7154 } 7155 } 7156 7157 $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 ); 7158 7159 foreach ( (array) $comments_to_delete as $comment ) { 7160 $comment_id = (int) $comment['comment_id']; 7161 if ( ! $comment_id ) { 7162 continue; 7163 } 7164 7165 $del_comment = get_comment( $comment_id ); 7166 7167 if ( ! $del_comment || 'trash' !== $del_comment->comment_approved ) { 7168 delete_comment_meta( $comment_id, '_wp_trash_meta_time' ); 7169 delete_comment_meta( $comment_id, '_wp_trash_meta_status' ); 7170 } else { 7171 wp_delete_comment( $del_comment ); 7172 } 7173 } 7174 } 7175 7176 /** 7177 * Retrieves metadata from a file. 7178 * 7179 * Searches for metadata in the first 8 KB of a file, such as a plugin or theme. 7180 * Each piece of metadata must be on its own line. Fields can not span multiple 7181 * lines, the value will get cut at the end of the first line. 7182 * 7183 * If the file data is not within that first 8 KB, then the author should correct 7184 * their plugin file and move the data headers to the top. 7185 * 7186 * @link https://codex.wordpress.org/File_Header 7187 * 7188 * @since 2.9.0 7189 * 7190 * @param string $file Absolute path to the file. 7191 * @param array $default_headers List of headers, in the format `array( 'HeaderKey' => 'Header Name' )`. 7192 * @param string $context Optional. If specified adds filter hook {@see 'extra_$context_headers'}. 7193 * Default empty string. 7194 * @return string[] Array of file header values keyed by header name. 7195 */ 7196 function get_file_data( $file, $default_headers, $context = '' ) { 7197 // Pull only the first 8 KB of the file in. 7198 $file_data = file_get_contents( $file, false, null, 0, 8 * KB_IN_BYTES ); 7199 7200 if ( false === $file_data ) { 7201 $file_data = ''; 7202 } 7203 7204 // Make sure we catch CR-only line endings. 7205 $file_data = str_replace( "\r", "\n", $file_data ); 7206 7207 /** 7208 * Filters extra file headers by context. 7209 * 7210 * The dynamic portion of the hook name, `$context`, refers to 7211 * the context where extra headers might be loaded. 7212 * 7213 * @since 2.9.0 7214 * 7215 * @param array $extra_context_headers Empty array by default. 7216 */ 7217 $extra_headers = $context ? apply_filters( "extra_{$context}_headers", array() ) : array(); 7218 if ( $extra_headers ) { 7219 $extra_headers = array_combine( $extra_headers, $extra_headers ); // Keys equal values. 7220 $all_headers = array_merge( $extra_headers, (array) $default_headers ); 7221 } else { 7222 $all_headers = $default_headers; 7223 } 7224 7225 foreach ( $all_headers as $field => $regex ) { 7226 if ( preg_match( '/^(?:[ \t]*<\?(?:php)?)?[ \t\/*#@]*' . preg_quote( $regex, '/' ) . ':(.*)$/mi', $file_data, $match ) && $match[1] ) { 7227 $all_headers[ $field ] = _cleanup_header_comment( $match[1] ); 7228 } else { 7229 $all_headers[ $field ] = ''; 7230 } 7231 } 7232 7233 return $all_headers; 7234 } 7235 7236 /** 7237 * Returns true. 7238 * 7239 * Useful for returning true to filters easily. 7240 * 7241 * @since 3.0.0 7242 * 7243 * @see __return_false() 7244 * 7245 * @return true True. 7246 */ 7247 function __return_true() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionDoubleUnderscore,PHPCompatibility.FunctionNameRestrictions.ReservedFunctionNames.FunctionDoubleUnderscore 7248 return true; 7249 } 7250 7251 /** 7252 * Returns false. 7253 * 7254 * Useful for returning false to filters easily. 7255 * 7256 * @since 3.0.0 7257 * 7258 * @see __return_true() 7259 * 7260 * @return false False. 7261 */ 7262 function __return_false() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionDoubleUnderscore,PHPCompatibility.FunctionNameRestrictions.ReservedFunctionNames.FunctionDoubleUnderscore 7263 return false; 7264 } 7265 7266 /** 7267 * Returns 0. 7268 * 7269 * Useful for returning 0 to filters easily. 7270 * 7271 * @since 3.0.0 7272 * 7273 * @return int 0. 7274 * 7275 * @phpstan-return 0 7276 */ 7277 function __return_zero() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionDoubleUnderscore,PHPCompatibility.FunctionNameRestrictions.ReservedFunctionNames.FunctionDoubleUnderscore 7278 return 0; 7279 } 7280 7281 /** 7282 * Returns an empty array. 7283 * 7284 * Useful for returning an empty array to filters easily. 7285 * 7286 * @since 3.0.0 7287 * 7288 * @return array Empty array. 7289 * 7290 * @phpstan-return array{} 7291 */ 7292 function __return_empty_array() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionDoubleUnderscore,PHPCompatibility.FunctionNameRestrictions.ReservedFunctionNames.FunctionDoubleUnderscore 7293 return array(); 7294 } 7295 7296 /** 7297 * Returns null. 7298 * 7299 * Useful for returning null to filters easily. 7300 * 7301 * @since 3.4.0 7302 * 7303 * @return null Null value. 7304 */ 7305 function __return_null() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionDoubleUnderscore,PHPCompatibility.FunctionNameRestrictions.ReservedFunctionNames.FunctionDoubleUnderscore 7306 return null; 7307 } 7308 7309 /** 7310 * Returns an empty string. 7311 * 7312 * Useful for returning an empty string to filters easily. 7313 * 7314 * @since 3.7.0 7315 * 7316 * @see __return_null() 7317 * 7318 * @return string Empty string. 7319 * 7320 * @phpstan-return '' 7321 */ 7322 function __return_empty_string() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionDoubleUnderscore,PHPCompatibility.FunctionNameRestrictions.ReservedFunctionNames.FunctionDoubleUnderscore 7323 return ''; 7324 } 7325 7326 /** 7327 * Sends a HTTP header to disable content type sniffing in browsers which support it. 7328 * 7329 * @since 3.0.0 7330 * 7331 * @link https://learn.microsoft.com/en-us/archive/blogs/ie/ie8-security-part-v-comprehensive-protection 7332 * @link https://fetch.spec.whatwg.org/#x-content-type-options-header 7333 */ 7334 function send_nosniff_header() { 7335 header( 'X-Content-Type-Options: nosniff' ); 7336 } 7337 7338 /** 7339 * Returns a MySQL expression for selecting the week number based on the start_of_week option. 7340 * 7341 * @ignore 7342 * @since 3.0.0 7343 * 7344 * @param string $column Database column. 7345 * @return string SQL clause. 7346 */ 7347 function _wp_mysql_week( $column ) { 7348 $start_of_week = (int) get_option( 'start_of_week' ); 7349 switch ( $start_of_week ) { 7350 case 1: 7351 return "WEEK( $column, 1 )"; 7352 case 2: 7353 case 3: 7354 case 4: 7355 case 5: 7356 case 6: 7357 return "WEEK( DATE_SUB( $column, INTERVAL $start_of_week DAY ), 0 )"; 7358 case 0: 7359 default: 7360 return "WEEK( $column, 0 )"; 7361 } 7362 } 7363 7364 /** 7365 * Finds hierarchy loops using a callback function that maps object IDs to parent IDs. 7366 * 7367 * @since 3.1.0 7368 * @access private 7369 * 7370 * @param callable $callback Function that accepts ( ID, $callback_args ) and outputs parent_ID. 7371 * @param int $start The ID to start the loop check at. 7372 * @param int $start_parent The parent_ID of $start to use instead of calling $callback( $start ). 7373 * Use null to always use $callback. 7374 * @param array $callback_args Optional. Additional arguments to send to $callback. Default empty array. 7375 * @return array IDs of all members of loop. 7376 */ 7377 function wp_find_hierarchy_loop( $callback, $start, $start_parent, $callback_args = array() ) { 7378 $override = is_null( $start_parent ) ? array() : array( $start => $start_parent ); 7379 7380 $arbitrary_loop_member = wp_find_hierarchy_loop_tortoise_hare( $callback, $start, $override, $callback_args ); 7381 if ( ! $arbitrary_loop_member ) { 7382 return array(); 7383 } 7384 7385 return wp_find_hierarchy_loop_tortoise_hare( $callback, $arbitrary_loop_member, $override, $callback_args, true ); 7386 } 7387 7388 /** 7389 * Uses the "The Tortoise and the Hare" algorithm to detect loops. 7390 * 7391 * For every step of the algorithm, the hare takes two steps and the tortoise one. 7392 * If the hare ever laps the tortoise, there must be a loop. 7393 * 7394 * @since 3.1.0 7395 * @access private 7396 * 7397 * @param callable $callback Function that accepts ( ID, callback_arg, ... ) and outputs parent_ID. 7398 * @param int $start The ID to start the loop check at. 7399 * @param array $override Optional. An array of ( ID => parent_ID, ... ) to use instead of $callback. 7400 * Default empty array. 7401 * @param array $callback_args Optional. Additional arguments to send to $callback. Default empty array. 7402 * @param bool $_return_loop Optional. Return loop members or just detect presence of loop? Only set 7403 * to true if you already know the given $start is part of a loop (otherwise 7404 * the returned array might include branches). Default false. 7405 * @return mixed Scalar ID of some arbitrary member of the loop, or array of IDs of all members of loop if 7406 * $_return_loop. False if no loop was found. 7407 * 7408 * @phpstan-return ( 7409 * $_return_loop is true ? array<array-key, true>|false : mixed 7410 * ) 7411 */ 7412 function wp_find_hierarchy_loop_tortoise_hare( $callback, $start, $override = array(), $callback_args = array(), $_return_loop = false ) { 7413 $tortoise = $start; 7414 $hare = $start; 7415 $evanescent_hare = $start; 7416 $return = array(); 7417 7418 // Set evanescent_hare to one past hare. Increment hare two steps. 7419 while ( 7420 $tortoise 7421 && 7422 ( $evanescent_hare = $override[ $hare ] ?? call_user_func_array( $callback, array_merge( array( $hare ), $callback_args ) ) ) 7423 && 7424 ( $hare = $override[ $evanescent_hare ] ?? call_user_func_array( $callback, array_merge( array( $evanescent_hare ), $callback_args ) ) ) 7425 ) { 7426 if ( $_return_loop ) { 7427 $return[ $tortoise ] = true; 7428 $return[ $evanescent_hare ] = true; 7429 $return[ $hare ] = true; 7430 } 7431 7432 // Tortoise got lapped - must be a loop. 7433 if ( $tortoise === $evanescent_hare || $tortoise === $hare ) { 7434 return $_return_loop ? $return : $tortoise; 7435 } 7436 7437 // Increment tortoise by one step. 7438 $tortoise = $override[ $tortoise ] ?? call_user_func_array( $callback, array_merge( array( $tortoise ), $callback_args ) ); 7439 } 7440 7441 return false; 7442 } 7443 7444 /** 7445 * Sends a HTTP header to limit rendering of pages to same origin iframes. 7446 * 7447 * @since 3.1.3 7448 * 7449 * @link https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-Frame-Options 7450 * @link https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Security-Policy/frame-ancestors 7451 */ 7452 function send_frame_options_header() { 7453 if ( ! headers_sent() ) { 7454 header( 'X-Frame-Options: SAMEORIGIN' ); 7455 header( "Content-Security-Policy: frame-ancestors 'self';" ); 7456 } 7457 } 7458 7459 /** 7460 * Sends a referrer policy header so referrers are not sent externally from administration screens. 7461 * 7462 * @since 4.9.0 7463 * @since 6.8.0 This function was moved from `wp-admin/includes/misc.php` to `wp-includes/functions.php`. 7464 */ 7465 function wp_admin_headers() { 7466 $policy = 'strict-origin-when-cross-origin'; 7467 7468 /** 7469 * Filters the admin referrer policy header value. 7470 * 7471 * @since 4.9.0 7472 * @since 4.9.5 The default value was changed to 'strict-origin-when-cross-origin'. 7473 * 7474 * @link https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Referrer-Policy 7475 * 7476 * @param string $policy The admin referrer policy header value. Default 'strict-origin-when-cross-origin'. 7477 */ 7478 $policy = apply_filters( 'admin_referrer_policy', $policy ); 7479 7480 header( sprintf( 'Referrer-Policy: %s', $policy ) ); 7481 } 7482 7483 /** 7484 * Retrieves a list of protocols to allow in HTML attributes. 7485 * 7486 * @since 3.3.0 7487 * @since 4.3.0 Added 'webcal' to the protocols array. 7488 * @since 4.7.0 Added 'urn' to the protocols array. 7489 * @since 5.3.0 Added 'sms' to the protocols array. 7490 * @since 5.6.0 Added 'irc6' and 'ircs' to the protocols array. 7491 * 7492 * @see wp_kses() 7493 * @see esc_url() 7494 * 7495 * @return string[] Array of allowed protocols. Defaults to an array containing 'http', 'https', 7496 * 'ftp', 'ftps', 'mailto', 'news', 'irc', 'irc6', 'ircs', 'gopher', 'nntp', 'feed', 7497 * 'telnet', 'mms', 'rtsp', 'sms', 'svn', 'tel', 'fax', 'xmpp', 'webcal', and 'urn'. 7498 * This covers all common link protocols, except for 'javascript' which should not 7499 * be allowed for untrusted users. 7500 */ 7501 function wp_allowed_protocols() { 7502 static $protocols = array(); 7503 7504 if ( empty( $protocols ) ) { 7505 $protocols = array( 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'irc6', 'ircs', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'sms', 'svn', 'tel', 'fax', 'xmpp', 'webcal', 'urn' ); 7506 } 7507 7508 if ( ! did_action( 'wp_loaded' ) ) { 7509 /** 7510 * Filters the list of protocols allowed in HTML attributes. 7511 * 7512 * @since 3.0.0 7513 * 7514 * @param string[] $protocols Array of allowed protocols e.g. 'http', 'ftp', 'tel', and more. 7515 */ 7516 $protocols = array_unique( (array) apply_filters( 'kses_allowed_protocols', $protocols ) ); 7517 } 7518 7519 return $protocols; 7520 } 7521 7522 /** 7523 * Returns a comma-separated string or array of functions that have been called to get 7524 * to the current point in code. 7525 * 7526 * @since 3.4.0 7527 * 7528 * @link https://core.trac.wordpress.org/ticket/19589 7529 * 7530 * @param string $ignore_class Optional. A class to ignore all function calls within - useful 7531 * when you want to just give info about the callee. Default null. 7532 * @param int $skip_frames Optional. A number of stack frames to skip - useful for unwinding 7533 * back to the source of the issue. Default 0. 7534 * @param bool $pretty Optional. Whether you want a comma separated string instead of 7535 * the raw array returned. Default true. 7536 * @return string|array Either a string containing a reversed comma separated trace or an array 7537 * of individual calls. 7538 * 7539 * @phpstan-return ( $pretty is true ? string : list<string> ) 7540 */ 7541 function wp_debug_backtrace_summary( $ignore_class = null, $skip_frames = 0, $pretty = true ) { 7542 static $truncate_paths; 7543 7544 $trace = debug_backtrace( false ); 7545 $caller = array(); 7546 $check_class = ! is_null( $ignore_class ); 7547 ++$skip_frames; // Skip this function. 7548 7549 if ( ! isset( $truncate_paths ) ) { 7550 $truncate_paths = array( 7551 wp_normalize_path( WP_CONTENT_DIR ), 7552 wp_normalize_path( ABSPATH ), 7553 ); 7554 } 7555 7556 foreach ( $trace as $call ) { 7557 if ( $skip_frames > 0 ) { 7558 --$skip_frames; 7559 } elseif ( isset( $call['class'] ) ) { 7560 if ( $check_class && $ignore_class === $call['class'] ) { 7561 continue; // Filter out calls. 7562 } 7563 7564 $caller[] = "{$call['class']}{$call['type']}{$call['function']}"; 7565 } else { 7566 if ( in_array( $call['function'], array( 'do_action', 'apply_filters', 'do_action_ref_array', 'apply_filters_ref_array' ), true ) ) { 7567 $caller[] = "{$call['function']}('{$call['args'][0]}')"; 7568 } elseif ( in_array( $call['function'], array( 'include', 'include_once', 'require', 'require_once' ), true ) ) { 7569 $filename = $call['args'][0] ?? ''; 7570 $caller[] = $call['function'] . "('" . str_replace( $truncate_paths, '', wp_normalize_path( $filename ) ) . "')"; 7571 } else { 7572 $caller[] = $call['function']; 7573 } 7574 } 7575 } 7576 if ( $pretty ) { 7577 return implode( ', ', array_reverse( $caller ) ); 7578 } else { 7579 return $caller; 7580 } 7581 } 7582 7583 /** 7584 * Retrieves IDs that are not already present in the cache. 7585 * 7586 * @since 3.4.0 7587 * @since 6.1.0 This function is no longer marked as "private". 7588 * 7589 * @param int[] $object_ids Array of IDs. 7590 * @param string $cache_group The cache group to check against. 7591 * @return int[] Array of IDs not present in the cache. 7592 */ 7593 function _get_non_cached_ids( $object_ids, $cache_group ) { 7594 $object_ids = array_filter( $object_ids, '_validate_cache_id' ); 7595 $object_ids = array_unique( array_map( 'intval', $object_ids ), SORT_NUMERIC ); 7596 7597 if ( empty( $object_ids ) ) { 7598 return array(); 7599 } 7600 7601 $non_cached_ids = array(); 7602 $cache_values = wp_cache_get_multiple( $object_ids, $cache_group ); 7603 7604 foreach ( $cache_values as $id => $value ) { 7605 if ( false === $value ) { 7606 $non_cached_ids[] = (int) $id; 7607 } 7608 } 7609 7610 return $non_cached_ids; 7611 } 7612 7613 /** 7614 * Checks whether the given cache ID is either an integer or an integer-like string. 7615 * 7616 * Both `16` and `"16"` are considered valid, other numeric types and numeric strings 7617 * (`16.3` and `"16.3"`) are considered invalid. 7618 * 7619 * @since 6.3.0 7620 * 7621 * @param mixed $object_id The cache ID to validate. 7622 * @return bool Whether the given $object_id is a valid cache ID. 7623 */ 7624 function _validate_cache_id( $object_id ) { 7625 /* 7626 * filter_var() could be used here, but the `filter` PHP extension 7627 * is considered optional and may not be available. 7628 */ 7629 if ( is_int( $object_id ) 7630 || ( is_string( $object_id ) && (string) (int) $object_id === $object_id ) ) { 7631 return true; 7632 } 7633 7634 /* translators: %s: The type of the given object ID. */ 7635 $message = sprintf( __( 'Object ID must be an integer, %s given.' ), gettype( $object_id ) ); 7636 _doing_it_wrong( '_get_non_cached_ids', $message, '6.3.0' ); 7637 7638 return false; 7639 } 7640 7641 /** 7642 * Tests if the current device has the capability to upload files. 7643 * 7644 * @since 3.4.0 7645 * @access private 7646 * 7647 * @return bool Whether the device is able to upload files. 7648 */ 7649 function _device_can_upload() { 7650 if ( ! wp_is_mobile() ) { 7651 return true; 7652 } 7653 7654 $ua = $_SERVER['HTTP_USER_AGENT']; 7655 7656 if ( str_contains( $ua, 'iPhone' ) 7657 || str_contains( $ua, 'iPad' ) 7658 || str_contains( $ua, 'iPod' ) ) { 7659 return preg_match( '#OS ([\d_]+) like Mac OS X#', $ua, $version ) && version_compare( $version[1], '6', '>=' ); 7660 } 7661 7662 return true; 7663 } 7664 7665 /** 7666 * Tests if a given path is a stream URL 7667 * 7668 * @since 3.5.0 7669 * 7670 * @param string $path The resource path or URL. 7671 * @return bool True if the path is a stream URL. 7672 * 7673 * @phpstan-assert-if-true =non-falsy-string $path 7674 */ 7675 function wp_is_stream( $path ) { 7676 $scheme_separator = strpos( $path, '://' ); 7677 7678 if ( false === $scheme_separator ) { 7679 // $path isn't a stream. 7680 return false; 7681 } 7682 7683 $stream = substr( $path, 0, $scheme_separator ); 7684 7685 return in_array( $stream, stream_get_wrappers(), true ); 7686 } 7687 7688 /** 7689 * Tests if the supplied date is valid for the Gregorian calendar. 7690 * 7691 * @since 3.5.0 7692 * 7693 * @link https://www.php.net/manual/en/function.checkdate.php 7694 * 7695 * @param int|string $month Month number. 7696 * @param int|string $day Day number. 7697 * @param int|string $year Year number. 7698 * @param string $source_date The date to filter. 7699 * @return bool True if valid date, false if not valid date. 7700 * 7701 * @phpstan-param int|numeric-string $month 7702 * @phpstan-param int|numeric-string $day 7703 * @phpstan-param int|numeric-string $year 7704 */ 7705 function wp_checkdate( $month, $day, $year, $source_date ) { 7706 $checkdate = false; 7707 if ( is_numeric( $month ) && is_numeric( $day ) && is_numeric( $year ) ) { 7708 $checkdate = checkdate( (int) $month, (int) $day, (int) $year ); 7709 } 7710 7711 /** 7712 * Filters whether the given date is valid for the Gregorian calendar. 7713 * 7714 * @since 3.5.0 7715 * 7716 * @param bool $checkdate Whether the given date is valid. 7717 * @param string $source_date Date to check. 7718 */ 7719 return apply_filters( 'wp_checkdate', $checkdate, $source_date ); 7720 } 7721 7722 /** 7723 * Loads the auth check for monitoring whether the user is still logged in. 7724 * 7725 * Can be disabled with remove_action( 'admin_enqueue_scripts', 'wp_auth_check_load' ); 7726 * 7727 * This is disabled for certain screens where a login screen could cause an 7728 * inconvenient interruption. A filter called {@see 'wp_auth_check_load'} can be used 7729 * for fine-grained control. 7730 * 7731 * @since 3.6.0 7732 */ 7733 function wp_auth_check_load() { 7734 if ( ! is_admin() && ! is_user_logged_in() ) { 7735 return; 7736 } 7737 7738 if ( defined( 'IFRAME_REQUEST' ) ) { 7739 return; 7740 } 7741 7742 $screen = get_current_screen(); 7743 $hidden = array( 'update', 'update-network', 'update-core', 'update-core-network', 'upgrade', 'upgrade-network', 'network' ); 7744 $show = ! in_array( $screen->id, $hidden, true ); 7745 7746 /** 7747 * Filters whether to load the authentication check. 7748 * 7749 * Returning a falsey value from the filter will effectively short-circuit 7750 * loading the authentication check. 7751 * 7752 * @since 3.6.0 7753 * 7754 * @param bool $show Whether to load the authentication check. 7755 * @param WP_Screen $screen The current screen object. 7756 */ 7757 if ( apply_filters( 'wp_auth_check_load', $show, $screen ) ) { 7758 // Prefetched from the login screen by wp_prefetch_admin_assets(), which needs updating if this changes. 7759 wp_enqueue_style( 'wp-auth-check' ); 7760 wp_enqueue_script( 'wp-auth-check' ); 7761 7762 add_action( 'admin_print_footer_scripts', 'wp_auth_check_html', 5 ); 7763 add_action( 'wp_print_footer_scripts', 'wp_auth_check_html', 5 ); 7764 } 7765 } 7766 7767 /** 7768 * Outputs the HTML that shows the wp-login dialog when the user is no longer logged in. 7769 * 7770 * @since 3.6.0 7771 */ 7772 function wp_auth_check_html() { 7773 $login_url = wp_login_url(); 7774 $current_domain = ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST']; 7775 $same_domain = str_starts_with( $login_url, $current_domain ); 7776 7777 /** 7778 * Filters whether the authentication check originated at the same domain. 7779 * 7780 * @since 3.6.0 7781 * 7782 * @param bool $same_domain Whether the authentication check originated at the same domain. 7783 */ 7784 $same_domain = apply_filters( 'wp_auth_check_same_domain', $same_domain ); 7785 $wrap_class = $same_domain ? 'hidden' : 'hidden fallback'; 7786 7787 ?> 7788 <div id="wp-auth-check-wrap" class="<?php echo $wrap_class; ?>"> 7789 <div id="wp-auth-check-bg"></div> 7790 <div id="wp-auth-check"> 7791 <button type="button" class="wp-auth-check-close button-link"><span class="screen-reader-text"> 7792 <?php 7793 /* translators: Hidden accessibility text. */ 7794 _e( 'Close dialog' ); 7795 ?> 7796 </span></button> 7797 <?php 7798 7799 if ( $same_domain ) { 7800 $login_src = add_query_arg( 7801 array( 7802 'interim-login' => '1', 7803 'wp_lang' => get_user_locale(), 7804 ), 7805 $login_url 7806 ); 7807 ?> 7808 <div id="wp-auth-check-form" class="loading" data-src="<?php echo esc_url( $login_src ); ?>"></div> 7809 <?php 7810 } 7811 7812 ?> 7813 <div class="wp-auth-fallback"> 7814 <p><b class="wp-auth-fallback-expired" tabindex="0"><?php _e( 'Session expired' ); ?></b></p> 7815 <p><a href="<?php echo esc_url( $login_url ); ?>" target="_blank"><?php _e( 'Please log in again.' ); ?></a> 7816 <?php _e( 'The login page will open in a new tab. After logging in you can close it and return to this page.' ); ?></p> 7817 </div> 7818 </div> 7819 </div> 7820 <?php 7821 } 7822 7823 /** 7824 * Checks whether a user is still logged in, for the heartbeat. 7825 * 7826 * Send a result that shows a log-in box if the user is no longer logged in, 7827 * or if their cookie is within the grace period. 7828 * 7829 * @since 3.6.0 7830 * 7831 * @global int $login_grace_period 7832 * 7833 * @param array $response The Heartbeat response. 7834 * @return array The Heartbeat response with 'wp-auth-check' value set. 7835 */ 7836 function wp_auth_check( $response ) { 7837 $response['wp-auth-check'] = is_user_logged_in() && empty( $GLOBALS['login_grace_period'] ); 7838 return $response; 7839 } 7840 7841 /** 7842 * Returns RegEx body to liberally match an opening HTML tag. 7843 * 7844 * Matches an opening HTML tag that: 7845 * 1. Is self-closing or 7846 * 2. Has no body but has a closing tag of the same name or 7847 * 3. Contains a body and a closing tag of the same name 7848 * 7849 * Note: this RegEx does not balance inner tags and does not attempt 7850 * to produce valid HTML 7851 * 7852 * @since 3.6.0 7853 * 7854 * @param string $tag An HTML tag name. Example: 'video'. 7855 * @return string Tag RegEx. 7856 * 7857 * @phpstan-return ( $tag is ''|'0' ? '' : non-falsy-string ) 7858 */ 7859 function get_tag_regex( $tag ) { 7860 if ( empty( $tag ) ) { 7861 return ''; 7862 } 7863 return sprintf( '<%1$s[^<]*?(?:>[\s\S]*?<\/%1$s>|\s*\/>)', tag_escape( $tag ) ); 7864 } 7865 7866 /** 7867 * Indicates if a given slug for a character set represents the UTF-8 7868 * text encoding. If not provided, examines the current blog's charset. 7869 * 7870 * A charset is considered to represent UTF-8 if it is a case-insensitive 7871 * match of "UTF-8" with or without the hyphen. 7872 * 7873 * Example: 7874 * 7875 * true === is_utf8_charset( 'UTF-8' ); 7876 * true === is_utf8_charset( 'utf8' ); 7877 * false === is_utf8_charset( 'latin1' ); 7878 * false === is_utf8_charset( 'UTF 8' ); 7879 * 7880 * // Only strings match. 7881 * false === is_utf8_charset( [ 'charset' => 'utf-8' ] ); 7882 * 7883 * // Without a given charset, it depends on the site option "blog_charset". 7884 * $is_utf8 = is_utf8_charset(); 7885 * 7886 * @since 6.6.0 7887 * @since 6.6.1 A wrapper for _is_utf8_charset 7888 * 7889 * @see _is_utf8_charset 7890 * 7891 * @param string|null $blog_charset Optional. Slug representing a text character encoding, or "charset". 7892 * E.g. "UTF-8", "Windows-1252", "ISO-8859-1", "SJIS". 7893 * Default value is to infer from "blog_charset" option. 7894 * @return bool Whether the slug represents the UTF-8 encoding. 7895 */ 7896 function is_utf8_charset( $blog_charset = null ) { 7897 return _is_utf8_charset( $blog_charset ?? get_option( 'blog_charset' ) ); 7898 } 7899 7900 /** 7901 * Retrieves a canonical form of the provided charset appropriate for passing to PHP 7902 * functions such as htmlspecialchars() and charset HTML attributes. 7903 * 7904 * @since 3.6.0 7905 * @access private 7906 * 7907 * @link https://core.trac.wordpress.org/ticket/23688 7908 * 7909 * @param string $charset A charset name, e.g. "UTF-8", "Windows-1252", "SJIS". 7910 * @return string The canonical form of the charset. 7911 */ 7912 function _canonical_charset( $charset ) { 7913 if ( is_utf8_charset( $charset ) ) { 7914 return 'UTF-8'; 7915 } 7916 7917 /* 7918 * Normalize the ISO-8859-1 family of languages. 7919 * 7920 * This is not required for htmlspecialchars(), as it properly recognizes all of 7921 * the input character sets that here are transformed into "ISO-8859-1". 7922 * 7923 * @todo Should this entire check be removed since it's not required for the stated purpose? 7924 * @todo Should WordPress transform other potential charset equivalents, such as "latin1"? 7925 */ 7926 if ( 7927 ( 0 === strcasecmp( 'iso-8859-1', $charset ) ) || 7928 ( 0 === strcasecmp( 'iso8859-1', $charset ) ) 7929 ) { 7930 return 'ISO-8859-1'; 7931 } 7932 7933 return $charset; 7934 } 7935 7936 /** 7937 * Sets the mbstring internal encoding to a binary safe encoding when func_overload 7938 * is enabled. 7939 * 7940 * When mbstring.func_overload is in use for multi-byte encodings, the results from 7941 * strlen() and similar functions respect the utf8 characters, causing binary data 7942 * to return incorrect lengths. 7943 * 7944 * This function overrides the mbstring encoding to a binary-safe encoding, and 7945 * resets it to the users expected encoding afterwards through the 7946 * `reset_mbstring_encoding` function. 7947 * 7948 * It is safe to recursively call this function, however each 7949 * `mbstring_binary_safe_encoding()` call must be followed up with an equal number 7950 * of `reset_mbstring_encoding()` calls. 7951 * 7952 * @since 3.7.0 7953 * 7954 * @see reset_mbstring_encoding() 7955 * 7956 * @param bool $reset Optional. Whether to reset the encoding back to a previously-set encoding. 7957 * Default false. 7958 */ 7959 function mbstring_binary_safe_encoding( $reset = false ) { 7960 static $encodings = array(); 7961 static $overloaded = null; 7962 7963 if ( is_null( $overloaded ) ) { 7964 if ( function_exists( 'mb_internal_encoding' ) 7965 && ( (int) ini_get( 'mbstring.func_overload' ) & 2 ) // phpcs:ignore PHPCompatibility.IniDirectives.RemovedIniDirectives.mbstring_func_overloadDeprecated 7966 ) { 7967 $overloaded = true; 7968 } else { 7969 $overloaded = false; 7970 } 7971 } 7972 7973 if ( false === $overloaded ) { 7974 return; 7975 } 7976 7977 if ( ! $reset ) { 7978 $encoding = mb_internal_encoding(); 7979 array_push( $encodings, $encoding ); 7980 mb_internal_encoding( 'ISO-8859-1' ); 7981 } 7982 7983 if ( $reset && $encodings ) { 7984 $encoding = array_pop( $encodings ); 7985 mb_internal_encoding( $encoding ); 7986 } 7987 } 7988 7989 /** 7990 * Resets the mbstring internal encoding to a users previously set encoding. 7991 * 7992 * @see mbstring_binary_safe_encoding() 7993 * 7994 * @since 3.7.0 7995 */ 7996 function reset_mbstring_encoding() { 7997 mbstring_binary_safe_encoding( true ); 7998 } 7999 8000 /** 8001 * Filters/validates a variable as a boolean. 8002 * 8003 * Alternative to `filter_var( $value, FILTER_VALIDATE_BOOLEAN )`. 8004 * 8005 * @since 4.0.0 8006 * 8007 * @param mixed $value Boolean value to validate. 8008 * @return bool Whether the value is validated. 8009 */ 8010 function wp_validate_boolean( $value ) { 8011 if ( is_bool( $value ) ) { 8012 return $value; 8013 } 8014 8015 if ( is_string( $value ) && 'false' === strtolower( $value ) ) { 8016 return false; 8017 } 8018 8019 return (bool) $value; 8020 } 8021 8022 /** 8023 * Deletes a file. 8024 * 8025 * @since 4.2.0 8026 * @since 6.7.0 A return value was added. 8027 * 8028 * @param string $file The path to the file to delete. 8029 * @return bool True on success, false on failure. 8030 */ 8031 function wp_delete_file( $file ) { 8032 /** 8033 * Filters the path of the file to delete. 8034 * 8035 * @since 2.1.0 8036 * 8037 * @param string $file Path to the file to delete. 8038 */ 8039 $delete = apply_filters( 'wp_delete_file', $file ); 8040 8041 if ( ! empty( $delete ) ) { 8042 return @unlink( $delete ); 8043 } 8044 8045 return false; 8046 } 8047 8048 /** 8049 * Deletes a file if its path is within the given directory. 8050 * 8051 * @since 4.9.7 8052 * 8053 * @param string $file Absolute path to the file to delete. 8054 * @param string $directory Absolute path to a directory. 8055 * @return bool True on success, false on failure. 8056 */ 8057 function wp_delete_file_from_directory( $file, $directory ) { 8058 if ( wp_is_stream( $file ) ) { 8059 $real_file = $file; 8060 $real_directory = $directory; 8061 } else { 8062 $real_file = realpath( wp_normalize_path( $file ) ); 8063 $real_directory = realpath( wp_normalize_path( $directory ) ); 8064 } 8065 8066 if ( false !== $real_file ) { 8067 $real_file = wp_normalize_path( $real_file ); 8068 } 8069 8070 if ( false !== $real_directory ) { 8071 $real_directory = wp_normalize_path( $real_directory ); 8072 } 8073 8074 if ( false === $real_file || false === $real_directory || ! str_starts_with( $real_file, trailingslashit( $real_directory ) ) ) { 8075 return false; 8076 } 8077 8078 return wp_delete_file( $file ); 8079 } 8080 8081 /** 8082 * Outputs a small JS snippet on preview tabs/windows to remove `window.name` when a user is navigating to another page. 8083 * 8084 * This prevents reusing the same tab for a preview when the user has navigated away. 8085 * 8086 * @since 4.3.0 8087 * 8088 * @global WP_Post $post Global post object. 8089 */ 8090 function wp_post_preview_js() { 8091 global $post; 8092 8093 if ( ! is_preview() || empty( $post ) ) { 8094 return; 8095 } 8096 8097 // Has to match the window name used in post_submit_meta_box(). 8098 $name = 'wp-preview-' . (int) $post->ID; 8099 8100 ob_start(); 8101 ?> 8102 <script> 8103 ( function() { 8104 var query = document.location.search; 8105 8106 if ( query && query.indexOf( 'preview=true' ) !== -1 ) { 8107 window.name = '<?php echo $name; ?>'; 8108 } 8109 8110 if ( window.addEventListener ) { 8111 window.addEventListener( 'pagehide', function() { window.name = ''; } ); 8112 } 8113 }()); 8114 //# sourceURL=<?php echo rawurlencode( __FUNCTION__ ); ?> 8115 </script> 8116 <?php 8117 wp_print_inline_script_tag( wp_remove_surrounding_empty_script_tags( ob_get_clean() ) ); 8118 } 8119 8120 /** 8121 * Parses and formats a MySQL datetime (Y-m-d H:i:s) for ISO8601 (Y-m-d\TH:i:s). 8122 * 8123 * Explicitly strips timezones, as datetimes are not saved with any timezone 8124 * information. Including any information on the offset could be misleading. 8125 * 8126 * Despite historical function name, the output does not conform to RFC3339 format, 8127 * which must contain timezone. 8128 * 8129 * @since 4.4.0 8130 * 8131 * @param string $date_string Date string to parse and format. 8132 * @return string Date formatted for ISO8601 without time zone. 8133 */ 8134 function mysql_to_rfc3339( $date_string ) { 8135 return mysql2date( 'Y-m-d\TH:i:s', $date_string, false ); 8136 } 8137 8138 /** 8139 * Attempts to raise the PHP memory limit for memory intensive processes. 8140 * 8141 * Only allows raising the existing limit and prevents lowering it. 8142 * 8143 * @since 4.6.0 8144 * 8145 * @param string $context Optional. Context in which the function is called. Accepts either 'admin', 8146 * 'image', 'cron', or an arbitrary other context. If an arbitrary context is passed, 8147 * the similarly arbitrary {@see '$context_memory_limit'} filter will be 8148 * invoked. Default 'admin'. 8149 * @return int|string|false The limit that was set or false on failure. 8150 */ 8151 function wp_raise_memory_limit( $context = 'admin' ) { 8152 // Exit early if the limit cannot be changed. 8153 if ( false === wp_is_ini_value_changeable( 'memory_limit' ) ) { 8154 return false; 8155 } 8156 8157 $current_limit = ini_get( 'memory_limit' ); 8158 $current_limit_int = wp_convert_hr_to_bytes( $current_limit ); 8159 8160 if ( -1 === $current_limit_int ) { 8161 return false; 8162 } 8163 8164 $wp_max_limit = WP_MAX_MEMORY_LIMIT; 8165 $wp_max_limit_int = wp_convert_hr_to_bytes( $wp_max_limit ); 8166 $filtered_limit = $wp_max_limit; 8167 8168 switch ( $context ) { 8169 case 'admin': 8170 /** 8171 * Filters the maximum memory limit available for administration screens. 8172 * 8173 * This only applies to administrators, who may require more memory for tasks 8174 * like updates. Memory limits when processing images (uploaded or edited by 8175 * users of any role) are handled separately. 8176 * 8177 * The `WP_MAX_MEMORY_LIMIT` constant specifically defines the maximum memory 8178 * limit available when in the administration back end. The default is 256M 8179 * (256 megabytes of memory) or the original `memory_limit` php.ini value if 8180 * this is higher. 8181 * 8182 * @since 3.0.0 8183 * @since 4.6.0 The default now takes the original `memory_limit` into account. 8184 * 8185 * @param int|string $filtered_limit The maximum WordPress memory limit. Accepts an integer 8186 * (bytes), or a shorthand string notation, such as '256M'. 8187 */ 8188 $filtered_limit = apply_filters( 'admin_memory_limit', $filtered_limit ); 8189 break; 8190 8191 case 'image': 8192 /** 8193 * Filters the memory limit allocated for image manipulation. 8194 * 8195 * @since 3.5.0 8196 * @since 4.6.0 The default now takes the original `memory_limit` into account. 8197 * 8198 * @param int|string $filtered_limit Maximum memory limit to allocate for image processing. 8199 * Default `WP_MAX_MEMORY_LIMIT` or the original 8200 * php.ini `memory_limit`, whichever is higher. 8201 * Accepts an integer (bytes), or a shorthand string 8202 * notation, such as '256M'. 8203 */ 8204 $filtered_limit = apply_filters( 'image_memory_limit', $filtered_limit ); 8205 break; 8206 8207 case 'cron': 8208 /** 8209 * Filters the memory limit allocated for WP-Cron event processing. 8210 * 8211 * @since 6.3.0 8212 * 8213 * @param int|string $filtered_limit Maximum memory limit to allocate for WP-Cron. 8214 * Default `WP_MAX_MEMORY_LIMIT` or the original 8215 * php.ini `memory_limit`, whichever is higher. 8216 * Accepts an integer (bytes), or a shorthand string 8217 * notation, such as '256M'. 8218 */ 8219 $filtered_limit = apply_filters( 'cron_memory_limit', $filtered_limit ); 8220 break; 8221 8222 default: 8223 /** 8224 * Filters the memory limit allocated for an arbitrary context. 8225 * 8226 * The dynamic portion of the hook name, `$context`, refers to an arbitrary 8227 * context passed on calling the function. This allows for plugins to define 8228 * their own contexts for raising the memory limit. 8229 * 8230 * @since 4.6.0 8231 * 8232 * @param int|string $filtered_limit Maximum memory limit to allocate for this context. 8233 * Default WP_MAX_MEMORY_LIMIT` or the original php.ini `memory_limit`, 8234 * whichever is higher. Accepts an integer (bytes), or a 8235 * shorthand string notation, such as '256M'. 8236 */ 8237 $filtered_limit = apply_filters( "{$context}_memory_limit", $filtered_limit ); 8238 break; 8239 } 8240 8241 $filtered_limit_int = wp_convert_hr_to_bytes( $filtered_limit ); 8242 8243 if ( -1 === $filtered_limit_int || ( $filtered_limit_int > $wp_max_limit_int && $filtered_limit_int > $current_limit_int ) ) { 8244 if ( false !== ini_set( 'memory_limit', $filtered_limit ) ) { 8245 return $filtered_limit; 8246 } else { 8247 return false; 8248 } 8249 } elseif ( -1 === $wp_max_limit_int || $wp_max_limit_int > $current_limit_int ) { 8250 if ( false !== ini_set( 'memory_limit', $wp_max_limit ) ) { 8251 return $wp_max_limit; 8252 } else { 8253 return false; 8254 } 8255 } 8256 8257 return false; 8258 } 8259 8260 /** 8261 * Generates a random UUID (version 4). 8262 * 8263 * @since 4.7.0 8264 * @since 7.0.0 Uses wp_rand if available. 8265 * 8266 * @return string UUID. 8267 * 8268 * @phpstan-return lowercase-string&non-falsy-string 8269 */ 8270 function wp_generate_uuid4() { 8271 static $backup_randomizer = false; 8272 $randomizer = function_exists( 'wp_rand' ) ? 'wp_rand' : $backup_randomizer; 8273 8274 if ( false === $randomizer ) { 8275 try { 8276 random_int( 0, 15705 ); 8277 $backup_randomizer = 'random_int'; 8278 } catch ( Exception $e ) { 8279 $backup_randomizer = 'mt_rand'; 8280 } 8281 $randomizer = $backup_randomizer; 8282 } 8283 8284 /** @var lowercase-string&non-falsy-string $uuid The %x conversion only produces lowercase hex digits. */ 8285 $uuid = sprintf( 8286 '%04x%04x-%04x-%04x-%04x-%04x%04x%04x', 8287 $randomizer( 0, 0xffff ), 8288 $randomizer( 0, 0xffff ), 8289 $randomizer( 0, 0xffff ), 8290 $randomizer( 0, 0x0fff ) | 0x4000, 8291 $randomizer( 0, 0x3fff ) | 0x8000, 8292 $randomizer( 0, 0xffff ), 8293 $randomizer( 0, 0xffff ), 8294 $randomizer( 0, 0xffff ) 8295 ); 8296 8297 return $uuid; 8298 } 8299 8300 /** 8301 * Validates that a UUID is valid. 8302 * 8303 * @since 4.9.0 8304 * 8305 * @param mixed $uuid UUID to check. 8306 * @param int $version Specify which version of UUID to check against. Default is none, 8307 * to accept any UUID version. Otherwise, only version allowed is `4`. 8308 * @return bool The string is a valid UUID or false on failure. 8309 * 8310 * @phpstan-assert-if-true =lowercase-string&non-falsy-string $uuid 8311 * @phpstan-return ( $version is 4|null ? bool : false ) 8312 */ 8313 function wp_is_uuid( $uuid, $version = null ) { 8314 8315 if ( ! is_string( $uuid ) ) { 8316 return false; 8317 } 8318 8319 if ( is_numeric( $version ) ) { 8320 if ( 4 !== (int) $version ) { 8321 _doing_it_wrong( __FUNCTION__, __( 'Only UUID V4 is supported at this time.' ), '4.9.0' ); 8322 return false; 8323 } 8324 $regex = '/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/'; 8325 } else { 8326 $regex = '/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/'; 8327 } 8328 8329 return (bool) preg_match( $regex, $uuid ); 8330 } 8331 8332 /** 8333 * Gets unique ID. 8334 * 8335 * This is a PHP implementation of Underscore's uniqueId method. A static variable 8336 * contains an integer that is incremented with each call. This number is returned 8337 * with the optional prefix. As such the returned value is not universally unique, 8338 * but it is unique across the life of the PHP process. 8339 * 8340 * @since 5.0.3 8341 * 8342 * @param string $prefix Prefix for the returned ID. 8343 * @return string Unique ID. 8344 * 8345 * @phpstan-return ( 8346 * ( $prefix is ''|numeric-string ? numeric-string : string ) 8347 * & non-falsy-string 8348 * & ( $prefix is lowercase-string ? lowercase-string : string ) 8349 * ) 8350 */ 8351 function wp_unique_id( $prefix = '' ) { 8352 static $id_counter = 0; 8353 return $prefix . (string) ++$id_counter; 8354 } 8355 8356 /** 8357 * Generates an incremental ID that is independent per each different prefix. 8358 * 8359 * It is similar to `wp_unique_id`, but each prefix has its own internal ID 8360 * counter to make each prefix independent from each other. The ID starts at 1 8361 * and increments on each call. The returned value is not universally unique, 8362 * but it is unique across the life of the PHP process and it's stable per 8363 * prefix. 8364 * 8365 * @since 6.4.0 8366 * 8367 * @param string $prefix Optional. Prefix for the returned ID. Default empty string. 8368 * @return string Incremental ID per prefix. 8369 * 8370 * @phpstan-return ( 8371 * ( $prefix is ''|numeric-string ? numeric-string : string ) 8372 * & non-falsy-string 8373 * & ( $prefix is lowercase-string ? lowercase-string : string ) 8374 * ) 8375 */ 8376 function wp_unique_prefixed_id( $prefix = '' ) { 8377 static $id_counters = array(); 8378 8379 if ( ! is_string( $prefix ) ) { 8380 wp_trigger_error( 8381 __FUNCTION__, 8382 sprintf( 'The prefix must be a string. "%s" data type given.', gettype( $prefix ) ) 8383 ); 8384 $prefix = ''; 8385 } 8386 8387 if ( ! isset( $id_counters[ $prefix ] ) ) { 8388 $id_counters[ $prefix ] = 0; 8389 } 8390 8391 $id = ++$id_counters[ $prefix ]; 8392 8393 return $prefix . (string) $id; 8394 } 8395 8396 /** 8397 * Generates a unique ID based on the structure and values of a given array. 8398 * 8399 * This function serializes the array into a JSON string and generates a hash 8400 * that serves as a unique identifier. Optionally, a prefix can be added to 8401 * the generated ID for context or categorization. 8402 * 8403 * @since 6.8.0 8404 * 8405 * @param array $data The input array to generate an ID from. 8406 * @param string $prefix Optional. A prefix to prepend to the generated ID. Default empty string. 8407 * @return string The generated unique ID for the array. 8408 * 8409 * @phpstan-param non-empty-array $data 8410 * @phpstan-return ( $prefix is lowercase-string ? lowercase-string&non-falsy-string : non-falsy-string ) 8411 */ 8412 function wp_unique_id_from_values( array $data, string $prefix = '' ): string { 8413 if ( empty( $data ) ) { 8414 _doing_it_wrong( 8415 __FUNCTION__, 8416 sprintf( 8417 /* translators: %s: The parameter name. */ 8418 __( 'The %s parameter must not be empty.' ), 8419 '$data' 8420 ), 8421 '6.8.0' 8422 ); 8423 } 8424 8425 $serialized = wp_json_encode( $data ); 8426 $hash = substr( md5( $serialized ), 0, 8 ); 8427 8428 return $prefix . $hash; 8429 } 8430 8431 /** 8432 * Gets last changed date for the specified cache group. 8433 * 8434 * @since 4.7.0 8435 * 8436 * @param string $group Where the cache contents are grouped. 8437 * @return string UNIX timestamp with microseconds representing when the group was last changed. 8438 */ 8439 function wp_cache_get_last_changed( $group ) { 8440 $last_changed = wp_cache_get( 'last_changed', $group ); 8441 8442 if ( $last_changed ) { 8443 return $last_changed; 8444 } 8445 8446 return wp_cache_set_last_changed( $group ); 8447 } 8448 8449 /** 8450 * Sets last changed date for the specified cache group to now. 8451 * 8452 * @since 6.3.0 8453 * 8454 * @param string $group Where the cache contents are grouped. 8455 * @return string UNIX timestamp when the group was last changed. 8456 */ 8457 function wp_cache_set_last_changed( $group ) { 8458 $previous_time = wp_cache_get( 'last_changed', $group ); 8459 8460 $time = microtime(); 8461 8462 wp_cache_set( 'last_changed', $time, $group ); 8463 8464 /** 8465 * Fires after a cache group `last_changed` time is updated. 8466 * This may occur multiple times per page load and registered 8467 * actions must be performant. 8468 * 8469 * @since 6.3.0 8470 * 8471 * @param string $group The cache group name. 8472 * @param string $time The new last changed time (msec sec). 8473 * @param string|false $previous_time The previous last changed time. False if not previously set. 8474 */ 8475 do_action( 'wp_cache_set_last_changed', $group, $time, $previous_time ); 8476 8477 return $time; 8478 } 8479 8480 /** 8481 * Sends an email to the old site admin email address when the site admin email address changes. 8482 * 8483 * @since 4.9.0 8484 * 8485 * @param string $old_email The old site admin email address. 8486 * @param string $new_email The new site admin email address. 8487 * @param string $option_name The relevant database option name. 8488 */ 8489 function wp_site_admin_email_change_notification( $old_email, $new_email, $option_name ) { 8490 $send = true; 8491 8492 // Don't send the notification for an empty email address or the default 'admin_email' value. 8493 if ( empty( $old_email ) || 'you@example.com' === $old_email ) { 8494 $send = false; 8495 } 8496 8497 /** 8498 * Filters whether to send the site admin email change notification email. 8499 * 8500 * @since 4.9.0 8501 * 8502 * @param bool $send Whether to send the email notification. 8503 * @param string $old_email The old site admin email address. 8504 * @param string $new_email The new site admin email address. 8505 */ 8506 $send = apply_filters( 'send_site_admin_email_change_email', $send, $old_email, $new_email ); 8507 8508 if ( ! $send ) { 8509 return; 8510 } 8511 8512 /* translators: Do not translate OLD_EMAIL, NEW_EMAIL, SITENAME, SITEURL: those are placeholders. */ 8513 $email_change_text = __( 8514 'Hi, 8515 8516 This notice confirms that the admin email address was changed on ###SITENAME###. 8517 8518 The new admin email address is ###NEW_EMAIL###. 8519 8520 This email has been sent to ###OLD_EMAIL### 8521 8522 Regards, 8523 All at ###SITENAME### 8524 ###SITEURL###' 8525 ); 8526 8527 $email_change_email = array( 8528 'to' => $old_email, 8529 /* translators: Site admin email change notification email subject. %s: Site title. */ 8530 'subject' => __( '[%s] Admin Email Changed' ), 8531 'message' => $email_change_text, 8532 'headers' => '', 8533 ); 8534 8535 // Get site name. 8536 $site_name = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ); 8537 8538 /** 8539 * Filters the contents of the email notification sent when the site admin email address is changed. 8540 * 8541 * @since 4.9.0 8542 * 8543 * @param array $email_change_email { 8544 * Used to build wp_mail(). 8545 * 8546 * @type string $to The intended recipient. 8547 * @type string $subject The subject of the email. 8548 * @type string $message The content of the email. 8549 * The following strings have a special meaning and will get replaced dynamically: 8550 * - `###OLD_EMAIL###` The old site admin email address. 8551 * - `###NEW_EMAIL###` The new site admin email address. 8552 * - `###SITENAME###` The name of the site. 8553 * - `###SITEURL###` The URL to the site. 8554 * @type string $headers Headers. 8555 * } 8556 * @param string $old_email The old site admin email address. 8557 * @param string $new_email The new site admin email address. 8558 */ 8559 $email_change_email = apply_filters( 'site_admin_email_change_email', $email_change_email, $old_email, $new_email ); 8560 8561 $email_change_email['message'] = str_replace( '###OLD_EMAIL###', $old_email, $email_change_email['message'] ); 8562 $email_change_email['message'] = str_replace( '###NEW_EMAIL###', $new_email, $email_change_email['message'] ); 8563 $email_change_email['message'] = str_replace( '###SITENAME###', $site_name, $email_change_email['message'] ); 8564 $email_change_email['message'] = str_replace( '###SITEURL###', home_url(), $email_change_email['message'] ); 8565 8566 wp_mail( 8567 $email_change_email['to'], 8568 sprintf( 8569 $email_change_email['subject'], 8570 $site_name 8571 ), 8572 $email_change_email['message'], 8573 $email_change_email['headers'] 8574 ); 8575 } 8576 8577 /** 8578 * Returns an anonymized IPv4 or IPv6 address. 8579 * 8580 * @since 4.9.6 Abstracted from `WP_Community_Events::get_unsafe_client_ip()`. 8581 * 8582 * @param string $ip_addr The IPv4 or IPv6 address to be anonymized. 8583 * @param bool $ipv6_fallback Optional. Whether to return the original IPv6 address if the needed functions 8584 * to anonymize it are not present. Default false, return `::` (unspecified address). 8585 * @return string The anonymized IP address. 8586 */ 8587 function wp_privacy_anonymize_ip( $ip_addr, $ipv6_fallback = false ) { 8588 if ( empty( $ip_addr ) ) { 8589 return '0.0.0.0'; 8590 } 8591 8592 // Detect what kind of IP address this is. 8593 $ip_prefix = ''; 8594 $is_ipv6 = substr_count( $ip_addr, ':' ) > 1; 8595 $is_ipv4 = ( 3 === substr_count( $ip_addr, '.' ) ); 8596 8597 if ( $is_ipv6 && $is_ipv4 ) { 8598 // IPv6 compatibility mode, temporarily strip the IPv6 part, and treat it like IPv4. 8599 $ip_prefix = '::ffff:'; 8600 $ip_addr = preg_replace( '/^\[?[0-9a-f:]*:/i', '', $ip_addr ); 8601 $ip_addr = str_replace( ']', '', $ip_addr ); 8602 $is_ipv6 = false; 8603 } 8604 8605 if ( $is_ipv6 ) { 8606 // IPv6 addresses will always be enclosed in [] if there's a port. 8607 $left_bracket = strpos( $ip_addr, '[' ); 8608 $right_bracket = strpos( $ip_addr, ']' ); 8609 $percent = strpos( $ip_addr, '%' ); 8610 $netmask = 'ffff:ffff:ffff:ffff:0000:0000:0000:0000'; 8611 8612 // Strip the port (and [] from IPv6 addresses), if they exist. 8613 if ( false !== $left_bracket && false !== $right_bracket ) { 8614 $ip_addr = substr( $ip_addr, $left_bracket + 1, $right_bracket - $left_bracket - 1 ); 8615 } elseif ( false !== $left_bracket || false !== $right_bracket ) { 8616 // The IP has one bracket, but not both, so it's malformed. 8617 return '::'; 8618 } 8619 8620 // Strip the reachability scope. 8621 if ( false !== $percent ) { 8622 $ip_addr = substr( $ip_addr, 0, $percent ); 8623 } 8624 8625 // No invalid characters should be left. 8626 if ( preg_match( '/[^0-9a-f:]/i', $ip_addr ) ) { 8627 return '::'; 8628 } 8629 8630 // Partially anonymize the IP by reducing it to the corresponding network ID. 8631 if ( function_exists( 'inet_pton' ) && function_exists( 'inet_ntop' ) ) { 8632 $ip_addr = inet_ntop( inet_pton( $ip_addr ) & inet_pton( $netmask ) ); 8633 if ( false === $ip_addr ) { 8634 return '::'; 8635 } 8636 } elseif ( ! $ipv6_fallback ) { 8637 return '::'; 8638 } 8639 } elseif ( $is_ipv4 ) { 8640 // Strip any port and partially anonymize the IP. 8641 $last_octet_position = strrpos( $ip_addr, '.' ); 8642 $ip_addr = substr( $ip_addr, 0, $last_octet_position ) . '.0'; 8643 } else { 8644 return '0.0.0.0'; 8645 } 8646 8647 // Restore the IPv6 prefix to compatibility mode addresses. 8648 return $ip_prefix . $ip_addr; 8649 } 8650 8651 /** 8652 * Returns uniform "anonymous" data by type. 8653 * 8654 * @since 4.9.6 8655 * 8656 * @param string $type The type of data to be anonymized. 8657 * @param string $data Optional. The data to be anonymized. Default empty string. 8658 * @return string The anonymous data for the requested type. 8659 */ 8660 function wp_privacy_anonymize_data( $type, $data = '' ) { 8661 8662 switch ( $type ) { 8663 case 'email': 8664 $anonymous = 'deleted@site.invalid'; 8665 break; 8666 case 'url': 8667 $anonymous = 'https://site.invalid'; 8668 break; 8669 case 'ip': 8670 $anonymous = wp_privacy_anonymize_ip( $data ); 8671 break; 8672 case 'date': 8673 $anonymous = '0000-00-00 00:00:00'; 8674 break; 8675 case 'text': 8676 /* translators: Deleted text. */ 8677 $anonymous = __( '[deleted]' ); 8678 break; 8679 case 'longtext': 8680 /* translators: Deleted long text. */ 8681 $anonymous = __( 'This content was deleted by the author.' ); 8682 break; 8683 default: 8684 $anonymous = ''; 8685 break; 8686 } 8687 8688 /** 8689 * Filters the anonymous data for each type. 8690 * 8691 * @since 4.9.6 8692 * 8693 * @param string $anonymous Anonymized data. 8694 * @param string $type Type of the data. 8695 * @param string $data Original data. 8696 */ 8697 return apply_filters( 'wp_privacy_anonymize_data', $anonymous, $type, $data ); 8698 } 8699 8700 /** 8701 * Returns the directory used to store personal data export files. 8702 * 8703 * @since 4.9.6 8704 * 8705 * @see wp_privacy_exports_url 8706 * 8707 * @return string Exports directory. 8708 */ 8709 function wp_privacy_exports_dir() { 8710 $upload_dir = wp_upload_dir(); 8711 $exports_dir = trailingslashit( $upload_dir['basedir'] ) . 'wp-personal-data-exports/'; 8712 8713 /** 8714 * Filters the directory used to store personal data export files. 8715 * 8716 * @since 4.9.6 8717 * @since 5.5.0 Exports now use relative paths, so changes to the directory 8718 * via this filter should be reflected on the server. 8719 * 8720 * @param string $exports_dir Exports directory. 8721 */ 8722 return apply_filters( 'wp_privacy_exports_dir', $exports_dir ); 8723 } 8724 8725 /** 8726 * Returns the URL of the directory used to store personal data export files. 8727 * 8728 * @since 4.9.6 8729 * 8730 * @see wp_privacy_exports_dir 8731 * 8732 * @return string Exports directory URL. 8733 */ 8734 function wp_privacy_exports_url() { 8735 $upload_dir = wp_upload_dir(); 8736 $exports_url = trailingslashit( $upload_dir['baseurl'] ) . 'wp-personal-data-exports/'; 8737 8738 /** 8739 * Filters the URL of the directory used to store personal data export files. 8740 * 8741 * @since 4.9.6 8742 * @since 5.5.0 Exports now use relative paths, so changes to the directory URL 8743 * via this filter should be reflected on the server. 8744 * 8745 * @param string $exports_url Exports directory URL. 8746 */ 8747 return apply_filters( 'wp_privacy_exports_url', $exports_url ); 8748 } 8749 8750 /** 8751 * Schedules a `WP_Cron` job to delete expired export files. 8752 * 8753 * @since 4.9.6 8754 */ 8755 function wp_schedule_delete_old_privacy_export_files() { 8756 if ( wp_installing() ) { 8757 return; 8758 } 8759 8760 if ( ! wp_next_scheduled( 'wp_privacy_delete_old_export_files' ) ) { 8761 wp_schedule_event( time(), 'hourly', 'wp_privacy_delete_old_export_files' ); 8762 } 8763 } 8764 8765 /** 8766 * Schedules a WP-Cron job to clean up personal data requests. 8767 * 8768 * @since 7.1.0 8769 * 8770 * @see wp_privacy_personal_data_cleanup_requests() 8771 */ 8772 function wp_schedule_personal_data_cleanup_requests(): void { 8773 if ( wp_installing() ) { 8774 return; 8775 } 8776 8777 if ( ! wp_next_scheduled( 'wp_privacy_personal_data_cleanup_requests' ) ) { 8778 wp_schedule_event( time(), 'daily', 'wp_privacy_personal_data_cleanup_requests' ); 8779 } 8780 } 8781 8782 /** 8783 * Fires the personal data cleanup requests handler during cron. 8784 * 8785 * Loads the admin privacy tools file if needed (e.g. during cron, where 8786 * wp-admin/includes/privacy-tools.php is not loaded automatically). 8787 * 8788 * @since 7.1.0 8789 */ 8790 function wp_privacy_personal_data_cleanup_requests(): void { 8791 if ( ! function_exists( '_wp_personal_data_cleanup_requests' ) ) { 8792 require_once ABSPATH . 'wp-admin/includes/privacy-tools.php'; 8793 } 8794 _wp_personal_data_cleanup_requests(); 8795 } 8796 8797 /** 8798 * Cleans up export files older than three days old. 8799 * 8800 * The export files are stored in `wp-content/uploads`, and are therefore publicly 8801 * accessible. A CSPRN is appended to the filename to mitigate the risk of an 8802 * unauthorized person downloading the file, but it is still possible. Deleting 8803 * the file after the data subject has had a chance to delete it adds an additional 8804 * layer of protection. 8805 * 8806 * @since 4.9.6 8807 */ 8808 function wp_privacy_delete_old_export_files() { 8809 $exports_dir = wp_privacy_exports_dir(); 8810 if ( ! is_dir( $exports_dir ) ) { 8811 return; 8812 } 8813 8814 require_once ABSPATH . 'wp-admin/includes/file.php'; 8815 $export_files = list_files( $exports_dir, 100, array( 'index.php' ) ); 8816 8817 /** 8818 * Filters the lifetime, in seconds, of a personal data export file. 8819 * 8820 * By default, the lifetime is 3 days. Once the file reaches that age, it will automatically 8821 * be deleted by a cron job. 8822 * 8823 * @since 4.9.6 8824 * 8825 * @param int $expiration The expiration age of the export, in seconds. 8826 */ 8827 $expiration = apply_filters( 'wp_privacy_export_expiration', 3 * DAY_IN_SECONDS ); 8828 8829 foreach ( (array) $export_files as $export_file ) { 8830 $file_age_in_seconds = time() - filemtime( $export_file ); 8831 8832 if ( $expiration < $file_age_in_seconds ) { 8833 unlink( $export_file ); 8834 } 8835 } 8836 } 8837 8838 /** 8839 * Gets the URL to learn more about updating the PHP version the site is running on. 8840 * 8841 * This URL can be overridden by specifying an environment variable `WP_UPDATE_PHP_URL` or by using the 8842 * {@see 'wp_update_php_url'} filter. Providing an empty string is not allowed and will result in the 8843 * default URL being used. Furthermore the page the URL links to should preferably be localized in the 8844 * site language. 8845 * 8846 * @since 5.1.0 8847 * 8848 * @return string URL to learn more about updating PHP. 8849 */ 8850 function wp_get_update_php_url() { 8851 $default_url = wp_get_default_update_php_url(); 8852 8853 $update_url = $default_url; 8854 if ( false !== getenv( 'WP_UPDATE_PHP_URL' ) ) { 8855 $update_url = getenv( 'WP_UPDATE_PHP_URL' ); 8856 } 8857 8858 /** 8859 * Filters the URL to learn more about updating the PHP version the site is running on. 8860 * 8861 * Providing an empty string is not allowed and will result in the default URL being used. Furthermore 8862 * the page the URL links to should preferably be localized in the site language. 8863 * 8864 * @since 5.1.0 8865 * 8866 * @param string $update_url URL to learn more about updating PHP. 8867 */ 8868 $update_url = apply_filters( 'wp_update_php_url', $update_url ); 8869 8870 if ( empty( $update_url ) ) { 8871 $update_url = $default_url; 8872 } 8873 8874 return $update_url; 8875 } 8876 8877 /** 8878 * Gets the default URL to learn more about updating the PHP version the site is running on. 8879 * 8880 * Do not use this function to retrieve this URL. Instead, use {@see wp_get_update_php_url()} when relying on the URL. 8881 * This function does not allow modifying the returned URL, and is only used to compare the actually used URL with the 8882 * default one. 8883 * 8884 * @since 5.1.0 8885 * @access private 8886 * 8887 * @return string Default URL to learn more about updating PHP. 8888 */ 8889 function wp_get_default_update_php_url() { 8890 return _x( 'https://wordpress.org/support/update-php/', 'localized PHP upgrade information page' ); 8891 } 8892 8893 /** 8894 * Prints the default annotation for the web host altering the "Update PHP" page URL. 8895 * 8896 * This function is to be used after {@see wp_get_update_php_url()} to display a consistent 8897 * annotation if the web host has altered the default "Update PHP" page URL. 8898 * 8899 * @since 5.1.0 8900 * @since 5.2.0 Added the `$before` and `$after` parameters. 8901 * @since 6.4.0 Added the `$display` parameter. 8902 * 8903 * @param string $before Markup to output before the annotation. Default `<p class="description">`. 8904 * @param string $after Markup to output after the annotation. Default `</p>`. 8905 * @param bool $display Whether to echo or return the markup. Default `true` for echo. 8906 * @return string|null|void Update PHP page annotation when `$display` is false, null when 8907 * no annotation is available. Nothing otherwise. 8908 * @phpstan-return ( $display is true ? void : string|null ) 8909 */ 8910 function wp_update_php_annotation( $before = '<p class="description">', $after = '</p>', $display = true ) { 8911 $annotation = wp_get_update_php_annotation(); 8912 8913 if ( ! $annotation ) { 8914 return null; 8915 } 8916 8917 if ( ! $display ) { 8918 return $before . $annotation . $after; 8919 } 8920 8921 echo $before . $annotation . $after; 8922 } 8923 8924 /** 8925 * Returns the default annotation for the web hosting altering the "Update PHP" page URL. 8926 * 8927 * This function is to be used after {@see wp_get_update_php_url()} to return a consistent 8928 * annotation if the web host has altered the default "Update PHP" page URL. 8929 * 8930 * @since 5.2.0 8931 * 8932 * @return string Update PHP page annotation. An empty string if no custom URLs are provided. 8933 */ 8934 function wp_get_update_php_annotation() { 8935 $update_url = wp_get_update_php_url(); 8936 $default_url = wp_get_default_update_php_url(); 8937 8938 if ( $update_url === $default_url ) { 8939 return ''; 8940 } 8941 8942 $annotation = sprintf( 8943 /* translators: %s: Default Update PHP page URL. */ 8944 __( '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>.' ), 8945 esc_url( $default_url ) 8946 ); 8947 8948 return $annotation; 8949 } 8950 8951 /** 8952 * Gets the URL for directly updating the PHP version the site is running on. 8953 * 8954 * A URL will only be returned if the `WP_DIRECT_UPDATE_PHP_URL` environment variable is specified or 8955 * by using the {@see 'wp_direct_php_update_url'} filter. This allows hosts to send users directly to 8956 * the page where they can update PHP to a newer version. 8957 * 8958 * @since 5.1.1 8959 * 8960 * @return string URL for directly updating PHP or empty string. 8961 */ 8962 function wp_get_direct_php_update_url() { 8963 $direct_update_url = ''; 8964 8965 if ( false !== getenv( 'WP_DIRECT_UPDATE_PHP_URL' ) ) { 8966 $direct_update_url = getenv( 'WP_DIRECT_UPDATE_PHP_URL' ); 8967 } 8968 8969 /** 8970 * Filters the URL for directly updating the PHP version the site is running on from the host. 8971 * 8972 * @since 5.1.1 8973 * 8974 * @param string $direct_update_url URL for directly updating PHP. 8975 */ 8976 $direct_update_url = apply_filters( 'wp_direct_php_update_url', $direct_update_url ); 8977 8978 return $direct_update_url; 8979 } 8980 8981 /** 8982 * Displays a button directly linking to a PHP update process. 8983 * 8984 * This provides hosts with a way for users to be sent directly to their PHP update process. 8985 * 8986 * The button is only displayed if a URL is returned by `wp_get_direct_php_update_url()`. 8987 * 8988 * @since 5.1.1 8989 */ 8990 function wp_direct_php_update_button() { 8991 $direct_update_url = wp_get_direct_php_update_url(); 8992 8993 if ( empty( $direct_update_url ) ) { 8994 return; 8995 } 8996 8997 echo '<p class="button-container">'; 8998 printf( 8999 '<a class="button button-primary" href="%1$s" target="_blank">%2$s<span class="screen-reader-text"> %3$s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a>', 9000 esc_url( $direct_update_url ), 9001 __( 'Update PHP' ), 9002 /* translators: Hidden accessibility text. */ 9003 __( '(opens in a new tab)' ) 9004 ); 9005 echo '</p>'; 9006 } 9007 9008 /** 9009 * Gets the URL to learn more about updating the site to use HTTPS. 9010 * 9011 * This URL can be overridden by specifying an environment variable `WP_UPDATE_HTTPS_URL` or by using the 9012 * {@see 'wp_update_https_url'} filter. Providing an empty string is not allowed and will result in the 9013 * default URL being used. Furthermore the page the URL links to should preferably be localized in the 9014 * site language. 9015 * 9016 * @since 5.7.0 9017 * 9018 * @return string URL to learn more about updating to HTTPS. 9019 */ 9020 function wp_get_update_https_url() { 9021 $default_url = wp_get_default_update_https_url(); 9022 9023 $update_url = $default_url; 9024 if ( false !== getenv( 'WP_UPDATE_HTTPS_URL' ) ) { 9025 $update_url = getenv( 'WP_UPDATE_HTTPS_URL' ); 9026 } 9027 9028 /** 9029 * Filters the URL to learn more about updating the HTTPS version the site is running on. 9030 * 9031 * Providing an empty string is not allowed and will result in the default URL being used. Furthermore 9032 * the page the URL links to should preferably be localized in the site language. 9033 * 9034 * @since 5.7.0 9035 * 9036 * @param string $update_url URL to learn more about updating HTTPS. 9037 */ 9038 $update_url = apply_filters( 'wp_update_https_url', $update_url ); 9039 if ( empty( $update_url ) ) { 9040 $update_url = $default_url; 9041 } 9042 9043 return $update_url; 9044 } 9045 9046 /** 9047 * Gets the default URL to learn more about updating the site to use HTTPS. 9048 * 9049 * Do not use this function to retrieve this URL. Instead, use {@see wp_get_update_https_url()} when relying on the URL. 9050 * This function does not allow modifying the returned URL, and is only used to compare the actually used URL with the 9051 * default one. 9052 * 9053 * @since 5.7.0 9054 * @access private 9055 * 9056 * @return string Default URL to learn more about updating to HTTPS. 9057 */ 9058 function wp_get_default_update_https_url() { 9059 /* translators: Documentation explaining HTTPS and why it should be used. */ 9060 return __( 'https://developer.wordpress.org/advanced-administration/security/https/' ); 9061 } 9062 9063 /** 9064 * Gets the URL for directly updating the site to use HTTPS. 9065 * 9066 * A URL will only be returned if the `WP_DIRECT_UPDATE_HTTPS_URL` environment variable is specified or 9067 * by using the {@see 'wp_direct_update_https_url'} filter. This allows hosts to send users directly to 9068 * the page where they can update their site to use HTTPS. 9069 * 9070 * @since 5.7.0 9071 * 9072 * @return string URL for directly updating to HTTPS or empty string. 9073 */ 9074 function wp_get_direct_update_https_url() { 9075 $direct_update_url = ''; 9076 9077 if ( false !== getenv( 'WP_DIRECT_UPDATE_HTTPS_URL' ) ) { 9078 $direct_update_url = getenv( 'WP_DIRECT_UPDATE_HTTPS_URL' ); 9079 } 9080 9081 /** 9082 * Filters the URL for directly updating the PHP version the site is running on from the host. 9083 * 9084 * @since 5.7.0 9085 * 9086 * @param string $direct_update_url URL for directly updating PHP. 9087 */ 9088 $direct_update_url = apply_filters( 'wp_direct_update_https_url', $direct_update_url ); 9089 9090 return $direct_update_url; 9091 } 9092 9093 /** 9094 * Gets the size of a directory. 9095 * 9096 * A helper function that is used primarily to check whether 9097 * a blog has exceeded its allowed upload space. 9098 * 9099 * @since MU (3.0.0) 9100 * @since 5.2.0 $max_execution_time parameter added. 9101 * 9102 * @param string $directory Full path of a directory. 9103 * @param int $max_execution_time Maximum time to run before giving up. In seconds. 9104 * The timeout is global and is measured from the moment WordPress started to load. 9105 * @return int|false|null Size in bytes if a valid directory. False if not. Null if timeout. 9106 */ 9107 function get_dirsize( $directory, $max_execution_time = null ) { 9108 9109 /* 9110 * Exclude individual site directories from the total when checking the main site of a network, 9111 * as they are subdirectories and should not be counted. 9112 */ 9113 if ( is_multisite() && is_main_site() ) { 9114 $size = recurse_dirsize( $directory, $directory . '/sites', $max_execution_time ); 9115 } else { 9116 $size = recurse_dirsize( $directory, null, $max_execution_time ); 9117 } 9118 9119 return $size; 9120 } 9121 9122 /** 9123 * Gets the size of a directory recursively. 9124 * 9125 * Used by get_dirsize() to get a directory size when it contains other directories. 9126 * 9127 * @since MU (3.0.0) 9128 * @since 4.3.0 The `$exclude` parameter was added. 9129 * @since 5.2.0 The `$max_execution_time` parameter was added. 9130 * @since 5.6.0 The `$directory_cache` parameter was added. 9131 * 9132 * @param string $directory Full path of a directory. 9133 * @param string|string[] $exclude Optional. Full path of a subdirectory to exclude from the total, 9134 * or array of paths. Expected without trailing slash(es). 9135 * Default null. 9136 * @param int $max_execution_time Optional. Maximum time to run before giving up. In seconds. 9137 * The timeout is global and is measured from the moment 9138 * WordPress started to load. Defaults to the value of 9139 * `max_execution_time` PHP setting. 9140 * @param array $directory_cache Optional. Array of cached directory paths. 9141 * Defaults to the value of `dirsize_cache` transient. 9142 * @return int|false|null Size in bytes if a valid directory. False if not. Null if timeout. 9143 */ 9144 function recurse_dirsize( $directory, $exclude = null, $max_execution_time = null, &$directory_cache = null ) { 9145 $directory = untrailingslashit( $directory ); 9146 $save_cache = false; 9147 9148 if ( ! isset( $directory_cache ) ) { 9149 $directory_cache = get_transient( 'dirsize_cache' ); 9150 $save_cache = true; 9151 } 9152 9153 if ( isset( $directory_cache[ $directory ] ) && is_int( $directory_cache[ $directory ] ) ) { 9154 return $directory_cache[ $directory ]; 9155 } 9156 9157 if ( ! file_exists( $directory ) || ! is_dir( $directory ) || ! is_readable( $directory ) ) { 9158 return false; 9159 } 9160 9161 if ( 9162 ( is_string( $exclude ) && $directory === $exclude ) || 9163 ( is_array( $exclude ) && in_array( $directory, $exclude, true ) ) 9164 ) { 9165 return false; 9166 } 9167 9168 if ( null === $max_execution_time ) { 9169 // Keep the previous behavior but attempt to prevent fatal errors from timeout if possible. 9170 $max_execution_time = ini_get( 'max_execution_time' ); 9171 9172 // Leave 1 second "buffer" for other operations if $max_execution_time has reasonable value. 9173 if ( $max_execution_time > 10 ) { 9174 $max_execution_time -= 1; 9175 } 9176 } 9177 9178 /** 9179 * Filters the amount of storage space used by one directory and all its children, in megabytes. 9180 * 9181 * Return the actual used space to short-circuit the recursive PHP file size calculation 9182 * and use something else, like a CDN API or native operating system tools for better performance. 9183 * 9184 * @since 5.6.0 9185 * 9186 * @param int|false $space_used The amount of used space, in bytes. Default false. 9187 * @param string $directory Full path of a directory. 9188 * @param string|string[]|null $exclude Full path of a subdirectory to exclude from the total, 9189 * or array of paths. 9190 * @param int $max_execution_time Maximum time to run before giving up. In seconds. 9191 * @param array $directory_cache Array of cached directory paths. 9192 */ 9193 $size = apply_filters( 'pre_recurse_dirsize', false, $directory, $exclude, $max_execution_time, $directory_cache ); 9194 9195 if ( false === $size ) { 9196 $size = 0; 9197 9198 $handle = opendir( $directory ); 9199 if ( $handle ) { 9200 while ( ( $file = readdir( $handle ) ) !== false ) { 9201 $path = $directory . '/' . $file; 9202 if ( '.' !== $file && '..' !== $file ) { 9203 if ( is_file( $path ) ) { 9204 $size += filesize( $path ); 9205 } elseif ( is_dir( $path ) ) { 9206 $handlesize = recurse_dirsize( $path, $exclude, $max_execution_time, $directory_cache ); 9207 if ( $handlesize > 0 ) { 9208 $size += $handlesize; 9209 } 9210 } 9211 9212 if ( $max_execution_time > 0 && 9213 ( microtime( true ) - WP_START_TIMESTAMP ) > $max_execution_time 9214 ) { 9215 // Time exceeded. Give up instead of risking a fatal timeout. 9216 $size = null; 9217 break; 9218 } 9219 } 9220 } 9221 closedir( $handle ); 9222 } 9223 } 9224 9225 if ( ! is_array( $directory_cache ) ) { 9226 $directory_cache = array(); 9227 } 9228 9229 $directory_cache[ $directory ] = $size; 9230 9231 // Only write the transient on the top level call and not on recursive calls. 9232 if ( $save_cache ) { 9233 $expiration = ( wp_using_ext_object_cache() ) ? 0 : 10 * YEAR_IN_SECONDS; 9234 set_transient( 'dirsize_cache', $directory_cache, $expiration ); 9235 } 9236 9237 return $size; 9238 } 9239 9240 /** 9241 * Cleans directory size cache used by recurse_dirsize(). 9242 * 9243 * Removes the current directory and all parent directories from the `dirsize_cache` transient. 9244 * 9245 * @since 5.6.0 9246 * @since 5.9.0 Added input validation with a notice for invalid input. 9247 * 9248 * @param string $path Full path of a directory or file. 9249 */ 9250 function clean_dirsize_cache( $path ) { 9251 if ( ! is_string( $path ) || empty( $path ) ) { 9252 wp_trigger_error( 9253 '', 9254 sprintf( 9255 /* translators: 1: Function name, 2: A variable type, like "boolean" or "integer". */ 9256 __( '%1$s only accepts a non-empty path string, received %2$s.' ), 9257 '<code>clean_dirsize_cache()</code>', 9258 '<code>' . gettype( $path ) . '</code>' 9259 ) 9260 ); 9261 return; 9262 } 9263 9264 $directory_cache = get_transient( 'dirsize_cache' ); 9265 9266 if ( empty( $directory_cache ) ) { 9267 return; 9268 } 9269 9270 $expiration = ( wp_using_ext_object_cache() ) ? 0 : 10 * YEAR_IN_SECONDS; 9271 if ( 9272 ! str_contains( $path, '/' ) && 9273 ! str_contains( $path, '\\' ) 9274 ) { 9275 unset( $directory_cache[ $path ] ); 9276 set_transient( 'dirsize_cache', $directory_cache, $expiration ); 9277 return; 9278 } 9279 9280 $last_path = null; 9281 $path = untrailingslashit( $path ); 9282 unset( $directory_cache[ $path ] ); 9283 9284 while ( 9285 $last_path !== $path && 9286 DIRECTORY_SEPARATOR !== $path && 9287 '.' !== $path && 9288 '..' !== $path 9289 ) { 9290 $last_path = $path; 9291 $path = dirname( $path ); 9292 unset( $directory_cache[ $path ] ); 9293 } 9294 9295 set_transient( 'dirsize_cache', $directory_cache, $expiration ); 9296 } 9297 9298 /** 9299 * Returns the current WordPress version. 9300 * 9301 * Returns an unmodified value of `$wp_version`. Some plugins modify the global 9302 * in an attempt to improve security through obscurity. This practice can cause 9303 * errors in WordPress, so the ability to get an unmodified version is needed. 9304 * 9305 * @since 6.7.0 9306 * 9307 * @return string The current WordPress version. 9308 * 9309 * @phpstan-return non-falsy-string 9310 */ 9311 function wp_get_wp_version() { 9312 static $wp_version; 9313 9314 if ( ! isset( $wp_version ) ) { 9315 require ABSPATH . WPINC . '/version.php'; 9316 } 9317 9318 /** @var non-falsy-string $wp_version */ 9319 return $wp_version; 9320 } 9321 9322 /** 9323 * Checks compatibility with the current WordPress version. 9324 * 9325 * @since 5.2.0 9326 * 9327 * @global string $_wp_tests_wp_version The WordPress version string. Used only in Core tests. 9328 * 9329 * @param string $required Minimum required WordPress version. 9330 * @return bool True if required version is compatible or empty, false if not. 9331 */ 9332 function is_wp_version_compatible( $required ) { 9333 if ( 9334 defined( 'WP_RUN_CORE_TESTS' ) 9335 && WP_RUN_CORE_TESTS 9336 && isset( $GLOBALS['_wp_tests_wp_version'] ) 9337 ) { 9338 $wp_version = $GLOBALS['_wp_tests_wp_version']; 9339 } else { 9340 $wp_version = wp_get_wp_version(); 9341 } 9342 9343 // Strip off any -alpha, -RC, -beta, -src suffixes. 9344 list( $version ) = explode( '-', $wp_version ); 9345 9346 if ( is_string( $required ) ) { 9347 $trimmed = trim( $required ); 9348 9349 if ( substr_count( $trimmed, '.' ) > 1 && str_ends_with( $trimmed, '.0' ) ) { 9350 $required = substr( $trimmed, 0, -2 ); 9351 } 9352 } 9353 9354 return empty( $required ) || version_compare( $version, $required, '>=' ); 9355 } 9356 9357 /** 9358 * Checks compatibility with the current PHP version. 9359 * 9360 * @since 5.2.0 9361 * 9362 * @param string $required Minimum required PHP version. 9363 * @return bool True if required version is compatible or empty, false if not. 9364 */ 9365 function is_php_version_compatible( $required ) { 9366 return empty( $required ) || version_compare( PHP_VERSION, $required, '>=' ); 9367 } 9368 9369 /** 9370 * Checks if two numbers are nearly the same. 9371 * 9372 * This is similar to using `round()` but the precision is more fine-grained. 9373 * 9374 * @since 5.3.0 9375 * 9376 * @param int|float $expected The expected value. 9377 * @param int|float $actual The actual number. 9378 * @param int|float $precision Optional. The allowed variation. Default 1. 9379 * @return bool Whether the numbers match within the specified precision. 9380 */ 9381 function wp_fuzzy_number_match( $expected, $actual, $precision = 1 ) { 9382 return abs( (float) $expected - (float) $actual ) <= $precision; 9383 } 9384 9385 /** 9386 * Creates and returns the markup for an admin notice. 9387 * 9388 * @since 6.4.0 9389 * 9390 * @param string $message The message. 9391 * @param array $args { 9392 * Optional. An array of arguments for the admin notice. Default empty array. 9393 * 9394 * @type string $type Optional. The type of admin notice. 9395 * For example, 'error', 'success', 'warning', 'info'. 9396 * Default empty string. 9397 * @type bool $dismissible Optional. Whether the admin notice is dismissible. Default false. 9398 * @type string $id Optional. The value of the admin notice's ID attribute. Default empty string. 9399 * @type string[] $additional_classes Optional. A string array of class names. Default empty array. 9400 * @type string[] $attributes Optional. Additional attributes for the notice div. Default empty array. 9401 * @type bool $paragraph_wrap Optional. Whether to wrap the message in paragraph tags. Default true. 9402 * } 9403 * @return string The markup for an admin notice. 9404 */ 9405 function wp_get_admin_notice( $message, $args = array() ) { 9406 $defaults = array( 9407 'type' => '', 9408 'dismissible' => false, 9409 'id' => '', 9410 'additional_classes' => array(), 9411 'attributes' => array(), 9412 'paragraph_wrap' => true, 9413 ); 9414 9415 $args = wp_parse_args( $args, $defaults ); 9416 9417 /** 9418 * Filters the arguments for an admin notice. 9419 * 9420 * @since 6.4.0 9421 * 9422 * @param array $args The arguments for the admin notice. 9423 * @param string $message The message for the admin notice. 9424 */ 9425 $args = apply_filters( 'wp_admin_notice_args', $args, $message ); 9426 9427 $wrap_with_p = false !== $args['paragraph_wrap']; 9428 $wrap_opener = $wrap_with_p ? '<p>' : ''; 9429 $wrap_closer = $wrap_with_p ? '</p>' : ''; 9430 $html_builder = new WP_HTML_Tag_Processor( "<div class=\"notice\">{$wrap_opener}" ); 9431 $html_builder->next_token(); 9432 9433 if ( is_string( $args['id'] ) ) { 9434 $trimmed_id = trim( $args['id'] ); 9435 9436 if ( '' !== $trimmed_id ) { 9437 $html_builder->set_attribute( 'id', $trimmed_id ); 9438 } 9439 } 9440 9441 if ( is_string( $args['type'] ) ) { 9442 $type = trim( $args['type'] ); 9443 9444 if ( strlen( $type ) !== strcspn( $type, " \f\t\r\n" ) ) { 9445 _doing_it_wrong( 9446 __FUNCTION__, 9447 sprintf( 9448 /* translators: %s: The "type" key. */ 9449 __( 'The %s key must be a string without spaces.' ), 9450 '<code>type</code>' 9451 ), 9452 '6.4.0' 9453 ); 9454 } 9455 9456 if ( '' !== $type ) { 9457 $html_builder->add_class( "notice-{$type}" ); 9458 } 9459 } 9460 9461 if ( true === $args['dismissible'] ) { 9462 $html_builder->add_class( 'is-dismissible' ); 9463 } 9464 9465 if ( is_array( $args['additional_classes'] ) && ! empty( $args['additional_classes'] ) ) { 9466 foreach ( $args['additional_classes'] as $class_name ) { 9467 $html_builder->add_class( $class_name ); 9468 } 9469 } 9470 9471 if ( is_array( $args['attributes'] ) && ! empty( $args['attributes'] ) ) { 9472 foreach ( $args['attributes'] as $name => $value ) { 9473 if ( is_int( $name ) ) { 9474 /* 9475 * Boolean attributes may have been appended as numeric list items, 9476 * for example, with `$args['attributes'][] = 'disabled'`. They should 9477 * be recorded with the value serving as their name. 9478 */ 9479 $html_builder->set_attribute( $value, true ); 9480 } elseif ( true === $value ) { 9481 $html_builder->set_attribute( $name, true ); 9482 } elseif ( false !== $value ) { 9483 $html_builder->set_attribute( $name, trim( (string) $value ) ); 9484 } 9485 } 9486 } 9487 9488 $markup = $html_builder->get_updated_html(); 9489 $markup .= $message; 9490 $markup .= "{$wrap_closer}</div>"; 9491 9492 /** 9493 * Filters the markup for an admin notice. 9494 * 9495 * @since 6.4.0 9496 * 9497 * @param string $markup The HTML markup for the admin notice. 9498 * @param string $message The message for the admin notice. 9499 * @param array $args The arguments for the admin notice. 9500 */ 9501 return apply_filters( 'wp_admin_notice_markup', $markup, $message, $args ); 9502 } 9503 9504 /** 9505 * Outputs an admin notice. 9506 * 9507 * @since 6.4.0 9508 * 9509 * @param string $message The message to output. 9510 * @param array $args { 9511 * Optional. An array of arguments for the admin notice. Default empty array. 9512 * 9513 * @type string $type Optional. The type of admin notice. 9514 * For example, 'error', 'success', 'warning', 'info'. 9515 * Default empty string. 9516 * @type bool $dismissible Optional. Whether the admin notice is dismissible. Default false. 9517 * @type string $id Optional. The value of the admin notice's ID attribute. Default empty string. 9518 * @type string[] $additional_classes Optional. A string array of class names. Default empty array. 9519 * @type string[] $attributes Optional. Additional attributes for the notice div. Default empty array. 9520 * @type bool $paragraph_wrap Optional. Whether to wrap the message in paragraph tags. Default true. 9521 * } 9522 */ 9523 function wp_admin_notice( $message, $args = array() ) { 9524 /** 9525 * Fires before an admin notice is output. 9526 * 9527 * @since 6.4.0 9528 * 9529 * @param string $message The message for the admin notice. 9530 * @param array $args The arguments for the admin notice. 9531 */ 9532 do_action( 'wp_admin_notice', $message, $args ); 9533 9534 echo wp_kses_post( wp_get_admin_notice( $message, $args ) ); 9535 } 9536 9537 /** 9538 * Checks if a mime type is for a HEIC/HEIF image. 9539 * 9540 * @since 6.7.0 9541 * 9542 * @param string $mime_type The mime type to check. 9543 * @return bool Whether the mime type is for a HEIC/HEIF image. 9544 */ 9545 function wp_is_heic_image_mime_type( $mime_type ) { 9546 $heic_mime_types = array( 9547 'image/heic', 9548 'image/heif', 9549 'image/heic-sequence', 9550 'image/heif-sequence', 9551 ); 9552 9553 return in_array( $mime_type, $heic_mime_types, true ); 9554 } 9555 9556 /** 9557 * Returns a cryptographically secure hash of a message using a fast generic hash function. 9558 * 9559 * Use the wp_verify_fast_hash() function to verify the hash. 9560 * 9561 * This function does not salt the value prior to being hashed, therefore input to this function must originate from 9562 * a random generator with sufficiently high entropy, preferably greater than 128 bits. This function is used internally 9563 * in WordPress to hash security keys and application passwords which are generated with high entropy. 9564 * 9565 * Important: 9566 * 9567 * - This function must not be used for hashing user-generated passwords. Use wp_hash_password() for that. 9568 * - This function must not be used for hashing other low-entropy input. Use wp_hash() for that. 9569 * 9570 * The BLAKE2b algorithm is used by Sodium to hash the message. 9571 * 9572 * @since 6.8.0 9573 * 9574 * @throws TypeError Thrown by Sodium if the message is not a string. 9575 * 9576 * @param string $message The message to hash. 9577 * @return string The hash of the message. 9578 * 9579 * @phpstan-return non-falsy-string 9580 */ 9581 function wp_fast_hash( 9582 #[\SensitiveParameter] 9583 string $message 9584 ): string { 9585 $hashed = sodium_crypto_generichash( $message, 'wp_fast_hash_6.8+', 30 ); 9586 return '$generic$' . sodium_bin2base64( $hashed, SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING ); 9587 } 9588 9589 /** 9590 * Checks whether a plaintext message matches the hashed value. Used to verify values hashed via wp_fast_hash(). 9591 * 9592 * The function uses Sodium to hash the message and compare it to the hashed value. If the hash is not a generic hash, 9593 * the hash is treated as a phpass portable hash in order to provide backward compatibility for passwords and security 9594 * keys which were hashed using phpass prior to WordPress 6.8.0. 9595 * 9596 * @since 6.8.0 9597 * 9598 * @throws TypeError Thrown by Sodium if the message is not a string. 9599 * 9600 * @param string $message The plaintext message. 9601 * @param string $hash Hash of the message to check against. 9602 * @return bool Whether the message matches the hashed message. 9603 */ 9604 function wp_verify_fast_hash( 9605 #[\SensitiveParameter] 9606 string $message, 9607 string $hash 9608 ): bool { 9609 if ( ! str_starts_with( $hash, '$generic$' ) ) { 9610 // Back-compat for old phpass hashes. 9611 require_once ABSPATH . WPINC . '/class-phpass.php'; 9612 return ( new PasswordHash( 8, true ) )->CheckPassword( $message, $hash ); 9613 } 9614 9615 return hash_equals( $hash, wp_fast_hash( $message ) ); 9616 } 9617 9618 /** 9619 * Sends an email to the user when a new application password is created. 9620 * 9621 * Hooked to the {@see 'wp_create_application_password'} action. 9622 * 9623 * @since 7.2.0 9624 * 9625 * @param int $user_id The user ID. 9626 * @param array $new_item The application password details. 9627 */ 9628 function wp_application_password_created_notification( $user_id, $new_item ) { 9629 $send = true; 9630 9631 // Get current user data. 9632 $user = get_userdata( $user_id ); 9633 9634 if ( ! $user ) { 9635 return; 9636 } 9637 9638 if ( ! is_email( $user->user_email ) ) { 9639 return; 9640 } 9641 9642 // Validate that the application password has a name. 9643 if ( empty( $new_item['name'] ) ) { 9644 return; 9645 } 9646 9647 /** 9648 * Filters whether to send the application password created notification email. 9649 * 9650 * @since 7.2.0 9651 * 9652 * @param bool $send Whether to send the email notification. 9653 * @param WP_User $user The user object. 9654 * @param array $new_item { 9655 * The details about the created password. 9656 * 9657 * @type string $uuid The unique identifier for the application password. 9658 * @type string $app_id A UUID provided by the application to uniquely identify it. 9659 * @type string $name The name of the application password. 9660 * @type string $password A one-way hash of the password. 9661 * @type int $created Unix timestamp of when the password was created. 9662 * @type null $last_used Null. 9663 * @type null $last_ip Null. 9664 * } 9665 */ 9666 $send = apply_filters( 'wp_send_application_password_created_email', $send, $user, $new_item ); 9667 9668 if ( ! $send ) { 9669 return; 9670 } 9671 9672 $switched_locale = switch_to_user_locale( $user->ID ); 9673 9674 /* translators: Do not translate USERNAME, APPLICATION_PASSWORD_NAME, ADMIN_EMAIL, SITENAME, SITEURL, EMAIL: those are placeholders. */ 9675 $application_password_create_text = __( 9676 'Hi ###USERNAME###, 9677 9678 A new application password was added to your account on ###SITENAME###. This password allows access to your account via the REST API. 9679 9680 If you did not expect this, please contact the Site Administrator at 9681 ###ADMIN_EMAIL### 9682 9683 Application password name: ###APPLICATION_PASSWORD_NAME### 9684 Site: ###SITEURL### 9685 9686 You can manage your application passwords in your account settings. 9687 9688 This email has been sent to ###EMAIL### 9689 9690 Regards, 9691 All at ###SITENAME### 9692 ###SITEURL###' 9693 ); 9694 9695 $email = array( 9696 'to' => $user->user_email, 9697 /* translators: Application password creation email subject. %s: Site title. */ 9698 'subject' => __( '[%s] Application Password Created' ), 9699 'message' => $application_password_create_text, 9700 'headers' => '', 9701 ); 9702 9703 // Get site name. 9704 $site_name = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ); 9705 9706 /** 9707 * Filters the contents of the email notification sent to a user when a new application password is created. 9708 * 9709 * @since 7.2.0 9710 * 9711 * @param array $email { 9712 * Used to build wp_mail(). 9713 * 9714 * @type string $to The email address of the intended recipient. 9715 * @type string $subject The subject of the email. 9716 * @type string $message The content of the email. 9717 * The following strings have a special meaning and will get replaced dynamically: 9718 * - `###USERNAME###` The user's display name. 9719 * - `###APPLICATION_PASSWORD_NAME###` The name of the application password. 9720 * - `###ADMIN_EMAIL###` The admin email in case this was unexpected. 9721 * - `###EMAIL###` The user's email address. 9722 * - `###SITENAME###` The name of the site. 9723 * - `###SITEURL###` The URL to the site. 9724 * @type string $headers Headers. 9725 * } 9726 * @param WP_User $user The user object. 9727 * @param array $new_item { 9728 * The details about the created password. 9729 * 9730 * @type string $uuid The unique identifier for the application password. 9731 * @type string $app_id A UUID provided by the application to uniquely identify it. 9732 * @type string $name The name of the application password. 9733 * @type string $password A one-way hash of the password. 9734 * @type int $created Unix timestamp of when the password was created. 9735 * @type null $last_used Null. 9736 * @type null $last_ip Null. 9737 * } 9738 */ 9739 $email = apply_filters( 'wp_application_password_created_email', $email, $user, $new_item ); 9740 9741 $email['message'] = str_replace( '###USERNAME###', $user->display_name, $email['message'] ); 9742 $email['message'] = str_replace( '###APPLICATION_PASSWORD_NAME###', $new_item['name'], $email['message'] ); 9743 $email['message'] = str_replace( '###ADMIN_EMAIL###', get_option( 'admin_email' ), $email['message'] ); 9744 $email['message'] = str_replace( '###EMAIL###', $user->user_email, $email['message'] ); 9745 $email['message'] = str_replace( '###SITENAME###', $site_name, $email['message'] ); 9746 $email['message'] = str_replace( '###SITEURL###', home_url(), $email['message'] ); 9747 9748 wp_mail( 9749 $email['to'], 9750 sprintf( 9751 $email['subject'], 9752 $site_name 9753 ), 9754 $email['message'], 9755 $email['headers'] 9756 ); 9757 9758 if ( $switched_locale ) { 9759 restore_previous_locale(); 9760 } 9761 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
| Generated : Sat Dec 5 08:20:02 2026 | Cross-referenced by PHPXref |