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