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