[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

/wp-includes/ -> formatting.php (source)

   1  <?php
   2  /**
   3   * Main WordPress Formatting API.
   4   *
   5   * Handles many functions for formatting output.
   6   *
   7   * @package WordPress
   8   */
   9  
  10  /**
  11   * Replaces common plain text characters with formatted entities.
  12   *
  13   * Returns given text with transformations of quotes into smart quotes, apostrophes,
  14   * dashes, ellipses, the trademark symbol, and the multiplication symbol.
  15   *
  16   * As an example,
  17   *
  18   *     'cause today's effort makes it worth tomorrow's "holiday" ...
  19   *
  20   * Becomes:
  21   *
  22   *     &#8217;cause today&#8217;s effort makes it worth tomorrow&#8217;s &#8220;holiday&#8221; &#8230;
  23   *
  24   * Code within certain HTML blocks are skipped.
  25   *
  26   * Do not use this function before the {@see 'init'} action hook; everything will break.
  27   *
  28   * @since 0.71
  29   *
  30   * @global array $wp_cockneyreplace Array of formatted entities for certain common phrases.
  31   * @global array $shortcode_tags
  32   *
  33   * @param string $text  The text to be formatted.
  34   * @param bool   $reset Set to true for unit testing. Translated patterns will reset.
  35   * @return string The string replaced with HTML entities.
  36   */
  37  function wptexturize( $text, $reset = false ) {
  38      global $wp_cockneyreplace, $shortcode_tags;
  39      static $static_characters            = null,
  40          $static_replacements             = null,
  41          $dynamic_characters              = null,
  42          $dynamic_replacements            = null,
  43          $default_no_texturize_tags       = null,
  44          $default_no_texturize_shortcodes = null,
  45          $run_texturize                   = true,
  46          $apos                            = null,
  47          $prime                           = null,
  48          $double_prime                    = null,
  49          $opening_quote                   = null,
  50          $closing_quote                   = null,
  51          $opening_single_quote            = null,
  52          $closing_single_quote            = null,
  53          $open_q_flag                     = '<!--oq-->',
  54          $open_sq_flag                    = '<!--osq-->',
  55          $apos_flag                       = '<!--apos-->';
  56  
  57      // If there's nothing to do, just stop.
  58      if ( empty( $text ) || false === $run_texturize ) {
  59          return $text;
  60      }
  61  
  62      // Set up static variables. Run once only.
  63      if ( $reset || ! isset( $static_characters ) ) {
  64          /**
  65           * Filters whether to skip running wptexturize().
  66           *
  67           * Returning false from the filter will effectively short-circuit wptexturize()
  68           * and return the original text passed to the function instead.
  69           *
  70           * The filter runs only once, the first time wptexturize() is called.
  71           *
  72           * @since 4.0.0
  73           *
  74           * @see wptexturize()
  75           *
  76           * @param bool $run_texturize Whether to short-circuit wptexturize().
  77           */
  78          $run_texturize = apply_filters( 'run_wptexturize', $run_texturize );
  79          if ( false === $run_texturize ) {
  80              return $text;
  81          }
  82  
  83          /* translators: Opening curly double quote. */
  84          $opening_quote = _x( '&#8220;', 'opening curly double quote' );
  85          /* translators: Closing curly double quote. */
  86          $closing_quote = _x( '&#8221;', 'closing curly double quote' );
  87  
  88          /* translators: Apostrophe, for example in 'cause or can't. */
  89          $apos = _x( '&#8217;', 'apostrophe' );
  90  
  91          /* translators: Prime, for example in 9' (nine feet). */
  92          $prime = _x( '&#8242;', 'prime' );
  93          /* translators: Double prime, for example in 9" (nine inches). */
  94          $double_prime = _x( '&#8243;', 'double prime' );
  95  
  96          /* translators: Opening curly single quote. */
  97          $opening_single_quote = _x( '&#8216;', 'opening curly single quote' );
  98          /* translators: Closing curly single quote. */
  99          $closing_single_quote = _x( '&#8217;', 'closing curly single quote' );
 100  
 101          /* translators: En dash. */
 102          $en_dash = _x( '&#8211;', 'en dash' );
 103          /* translators: Em dash. */
 104          $em_dash = _x( '&#8212;', 'em dash' );
 105  
 106          $default_no_texturize_tags       = array( 'pre', 'code', 'kbd', 'style', 'script', 'tt' );
 107          $default_no_texturize_shortcodes = array( 'code' );
 108  
 109          // If a plugin has provided an autocorrect array, use it.
 110          if ( isset( $wp_cockneyreplace ) ) {
 111              $cockney        = array_keys( $wp_cockneyreplace );
 112              $cockneyreplace = array_values( $wp_cockneyreplace );
 113          } else {
 114              /*
 115               * translators: This is a comma-separated list of words that defy the syntax of quotations in normal use,
 116               * for example... 'We do not have enough words yet'... is a typical quoted phrase. But when we write
 117               * lines of code 'til we have enough of 'em, then we need to insert apostrophes instead of quotes.
 118               */
 119              $cockney = explode(
 120                  ',',
 121                  _x(
 122                      "'tain't,'twere,'twas,'tis,'twill,'til,'bout,'nuff,'round,'cause,'em",
 123                      'Comma-separated list of words to texturize in your language'
 124                  )
 125              );
 126  
 127              $cockneyreplace = explode(
 128                  ',',
 129                  _x(
 130                      '&#8217;tain&#8217;t,&#8217;twere,&#8217;twas,&#8217;tis,&#8217;twill,&#8217;til,&#8217;bout,&#8217;nuff,&#8217;round,&#8217;cause,&#8217;em',
 131                      'Comma-separated list of replacement words in your language'
 132                  )
 133              );
 134          }
 135  
 136          $static_characters   = array_merge( array( '...', '``', '\'\'', ' (tm)' ), $cockney );
 137          $static_replacements = array_merge( array( '&#8230;', $opening_quote, $closing_quote, ' &#8482;' ), $cockneyreplace );
 138  
 139          // Pattern-based replacements of characters.
 140          // Sort the remaining patterns into several arrays for performance tuning.
 141          $dynamic_characters   = array(
 142              'apos'  => array(),
 143              'quote' => array(),
 144              'dash'  => array(),
 145          );
 146          $dynamic_replacements = array(
 147              'apos'  => array(),
 148              'quote' => array(),
 149              'dash'  => array(),
 150          );
 151          $dynamic              = array();
 152          $spaces               = wp_spaces_regexp();
 153  
 154          // '99' and '99" are ambiguous among other patterns; assume it's an abbreviated year at the end of a quotation.
 155          if ( "'" !== $apos || "'" !== $closing_single_quote ) {
 156              $dynamic[ '/\'(\d\d)\'(?=\Z|[.,:;!?)}\-\]]|&gt;|' . $spaces . ')/' ] = $apos_flag . '$1' . $closing_single_quote;
 157          }
 158          if ( "'" !== $apos || '"' !== $closing_quote ) {
 159              $dynamic[ '/\'(\d\d)"(?=\Z|[.,:;!?)}\-\]]|&gt;|' . $spaces . ')/' ] = $apos_flag . '$1' . $closing_quote;
 160          }
 161  
 162          // '99 '99s '99's (apostrophe)  But never '9 or '99% or '999 or '99.0.
 163          if ( "'" !== $apos ) {
 164              $dynamic['/\'(?=\d\d(?:\Z|(?![%\d]|[.,]\d)))/'] = $apos_flag;
 165          }
 166  
 167          // Quoted numbers like '0.42'.
 168          if ( "'" !== $opening_single_quote && "'" !== $closing_single_quote ) {
 169              $dynamic[ '/(?<=\A|' . $spaces . ')\'(\d[.,\d]*)\'/' ] = $open_sq_flag . '$1' . $closing_single_quote;
 170          }
 171  
 172          // Single quote at start, or preceded by (, {, <, [, ", -, or spaces.
 173          if ( "'" !== $opening_single_quote ) {
 174              $dynamic[ '/(?<=\A|[([{"\-]|&lt;|' . $spaces . ')\'/' ] = $open_sq_flag;
 175          }
 176  
 177          // Apostrophe in a word. No spaces, double apostrophes, or other punctuation.
 178          if ( "'" !== $apos ) {
 179              $dynamic[ '/(?<!' . $spaces . ')\'(?!\Z|[.,:;!?"\'(){}[\]\-]|&[lg]t;|' . $spaces . ')/' ] = $apos_flag;
 180          }
 181  
 182          $dynamic_characters['apos']   = array_keys( $dynamic );
 183          $dynamic_replacements['apos'] = array_values( $dynamic );
 184          $dynamic                      = array();
 185  
 186          // Quoted numbers like "42".
 187          if ( '"' !== $opening_quote && '"' !== $closing_quote ) {
 188              $dynamic[ '/(?<=\A|' . $spaces . ')"(\d[.,\d]*)"/' ] = $open_q_flag . '$1' . $closing_quote;
 189          }
 190  
 191          // Double quote at start, or preceded by (, {, <, [, -, or spaces, and not followed by spaces.
 192          if ( '"' !== $opening_quote ) {
 193              $dynamic[ '/(?<=\A|[([{\-]|&lt;|' . $spaces . ')"(?!' . $spaces . ')/' ] = $open_q_flag;
 194          }
 195  
 196          $dynamic_characters['quote']   = array_keys( $dynamic );
 197          $dynamic_replacements['quote'] = array_values( $dynamic );
 198          $dynamic                       = array();
 199  
 200          // Dashes and spaces.
 201          $dynamic['/---/'] = $em_dash;
 202          $dynamic[ '/(?<=^|' . $spaces . ')--(?=$|' . $spaces . ')/' ] = $em_dash;
 203          $dynamic['/(?<!xn)--/']                                       = $en_dash;
 204          $dynamic[ '/(?<=^|' . $spaces . ')-(?=$|' . $spaces . ')/' ]  = $en_dash;
 205  
 206          $dynamic_characters['dash']   = array_keys( $dynamic );
 207          $dynamic_replacements['dash'] = array_values( $dynamic );
 208      }
 209  
 210      // Must do this every time in case plugins use these filters in a context sensitive manner.
 211      /**
 212       * Filters the list of HTML elements not to texturize.
 213       *
 214       * @since 2.8.0
 215       *
 216       * @param string[] $default_no_texturize_tags An array of HTML element names.
 217       */
 218      $no_texturize_tags = apply_filters( 'no_texturize_tags', $default_no_texturize_tags );
 219      /**
 220       * Filters the list of shortcodes not to texturize.
 221       *
 222       * @since 2.8.0
 223       *
 224       * @param string[] $default_no_texturize_shortcodes An array of shortcode names.
 225       */
 226      $no_texturize_shortcodes = apply_filters( 'no_texturize_shortcodes', $default_no_texturize_shortcodes );
 227  
 228      $no_texturize_tags_stack       = array();
 229      $no_texturize_shortcodes_stack = array();
 230  
 231      // Look for shortcodes and HTML elements.
 232  
 233      preg_match_all( '@\[/?([^<>&/\[\]\x00-\x20=]++)@', $text, $matches );
 234      $tagnames         = array_intersect( array_keys( $shortcode_tags ), $matches[1] );
 235      $found_shortcodes = ! empty( $tagnames );
 236      $shortcode_regex  = $found_shortcodes ? _get_wptexturize_shortcode_regex( $tagnames ) : '';
 237      $regex            = _get_wptexturize_split_regex( $shortcode_regex );
 238  
 239      $textarr = preg_split( $regex, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY );
 240  
 241      foreach ( $textarr as &$curl ) {
 242          // Only call _wptexturize_pushpop_element if $curl is a delimiter.
 243          $first = $curl[0];
 244          if ( '<' === $first ) {
 245              if ( '<!--' === substr( $curl, 0, 4 ) ) {
 246                  // This is an HTML comment delimiter.
 247                  continue;
 248              } else {
 249                  // This is an HTML element delimiter.
 250  
 251                  // Replace each & with &#038; unless it already looks like an entity.
 252                  $curl = preg_replace( '/&(?!#(?:\d+|x[a-f0-9]+);|[a-z1-4]{1,8};)/i', '&#038;', $curl );
 253  
 254                  _wptexturize_pushpop_element( $curl, $no_texturize_tags_stack, $no_texturize_tags );
 255              }
 256          } elseif ( '' === trim( $curl ) ) {
 257              // This is a newline between delimiters. Performance improves when we check this.
 258              continue;
 259  
 260          } elseif ( '[' === $first && $found_shortcodes && 1 === preg_match( '/^' . $shortcode_regex . '$/', $curl ) ) {
 261              // This is a shortcode delimiter.
 262  
 263              if ( '[[' !== substr( $curl, 0, 2 ) && ']]' !== substr( $curl, -2 ) ) {
 264                  // Looks like a normal shortcode.
 265                  _wptexturize_pushpop_element( $curl, $no_texturize_shortcodes_stack, $no_texturize_shortcodes );
 266              } else {
 267                  // Looks like an escaped shortcode.
 268                  continue;
 269              }
 270          } elseif ( empty( $no_texturize_shortcodes_stack ) && empty( $no_texturize_tags_stack ) ) {
 271              // This is neither a delimiter, nor is this content inside of no_texturize pairs. Do texturize.
 272  
 273              $curl = str_replace( $static_characters, $static_replacements, $curl );
 274  
 275              if ( false !== strpos( $curl, "'" ) ) {
 276                  $curl = preg_replace( $dynamic_characters['apos'], $dynamic_replacements['apos'], $curl );
 277                  $curl = wptexturize_primes( $curl, "'", $prime, $open_sq_flag, $closing_single_quote );
 278                  $curl = str_replace( $apos_flag, $apos, $curl );
 279                  $curl = str_replace( $open_sq_flag, $opening_single_quote, $curl );
 280              }
 281              if ( false !== strpos( $curl, '"' ) ) {
 282                  $curl = preg_replace( $dynamic_characters['quote'], $dynamic_replacements['quote'], $curl );
 283                  $curl = wptexturize_primes( $curl, '"', $double_prime, $open_q_flag, $closing_quote );
 284                  $curl = str_replace( $open_q_flag, $opening_quote, $curl );
 285              }
 286              if ( false !== strpos( $curl, '-' ) ) {
 287                  $curl = preg_replace( $dynamic_characters['dash'], $dynamic_replacements['dash'], $curl );
 288              }
 289  
 290              // 9x9 (times), but never 0x9999.
 291              if ( 1 === preg_match( '/(?<=\d)x\d/', $curl ) ) {
 292                  // Searching for a digit is 10 times more expensive than for the x, so we avoid doing this one!
 293                  $curl = preg_replace( '/\b(\d(?(?<=0)[\d\.,]+|[\d\.,]*))x(\d[\d\.,]*)\b/', '$1&#215;$2', $curl );
 294              }
 295  
 296              // Replace each & with &#038; unless it already looks like an entity.
 297              $curl = preg_replace( '/&(?!#(?:\d+|x[a-f0-9]+);|[a-z1-4]{1,8};)/i', '&#038;', $curl );
 298          }
 299      }
 300  
 301      return implode( '', $textarr );
 302  }
 303  
 304  /**
 305   * Implements a logic tree to determine whether or not "7'." represents seven feet,
 306   * then converts the special char into either a prime char or a closing quote char.
 307   *
 308   * @since 4.3.0
 309   *
 310   * @param string $haystack    The plain text to be searched.
 311   * @param string $needle      The character to search for such as ' or ".
 312   * @param string $prime       The prime char to use for replacement.
 313   * @param string $open_quote  The opening quote char. Opening quote replacement must be
 314   *                            accomplished already.
 315   * @param string $close_quote The closing quote char to use for replacement.
 316   * @return string The $haystack value after primes and quotes replacements.
 317   */
 318  function wptexturize_primes( $haystack, $needle, $prime, $open_quote, $close_quote ) {
 319      $spaces           = wp_spaces_regexp();
 320      $flag             = '<!--wp-prime-or-quote-->';
 321      $quote_pattern    = "/$needle(?=\\Z|[.,:;!?)}\\-\\]]|&gt;|" . $spaces . ')/';
 322      $prime_pattern    = "/(?<=\\d)$needle/";
 323      $flag_after_digit = "/(?<=\\d)$flag/";
 324      $flag_no_digit    = "/(?<!\\d)$flag/";
 325  
 326      $sentences = explode( $open_quote, $haystack );
 327  
 328      foreach ( $sentences as $key => &$sentence ) {
 329          if ( false === strpos( $sentence, $needle ) ) {
 330              continue;
 331          } elseif ( 0 !== $key && 0 === substr_count( $sentence, $close_quote ) ) {
 332              $sentence = preg_replace( $quote_pattern, $flag, $sentence, -1, $count );
 333              if ( $count > 1 ) {
 334                  // This sentence appears to have multiple closing quotes. Attempt Vulcan logic.
 335                  $sentence = preg_replace( $flag_no_digit, $close_quote, $sentence, -1, $count2 );
 336                  if ( 0 === $count2 ) {
 337                      // Try looking for a quote followed by a period.
 338                      $count2 = substr_count( $sentence, "$flag." );
 339                      if ( $count2 > 0 ) {
 340                          // Assume the rightmost quote-period match is the end of quotation.
 341                          $pos = strrpos( $sentence, "$flag." );
 342                      } else {
 343                          // When all else fails, make the rightmost candidate a closing quote.
 344                          // This is most likely to be problematic in the context of bug #18549.
 345                          $pos = strrpos( $sentence, $flag );
 346                      }
 347                      $sentence = substr_replace( $sentence, $close_quote, $pos, strlen( $flag ) );
 348                  }
 349                  // Use conventional replacement on any remaining primes and quotes.
 350                  $sentence = preg_replace( $prime_pattern, $prime, $sentence );
 351                  $sentence = preg_replace( $flag_after_digit, $prime, $sentence );
 352                  $sentence = str_replace( $flag, $close_quote, $sentence );
 353              } elseif ( 1 == $count ) {
 354                  // Found only one closing quote candidate, so give it priority over primes.
 355                  $sentence = str_replace( $flag, $close_quote, $sentence );
 356                  $sentence = preg_replace( $prime_pattern, $prime, $sentence );
 357              } else {
 358                  // No closing quotes found. Just run primes pattern.
 359                  $sentence = preg_replace( $prime_pattern, $prime, $sentence );
 360              }
 361          } else {
 362              $sentence = preg_replace( $prime_pattern, $prime, $sentence );
 363              $sentence = preg_replace( $quote_pattern, $close_quote, $sentence );
 364          }
 365          if ( '"' === $needle && false !== strpos( $sentence, '"' ) ) {
 366              $sentence = str_replace( '"', $close_quote, $sentence );
 367          }
 368      }
 369  
 370      return implode( $open_quote, $sentences );
 371  }
 372  
 373  /**
 374   * Search for disabled element tags. Push element to stack on tag open and pop
 375   * on tag close.
 376   *
 377   * Assumes first char of $text is tag opening and last char is tag closing.
 378   * Assumes second char of $text is optionally '/' to indicate closing as in </html>.
 379   *
 380   * @since 2.9.0
 381   * @access private
 382   *
 383   * @param string   $text              Text to check. Must be a tag like `<html>` or `[shortcode]`.
 384   * @param string[] $stack             Array of open tag elements.
 385   * @param string[] $disabled_elements Array of tag names to match against. Spaces are not allowed in tag names.
 386   */
 387  function _wptexturize_pushpop_element( $text, &$stack, $disabled_elements ) {
 388      // Is it an opening tag or closing tag?
 389      if ( isset( $text[1] ) && '/' !== $text[1] ) {
 390          $opening_tag = true;
 391          $name_offset = 1;
 392      } elseif ( 0 === count( $stack ) ) {
 393          // Stack is empty. Just stop.
 394          return;
 395      } else {
 396          $opening_tag = false;
 397          $name_offset = 2;
 398      }
 399  
 400      // Parse out the tag name.
 401      $space = strpos( $text, ' ' );
 402      if ( false === $space ) {
 403          $space = -1;
 404      } else {
 405          $space -= $name_offset;
 406      }
 407      $tag = substr( $text, $name_offset, $space );
 408  
 409      // Handle disabled tags.
 410      if ( in_array( $tag, $disabled_elements, true ) ) {
 411          if ( $opening_tag ) {
 412              /*
 413               * This disables texturize until we find a closing tag of our type
 414               * (e.g. <pre>) even if there was invalid nesting before that.
 415               *
 416               * Example: in the case <pre>sadsadasd</code>"baba"</pre>
 417               *          "baba" won't be texturized.
 418               */
 419  
 420              array_push( $stack, $tag );
 421          } elseif ( end( $stack ) == $tag ) {
 422              array_pop( $stack );
 423          }
 424      }
 425  }
 426  
 427  /**
 428   * Replaces double line breaks with paragraph elements.
 429   *
 430   * A group of regex replaces used to identify text formatted with newlines and
 431   * replace double line breaks with HTML paragraph tags. The remaining line breaks
 432   * after conversion become <<br />> tags, unless $br is set to '0' or 'false'.
 433   *
 434   * @since 0.71
 435   *
 436   * @param string $pee The text which has to be formatted.
 437   * @param bool   $br  Optional. If set, this will convert all remaining line breaks
 438   *                    after paragraphing. Line breaks within `<script>`, `<style>`,
 439   *                    and `<svg>` tags are not affected. Default true.
 440   * @return string Text which has been converted into correct paragraph tags.
 441   */
 442  function wpautop( $pee, $br = true ) {
 443      $pre_tags = array();
 444  
 445      if ( trim( $pee ) === '' ) {
 446          return '';
 447      }
 448  
 449      // Just to make things a little easier, pad the end.
 450      $pee = $pee . "\n";
 451  
 452      /*
 453       * Pre tags shouldn't be touched by autop.
 454       * Replace pre tags with placeholders and bring them back after autop.
 455       */
 456      if ( strpos( $pee, '<pre' ) !== false ) {
 457          $pee_parts = explode( '</pre>', $pee );
 458          $last_pee  = array_pop( $pee_parts );
 459          $pee       = '';
 460          $i         = 0;
 461  
 462          foreach ( $pee_parts as $pee_part ) {
 463              $start = strpos( $pee_part, '<pre' );
 464  
 465              // Malformed HTML?
 466              if ( false === $start ) {
 467                  $pee .= $pee_part;
 468                  continue;
 469              }
 470  
 471              $name              = "<pre wp-pre-tag-$i></pre>";
 472              $pre_tags[ $name ] = substr( $pee_part, $start ) . '</pre>';
 473  
 474              $pee .= substr( $pee_part, 0, $start ) . $name;
 475              $i++;
 476          }
 477  
 478          $pee .= $last_pee;
 479      }
 480      // Change multiple <br>'s into two line breaks, which will turn into paragraphs.
 481      $pee = preg_replace( '|<br\s*/?>\s*<br\s*/?>|', "\n\n", $pee );
 482  
 483      $allblocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|form|map|area|blockquote|address|math|style|p|h[1-6]|hr|fieldset|legend|section|article|aside|hgroup|header|footer|nav|figure|figcaption|details|menu|summary)';
 484  
 485      // Add a double line break above block-level opening tags.
 486      $pee = preg_replace( '!(<' . $allblocks . '[\s/>])!', "\n\n$1", $pee );
 487  
 488      // Add a double line break below block-level closing tags.
 489      $pee = preg_replace( '!(</' . $allblocks . '>)!', "$1\n\n", $pee );
 490  
 491      // Add a double line break after hr tags, which are self closing.
 492      $pee = preg_replace( '!(<hr\s*?/?>)!', "$1\n\n", $pee );
 493  
 494      // Standardize newline characters to "\n".
 495      $pee = str_replace( array( "\r\n", "\r" ), "\n", $pee );
 496  
 497      // Find newlines in all elements and add placeholders.
 498      $pee = wp_replace_in_html_tags( $pee, array( "\n" => ' <!-- wpnl --> ' ) );
 499  
 500      // Collapse line breaks before and after <option> elements so they don't get autop'd.
 501      if ( strpos( $pee, '<option' ) !== false ) {
 502          $pee = preg_replace( '|\s*<option|', '<option', $pee );
 503          $pee = preg_replace( '|</option>\s*|', '</option>', $pee );
 504      }
 505  
 506      /*
 507       * Collapse line breaks inside <object> elements, before <param> and <embed> elements
 508       * so they don't get autop'd.
 509       */
 510      if ( strpos( $pee, '</object>' ) !== false ) {
 511          $pee = preg_replace( '|(<object[^>]*>)\s*|', '$1', $pee );
 512          $pee = preg_replace( '|\s*</object>|', '</object>', $pee );
 513          $pee = preg_replace( '%\s*(</?(?:param|embed)[^>]*>)\s*%', '$1', $pee );
 514      }
 515  
 516      /*
 517       * Collapse line breaks inside <audio> and <video> elements,
 518       * before and after <source> and <track> elements.
 519       */
 520      if ( strpos( $pee, '<source' ) !== false || strpos( $pee, '<track' ) !== false ) {
 521          $pee = preg_replace( '%([<\[](?:audio|video)[^>\]]*[>\]])\s*%', '$1', $pee );
 522          $pee = preg_replace( '%\s*([<\[]/(?:audio|video)[>\]])%', '$1', $pee );
 523          $pee = preg_replace( '%\s*(<(?:source|track)[^>]*>)\s*%', '$1', $pee );
 524      }
 525  
 526      // Collapse line breaks before and after <figcaption> elements.
 527      if ( strpos( $pee, '<figcaption' ) !== false ) {
 528          $pee = preg_replace( '|\s*(<figcaption[^>]*>)|', '$1', $pee );
 529          $pee = preg_replace( '|</figcaption>\s*|', '</figcaption>', $pee );
 530      }
 531  
 532      // Remove more than two contiguous line breaks.
 533      $pee = preg_replace( "/\n\n+/", "\n\n", $pee );
 534  
 535      // Split up the contents into an array of strings, separated by double line breaks.
 536      $pees = preg_split( '/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY );
 537  
 538      // Reset $pee prior to rebuilding.
 539      $pee = '';
 540  
 541      // Rebuild the content as a string, wrapping every bit with a <p>.
 542      foreach ( $pees as $tinkle ) {
 543          $pee .= '<p>' . trim( $tinkle, "\n" ) . "</p>\n";
 544      }
 545  
 546      // Under certain strange conditions it could create a P of entirely whitespace.
 547      $pee = preg_replace( '|<p>\s*</p>|', '', $pee );
 548  
 549      // Add a closing <p> inside <div>, <address>, or <form> tag if missing.
 550      $pee = preg_replace( '!<p>([^<]+)</(div|address|form)>!', '<p>$1</p></$2>', $pee );
 551  
 552      // If an opening or closing block element tag is wrapped in a <p>, unwrap it.
 553      $pee = preg_replace( '!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', '$1', $pee );
 554  
 555      // In some cases <li> may get wrapped in <p>, fix them.
 556      $pee = preg_replace( '|<p>(<li.+?)</p>|', '$1', $pee );
 557  
 558      // If a <blockquote> is wrapped with a <p>, move it inside the <blockquote>.
 559      $pee = preg_replace( '|<p><blockquote([^>]*)>|i', '<blockquote$1><p>', $pee );
 560      $pee = str_replace( '</blockquote></p>', '</p></blockquote>', $pee );
 561  
 562      // If an opening or closing block element tag is preceded by an opening <p> tag, remove it.
 563      $pee = preg_replace( '!<p>\s*(</?' . $allblocks . '[^>]*>)!', '$1', $pee );
 564  
 565      // If an opening or closing block element tag is followed by a closing <p> tag, remove it.
 566      $pee = preg_replace( '!(</?' . $allblocks . '[^>]*>)\s*</p>!', '$1', $pee );
 567  
 568      // Optionally insert line breaks.
 569      if ( $br ) {
 570          // Replace newlines that shouldn't be touched with a placeholder.
 571          $pee = preg_replace_callback( '/<(script|style|svg).*?<\/\\1>/s', '_autop_newline_preservation_helper', $pee );
 572  
 573          // Normalize <br>
 574          $pee = str_replace( array( '<br>', '<br/>' ), '<br />', $pee );
 575  
 576          // Replace any new line characters that aren't preceded by a <br /> with a <br />.
 577          $pee = preg_replace( '|(?<!<br />)\s*\n|', "<br />\n", $pee );
 578  
 579          // Replace newline placeholders with newlines.
 580          $pee = str_replace( '<WPPreserveNewline />', "\n", $pee );
 581      }
 582  
 583      // If a <br /> tag is after an opening or closing block tag, remove it.
 584      $pee = preg_replace( '!(</?' . $allblocks . '[^>]*>)\s*<br />!', '$1', $pee );
 585  
 586      // If a <br /> tag is before a subset of opening or closing block tags, remove it.
 587      $pee = preg_replace( '!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee );
 588      $pee = preg_replace( "|\n</p>$|", '</p>', $pee );
 589  
 590      // Replace placeholder <pre> tags with their original content.
 591      if ( ! empty( $pre_tags ) ) {
 592          $pee = str_replace( array_keys( $pre_tags ), array_values( $pre_tags ), $pee );
 593      }
 594  
 595      // Restore newlines in all elements.
 596      if ( false !== strpos( $pee, '<!-- wpnl -->' ) ) {
 597          $pee = str_replace( array( ' <!-- wpnl --> ', '<!-- wpnl -->' ), "\n", $pee );
 598      }
 599  
 600      return $pee;
 601  }
 602  
 603  /**
 604   * Separate HTML elements and comments from the text.
 605   *
 606   * @since 4.2.4
 607   *
 608   * @param string $input The text which has to be formatted.
 609   * @return string[] Array of the formatted text.
 610   */
 611  function wp_html_split( $input ) {
 612      return preg_split( get_html_split_regex(), $input, -1, PREG_SPLIT_DELIM_CAPTURE );
 613  }
 614  
 615  /**
 616   * Retrieve the regular expression for an HTML element.
 617   *
 618   * @since 4.4.0
 619   *
 620   * @return string The regular expression
 621   */
 622  function get_html_split_regex() {
 623      static $regex;
 624  
 625      if ( ! isset( $regex ) ) {
 626          // phpcs:disable Squiz.Strings.ConcatenationSpacing.PaddingFound -- don't remove regex indentation
 627          $comments =
 628              '!'             // Start of comment, after the <.
 629              . '(?:'         // Unroll the loop: Consume everything until --> is found.
 630              .     '-(?!->)' // Dash not followed by end of comment.
 631              .     '[^\-]*+' // Consume non-dashes.
 632              . ')*+'         // Loop possessively.
 633              . '(?:-->)?';   // End of comment. If not found, match all input.
 634  
 635          $cdata =
 636              '!\[CDATA\['    // Start of comment, after the <.
 637              . '[^\]]*+'     // Consume non-].
 638              . '(?:'         // Unroll the loop: Consume everything until ]]> is found.
 639              .     '](?!]>)' // One ] not followed by end of comment.
 640              .     '[^\]]*+' // Consume non-].
 641              . ')*+'         // Loop possessively.
 642              . '(?:]]>)?';   // End of comment. If not found, match all input.
 643  
 644          $escaped =
 645              '(?='             // Is the element escaped?
 646              .    '!--'
 647              . '|'
 648              .    '!\[CDATA\['
 649              . ')'
 650              . '(?(?=!-)'      // If yes, which type?
 651              .     $comments
 652              . '|'
 653              .     $cdata
 654              . ')';
 655  
 656          $regex =
 657              '/('                // Capture the entire match.
 658              .     '<'           // Find start of element.
 659              .     '(?'          // Conditional expression follows.
 660              .         $escaped  // Find end of escaped element.
 661              .     '|'           // ...else...
 662              .         '[^>]*>?' // Find end of normal element.
 663              .     ')'
 664              . ')/';
 665          // phpcs:enable
 666      }
 667  
 668      return $regex;
 669  }
 670  
 671  /**
 672   * Retrieve the combined regular expression for HTML and shortcodes.
 673   *
 674   * @access private
 675   * @ignore
 676   * @internal This function will be removed in 4.5.0 per Shortcode API Roadmap.
 677   * @since 4.4.0
 678   *
 679   * @param string $shortcode_regex The result from _get_wptexturize_shortcode_regex(). Optional.
 680   * @return string The regular expression
 681   */
 682  function _get_wptexturize_split_regex( $shortcode_regex = '' ) {
 683      static $html_regex;
 684  
 685      if ( ! isset( $html_regex ) ) {
 686          // phpcs:disable Squiz.Strings.ConcatenationSpacing.PaddingFound -- don't remove regex indentation
 687          $comment_regex =
 688              '!'             // Start of comment, after the <.
 689              . '(?:'         // Unroll the loop: Consume everything until --> is found.
 690              .     '-(?!->)' // Dash not followed by end of comment.
 691              .     '[^\-]*+' // Consume non-dashes.
 692              . ')*+'         // Loop possessively.
 693              . '(?:-->)?';   // End of comment. If not found, match all input.
 694  
 695          $html_regex = // Needs replaced with wp_html_split() per Shortcode API Roadmap.
 696              '<'                  // Find start of element.
 697              . '(?(?=!--)'        // Is this a comment?
 698              .     $comment_regex // Find end of comment.
 699              . '|'
 700              .     '[^>]*>?'      // Find end of element. If not found, match all input.
 701              . ')';
 702          // phpcs:enable
 703      }
 704  
 705      if ( empty( $shortcode_regex ) ) {
 706          $regex = '/(' . $html_regex . ')/';
 707      } else {
 708          $regex = '/(' . $html_regex . '|' . $shortcode_regex . ')/';
 709      }
 710  
 711      return $regex;
 712  }
 713  
 714  /**
 715   * Retrieve the regular expression for shortcodes.
 716   *
 717   * @access private
 718   * @ignore
 719   * @since 4.4.0
 720   *
 721   * @param string[] $tagnames Array of shortcodes to find.
 722   * @return string The regular expression
 723   */
 724  function _get_wptexturize_shortcode_regex( $tagnames ) {
 725      $tagregexp = implode( '|', array_map( 'preg_quote', $tagnames ) );
 726      $tagregexp = "(?:$tagregexp)(?=[\\s\\]\\/])"; // Excerpt of get_shortcode_regex().
 727      // phpcs:disable Squiz.Strings.ConcatenationSpacing.PaddingFound -- don't remove regex indentation
 728      $regex =
 729          '\['                // Find start of shortcode.
 730          . '[\/\[]?'         // Shortcodes may begin with [/ or [[.
 731          . $tagregexp        // Only match registered shortcodes, because performance.
 732          . '(?:'
 733          .     '[^\[\]<>]+'  // Shortcodes do not contain other shortcodes. Quantifier critical.
 734          . '|'
 735          .     '<[^\[\]>]*>' // HTML elements permitted. Prevents matching ] before >.
 736          . ')*+'             // Possessive critical.
 737          . '\]'              // Find end of shortcode.
 738          . '\]?';            // Shortcodes may end with ]].
 739      // phpcs:enable
 740  
 741      return $regex;
 742  }
 743  
 744  /**
 745   * Replace characters or phrases within HTML elements only.
 746   *
 747   * @since 4.2.3
 748   *
 749   * @param string $haystack      The text which has to be formatted.
 750   * @param array  $replace_pairs In the form array('from' => 'to', ...).
 751   * @return string The formatted text.
 752   */
 753  function wp_replace_in_html_tags( $haystack, $replace_pairs ) {
 754      // Find all elements.
 755      $textarr = wp_html_split( $haystack );
 756      $changed = false;
 757  
 758      // Optimize when searching for one item.
 759      if ( 1 === count( $replace_pairs ) ) {
 760          // Extract $needle and $replace.
 761          foreach ( $replace_pairs as $needle => $replace ) {
 762          }
 763  
 764          // Loop through delimiters (elements) only.
 765          for ( $i = 1, $c = count( $textarr ); $i < $c; $i += 2 ) {
 766              if ( false !== strpos( $textarr[ $i ], $needle ) ) {
 767                  $textarr[ $i ] = str_replace( $needle, $replace, $textarr[ $i ] );
 768                  $changed       = true;
 769              }
 770          }
 771      } else {
 772          // Extract all $needles.
 773          $needles = array_keys( $replace_pairs );
 774  
 775          // Loop through delimiters (elements) only.
 776          for ( $i = 1, $c = count( $textarr ); $i < $c; $i += 2 ) {
 777              foreach ( $needles as $needle ) {
 778                  if ( false !== strpos( $textarr[ $i ], $needle ) ) {
 779                      $textarr[ $i ] = strtr( $textarr[ $i ], $replace_pairs );
 780                      $changed       = true;
 781                      // After one strtr() break out of the foreach loop and look at next element.
 782                      break;
 783                  }
 784              }
 785          }
 786      }
 787  
 788      if ( $changed ) {
 789          $haystack = implode( $textarr );
 790      }
 791  
 792      return $haystack;
 793  }
 794  
 795  /**
 796   * Newline preservation help function for wpautop
 797   *
 798   * @since 3.1.0
 799   * @access private
 800   *
 801   * @param array $matches preg_replace_callback matches array
 802   * @return string
 803   */
 804  function _autop_newline_preservation_helper( $matches ) {
 805      return str_replace( "\n", '<WPPreserveNewline />', $matches[0] );
 806  }
 807  
 808  /**
 809   * Don't auto-p wrap shortcodes that stand alone
 810   *
 811   * Ensures that shortcodes are not wrapped in `<p>...</p>`.
 812   *
 813   * @since 2.9.0
 814   *
 815   * @global array $shortcode_tags
 816   *
 817   * @param string $pee The content.
 818   * @return string The filtered content.
 819   */
 820  function shortcode_unautop( $pee ) {
 821      global $shortcode_tags;
 822  
 823      if ( empty( $shortcode_tags ) || ! is_array( $shortcode_tags ) ) {
 824          return $pee;
 825      }
 826  
 827      $tagregexp = implode( '|', array_map( 'preg_quote', array_keys( $shortcode_tags ) ) );
 828      $spaces    = wp_spaces_regexp();
 829  
 830      // phpcs:disable Squiz.Strings.ConcatenationSpacing.PaddingFound,WordPress.WhiteSpace.PrecisionAlignment.Found -- don't remove regex indentation
 831      $pattern =
 832          '/'
 833          . '<p>'                              // Opening paragraph.
 834          . '(?:' . $spaces . ')*+'            // Optional leading whitespace.
 835          . '('                                // 1: The shortcode.
 836          .     '\\['                          // Opening bracket.
 837          .     "($tagregexp)"                 // 2: Shortcode name.
 838          .     '(?![\\w-])'                   // Not followed by word character or hyphen.
 839                                               // Unroll the loop: Inside the opening shortcode tag.
 840          .     '[^\\]\\/]*'                   // Not a closing bracket or forward slash.
 841          .     '(?:'
 842          .         '\\/(?!\\])'               // A forward slash not followed by a closing bracket.
 843          .         '[^\\]\\/]*'               // Not a closing bracket or forward slash.
 844          .     ')*?'
 845          .     '(?:'
 846          .         '\\/\\]'                   // Self closing tag and closing bracket.
 847          .     '|'
 848          .         '\\]'                      // Closing bracket.
 849          .         '(?:'                      // Unroll the loop: Optionally, anything between the opening and closing shortcode tags.
 850          .             '[^\\[]*+'             // Not an opening bracket.
 851          .             '(?:'
 852          .                 '\\[(?!\\/\\2\\])' // An opening bracket not followed by the closing shortcode tag.
 853          .                 '[^\\[]*+'         // Not an opening bracket.
 854          .             ')*+'
 855          .             '\\[\\/\\2\\]'         // Closing shortcode tag.
 856          .         ')?'
 857          .     ')'
 858          . ')'
 859          . '(?:' . $spaces . ')*+'            // Optional trailing whitespace.
 860          . '<\\/p>'                           // Closing paragraph.
 861          . '/';
 862      // phpcs:enable
 863  
 864      return preg_replace( $pattern, '$1', $pee );
 865  }
 866  
 867  /**
 868   * Checks to see if a string is utf8 encoded.
 869   *
 870   * NOTE: This function checks for 5-Byte sequences, UTF8
 871   *       has Bytes Sequences with a maximum length of 4.
 872   *
 873   * @author bmorel at ssi dot fr (modified)
 874   * @since 1.2.1
 875   *
 876   * @param string $str The string to be checked
 877   * @return bool True if $str fits a UTF-8 model, false otherwise.
 878   */
 879  function seems_utf8( $str ) {
 880      mbstring_binary_safe_encoding();
 881      $length = strlen( $str );
 882      reset_mbstring_encoding();
 883      for ( $i = 0; $i < $length; $i++ ) {
 884          $c = ord( $str[ $i ] );
 885          if ( $c < 0x80 ) {
 886              $n = 0; // 0bbbbbbb
 887          } elseif ( ( $c & 0xE0 ) == 0xC0 ) {
 888              $n = 1; // 110bbbbb
 889          } elseif ( ( $c & 0xF0 ) == 0xE0 ) {
 890              $n = 2; // 1110bbbb
 891          } elseif ( ( $c & 0xF8 ) == 0xF0 ) {
 892              $n = 3; // 11110bbb
 893          } elseif ( ( $c & 0xFC ) == 0xF8 ) {
 894              $n = 4; // 111110bb
 895          } elseif ( ( $c & 0xFE ) == 0xFC ) {
 896              $n = 5; // 1111110b
 897          } else {
 898              return false; // Does not match any model.
 899          }
 900          for ( $j = 0; $j < $n; $j++ ) { // n bytes matching 10bbbbbb follow ?
 901              if ( ( ++$i == $length ) || ( ( ord( $str[ $i ] ) & 0xC0 ) != 0x80 ) ) {
 902                  return false;
 903              }
 904          }
 905      }
 906      return true;
 907  }
 908  
 909  /**
 910   * Converts a number of special characters into their HTML entities.
 911   *
 912   * Specifically deals with: &, <, >, ", and '.
 913   *
 914   * $quote_style can be set to ENT_COMPAT to encode " to
 915   * &quot;, or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded.
 916   *
 917   * @since 1.2.2
 918   * @since 5.5.0 `$quote_style` also accepts `ENT_XML1`.
 919   * @access private
 920   *
 921   * @param string       $string        The text which is to be encoded.
 922   * @param int|string   $quote_style   Optional. Converts double quotes if set to ENT_COMPAT,
 923   *                                    both single and double if set to ENT_QUOTES or none if set to ENT_NOQUOTES.
 924   *                                    Converts single and double quotes, as well as converting HTML
 925   *                                    named entities (that are not also XML named entities) to their
 926   *                                    code points if set to ENT_XML1. Also compatible with old values;
 927   *                                    converting single quotes if set to 'single',
 928   *                                    double if set to 'double' or both if otherwise set.
 929   *                                    Default is ENT_NOQUOTES.
 930   * @param false|string $charset       Optional. The character encoding of the string. Default false.
 931   * @param bool         $double_encode Optional. Whether to encode existing HTML entities. Default false.
 932   * @return string The encoded text with HTML entities.
 933   */
 934  function _wp_specialchars( $string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false ) {
 935      $string = (string) $string;
 936  
 937      if ( 0 === strlen( $string ) ) {
 938          return '';
 939      }
 940  
 941      // Don't bother if there are no specialchars - saves some processing.
 942      if ( ! preg_match( '/[&<>"\']/', $string ) ) {
 943          return $string;
 944      }
 945  
 946      // Account for the previous behaviour of the function when the $quote_style is not an accepted value.
 947      if ( empty( $quote_style ) ) {
 948          $quote_style = ENT_NOQUOTES;
 949      } elseif ( ENT_XML1 === $quote_style ) {
 950          $quote_style = ENT_QUOTES | ENT_XML1;
 951      } elseif ( ! in_array( $quote_style, array( ENT_NOQUOTES, ENT_COMPAT, ENT_QUOTES, 'single', 'double' ), true ) ) {
 952          $quote_style = ENT_QUOTES;
 953      }
 954  
 955      // Store the site charset as a static to avoid multiple calls to wp_load_alloptions().
 956      if ( ! $charset ) {
 957          static $_charset = null;
 958          if ( ! isset( $_charset ) ) {
 959              $alloptions = wp_load_alloptions();
 960              $_charset   = isset( $alloptions['blog_charset'] ) ? $alloptions['blog_charset'] : '';
 961          }
 962          $charset = $_charset;
 963      }
 964  
 965      if ( in_array( $charset, array( 'utf8', 'utf-8', 'UTF8' ), true ) ) {
 966          $charset = 'UTF-8';
 967      }
 968  
 969      $_quote_style = $quote_style;
 970  
 971      if ( 'double' === $quote_style ) {
 972          $quote_style  = ENT_COMPAT;
 973          $_quote_style = ENT_COMPAT;
 974      } elseif ( 'single' === $quote_style ) {
 975          $quote_style = ENT_NOQUOTES;
 976      }
 977  
 978      if ( ! $double_encode ) {
 979          // Guarantee every &entity; is valid, convert &garbage; into &amp;garbage;
 980          // This is required for PHP < 5.4.0 because ENT_HTML401 flag is unavailable.
 981          $string = wp_kses_normalize_entities( $string, ( $quote_style & ENT_XML1 ) ? 'xml' : 'html' );
 982      }
 983  
 984      $string = htmlspecialchars( $string, $quote_style, $charset, $double_encode );
 985  
 986      // Back-compat.
 987      if ( 'single' === $_quote_style ) {
 988          $string = str_replace( "'", '&#039;', $string );
 989      }
 990  
 991      return $string;
 992  }
 993  
 994  /**
 995   * Converts a number of HTML entities into their special characters.
 996   *
 997   * Specifically deals with: &, <, >, ", and '.
 998   *
 999   * $quote_style can be set to ENT_COMPAT to decode " entities,
1000   * or ENT_QUOTES to do both " and '. Default is ENT_NOQUOTES where no quotes are decoded.
1001   *
1002   * @since 2.8.0
1003   *
1004   * @param string     $string The text which is to be decoded.
1005   * @param string|int $quote_style Optional. Converts double quotes if set to ENT_COMPAT,
1006   *                                both single and double if set to ENT_QUOTES or
1007   *                                none if set to ENT_NOQUOTES.
1008   *                                Also compatible with old _wp_specialchars() values;
1009   *                                converting single quotes if set to 'single',
1010   *                                double if set to 'double' or both if otherwise set.
1011   *                                Default is ENT_NOQUOTES.
1012   * @return string The decoded text without HTML entities.
1013   */
1014  function wp_specialchars_decode( $string, $quote_style = ENT_NOQUOTES ) {
1015      $string = (string) $string;
1016  
1017      if ( 0 === strlen( $string ) ) {
1018          return '';
1019      }
1020  
1021      // Don't bother if there are no entities - saves a lot of processing.
1022      if ( strpos( $string, '&' ) === false ) {
1023          return $string;
1024      }
1025  
1026      // Match the previous behaviour of _wp_specialchars() when the $quote_style is not an accepted value.
1027      if ( empty( $quote_style ) ) {
1028          $quote_style = ENT_NOQUOTES;
1029      } elseif ( ! in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
1030          $quote_style = ENT_QUOTES;
1031      }
1032  
1033      // More complete than get_html_translation_table( HTML_SPECIALCHARS ).
1034      $single      = array(
1035          '&#039;' => '\'',
1036          '&#x27;' => '\'',
1037      );
1038      $single_preg = array(
1039          '/&#0*39;/'   => '&#039;',
1040          '/&#x0*27;/i' => '&#x27;',
1041      );
1042      $double      = array(
1043          '&quot;' => '"',
1044          '&#034;' => '"',
1045          '&#x22;' => '"',
1046      );
1047      $double_preg = array(
1048          '/&#0*34;/'   => '&#034;',
1049          '/&#x0*22;/i' => '&#x22;',
1050      );
1051      $others      = array(
1052          '&lt;'   => '<',
1053          '&#060;' => '<',
1054          '&gt;'   => '>',
1055          '&#062;' => '>',
1056          '&amp;'  => '&',
1057          '&#038;' => '&',
1058          '&#x26;' => '&',
1059      );
1060      $others_preg = array(
1061          '/&#0*60;/'   => '&#060;',
1062          '/&#0*62;/'   => '&#062;',
1063          '/&#0*38;/'   => '&#038;',
1064          '/&#x0*26;/i' => '&#x26;',
1065      );
1066  
1067      if ( ENT_QUOTES === $quote_style ) {
1068          $translation      = array_merge( $single, $double, $others );
1069          $translation_preg = array_merge( $single_preg, $double_preg, $others_preg );
1070      } elseif ( ENT_COMPAT === $quote_style || 'double' === $quote_style ) {
1071          $translation      = array_merge( $double, $others );
1072          $translation_preg = array_merge( $double_preg, $others_preg );
1073      } elseif ( 'single' === $quote_style ) {
1074          $translation      = array_merge( $single, $others );
1075          $translation_preg = array_merge( $single_preg, $others_preg );
1076      } elseif ( ENT_NOQUOTES === $quote_style ) {
1077          $translation      = $others;
1078          $translation_preg = $others_preg;
1079      }
1080  
1081      // Remove zero padding on numeric entities.
1082      $string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string );
1083  
1084      // Replace characters according to translation table.
1085      return strtr( $string, $translation );
1086  }
1087  
1088  /**
1089   * Checks for invalid UTF8 in a string.
1090   *
1091   * @since 2.8.0
1092   *
1093   * @param string $string The text which is to be checked.
1094   * @param bool   $strip  Optional. Whether to attempt to strip out invalid UTF8. Default false.
1095   * @return string The checked text.
1096   */
1097  function wp_check_invalid_utf8( $string, $strip = false ) {
1098      $string = (string) $string;
1099  
1100      if ( 0 === strlen( $string ) ) {
1101          return '';
1102      }
1103  
1104      // Store the site charset as a static to avoid multiple calls to get_option().
1105      static $is_utf8 = null;
1106      if ( ! isset( $is_utf8 ) ) {
1107          $is_utf8 = in_array( get_option( 'blog_charset' ), array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ), true );
1108      }
1109      if ( ! $is_utf8 ) {
1110          return $string;
1111      }
1112  
1113      // Check for support for utf8 in the installed PCRE library once and store the result in a static.
1114      static $utf8_pcre = null;
1115      if ( ! isset( $utf8_pcre ) ) {
1116          // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
1117          $utf8_pcre = @preg_match( '/^./u', 'a' );
1118      }
1119      // We can't demand utf8 in the PCRE installation, so just return the string in those cases.
1120      if ( ! $utf8_pcre ) {
1121          return $string;
1122      }
1123  
1124      // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- preg_match fails when it encounters invalid UTF8 in $string.
1125      if ( 1 === @preg_match( '/^./us', $string ) ) {
1126          return $string;
1127      }
1128  
1129      // Attempt to strip the bad chars if requested (not recommended).
1130      if ( $strip && function_exists( 'iconv' ) ) {
1131          return iconv( 'utf-8', 'utf-8', $string );
1132      }
1133  
1134      return '';
1135  }
1136  
1137  /**
1138   * Encode the Unicode values to be used in the URI.
1139   *
1140   * @since 1.5.0
1141   *
1142   * @param string $utf8_string
1143   * @param int    $length Max  length of the string
1144   * @return string String with Unicode encoded for URI.
1145   */
1146  function utf8_uri_encode( $utf8_string, $length = 0 ) {
1147      $unicode        = '';
1148      $values         = array();
1149      $num_octets     = 1;
1150      $unicode_length = 0;
1151  
1152      mbstring_binary_safe_encoding();
1153      $string_length = strlen( $utf8_string );
1154      reset_mbstring_encoding();
1155  
1156      for ( $i = 0; $i < $string_length; $i++ ) {
1157  
1158          $value = ord( $utf8_string[ $i ] );
1159  
1160          if ( $value < 128 ) {
1161              if ( $length && ( $unicode_length >= $length ) ) {
1162                  break;
1163              }
1164              $unicode .= chr( $value );
1165              $unicode_length++;
1166          } else {
1167              if ( count( $values ) == 0 ) {
1168                  if ( $value < 224 ) {
1169                      $num_octets = 2;
1170                  } elseif ( $value < 240 ) {
1171                      $num_octets = 3;
1172                  } else {
1173                      $num_octets = 4;
1174                  }
1175              }
1176  
1177              $values[] = $value;
1178  
1179              if ( $length && ( $unicode_length + ( $num_octets * 3 ) ) > $length ) {
1180                  break;
1181              }
1182              if ( count( $values ) == $num_octets ) {
1183                  for ( $j = 0; $j < $num_octets; $j++ ) {
1184                      $unicode .= '%' . dechex( $values[ $j ] );
1185                  }
1186  
1187                  $unicode_length += $num_octets * 3;
1188  
1189                  $values     = array();
1190                  $num_octets = 1;
1191              }
1192          }
1193      }
1194  
1195      return $unicode;
1196  }
1197  
1198  /**
1199   * Converts all accent characters to ASCII characters.
1200   *
1201   * If there are no accent characters, then the string given is just returned.
1202   *
1203   * **Accent characters converted:**
1204   *
1205   * Currency signs:
1206   *
1207   * |   Code   | Glyph | Replacement |     Description     |
1208   * | -------- | ----- | ----------- | ------------------- |
1209   * | U+00A3   | £     | (empty)     | British Pound sign  |
1210   * | U+20AC   | €     | E           | Euro sign           |
1211   *
1212   * Decompositions for Latin-1 Supplement:
1213   *
1214   * |  Code   | Glyph | Replacement |               Description              |
1215   * | ------- | ----- | ----------- | -------------------------------------- |
1216   * | U+00AA  | ª     | a           | Feminine ordinal indicator             |
1217   * | U+00BA  | º     | o           | Masculine ordinal indicator            |
1218   * | U+00C0  | À     | A           | Latin capital letter A with grave      |
1219   * | U+00C1  | Á     | A           | Latin capital letter A with acute      |
1220   * | U+00C2  | Â     | A           | Latin capital letter A with circumflex |
1221   * | U+00C3  | Ã     | A           | Latin capital letter A with tilde      |
1222   * | U+00C4  | Ä     | A           | Latin capital letter A with diaeresis  |
1223   * | U+00C5  | Å     | A           | Latin capital letter A with ring above |
1224   * | U+00C6  | Æ     | AE          | Latin capital letter AE                |
1225   * | U+00C7  | Ç     | C           | Latin capital letter C with cedilla    |
1226   * | U+00C8  | È     | E           | Latin capital letter E with grave      |
1227   * | U+00C9  | É     | E           | Latin capital letter E with acute      |
1228   * | U+00CA  | Ê     | E           | Latin capital letter E with circumflex |
1229   * | U+00CB  | Ë     | E           | Latin capital letter E with diaeresis  |
1230   * | U+00CC  | Ì     | I           | Latin capital letter I with grave      |
1231   * | U+00CD  | Í     | I           | Latin capital letter I with acute      |
1232   * | U+00CE  | Î     | I           | Latin capital letter I with circumflex |
1233   * | U+00CF  | Ï     | I           | Latin capital letter I with diaeresis  |
1234   * | U+00D0  | Ð     | D           | Latin capital letter Eth               |
1235   * | U+00D1  | Ñ     | N           | Latin capital letter N with tilde      |
1236   * | U+00D2  | Ò     | O           | Latin capital letter O with grave      |
1237   * | U+00D3  | Ó     | O           | Latin capital letter O with acute      |
1238   * | U+00D4  | Ô     | O           | Latin capital letter O with circumflex |
1239   * | U+00D5  | Õ     | O           | Latin capital letter O with tilde      |
1240   * | U+00D6  | Ö     | O           | Latin capital letter O with diaeresis  |
1241   * | U+00D8  | Ø     | O           | Latin capital letter O with stroke     |
1242   * | U+00D9  | Ù     | U           | Latin capital letter U with grave      |
1243   * | U+00DA  | Ú     | U           | Latin capital letter U with acute      |
1244   * | U+00DB  | Û     | U           | Latin capital letter U with circumflex |
1245   * | U+00DC  | Ü     | U           | Latin capital letter U with diaeresis  |
1246   * | U+00DD  | Ý     | Y           | Latin capital letter Y with acute      |
1247   * | U+00DE  | Þ     | TH          | Latin capital letter Thorn             |
1248   * | U+00DF  | ß     | s           | Latin small letter sharp s             |
1249   * | U+00E0  | à     | a           | Latin small letter a with grave        |
1250   * | U+00E1  | á     | a           | Latin small letter a with acute        |
1251   * | U+00E2  | â     | a           | Latin small letter a with circumflex   |
1252   * | U+00E3  | ã     | a           | Latin small letter a with tilde        |
1253   * | U+00E4  | ä     | a           | Latin small letter a with diaeresis    |
1254   * | U+00E5  | å     | a           | Latin small letter a with ring above   |
1255   * | U+00E6  | æ     | ae          | Latin small letter ae                  |
1256   * | U+00E7  | ç     | c           | Latin small letter c with cedilla      |
1257   * | U+00E8  | è     | e           | Latin small letter e with grave        |
1258   * | U+00E9  | é     | e           | Latin small letter e with acute        |
1259   * | U+00EA  | ê     | e           | Latin small letter e with circumflex   |
1260   * | U+00EB  | ë     | e           | Latin small letter e with diaeresis    |
1261   * | U+00EC  | ì     | i           | Latin small letter i with grave        |
1262   * | U+00ED  | í     | i           | Latin small letter i with acute        |
1263   * | U+00EE  | î     | i           | Latin small letter i with circumflex   |
1264   * | U+00EF  | ï     | i           | Latin small letter i with diaeresis    |
1265   * | U+00F0  | ð     | d           | Latin small letter Eth                 |
1266   * | U+00F1  | ñ     | n           | Latin small letter n with tilde        |
1267   * | U+00F2  | ò     | o           | Latin small letter o with grave        |
1268   * | U+00F3  | ó     | o           | Latin small letter o with acute        |
1269   * | U+00F4  | ô     | o           | Latin small letter o with circumflex   |
1270   * | U+00F5  | õ     | o           | Latin small letter o with tilde        |
1271   * | U+00F6  | ö     | o           | Latin small letter o with diaeresis    |
1272   * | U+00F8  | ø     | o           | Latin small letter o with stroke       |
1273   * | U+00F9  | ù     | u           | Latin small letter u with grave        |
1274   * | U+00FA  | ú     | u           | Latin small letter u with acute        |
1275   * | U+00FB  | û     | u           | Latin small letter u with circumflex   |
1276   * | U+00FC  | ü     | u           | Latin small letter u with diaeresis    |
1277   * | U+00FD  | ý     | y           | Latin small letter y with acute        |
1278   * | U+00FE  | þ     | th          | Latin small letter Thorn               |
1279   * | U+00FF  | ÿ     | y           | Latin small letter y with diaeresis    |
1280   *
1281   * Decompositions for Latin Extended-A:
1282   *
1283   * |  Code   | Glyph | Replacement |                    Description                    |
1284   * | ------- | ----- | ----------- | ------------------------------------------------- |
1285   * | U+0100  | Ā     | A           | Latin capital letter A with macron                |
1286   * | U+0101  | ā     | a           | Latin small letter a with macron                  |
1287   * | U+0102  | Ă     | A           | Latin capital letter A with breve                 |
1288   * | U+0103  | ă     | a           | Latin small letter a with breve                   |
1289   * | U+0104  | Ą     | A           | Latin capital letter A with ogonek                |
1290   * | U+0105  | ą     | a           | Latin small letter a with ogonek                  |
1291   * | U+01006 | Ć     | C           | Latin capital letter C with acute                 |
1292   * | U+0107  | ć     | c           | Latin small letter c with acute                   |
1293   * | U+0108  | Ĉ     | C           | Latin capital letter C with circumflex            |
1294   * | U+0109  | ĉ     | c           | Latin small letter c with circumflex              |
1295   * | U+010A  | Ċ     | C           | Latin capital letter C with dot above             |
1296   * | U+010B  | ċ     | c           | Latin small letter c with dot above               |
1297   * | U+010C  | Č     | C           | Latin capital letter C with caron                 |
1298   * | U+010D  | č     | c           | Latin small letter c with caron                   |
1299   * | U+010E  | Ď     | D           | Latin capital letter D with caron                 |
1300   * | U+010F  | ď     | d           | Latin small letter d with caron                   |
1301   * | U+0110  | Đ     | D           | Latin capital letter D with stroke                |
1302   * | U+0111  | đ     | d           | Latin small letter d with stroke                  |
1303   * | U+0112  | Ē     | E           | Latin capital letter E with macron                |
1304   * | U+0113  | ē     | e           | Latin small letter e with macron                  |
1305   * | U+0114  | Ĕ     | E           | Latin capital letter E with breve                 |
1306   * | U+0115  | ĕ     | e           | Latin small letter e with breve                   |
1307   * | U+0116  | Ė     | E           | Latin capital letter E with dot above             |
1308   * | U+0117  | ė     | e           | Latin small letter e with dot above               |
1309   * | U+0118  | Ę     | E           | Latin capital letter E with ogonek                |
1310   * | U+0119  | ę     | e           | Latin small letter e with ogonek                  |
1311   * | U+011A  | Ě     | E           | Latin capital letter E with caron                 |
1312   * | U+011B  | ě     | e           | Latin small letter e with caron                   |
1313   * | U+011C  | Ĝ     | G           | Latin capital letter G with circumflex            |
1314   * | U+011D  | ĝ     | g           | Latin small letter g with circumflex              |
1315   * | U+011E  | Ğ     | G           | Latin capital letter G with breve                 |
1316   * | U+011F  | ğ     | g           | Latin small letter g with breve                   |
1317   * | U+0120  | Ġ     | G           | Latin capital letter G with dot above             |
1318   * | U+0121  | ġ     | g           | Latin small letter g with dot above               |
1319   * | U+0122  | Ģ     | G           | Latin capital letter G with cedilla               |
1320   * | U+0123  | ģ     | g           | Latin small letter g with cedilla                 |
1321   * | U+0124  | Ĥ     | H           | Latin capital letter H with circumflex            |
1322   * | U+0125  | ĥ     | h           | Latin small letter h with circumflex              |
1323   * | U+0126  | Ħ     | H           | Latin capital letter H with stroke                |
1324   * | U+0127  | ħ     | h           | Latin small letter h with stroke                  |
1325   * | U+0128  | Ĩ     | I           | Latin capital letter I with tilde                 |
1326   * | U+0129  | ĩ     | i           | Latin small letter i with tilde                   |
1327   * | U+012A  | Ī     | I           | Latin capital letter I with macron                |
1328   * | U+012B  | ī     | i           | Latin small letter i with macron                  |
1329   * | U+012C  | Ĭ     | I           | Latin capital letter I with breve                 |
1330   * | U+012D  | ĭ     | i           | Latin small letter i with breve                   |
1331   * | U+012E  | Į     | I           | Latin capital letter I with ogonek                |
1332   * | U+012F  | į     | i           | Latin small letter i with ogonek                  |
1333   * | U+0130  | İ     | I           | Latin capital letter I with dot above             |
1334   * | U+0131  | ı     | i           | Latin small letter dotless i                      |
1335   * | U+0132  | IJ     | IJ          | Latin capital ligature IJ                         |
1336   * | U+0133  | ij     | ij          | Latin small ligature ij                           |
1337   * | U+0134  | Ĵ     | J           | Latin capital letter J with circumflex            |
1338   * | U+0135  | ĵ     | j           | Latin small letter j with circumflex              |
1339   * | U+0136  | Ķ     | K           | Latin capital letter K with cedilla               |
1340   * | U+0137  | ķ     | k           | Latin small letter k with cedilla                 |
1341   * | U+0138  | ĸ     | k           | Latin small letter Kra                            |
1342   * | U+0139  | Ĺ     | L           | Latin capital letter L with acute                 |
1343   * | U+013A  | ĺ     | l           | Latin small letter l with acute                   |
1344   * | U+013B  | Ļ     | L           | Latin capital letter L with cedilla               |
1345   * | U+013C  | ļ     | l           | Latin small letter l with cedilla                 |
1346   * | U+013D  | Ľ     | L           | Latin capital letter L with caron                 |
1347   * | U+013E  | ľ     | l           | Latin small letter l with caron                   |
1348   * | U+013F  | Ŀ     | L           | Latin capital letter L with middle dot            |
1349   * | U+0140  | ŀ     | l           | Latin small letter l with middle dot              |
1350   * | U+0141  | Ł     | L           | Latin capital letter L with stroke                |
1351   * | U+0142  | ł     | l           | Latin small letter l with stroke                  |
1352   * | U+0143  | Ń     | N           | Latin capital letter N with acute                 |
1353   * | U+0144  | ń     | n           | Latin small letter N with acute                   |
1354   * | U+0145  | Ņ     | N           | Latin capital letter N with cedilla               |
1355   * | U+0146  | ņ     | n           | Latin small letter n with cedilla                 |
1356   * | U+0147  | Ň     | N           | Latin capital letter N with caron                 |
1357   * | U+0148  | ň     | n           | Latin small letter n with caron                   |
1358   * | U+0149  | ʼn     | n           | Latin small letter n preceded by apostrophe       |
1359   * | U+014A  | Ŋ     | N           | Latin capital letter Eng                          |
1360   * | U+014B  | ŋ     | n           | Latin small letter Eng                            |
1361   * | U+014C  | Ō     | O           | Latin capital letter O with macron                |
1362   * | U+014D  | ō     | o           | Latin small letter o with macron                  |
1363   * | U+014E  | Ŏ     | O           | Latin capital letter O with breve                 |
1364   * | U+014F  | ŏ     | o           | Latin small letter o with breve                   |
1365   * | U+0150  | Ő     | O           | Latin capital letter O with double acute          |
1366   * | U+0151  | ő     | o           | Latin small letter o with double acute            |
1367   * | U+0152  | Π    | OE          | Latin capital ligature OE                         |
1368   * | U+0153  | œ     | oe          | Latin small ligature oe                           |
1369   * | U+0154  | Ŕ     | R           | Latin capital letter R with acute                 |
1370   * | U+0155  | ŕ     | r           | Latin small letter r with acute                   |
1371   * | U+0156  | Ŗ     | R           | Latin capital letter R with cedilla               |
1372   * | U+0157  | ŗ     | r           | Latin small letter r with cedilla                 |
1373   * | U+0158  | Ř     | R           | Latin capital letter R with caron                 |
1374   * | U+0159  | ř     | r           | Latin small letter r with caron                   |
1375   * | U+015A  | Ś     | S           | Latin capital letter S with acute                 |
1376   * | U+015B  | ś     | s           | Latin small letter s with acute                   |
1377   * | U+015C  | Ŝ     | S           | Latin capital letter S with circumflex            |
1378   * | U+015D  | ŝ     | s           | Latin small letter s with circumflex              |
1379   * | U+015E  | Ş     | S           | Latin capital letter S with cedilla               |
1380   * | U+015F  | ş     | s           | Latin small letter s with cedilla                 |
1381   * | U+0160  | Š     | S           | Latin capital letter S with caron                 |
1382   * | U+0161  | š     | s           | Latin small letter s with caron                   |
1383   * | U+0162  | Ţ     | T           | Latin capital letter T with cedilla               |
1384   * | U+0163  | ţ     | t           | Latin small letter t with cedilla                 |
1385   * | U+0164  | Ť     | T           | Latin capital letter T with caron                 |
1386   * | U+0165  | ť     | t           | Latin small letter t with caron                   |
1387   * | U+0166  | Ŧ     | T           | Latin capital letter T with stroke                |
1388   * | U+0167  | ŧ     | t           | Latin small letter t with stroke                  |
1389   * | U+0168  | Ũ     | U           | Latin capital letter U with tilde                 |
1390   * | U+0169  | ũ     | u           | Latin small letter u with tilde                   |
1391   * | U+016A  | Ū     | U           | Latin capital letter U with macron                |
1392   * | U+016B  | ū     | u           | Latin small letter u with macron                  |
1393   * | U+016C  | Ŭ     | U           | Latin capital letter U with breve                 |
1394   * | U+016D  | ŭ     | u           | Latin small letter u with breve                   |
1395   * | U+016E  | Ů     | U           | Latin capital letter U with ring above            |
1396   * | U+016F  | ů     | u           | Latin small letter u with ring above              |
1397   * | U+0170  | Ű     | U           | Latin capital letter U with double acute          |
1398   * | U+0171  | ű     | u           | Latin small letter u with double acute            |
1399   * | U+0172  | Ų     | U           | Latin capital letter U with ogonek                |
1400   * | U+0173  | ų     | u           | Latin small letter u with ogonek                  |
1401   * | U+0174  | Ŵ     | W           | Latin capital letter W with circumflex            |
1402   * | U+0175  | ŵ     | w           | Latin small letter w with circumflex              |
1403   * | U+0176  | Ŷ     | Y           | Latin capital letter Y with circumflex            |
1404   * | U+0177  | ŷ     | y           | Latin small letter y with circumflex              |
1405   * | U+0178  | Ÿ     | Y           | Latin capital letter Y with diaeresis             |
1406   * | U+0179  | Ź     | Z           | Latin capital letter Z with acute                 |
1407   * | U+017A  | ź     | z           | Latin small letter z with acute                   |
1408   * | U+017B  | Ż     | Z           | Latin capital letter Z with dot above             |
1409   * | U+017C  | ż     | z           | Latin small letter z with dot above               |
1410   * | U+017D  | Ž     | Z           | Latin capital letter Z with caron                 |
1411   * | U+017E  | ž     | z           | Latin small letter z with caron                   |
1412   * | U+017F  | ſ     | s           | Latin small letter long s                         |
1413   * | U+01A0  | Ơ     | O           | Latin capital letter O with horn                  |
1414   * | U+01A1  | ơ     | o           | Latin small letter o with horn                    |
1415   * | U+01AF  | Ư     | U           | Latin capital letter U with horn                  |
1416   * | U+01B0  | ư     | u           | Latin small letter u with horn                    |
1417   * | U+01CD  | Ǎ     | A           | Latin capital letter A with caron                 |
1418   * | U+01CE  | ǎ     | a           | Latin small letter a with caron                   |
1419   * | U+01CF  | Ǐ     | I           | Latin capital letter I with caron                 |
1420   * | U+01D0  | ǐ     | i           | Latin small letter i with caron                   |
1421   * | U+01D1  | Ǒ     | O           | Latin capital letter O with caron                 |
1422   * | U+01D2  | ǒ     | o           | Latin small letter o with caron                   |
1423   * | U+01D3  | Ǔ     | U           | Latin capital letter U with caron                 |
1424   * | U+01D4  | ǔ     | u           | Latin small letter u with caron                   |
1425   * | U+01D5  | Ǖ     | U           | Latin capital letter U with diaeresis and macron  |
1426   * | U+01D6  | ǖ     | u           | Latin small letter u with diaeresis and macron    |
1427   * | U+01D7  | Ǘ     | U           | Latin capital letter U with diaeresis and acute   |
1428   * | U+01D8  | ǘ     | u           | Latin small letter u with diaeresis and acute     |
1429   * | U+01D9  | Ǚ     | U           | Latin capital letter U with diaeresis and caron   |
1430   * | U+01DA  | ǚ     | u           | Latin small letter u with diaeresis and caron     |
1431   * | U+01DB  | Ǜ     | U           | Latin capital letter U with diaeresis and grave   |
1432   * | U+01DC  | ǜ     | u           | Latin small letter u with diaeresis and grave     |
1433   *
1434   * Decompositions for Latin Extended-B:
1435   *
1436   * |   Code   | Glyph | Replacement |                Description                |
1437   * | -------- | ----- | ----------- | ----------------------------------------- |
1438   * | U+0218   | Ș     | S           | Latin capital letter S with comma below   |
1439   * | U+0219   | ș     | s           | Latin small letter s with comma below     |
1440   * | U+021A   | Ț     | T           | Latin capital letter T with comma below   |
1441   * | U+021B   | ț     | t           | Latin small letter t with comma below     |
1442   *
1443   * Vowels with diacritic (Chinese, Hanyu Pinyin):
1444   *
1445   * |   Code   | Glyph | Replacement |                      Description                      |
1446   * | -------- | ----- | ----------- | ----------------------------------------------------- |
1447   * | U+0251   | ɑ     | a           | Latin small letter alpha                              |
1448   * | U+1EA0   | Ạ     | A           | Latin capital letter A with dot below                 |
1449   * | U+1EA1   | ạ     | a           | Latin small letter a with dot below                   |
1450   * | U+1EA2   | Ả     | A           | Latin capital letter A with hook above                |
1451   * | U+1EA3   | ả     | a           | Latin small letter a with hook above                  |
1452   * | U+1EA4   | Ấ     | A           | Latin capital letter A with circumflex and acute      |
1453   * | U+1EA5   | ấ     | a           | Latin small letter a with circumflex and acute        |
1454   * | U+1EA6   | Ầ     | A           | Latin capital letter A with circumflex and grave      |
1455   * | U+1EA7   | ầ     | a           | Latin small letter a with circumflex and grave        |
1456   * | U+1EA8   | Ẩ     | A           | Latin capital letter A with circumflex and hook above |
1457   * | U+1EA9   | ẩ     | a           | Latin small letter a with circumflex and hook above   |
1458   * | U+1EAA   | Ẫ     | A           | Latin capital letter A with circumflex and tilde      |
1459   * | U+1EAB   | ẫ     | a           | Latin small letter a with circumflex and tilde        |
1460   * | U+1EA6   | Ậ     | A           | Latin capital letter A with circumflex and dot below  |
1461   * | U+1EAD   | ậ     | a           | Latin small letter a with circumflex and dot below    |
1462   * | U+1EAE   | Ắ     | A           | Latin capital letter A with breve and acute           |
1463   * | U+1EAF   | ắ     | a           | Latin small letter a with breve and acute             |
1464   * | U+1EB0   | Ằ     | A           | Latin capital letter A with breve and grave           |
1465   * | U+1EB1   | ằ     | a           | Latin small letter a with breve and grave             |
1466   * | U+1EB2   | Ẳ     | A           | Latin capital letter A with breve and hook above      |
1467   * | U+1EB3   | ẳ     | a           | Latin small letter a with breve and hook above        |
1468   * | U+1EB4   | Ẵ     | A           | Latin capital letter A with breve and tilde           |
1469   * | U+1EB5   | ẵ     | a           | Latin small letter a with breve and tilde             |
1470   * | U+1EB6   | Ặ     | A           | Latin capital letter A with breve and dot below       |
1471   * | U+1EB7   | ặ     | a           | Latin small letter a with breve and dot below         |
1472   * | U+1EB8   | Ẹ     | E           | Latin capital letter E with dot below                 |
1473   * | U+1EB9   | ẹ     | e           | Latin small letter e with dot below                   |
1474   * | U+1EBA   | Ẻ     | E           | Latin capital letter E with hook above                |
1475   * | U+1EBB   | ẻ     | e           | Latin small letter e with hook above                  |
1476   * | U+1EBC   | Ẽ     | E           | Latin capital letter E with tilde                     |
1477   * | U+1EBD   | ẽ     | e           | Latin small letter e with tilde                       |
1478   * | U+1EBE   | Ế     | E           | Latin capital letter E with circumflex and acute      |
1479   * | U+1EBF   | ế     | e           | Latin small letter e with circumflex and acute        |
1480   * | U+1EC0   | Ề     | E           | Latin capital letter E with circumflex and grave      |
1481   * | U+1EC1   | ề     | e           | Latin small letter e with circumflex and grave        |
1482   * | U+1EC2   | Ể     | E           | Latin capital letter E with circumflex and hook above |
1483   * | U+1EC3   | ể     | e           | Latin small letter e with circumflex and hook above   |
1484   * | U+1EC4   | Ễ     | E           | Latin capital letter E with circumflex and tilde      |
1485   * | U+1EC5   | ễ     | e           | Latin small letter e with circumflex and tilde        |
1486   * | U+1EC6   | Ệ     | E           | Latin capital letter E with circumflex and dot below  |
1487   * | U+1EC7   | ệ     | e           | Latin small letter e with circumflex and dot below    |
1488   * | U+1EC8   | Ỉ     | I           | Latin capital letter I with hook above                |
1489   * | U+1EC9   | ỉ     | i           | Latin small letter i with hook above                  |
1490   * | U+1ECA   | Ị     | I           | Latin capital letter I with dot below                 |
1491   * | U+1ECB   | ị     | i           | Latin small letter i with dot below                   |
1492   * | U+1ECC   | Ọ     | O           | Latin capital letter O with dot below                 |
1493   * | U+1ECD   | ọ     | o           | Latin small letter o with dot below                   |
1494   * | U+1ECE   | Ỏ     | O           | Latin capital letter O with hook above                |
1495   * | U+1ECF   | ỏ     | o           | Latin small letter o with hook above                  |
1496   * | U+1ED0   | Ố     | O           | Latin capital letter O with circumflex and acute      |
1497   * | U+1ED1   | ố     | o           | Latin small letter o with circumflex and acute        |
1498   * | U+1ED2   | Ồ     | O           | Latin capital letter O with circumflex and grave      |
1499   * | U+1ED3   | ồ     | o           | Latin small letter o with circumflex and grave        |
1500   * | U+1ED4   | Ổ     | O           | Latin capital letter O with circumflex and hook above |
1501   * | U+1ED5   | ổ     | o           | Latin small letter o with circumflex and hook above   |
1502   * | U+1ED6   | Ỗ     | O           | Latin capital letter O with circumflex and tilde      |
1503   * | U+1ED7   | ỗ     | o           | Latin small letter o with circumflex and tilde        |
1504   * | U+1ED8   | Ộ     | O           | Latin capital letter O with circumflex and dot below  |
1505   * | U+1ED9   | ộ     | o           | Latin small letter o with circumflex and dot below    |
1506   * | U+1EDA   | Ớ     | O           | Latin capital letter O with horn and acute            |
1507   * | U+1EDB   | ớ     | o           | Latin small letter o with horn and acute              |
1508   * | U+1EDC   | Ờ     | O           | Latin capital letter O with horn and grave            |
1509   * | U+1EDD   | ờ     | o           | Latin small letter o with horn and grave              |
1510   * | U+1EDE   | Ở     | O           | Latin capital letter O with horn and hook above       |
1511   * | U+1EDF   | ở     | o           | Latin small letter o with horn and hook above         |
1512   * | U+1EE0   | Ỡ     | O           | Latin capital letter O with horn and tilde            |
1513   * | U+1EE1   | ỡ     | o           | Latin small letter o with horn and tilde              |
1514   * | U+1EE2   | Ợ     | O           | Latin capital letter O with horn and dot below        |
1515   * | U+1EE3   | ợ     | o           | Latin small letter o with horn and dot below          |
1516   * | U+1EE4   | Ụ     | U           | Latin capital letter U with dot below                 |
1517   * | U+1EE5   | ụ     | u           | Latin small letter u with dot below                   |
1518   * | U+1EE6   | Ủ     | U           | Latin capital letter U with hook above                |
1519   * | U+1EE7   | ủ     | u           | Latin small letter u with hook above                  |
1520   * | U+1EE8   | Ứ     | U           | Latin capital letter U with horn and acute            |
1521   * | U+1EE9   | ứ     | u           | Latin small letter u with horn and acute              |
1522   * | U+1EEA   | Ừ     | U           | Latin capital letter U with horn and grave            |
1523   * | U+1EEB   | ừ     | u           | Latin small letter u with horn and grave              |
1524   * | U+1EEC   | Ử     | U           | Latin capital letter U with horn and hook above       |
1525   * | U+1EED   | ử     | u           | Latin small letter u with horn and hook above         |
1526   * | U+1EEE   | Ữ     | U           | Latin capital letter U with horn and tilde            |
1527   * | U+1EEF   | ữ     | u           | Latin small letter u with horn and tilde              |
1528   * | U+1EF0   | Ự     | U           | Latin capital letter U with horn and dot below        |
1529   * | U+1EF1   | ự     | u           | Latin small letter u with horn and dot below          |
1530   * | U+1EF2   | Ỳ     | Y           | Latin capital letter Y with grave                     |
1531   * | U+1EF3   | ỳ     | y           | Latin small letter y with grave                       |
1532   * | U+1EF4   | Ỵ     | Y           | Latin capital letter Y with dot below                 |
1533   * | U+1EF5   | ỵ     | y           | Latin small letter y with dot below                   |
1534   * | U+1EF6   | Ỷ     | Y           | Latin capital letter Y with hook above                |
1535   * | U+1EF7   | ỷ     | y           | Latin small letter y with hook above                  |
1536   * | U+1EF8   | Ỹ     | Y           | Latin capital letter Y with tilde                     |
1537   * | U+1EF9   | ỹ     | y           | Latin small letter y with tilde                       |
1538   *
1539   * German (`de_DE`), German formal (`de_DE_formal`), German (Switzerland) formal (`de_CH`),
1540   * and German (Switzerland) informal (`de_CH_informal`) locales:
1541   *
1542   * |   Code   | Glyph | Replacement |               Description               |
1543   * | -------- | ----- | ----------- | --------------------------------------- |
1544   * | U+00C4   | Ä     | Ae          | Latin capital letter A with diaeresis   |
1545   * | U+00E4   | ä     | ae          | Latin small letter a with diaeresis     |
1546   * | U+00D6   | Ö     | Oe          | Latin capital letter O with diaeresis   |
1547   * | U+00F6   | ö     | oe          | Latin small letter o with diaeresis     |
1548   * | U+00DC   | Ü     | Ue          | Latin capital letter U with diaeresis   |
1549   * | U+00FC   | ü     | ue          | Latin small letter u with diaeresis     |
1550   * | U+00DF   | ß     | ss          | Latin small letter sharp s              |
1551   *
1552   * Danish (`da_DK`) locale:
1553   *
1554   * |   Code   | Glyph | Replacement |               Description               |
1555   * | -------- | ----- | ----------- | --------------------------------------- |
1556   * | U+00C6   | Æ     | Ae          | Latin capital letter AE                 |
1557   * | U+00E6   | æ     | ae          | Latin small letter ae                   |
1558   * | U+00D8   | Ø     | Oe          | Latin capital letter O with stroke      |
1559   * | U+00F8   | ø     | oe          | Latin small letter o with stroke        |
1560   * | U+00C5   | Å     | Aa          | Latin capital letter A with ring above  |
1561   * | U+00E5   | å     | aa          | Latin small letter a with ring above    |
1562   *
1563   * Catalan (`ca`) locale:
1564   *
1565   * |   Code   | Glyph | Replacement |               Description               |
1566   * | -------- | ----- | ----------- | --------------------------------------- |
1567   * | U+00B7   | l·l   | ll          | Flown dot (between two Ls)              |
1568   *
1569   * Serbian (`sr_RS`) and Bosnian (`bs_BA`) locales:
1570   *
1571   * |   Code   | Glyph | Replacement |               Description               |
1572   * | -------- | ----- | ----------- | --------------------------------------- |
1573   * | U+0110   | Đ     | DJ          | Latin capital letter D with stroke      |
1574   * | U+0111   | đ     | dj          | Latin small letter d with stroke        |
1575   *
1576   * @since 1.2.1
1577   * @since 4.6.0 Added locale support for `de_CH`, `de_CH_informal`, and `ca`.
1578   * @since 4.7.0 Added locale support for `sr_RS`.
1579   * @since 4.8.0 Added locale support for `bs_BA`.
1580   *
1581   * @param string $string Text that might have accent characters
1582   * @return string Filtered string with replaced "nice" characters.
1583   */
1584  function remove_accents( $string ) {
1585      if ( ! preg_match( '/[\x80-\xff]/', $string ) ) {
1586          return $string;
1587      }
1588  
1589      if ( seems_utf8( $string ) ) {
1590          $chars = array(
1591              // Decompositions for Latin-1 Supplement.
1592              'ª' => 'a',
1593              'º' => 'o',
1594              'À' => 'A',
1595              'Á' => 'A',
1596              'Â' => 'A',
1597              'Ã' => 'A',
1598              'Ä' => 'A',
1599              'Å' => 'A',
1600              'Æ' => 'AE',
1601              'Ç' => 'C',
1602              'È' => 'E',
1603              'É' => 'E',
1604              'Ê' => 'E',
1605              'Ë' => 'E',
1606              'Ì' => 'I',
1607              'Í' => 'I',
1608              'Î' => 'I',
1609              'Ï' => 'I',
1610              'Ð' => 'D',
1611              'Ñ' => 'N',
1612              'Ò' => 'O',
1613              'Ó' => 'O',
1614              'Ô' => 'O',
1615              'Õ' => 'O',
1616              'Ö' => 'O',
1617              'Ù' => 'U',
1618              'Ú' => 'U',
1619              'Û' => 'U',
1620              'Ü' => 'U',
1621              'Ý' => 'Y',
1622              'Þ' => 'TH',
1623              'ß' => 's',
1624              'à' => 'a',
1625              'á' => 'a',
1626              'â' => 'a',
1627              'ã' => 'a',
1628              'ä' => 'a',
1629              'å' => 'a',
1630              'æ' => 'ae',
1631              'ç' => 'c',
1632              'è' => 'e',
1633              'é' => 'e',
1634              'ê' => 'e',
1635              'ë' => 'e',
1636              'ì' => 'i',
1637              'í' => 'i',
1638              'î' => 'i',
1639              'ï' => 'i',
1640              'ð' => 'd',
1641              'ñ' => 'n',
1642              'ò' => 'o',
1643              'ó' => 'o',
1644              'ô' => 'o',
1645              'õ' => 'o',
1646              'ö' => 'o',
1647              'ø' => 'o',
1648              'ù' => 'u',
1649              'ú' => 'u',
1650              'û' => 'u',
1651              'ü' => 'u',
1652              'ý' => 'y',
1653              'þ' => 'th',
1654              'ÿ' => 'y',
1655              'Ø' => 'O',
1656              // Decompositions for Latin Extended-A.
1657              'Ā' => 'A',
1658              'ā' => 'a',
1659              'Ă' => 'A',
1660              'ă' => 'a',
1661              'Ą' => 'A',
1662              'ą' => 'a',
1663              'Ć' => 'C',
1664              'ć' => 'c',
1665              'Ĉ' => 'C',
1666              'ĉ' => 'c',
1667              'Ċ' => 'C',
1668              'ċ' => 'c',
1669              'Č' => 'C',
1670              'č' => 'c',
1671              'Ď' => 'D',
1672              'ď' => 'd',
1673              'Đ' => 'D',
1674              'đ' => 'd',
1675              'Ē' => 'E',
1676              'ē' => 'e',
1677              'Ĕ' => 'E',
1678              'ĕ' => 'e',
1679              'Ė' => 'E',
1680              'ė' => 'e',
1681              'Ę' => 'E',
1682              'ę' => 'e',
1683              'Ě' => 'E',
1684              'ě' => 'e',
1685              'Ĝ' => 'G',
1686              'ĝ' => 'g',
1687              'Ğ' => 'G',
1688              'ğ' => 'g',
1689              'Ġ' => 'G',
1690              'ġ' => 'g',
1691              'Ģ' => 'G',
1692              'ģ' => 'g',
1693              'Ĥ' => 'H',
1694              'ĥ' => 'h',
1695              'Ħ' => 'H',
1696              'ħ' => 'h',
1697              'Ĩ' => 'I',
1698              'ĩ' => 'i',
1699              'Ī' => 'I',
1700              'ī' => 'i',
1701              'Ĭ' => 'I',
1702              'ĭ' => 'i',
1703              'Į' => 'I',
1704              'į' => 'i',
1705              'İ' => 'I',
1706              'ı' => 'i',
1707              'IJ' => 'IJ',
1708              'ij' => 'ij',
1709              'Ĵ' => 'J',
1710              'ĵ' => 'j',
1711              'Ķ' => 'K',
1712              'ķ' => 'k',
1713              'ĸ' => 'k',
1714              'Ĺ' => 'L',
1715              'ĺ' => 'l',
1716              'Ļ' => 'L',
1717              'ļ' => 'l',
1718              'Ľ' => 'L',
1719              'ľ' => 'l',
1720              'Ŀ' => 'L',
1721              'ŀ' => 'l',
1722              'Ł' => 'L',
1723              'ł' => 'l',
1724              'Ń' => 'N',
1725              'ń' => 'n',
1726              'Ņ' => 'N',
1727              'ņ' => 'n',
1728              'Ň' => 'N',
1729              'ň' => 'n',
1730              'ʼn' => 'n',
1731              'Ŋ' => 'N',
1732              'ŋ' => 'n',
1733              'Ō' => 'O',
1734              'ō' => 'o',
1735              'Ŏ' => 'O',
1736              'ŏ' => 'o',
1737              'Ő' => 'O',
1738              'ő' => 'o',
1739              'Œ' => 'OE',
1740              'œ' => 'oe',
1741              'Ŕ' => 'R',
1742              'ŕ' => 'r',
1743              'Ŗ' => 'R',
1744              'ŗ' => 'r',
1745              'Ř' => 'R',
1746              'ř' => 'r',
1747              'Ś' => 'S',
1748              'ś' => 's',
1749              'Ŝ' => 'S',
1750              'ŝ' => 's',
1751              'Ş' => 'S',
1752              'ş' => 's',
1753              'Š' => 'S',
1754              'š' => 's',
1755              'Ţ' => 'T',
1756              'ţ' => 't',
1757              'Ť' => 'T',
1758              'ť' => 't',
1759              'Ŧ' => 'T',
1760              'ŧ' => 't',
1761              'Ũ' => 'U',
1762              'ũ' => 'u',
1763              'Ū' => 'U',
1764              'ū' => 'u',
1765              'Ŭ' => 'U',
1766              'ŭ' => 'u',
1767              'Ů' => 'U',
1768              'ů' => 'u',
1769              'Ű' => 'U',
1770              'ű' => 'u',
1771              'Ų' => 'U',
1772              'ų' => 'u',
1773              'Ŵ' => 'W',
1774              'ŵ' => 'w',
1775              'Ŷ' => 'Y',
1776              'ŷ' => 'y',
1777              'Ÿ' => 'Y',
1778              'Ź' => 'Z',
1779              'ź' => 'z',
1780              'Ż' => 'Z',
1781              'ż' => 'z',
1782              'Ž' => 'Z',
1783              'ž' => 'z',
1784              'ſ' => 's',
1785              // Decompositions for Latin Extended-B.
1786              'Ș' => 'S',
1787              'ș' => 's',
1788              'Ț' => 'T',
1789              'ț' => 't',
1790              // Euro sign.
1791              '€' => 'E',
1792              // GBP (Pound) sign.
1793              '£' => '',
1794              // Vowels with diacritic (Vietnamese).
1795              // Unmarked.
1796              'Ơ' => 'O',
1797              'ơ' => 'o',
1798              'Ư' => 'U',
1799              'ư' => 'u',
1800              // Grave accent.
1801              'Ầ' => 'A',
1802              'ầ' => 'a',
1803              'Ằ' => 'A',
1804              'ằ' => 'a',
1805              'Ề' => 'E',
1806              'ề' => 'e',
1807              'Ồ' => 'O',
1808              'ồ' => 'o',
1809              'Ờ' => 'O',
1810              'ờ' => 'o',
1811              'Ừ' => 'U',
1812              'ừ' => 'u',
1813              'Ỳ' => 'Y',
1814              'ỳ' => 'y',
1815              // Hook.
1816              'Ả' => 'A',
1817              'ả' => 'a',
1818              'Ẩ' => 'A',
1819              'ẩ' => 'a',
1820              'Ẳ' => 'A',
1821              'ẳ' => 'a',
1822              'Ẻ' => 'E',
1823              'ẻ' => 'e',
1824              'Ể' => 'E',
1825              'ể' => 'e',
1826              'Ỉ' => 'I',
1827              'ỉ' => 'i',
1828              'Ỏ' => 'O',
1829              'ỏ' => 'o',
1830              'Ổ' => 'O',
1831              'ổ' => 'o',
1832              'Ở' => 'O',
1833              'ở' => 'o',
1834              'Ủ' => 'U',
1835              'ủ' => 'u',
1836              'Ử' => 'U',
1837              'ử' => 'u',
1838              'Ỷ' => 'Y',
1839              'ỷ' => 'y',
1840              // Tilde.
1841              'Ẫ' => 'A',
1842              'ẫ' => 'a',
1843              'Ẵ' => 'A',
1844              'ẵ' => 'a',
1845              'Ẽ' => 'E',
1846              'ẽ' => 'e',
1847              'Ễ' => 'E',
1848              'ễ' => 'e',
1849              'Ỗ' => 'O',
1850              'ỗ' => 'o',
1851              'Ỡ' => 'O',
1852              'ỡ' => 'o',
1853              'Ữ' => 'U',
1854              'ữ' => 'u',
1855              'Ỹ' => 'Y',
1856              'ỹ' => 'y',
1857              // Acute accent.
1858              'Ấ' => 'A',
1859              'ấ' => 'a',
1860              'Ắ' => 'A',
1861              'ắ' => 'a',
1862              'Ế' => 'E',
1863              'ế' => 'e',
1864              'Ố' => 'O',
1865              'ố' => 'o',
1866              'Ớ' => 'O',
1867              'ớ' => 'o',
1868              'Ứ' => 'U',
1869              'ứ' => 'u',
1870              // Dot below.
1871              'Ạ' => 'A',
1872              'ạ' => 'a',
1873              'Ậ' => 'A',
1874              'ậ' => 'a',
1875              'Ặ' => 'A',
1876              'ặ' => 'a',
1877              'Ẹ' => 'E',
1878              'ẹ' => 'e',
1879              'Ệ' => 'E',
1880              'ệ' => 'e',
1881              'Ị' => 'I',
1882              'ị' => 'i',
1883              'Ọ' => 'O',
1884              'ọ' => 'o',
1885              'Ộ' => 'O',
1886              'ộ' => 'o',
1887              'Ợ' => 'O',
1888              'ợ' => 'o',
1889              'Ụ' => 'U',
1890              'ụ' => 'u',
1891              'Ự' => 'U',
1892              'ự' => 'u',
1893              'Ỵ' => 'Y',
1894              'ỵ' => 'y',
1895              // Vowels with diacritic (Chinese, Hanyu Pinyin).
1896              'ɑ' => 'a',
1897              // Macron.
1898              'Ǖ' => 'U',
1899              'ǖ' => 'u',
1900              // Acute accent.
1901              'Ǘ' => 'U',
1902              'ǘ' => 'u',
1903              // Caron.
1904              'Ǎ' => 'A',
1905              'ǎ' => 'a',
1906              'Ǐ' => 'I',
1907              'ǐ' => 'i',
1908              'Ǒ' => 'O',
1909              'ǒ' => 'o',
1910              'Ǔ' => 'U',
1911              'ǔ' => 'u',
1912              'Ǚ' => 'U',
1913              'ǚ' => 'u',
1914              // Grave accent.
1915              'Ǜ' => 'U',
1916              'ǜ' => 'u',
1917          );
1918  
1919          // Used for locale-specific rules.
1920          $locale = get_locale();
1921  
1922          if ( in_array( $locale, array( 'de_DE', 'de_DE_formal', 'de_CH', 'de_CH_informal' ), true ) ) {
1923              $chars['Ä'] = 'Ae';
1924              $chars['ä'] = 'ae';
1925              $chars['Ö'] = 'Oe';
1926              $chars['ö'] = 'oe';
1927              $chars['Ü'] = 'Ue';
1928              $chars['ü'] = 'ue';
1929              $chars['ß'] = 'ss';
1930          } elseif ( 'da_DK' === $locale ) {
1931              $chars['Æ'] = 'Ae';
1932              $chars['æ'] = 'ae';
1933              $chars['Ø'] = 'Oe';
1934              $chars['ø'] = 'oe';
1935              $chars['Å'] = 'Aa';
1936              $chars['å'] = 'aa';
1937          } elseif ( 'ca' === $locale ) {
1938              $chars['l·l'] = 'll';
1939          } elseif ( 'sr_RS' === $locale || 'bs_BA' === $locale ) {
1940              $chars['Đ'] = 'DJ';
1941              $chars['đ'] = 'dj';
1942          }
1943  
1944          $string = strtr( $string, $chars );
1945      } else {
1946          $chars = array();
1947          // Assume ISO-8859-1 if not UTF-8.
1948          $chars['in'] = "\x80\x83\x8a\x8e\x9a\x9e"
1949              . "\x9f\xa2\xa5\xb5\xc0\xc1\xc2"
1950              . "\xc3\xc4\xc5\xc7\xc8\xc9\xca"
1951              . "\xcb\xcc\xcd\xce\xcf\xd1\xd2"
1952              . "\xd3\xd4\xd5\xd6\xd8\xd9\xda"
1953              . "\xdb\xdc\xdd\xe0\xe1\xe2\xe3"
1954              . "\xe4\xe5\xe7\xe8\xe9\xea\xeb"
1955              . "\xec\xed\xee\xef\xf1\xf2\xf3"
1956              . "\xf4\xf5\xf6\xf8\xf9\xfa\xfb"
1957              . "\xfc\xfd\xff";
1958  
1959          $chars['out'] = 'EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy';
1960  
1961          $string              = strtr( $string, $chars['in'], $chars['out'] );
1962          $double_chars        = array();
1963          $double_chars['in']  = array( "\x8c", "\x9c", "\xc6", "\xd0", "\xde", "\xdf", "\xe6", "\xf0", "\xfe" );
1964          $double_chars['out'] = array( 'OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th' );
1965          $string              = str_replace( $double_chars['in'], $double_chars['out'], $string );
1966      }
1967  
1968      return $string;
1969  }
1970  
1971  /**
1972   * Sanitizes a filename, replacing whitespace with dashes.
1973   *
1974   * Removes special characters that are illegal in filenames on certain
1975   * operating systems and special characters requiring special escaping
1976   * to manipulate at the command line. Replaces spaces and consecutive
1977   * dashes with a single dash. Trims period, dash and underscore from beginning
1978   * and end of filename. It is not guaranteed that this function will return a
1979   * filename that is allowed to be uploaded.
1980   *
1981   * @since 2.1.0
1982   *
1983   * @param string $filename The filename to be sanitized.
1984   * @return string The sanitized filename.
1985   */
1986  function sanitize_file_name( $filename ) {
1987      $filename_raw = $filename;
1988      $filename     = remove_accents( $filename );
1989  
1990      $special_chars = array( '?', '[', ']', '/', '\\', '=', '<', '>', ':', ';', ',', "'", '"', '&', '$', '#', '*', '(', ')', '|', '~', '`', '!', '{', '}', '%', '+', '’', '«', '»', '”', '“', chr( 0 ) );
1991  
1992      // Check for support for utf8 in the installed PCRE library once and store the result in a static.
1993      static $utf8_pcre = null;
1994      if ( ! isset( $utf8_pcre ) ) {
1995          // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
1996          $utf8_pcre = @preg_match( '/^./u', 'a' );
1997      }
1998  
1999      if ( ! seems_utf8( $filename ) ) {
2000          $_ext     = pathinfo( $filename, PATHINFO_EXTENSION );
2001          $_name    = pathinfo( $filename, PATHINFO_FILENAME );
2002          $filename = sanitize_title_with_dashes( $_name ) . '.' . $_ext;
2003      }
2004  
2005      if ( $utf8_pcre ) {
2006          $filename = preg_replace( "#\x{00a0}#siu", ' ', $filename );
2007      }
2008  
2009      /**
2010       * Filters the list of characters to remove from a filename.
2011       *
2012       * @since 2.8.0
2013       *
2014       * @param string[] $special_chars Array of characters to remove.
2015       * @param string   $filename_raw  The original filename to be sanitized.
2016       */
2017      $special_chars = apply_filters( 'sanitize_file_name_chars', $special_chars, $filename_raw );
2018  
2019      $filename = str_replace( $special_chars, '', $filename );
2020      $filename = str_replace( array( '%20', '+' ), '-', $filename );
2021      $filename = preg_replace( '/[\r\n\t -]+/', '-', $filename );
2022      $filename = trim( $filename, '.-_' );
2023  
2024      if ( false === strpos( $filename, '.' ) ) {
2025          $mime_types = wp_get_mime_types();
2026          $filetype   = wp_check_filetype( 'test.' . $filename, $mime_types );
2027          if ( $filetype['ext'] === $filename ) {
2028              $filename = 'unnamed-file.' . $filetype['ext'];
2029          }
2030      }
2031  
2032      // Split the filename into a base and extension[s].
2033      $parts = explode( '.', $filename );
2034  
2035      // Return if only one extension.
2036      if ( count( $parts ) <= 2 ) {
2037          /**
2038           * Filters a sanitized filename string.
2039           *
2040           * @since 2.8.0
2041           *
2042           * @param string $filename     Sanitized filename.
2043           * @param string $filename_raw The filename prior to sanitization.
2044           */
2045          return apply_filters( 'sanitize_file_name', $filename, $filename_raw );
2046      }
2047  
2048      // Process multiple extensions.
2049      $filename  = array_shift( $parts );
2050      $extension = array_pop( $parts );
2051      $mimes     = get_allowed_mime_types();
2052  
2053      /*
2054       * Loop over any intermediate extensions. Postfix them with a trailing underscore
2055       * if they are a 2 - 5 character long alpha string not in the allowed extension list.
2056       */
2057      foreach ( (array) $parts as $part ) {
2058          $filename .= '.' . $part;
2059  
2060          if ( preg_match( '/^[a-zA-Z]{2,5}\d?$/', $part ) ) {
2061              $allowed = false;
2062              foreach ( $mimes as $ext_preg => $mime_match ) {
2063                  $ext_preg = '!^(' . $ext_preg . ')$!i';
2064                  if ( preg_match( $ext_preg, $part ) ) {
2065                      $allowed = true;
2066                      break;
2067                  }
2068              }
2069              if ( ! $allowed ) {
2070                  $filename .= '_';
2071              }
2072          }
2073      }
2074  
2075      $filename .= '.' . $extension;
2076  
2077      /** This filter is documented in wp-includes/formatting.php */
2078      return apply_filters( 'sanitize_file_name', $filename, $filename_raw );
2079  }
2080  
2081  /**
2082   * Sanitizes a username, stripping out unsafe characters.
2083   *
2084   * Removes tags, octets, entities, and if strict is enabled, will only keep
2085   * alphanumeric, _, space, ., -, @. After sanitizing, it passes the username,
2086   * raw username (the username in the parameter), and the value of $strict as
2087   * parameters for the {@see 'sanitize_user'} filter.
2088   *
2089   * @since 2.0.0
2090   *
2091   * @param string $username The username to be sanitized.
2092   * @param bool   $strict   Optional. If set limits $username to specific characters.
2093   *                         Default false.
2094   * @return string The sanitized username, after passing through filters.
2095   */
2096  function sanitize_user( $username, $strict = false ) {
2097      $raw_username = $username;
2098      $username     = wp_strip_all_tags( $username );
2099      $username     = remove_accents( $username );
2100      // Kill octets.
2101      $username = preg_replace( '|%([a-fA-F0-9][a-fA-F0-9])|', '', $username );
2102      // Kill entities.
2103      $username = preg_replace( '/&.+?;/', '', $username );
2104  
2105      // If strict, reduce to ASCII for max portability.
2106      if ( $strict ) {
2107          $username = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $username );
2108      }
2109  
2110      $username = trim( $username );
2111      // Consolidate contiguous whitespace.
2112      $username = preg_replace( '|\s+|', ' ', $username );
2113  
2114      /**
2115       * Filters a sanitized username string.
2116       *
2117       * @since 2.0.1
2118       *
2119       * @param string $username     Sanitized username.
2120       * @param string $raw_username The username prior to sanitization.
2121       * @param bool   $strict       Whether to limit the sanitization to specific characters.
2122       */
2123      return apply_filters( 'sanitize_user', $username, $raw_username, $strict );
2124  }
2125  
2126  /**
2127   * Sanitizes a string key.
2128   *
2129   * Keys are used as internal identifiers. Lowercase alphanumeric characters,
2130   * dashes, and underscores are allowed.
2131   *
2132   * @since 3.0.0
2133   *
2134   * @param string $key String key
2135   * @return string Sanitized key
2136   */
2137  function sanitize_key( $key ) {
2138      $raw_key = $key;
2139      $key     = strtolower( $key );
2140      $key     = preg_replace( '/[^a-z0-9_\-]/', '', $key );
2141  
2142      /**
2143       * Filters a sanitized key string.
2144       *
2145       * @since 3.0.0
2146       *
2147       * @param string $key     Sanitized key.
2148       * @param string $raw_key The key prior to sanitization.
2149       */
2150      return apply_filters( 'sanitize_key', $key, $raw_key );
2151  }
2152  
2153  /**
2154   * Sanitizes a string into a slug, which can be used in URLs or HTML attributes.
2155   *
2156   * By default, converts accent characters to ASCII characters and further
2157   * limits the output to alphanumeric characters, underscore (_) and dash (-)
2158   * through the {@see 'sanitize_title'} filter.
2159   *
2160   * If `$title` is empty and `$fallback_title` is set, the latter will be used.
2161   *
2162   * @since 1.0.0
2163   *
2164   * @param string $title          The string to be sanitized.
2165   * @param string $fallback_title Optional. A title to use if $title is empty. Default empty.
2166   * @param string $context        Optional. The operation for which the string is sanitized.
2167   *                               When set to 'save', the string runs through remove_accents().
2168   *                               Default 'save'.
2169   * @return string The sanitized string.
2170   */
2171  function sanitize_title( $title, $fallback_title = '', $context = 'save' ) {
2172      $raw_title = $title;
2173  
2174      if ( 'save' === $context ) {
2175          $title = remove_accents( $title );
2176      }
2177  
2178      /**
2179       * Filters a sanitized title string.
2180       *
2181       * @since 1.2.0
2182       *
2183       * @param string $title     Sanitized title.
2184       * @param string $raw_title The title prior to sanitization.
2185       * @param string $context   The context for which the title is being sanitized.
2186       */
2187      $title = apply_filters( 'sanitize_title', $title, $raw_title, $context );
2188  
2189      if ( '' === $title || false === $title ) {
2190          $title = $fallback_title;
2191      }
2192  
2193      return $title;
2194  }
2195  
2196  /**
2197   * Sanitizes a title with the 'query' context.
2198   *
2199   * Used for querying the database for a value from URL.
2200   *
2201   * @since 3.1.0
2202   *
2203   * @param string $title The string to be sanitized.
2204   * @return string The sanitized string.
2205   */
2206  function sanitize_title_for_query( $title ) {
2207      return sanitize_title( $title, '', 'query' );
2208  }
2209  
2210  /**
2211   * Sanitizes a title, replacing whitespace and a few other characters with dashes.
2212   *
2213   * Limits the output to alphanumeric characters, underscore (_) and dash (-).
2214   * Whitespace becomes a dash.
2215   *
2216   * @since 1.2.0
2217   *
2218   * @param string $title     The title to be sanitized.
2219   * @param string $raw_title Optional. Not used. Default empty.
2220   * @param string $context   Optional. The operation for which the string is sanitized.
2221   *                          When set to 'save', additional entities are converted to hyphens
2222   *                          or stripped entirely. Default 'display'.
2223   * @return string The sanitized title.
2224   */
2225  function sanitize_title_with_dashes( $title, $raw_title = '', $context = 'display' ) {
2226      $title = strip_tags( $title );
2227      // Preserve escaped octets.
2228      $title = preg_replace( '|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title );
2229      // Remove percent signs that are not part of an octet.
2230      $title = str_replace( '%', '', $title );
2231      // Restore octets.
2232      $title = preg_replace( '|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title );
2233  
2234      if ( seems_utf8( $title ) ) {
2235          if ( function_exists( 'mb_strtolower' ) ) {
2236              $title = mb_strtolower( $title, 'UTF-8' );
2237          }
2238          $title = utf8_uri_encode( $title, 200 );
2239      }
2240  
2241      $title = strtolower( $title );
2242  
2243      if ( 'save' === $context ) {
2244          // Convert &nbsp, &ndash, and &mdash to hyphens.
2245          $title = str_replace( array( '%c2%a0', '%e2%80%93', '%e2%80%94' ), '-', $title );
2246          // Convert &nbsp, &ndash, and &mdash HTML entities to hyphens.
2247          $title = str_replace( array( '&nbsp;', '&#160;', '&ndash;', '&#8211;', '&mdash;', '&#8212;' ), '-', $title );
2248          // Convert forward slash to hyphen.
2249          $title = str_replace( '/', '-', $title );
2250  
2251          // Strip these characters entirely.
2252          $title = str_replace(
2253              array(
2254                  // Soft hyphens.
2255                  '%c2%ad',
2256                  // &iexcl and &iquest.
2257                  '%c2%a1',
2258                  '%c2%bf',
2259                  // Angle quotes.
2260                  '%c2%ab',
2261                  '%c2%bb',
2262                  '%e2%80%b9',
2263                  '%e2%80%ba',
2264                  // Curly quotes.
2265                  '%e2%80%98',
2266                  '%e2%80%99',
2267                  '%e2%80%9c',
2268                  '%e2%80%9d',
2269                  '%e2%80%9a',
2270                  '%e2%80%9b',
2271                  '%e2%80%9e',
2272                  '%e2%80%9f',
2273                  // Bullet.
2274                  '%e2%80%a2',
2275                  // &copy, &reg, &deg, &hellip, and &trade.
2276                  '%c2%a9',
2277                  '%c2%ae',
2278                  '%c2%b0',
2279                  '%e2%80%a6',
2280                  '%e2%84%a2',
2281                  // Acute accents.
2282                  '%c2%b4',
2283                  '%cb%8a',
2284                  '%cc%81',
2285                  '%cd%81',
2286                  // Grave accent, macron, caron.
2287                  '%cc%80',
2288                  '%cc%84',
2289                  '%cc%8c',
2290              ),
2291              '',
2292              $title
2293          );
2294  
2295          // Convert &times to 'x'.
2296          $title = str_replace( '%c3%97', 'x', $title );
2297      }
2298  
2299      // Kill entities.
2300      $title = preg_replace( '/&.+?;/', '', $title );
2301      $title = str_replace( '.', '-', $title );
2302  
2303      $title = preg_replace( '/[^%a-z0-9 _-]/', '', $title );
2304      $title = preg_replace( '/\s+/', '-', $title );
2305      $title = preg_replace( '|-+|', '-', $title );
2306      $title = trim( $title, '-' );
2307  
2308      return $title;
2309  }
2310  
2311  /**
2312   * Ensures a string is a valid SQL 'order by' clause.
2313   *
2314   * Accepts one or more columns, with or without a sort order (ASC / DESC).
2315   * e.g. 'column_1', 'column_1, column_2', 'column_1 ASC, column_2 DESC' etc.
2316   *
2317   * Also accepts 'RAND()'.
2318   *
2319   * @since 2.5.1
2320   *
2321   * @param string $orderby Order by clause to be validated.
2322   * @return string|false Returns $orderby if valid, false otherwise.
2323   */
2324  function sanitize_sql_orderby( $orderby ) {
2325      if ( preg_match( '/^\s*(([a-z0-9_]+|`[a-z0-9_]+`)(\s+(ASC|DESC))?\s*(,\s*(?=[a-z0-9_`])|$))+$/i', $orderby ) || preg_match( '/^\s*RAND\(\s*\)\s*$/i', $orderby ) ) {
2326          return $orderby;
2327      }
2328      return false;
2329  }
2330  
2331  /**
2332   * Sanitizes an HTML classname to ensure it only contains valid characters.
2333   *
2334   * Strips the string down to A-Z,a-z,0-9,_,-. If this results in an empty
2335   * string then it will return the alternative value supplied.
2336   *
2337   * @todo Expand to support the full range of CDATA that a class attribute can contain.
2338   *
2339   * @since 2.8.0
2340   *
2341   * @param string $class    The classname to be sanitized
2342   * @param string $fallback Optional. The value to return if the sanitization ends up as an empty string.
2343   *  Defaults to an empty string.
2344   * @return string The sanitized value
2345   */
2346  function sanitize_html_class( $class, $fallback = '' ) {
2347      // Strip out any %-encoded octets.
2348      $sanitized = preg_replace( '|%[a-fA-F0-9][a-fA-F0-9]|', '', $class );
2349  
2350      // Limit to A-Z, a-z, 0-9, '_', '-'.
2351      $sanitized = preg_replace( '/[^A-Za-z0-9_-]/', '', $sanitized );
2352  
2353      if ( '' === $sanitized && $fallback ) {
2354          return sanitize_html_class( $fallback );
2355      }
2356      /**
2357       * Filters a sanitized HTML class string.
2358       *
2359       * @since 2.8.0
2360       *
2361       * @param string $sanitized The sanitized HTML class.
2362       * @param string $class     HTML class before sanitization.
2363       * @param string $fallback  The fallback string.
2364       */
2365      return apply_filters( 'sanitize_html_class', $sanitized, $class, $fallback );
2366  }
2367  
2368  /**
2369   * Converts lone & characters into `&#038;` (a.k.a. `&amp;`)
2370   *
2371   * @since 0.71
2372   *
2373   * @param string $content    String of characters to be converted.
2374   * @param string $deprecated Not used.
2375   * @return string Converted string.
2376   */
2377  function convert_chars( $content, $deprecated = '' ) {
2378      if ( ! empty( $deprecated ) ) {
2379          _deprecated_argument( __FUNCTION__, '0.71' );
2380      }
2381  
2382      if ( strpos( $content, '&' ) !== false ) {
2383          $content = preg_replace( '/&([^#])(?![a-z1-4]{1,8};)/i', '&#038;$1', $content );
2384      }
2385  
2386      return $content;
2387  }
2388  
2389  /**
2390   * Converts invalid Unicode references range to valid range.
2391   *
2392   * @since 4.3.0
2393   *
2394   * @param string $content String with entities that need converting.
2395   * @return string Converted string.
2396   */
2397  function convert_invalid_entities( $content ) {
2398      $wp_htmltranswinuni = array(
2399          '&#128;' => '&#8364;', // The Euro sign.
2400          '&#129;' => '',
2401          '&#130;' => '&#8218;', // These are Windows CP1252 specific characters.
2402          '&#131;' => '&#402;',  // They would look weird on non-Windows browsers.
2403          '&#132;' => '&#8222;',
2404          '&#133;' => '&#8230;',
2405          '&#134;' => '&#8224;',
2406          '&#135;' => '&#8225;',
2407          '&#136;' => '&#710;',
2408          '&#137;' => '&#8240;',
2409          '&#138;' => '&#352;',
2410          '&#139;' => '&#8249;',
2411          '&#140;' => '&#338;',
2412          '&#141;' => '',
2413          '&#142;' => '&#381;',
2414          '&#143;' => '',
2415          '&#144;' => '',
2416          '&#145;' => '&#8216;',
2417          '&#146;' => '&#8217;',
2418          '&#147;' => '&#8220;',
2419          '&#148;' => '&#8221;',
2420          '&#149;' => '&#8226;',
2421          '&#150;' => '&#8211;',
2422          '&#151;' => '&#8212;',
2423          '&#152;' => '&#732;',
2424          '&#153;' => '&#8482;',
2425          '&#154;' => '&#353;',
2426          '&#155;' => '&#8250;',
2427          '&#156;' => '&#339;',
2428          '&#157;' => '',
2429          '&#158;' => '&#382;',
2430          '&#159;' => '&#376;',
2431      );
2432  
2433      if ( strpos( $content, '&#1' ) !== false ) {
2434          $content = strtr( $content, $wp_htmltranswinuni );
2435      }
2436  
2437      return $content;
2438  }
2439  
2440  /**
2441   * Balances tags if forced to, or if the 'use_balanceTags' option is set to true.
2442   *
2443   * @since 0.71
2444   *
2445   * @param string $text  Text to be balanced
2446   * @param bool   $force If true, forces balancing, ignoring the value of the option. Default false.
2447   * @return string Balanced text
2448   */
2449  function balanceTags( $text, $force = false ) {  // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid
2450      if ( $force || (int) get_option( 'use_balanceTags' ) === 1 ) {
2451          return force_balance_tags( $text );
2452      } else {
2453          return $text;
2454      }
2455  }
2456  
2457  /**
2458   * Balances tags of string using a modified stack.
2459   *
2460   * @since 2.0.4
2461   * @since 5.3.0 Improve accuracy and add support for custom element tags.
2462   *
2463   * @author Leonard Lin <leonard@acm.org>
2464   * @license GPL
2465   * @copyright November 4, 2001
2466   * @version 1.1
2467   * @todo Make better - change loop condition to $text in 1.2
2468   * @internal Modified by Scott Reilly (coffee2code) 02 Aug 2004
2469   *      1.1  Fixed handling of append/stack pop order of end text
2470   *           Added Cleaning Hooks
2471   *      1.0  First Version
2472   *
2473   * @param string $text Text to be balanced.
2474   * @return string Balanced text.
2475   */
2476  function force_balance_tags( $text ) {
2477      $tagstack  = array();
2478      $stacksize = 0;
2479      $tagqueue  = '';
2480      $newtext   = '';
2481      // Known single-entity/self-closing tags.
2482      $single_tags = array( 'area', 'base', 'basefont', 'br', 'col', 'command', 'embed', 'frame', 'hr', 'img', 'input', 'isindex', 'link', 'meta', 'param', 'source' );
2483      // Tags that can be immediately nested within themselves.
2484      $nestable_tags = array( 'blockquote', 'div', 'object', 'q', 'span' );
2485  
2486      // WP bug fix for comments - in case you REALLY meant to type '< !--'.
2487      $text = str_replace( '< !--', '<    !--', $text );
2488      // WP bug fix for LOVE <3 (and other situations with '<' before a number).
2489      $text = preg_replace( '#<([0-9]{1})#', '&lt;$1', $text );
2490  
2491      /**
2492       * Matches supported tags.
2493       *
2494       * To get the pattern as a string without the comments paste into a PHP
2495       * REPL like `php -a`.
2496       *
2497       * @see https://html.spec.whatwg.org/#elements-2
2498       * @see https://w3c.github.io/webcomponents/spec/custom/#valid-custom-element-name
2499       *
2500       * @example
2501       * ~# php -a
2502       * php > $s = [paste copied contents of expression below including parentheses];
2503       * php > echo $s;
2504       */
2505      $tag_pattern = (
2506          '#<' . // Start with an opening bracket.
2507          '(/?)' . // Group 1 - If it's a closing tag it'll have a leading slash.
2508          '(' . // Group 2 - Tag name.
2509              // Custom element tags have more lenient rules than HTML tag names.
2510              '(?:[a-z](?:[a-z0-9._]*)-(?:[a-z0-9._-]+)+)' .
2511                  '|' .
2512              // Traditional tag rules approximate HTML tag names.
2513              '(?:[\w:]+)' .
2514          ')' .
2515          '(?:' .
2516              // We either immediately close the tag with its '>' and have nothing here.
2517              '\s*' .
2518              '(/?)' . // Group 3 - "attributes" for empty tag.
2519                  '|' .
2520              // Or we must start with space characters to separate the tag name from the attributes (or whitespace).
2521              '(\s+)' . // Group 4 - Pre-attribute whitespace.
2522              '([^>]*)' . // Group 5 - Attributes.
2523          ')' .
2524          '>#' // End with a closing bracket.
2525      );
2526  
2527      while ( preg_match( $tag_pattern, $text, $regex ) ) {
2528          $full_match        = $regex[0];
2529          $has_leading_slash = ! empty( $regex[1] );
2530          $tag_name          = $regex[2];
2531          $tag               = strtolower( $tag_name );
2532          $is_single_tag     = in_array( $tag, $single_tags, true );
2533          $pre_attribute_ws  = isset( $regex[4] ) ? $regex[4] : '';
2534          $attributes        = trim( isset( $regex[5] ) ? $regex[5] : $regex[3] );
2535          $has_self_closer   = '/' === substr( $attributes, -1 );
2536  
2537          $newtext .= $tagqueue;
2538  
2539          $i = strpos( $text, $full_match );
2540          $l = strlen( $full_match );
2541  
2542          // Clear the shifter.
2543          $tagqueue = '';
2544          if ( $has_leading_slash ) { // End tag.
2545              // If too many closing tags.
2546              if ( $stacksize <= 0 ) {
2547                  $tag = '';
2548                  // Or close to be safe $tag = '/' . $tag.
2549  
2550                  // If stacktop value = tag close value, then pop.
2551              } elseif ( $tagstack[ $stacksize - 1 ] === $tag ) { // Found closing tag.
2552                  $tag = '</' . $tag . '>'; // Close tag.
2553                  array_pop( $tagstack );
2554                  $stacksize--;
2555              } else { // Closing tag not at top, search for it.
2556                  for ( $j = $stacksize - 1; $j >= 0; $j-- ) {
2557                      if ( $tagstack[ $j ] === $tag ) {
2558                          // Add tag to tagqueue.
2559                          for ( $k = $stacksize - 1; $k >= $j; $k-- ) {
2560                              $tagqueue .= '</' . array_pop( $tagstack ) . '>';
2561                              $stacksize--;
2562                          }
2563                          break;
2564                      }
2565                  }
2566                  $tag = '';
2567              }
2568          } else { // Begin tag.
2569              if ( $has_self_closer ) { // If it presents itself as a self-closing tag...
2570                  // ...but it isn't a known single-entity self-closing tag, then don't let it be treated as such
2571                  // and immediately close it with a closing tag (the tag will encapsulate no text as a result).
2572                  if ( ! $is_single_tag ) {
2573                      $attributes = trim( substr( $attributes, 0, -1 ) ) . "></$tag";
2574                  }
2575              } elseif ( $is_single_tag ) { // Else if it's a known single-entity tag but it doesn't close itself, do so.
2576                  $pre_attribute_ws = ' ';
2577                  $attributes      .= '/';
2578              } else { // It's not a single-entity tag.
2579                  // If the top of the stack is the same as the tag we want to push, close previous tag.
2580                  if ( $stacksize > 0 && ! in_array( $tag, $nestable_tags, true ) && $tagstack[ $stacksize - 1 ] === $tag ) {
2581                      $tagqueue = '</' . array_pop( $tagstack ) . '>';
2582                      $stacksize--;
2583                  }
2584                  $stacksize = array_push( $tagstack, $tag );
2585              }
2586  
2587              // Attributes.
2588              if ( $has_self_closer && $is_single_tag ) {
2589                  // We need some space - avoid <br/> and prefer <br />.
2590                  $pre_attribute_ws = ' ';
2591              }
2592  
2593              $tag = '<' . $tag . $pre_attribute_ws . $attributes . '>';
2594              // If already queuing a close tag, then put this tag on too.
2595              if ( ! empty( $tagqueue ) ) {
2596                  $tagqueue .= $tag;
2597                  $tag       = '';
2598              }
2599          }
2600          $newtext .= substr( $text, 0, $i ) . $tag;
2601          $text     = substr( $text, $i + $l );
2602      }
2603  
2604      // Clear tag queue.
2605      $newtext .= $tagqueue;
2606  
2607      // Add remaining text.
2608      $newtext .= $text;
2609  
2610      while ( $x = array_pop( $tagstack ) ) {
2611          $newtext .= '</' . $x . '>'; // Add remaining tags to close.
2612      }
2613  
2614      // WP fix for the bug with HTML comments.
2615      $newtext = str_replace( '< !--', '<!--', $newtext );
2616      $newtext = str_replace( '<    !--', '< !--', $newtext );
2617  
2618      return $newtext;
2619  }
2620  
2621  /**
2622   * Acts on text which is about to be edited.
2623   *
2624   * The $content is run through esc_textarea(), which uses htmlspecialchars()
2625   * to convert special characters to HTML entities. If `$richedit` is set to true,
2626   * it is simply a holder for the {@see 'format_to_edit'} filter.
2627   *
2628   * @since 0.71
2629   * @since 4.4.0 The `$richedit` parameter was renamed to `$rich_text` for clarity.
2630   *
2631   * @param string $content   The text about to be edited.
2632   * @param bool   $rich_text Optional. Whether `$content` should be considered rich text,
2633   *                          in which case it would not be passed through esc_textarea().
2634   *                          Default false.
2635   * @return string The text after the filter (and possibly htmlspecialchars()) has been run.
2636   */
2637  function format_to_edit( $content, $rich_text = false ) {
2638      /**
2639       * Filters the text to be formatted for editing.
2640       *
2641       * @since 1.2.0
2642       *
2643       * @param string $content The text, prior to formatting for editing.
2644       */
2645      $content = apply_filters( 'format_to_edit', $content );
2646      if ( ! $rich_text ) {
2647          $content = esc_textarea( $content );
2648      }
2649      return $content;
2650  }
2651  
2652  /**
2653   * Add leading zeros when necessary.
2654   *
2655   * If you set the threshold to '4' and the number is '10', then you will get
2656   * back '0010'. If you set the threshold to '4' and the number is '5000', then you
2657   * will get back '5000'.
2658   *
2659   * Uses sprintf to append the amount of zeros based on the $threshold parameter
2660   * and the size of the number. If the number is large enough, then no zeros will
2661   * be appended.
2662   *
2663   * @since 0.71
2664   *
2665   * @param int $number     Number to append zeros to if not greater than threshold.
2666   * @param int $threshold  Digit places number needs to be to not have zeros added.
2667   * @return string Adds leading zeros to number if needed.
2668   */
2669  function zeroise( $number, $threshold ) {
2670      return sprintf( '%0' . $threshold . 's', $number );
2671  }
2672  
2673  /**
2674   * Adds backslashes before letters and before a number at the start of a string.
2675   *
2676   * @since 0.71
2677   *
2678   * @param string $string Value to which backslashes will be added.
2679   * @return string String with backslashes inserted.
2680   */
2681  function backslashit( $string ) {
2682      if ( isset( $string[0] ) && $string[0] >= '0' && $string[0] <= '9' ) {
2683          $string = '\\\\' . $string;
2684      }
2685      return addcslashes( $string, 'A..Za..z' );
2686  }
2687  
2688  /**
2689   * Appends a trailing slash.
2690   *
2691   * Will remove trailing forward and backslashes if it exists already before adding
2692   * a trailing forward slash. This prevents double slashing a string or path.
2693   *
2694   * The primary use of this is for paths and thus should be used for paths. It is
2695   * not restricted to paths and offers no specific path support.
2696   *
2697   * @since 1.2.0
2698   *
2699   * @param string $string What to add the trailing slash to.
2700   * @return string String with trailing slash added.
2701   */
2702  function trailingslashit( $string ) {
2703      return untrailingslashit( $string ) . '/';
2704  }
2705  
2706  /**
2707   * Removes trailing forward slashes and backslashes if they exist.
2708   *
2709   * The primary use of this is for paths and thus should be used for paths. It is
2710   * not restricted to paths and offers no specific path support.
2711   *
2712   * @since 2.2.0
2713   *
2714   * @param string $string What to remove the trailing slashes from.
2715   * @return string String without the trailing slashes.
2716   */
2717  function untrailingslashit( $string ) {
2718      return rtrim( $string, '/\\' );
2719  }
2720  
2721  /**
2722   * Adds slashes to escape strings.
2723   *
2724   * Slashes will first be removed if magic_quotes_gpc is set, see {@link
2725   * https://www.php.net/magic_quotes} for more details.
2726   *
2727   * @since 0.71
2728   *
2729   * @param string $gpc The string returned from HTTP request data.
2730   * @return string Returns a string escaped with slashes.
2731   */
2732  function addslashes_gpc( $gpc ) {
2733      return wp_slash( $gpc );
2734  }
2735  
2736  /**
2737   * Navigates through an array, object, or scalar, and removes slashes from the values.
2738   *
2739   * @since 2.0.0
2740   *
2741   * @param mixed $value The value to be stripped.
2742   * @return mixed Stripped value.
2743   */
2744  function stripslashes_deep( $value ) {
2745      return map_deep( $value, 'stripslashes_from_strings_only' );
2746  }
2747  
2748  /**
2749   * Callback function for `stripslashes_deep()` which strips slashes from strings.
2750   *
2751   * @since 4.4.0
2752   *
2753   * @param mixed $value The array or string to be stripped.
2754   * @return mixed The stripped value.
2755   */
2756  function stripslashes_from_strings_only( $value ) {
2757      return is_string( $value ) ? stripslashes( $value ) : $value;
2758  }
2759  
2760  /**
2761   * Navigates through an array, object, or scalar, and encodes the values to be used in a URL.
2762   *
2763   * @since 2.2.0
2764   *
2765   * @param mixed $value The array or string to be encoded.
2766   * @return mixed The encoded value.
2767   */
2768  function urlencode_deep( $value ) {
2769      return map_deep( $value, 'urlencode' );
2770  }
2771  
2772  /**
2773   * Navigates through an array, object, or scalar, and raw-encodes the values to be used in a URL.
2774   *
2775   * @since 3.4.0
2776   *
2777   * @param mixed $value The array or string to be encoded.
2778   * @return mixed The encoded value.
2779   */
2780  function rawurlencode_deep( $value ) {
2781      return map_deep( $value, 'rawurlencode' );
2782  }
2783  
2784  /**
2785   * Navigates through an array, object, or scalar, and decodes URL-encoded values
2786   *
2787   * @since 4.4.0
2788   *
2789   * @param mixed $value The array or string to be decoded.
2790   * @return mixed The decoded value.
2791   */
2792  function urldecode_deep( $value ) {
2793      return map_deep( $value, 'urldecode' );
2794  }
2795  
2796  /**
2797   * Converts email addresses characters to HTML entities to block spam bots.
2798   *
2799   * @since 0.71
2800   *
2801   * @param string $email_address Email address.
2802   * @param int    $hex_encoding  Optional. Set to 1 to enable hex encoding.
2803   * @return string Converted email address.
2804   */
2805  function antispambot( $email_address, $hex_encoding = 0 ) {
2806      $email_no_spam_address = '';
2807      for ( $i = 0, $len = strlen( $email_address ); $i < $len; $i++ ) {
2808          $j = rand( 0, 1 + $hex_encoding );
2809          if ( 0 == $j ) {
2810              $email_no_spam_address .= '&#' . ord( $email_address[ $i ] ) . ';';
2811          } elseif ( 1 == $j ) {
2812              $email_no_spam_address .= $email_address[ $i ];
2813          } elseif ( 2 == $j ) {
2814              $email_no_spam_address .= '%' . zeroise( dechex( ord( $email_address[ $i ] ) ), 2 );
2815          }
2816      }
2817  
2818      return str_replace( '@', '&#64;', $email_no_spam_address );
2819  }
2820  
2821  /**
2822   * Callback to convert URI match to HTML A element.
2823   *
2824   * This function was backported from 2.5.0 to 2.3.2. Regex callback for make_clickable().
2825   *
2826   * @since 2.3.2
2827   * @access private
2828   *
2829   * @param array $matches Single Regex Match.
2830   * @return string HTML A element with URI address.
2831   */
2832  function _make_url_clickable_cb( $matches ) {
2833      $url = $matches[2];
2834  
2835      if ( ')' === $matches[3] && strpos( $url, '(' ) ) {
2836          // If the trailing character is a closing parethesis, and the URL has an opening parenthesis in it,
2837          // add the closing parenthesis to the URL. Then we can let the parenthesis balancer do its thing below.
2838          $url   .= $matches[3];
2839          $suffix = '';
2840      } else {
2841          $suffix = $matches[3];
2842      }
2843  
2844      // Include parentheses in the URL only if paired.
2845      while ( substr_count( $url, '(' ) < substr_count( $url, ')' ) ) {
2846          $suffix = strrchr( $url, ')' ) . $suffix;
2847          $url    = substr( $url, 0, strrpos( $url, ')' ) );
2848      }
2849  
2850      $url = esc_url( $url );
2851      if ( empty( $url ) ) {
2852          return $matches[0];
2853      }
2854  
2855      if ( 'comment_text' === current_filter() ) {
2856          $rel = 'nofollow ugc';
2857      } else {
2858          $rel = 'nofollow';
2859      }
2860  
2861      /**
2862       * Filters the rel value that is added to URL matches converted to links.
2863       *
2864       * @since 5.3.0
2865       *
2866       * @param string $rel The rel value.
2867       * @param string $url The matched URL being converted to a link tag.
2868       */
2869      $rel = apply_filters( 'make_clickable_rel', $rel, $url );
2870      $rel = esc_attr( $rel );
2871  
2872      return $matches[1] . "<a href=\"$url\" rel=\"$rel\">$url</a>" . $suffix;
2873  }
2874  
2875  /**
2876   * Callback to convert URL match to HTML A element.
2877   *
2878   * This function was backported from 2.5.0 to 2.3.2. Regex callback for make_clickable().
2879   *
2880   * @since 2.3.2
2881   * @access private
2882   *
2883   * @param array $matches Single Regex Match.
2884   * @return string HTML A element with URL address.
2885   */
2886  function _make_web_ftp_clickable_cb( $matches ) {
2887      $ret  = '';
2888      $dest = $matches[2];
2889      $dest = 'http://' . $dest;
2890  
2891      // Removed trailing [.,;:)] from URL.
2892      $last_char = substr( $dest, -1 );
2893      if ( in_array( $last_char, array( '.', ',', ';', ':', ')' ), true ) === true ) {
2894          $ret  = $last_char;
2895          $dest = substr( $dest, 0, strlen( $dest ) - 1 );
2896      }
2897  
2898      $dest = esc_url( $dest );
2899      if ( empty( $dest ) ) {
2900          return $matches[0];
2901      }
2902  
2903      if ( 'comment_text' === current_filter() ) {
2904          $rel = 'nofollow ugc';
2905      } else {
2906          $rel = 'nofollow';
2907      }
2908  
2909      /** This filter is documented in wp-includes/formatting.php */
2910      $rel = apply_filters( 'make_clickable_rel', $rel, $dest );
2911      $rel = esc_attr( $rel );
2912  
2913      return $matches[1] . "<a href=\"$dest\" rel=\"$rel\">$dest</a>$ret";
2914  }
2915  
2916  /**
2917   * Callback to convert email address match to HTML A element.
2918   *
2919   * This function was backported from 2.5.0 to 2.3.2. Regex callback for make_clickable().
2920   *
2921   * @since 2.3.2
2922   * @access private
2923   *
2924   * @param array $matches Single Regex Match.
2925   * @return string HTML A element with email address.
2926   */
2927  function _make_email_clickable_cb( $matches ) {
2928      $email = $matches[2] . '@' . $matches[3];
2929      return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
2930  }
2931  
2932  /**
2933   * Convert plaintext URI to HTML links.
2934   *
2935   * Converts URI, www and ftp, and email addresses. Finishes by fixing links
2936   * within links.
2937   *
2938   * @since 0.71
2939   *
2940   * @param string $text Content to convert URIs.
2941   * @return string Content with converted URIs.
2942   */
2943  function make_clickable( $text ) {
2944      $r               = '';
2945      $textarr         = preg_split( '/(<[^<>]+>)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // Split out HTML tags.
2946      $nested_code_pre = 0; // Keep track of how many levels link is nested inside <pre> or <code>.
2947      foreach ( $textarr as $piece ) {
2948  
2949          if ( preg_match( '|^<code[\s>]|i', $piece ) || preg_match( '|^<pre[\s>]|i', $piece ) || preg_match( '|^<script[\s>]|i', $piece ) || preg_match( '|^<style[\s>]|i', $piece ) ) {
2950              $nested_code_pre++;
2951          } elseif ( $nested_code_pre && ( '</code>' === strtolower( $piece ) || '</pre>' === strtolower( $piece ) || '</script>' === strtolower( $piece ) || '</style>' === strtolower( $piece ) ) ) {
2952              $nested_code_pre--;
2953          }
2954  
2955          if ( $nested_code_pre || empty( $piece ) || ( '<' === $piece[0] && ! preg_match( '|^<\s*[\w]{1,20}+://|', $piece ) ) ) {
2956              $r .= $piece;
2957              continue;
2958          }
2959  
2960          // Long strings might contain expensive edge cases...
2961          if ( 10000 < strlen( $piece ) ) {
2962              // ...break it up.
2963              foreach ( _split_str_by_whitespace( $piece, 2100 ) as $chunk ) { // 2100: Extra room for scheme and leading and trailing paretheses.
2964                  if ( 2101 < strlen( $chunk ) ) {
2965                      $r .= $chunk; // Too big, no whitespace: bail.
2966                  } else {
2967                      $r .= make_clickable( $chunk );
2968                  }
2969              }
2970          } else {
2971              $ret = " $piece "; // Pad with whitespace to simplify the regexes.
2972  
2973              $url_clickable = '~
2974                  ([\\s(<.,;:!?])                                # 1: Leading whitespace, or punctuation.
2975                  (                                              # 2: URL.
2976                      [\\w]{1,20}+://                                # Scheme and hier-part prefix.
2977                      (?=\S{1,2000}\s)                               # Limit to URLs less than about 2000 characters long.
2978                      [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]*+         # Non-punctuation URL character.
2979                      (?:                                            # Unroll the Loop: Only allow puctuation URL character if followed by a non-punctuation URL character.
2980                          [\'.,;:!?)]                                    # Punctuation URL character.
2981                          [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]++         # Non-punctuation URL character.
2982                      )*
2983                  )
2984                  (\)?)                                          # 3: Trailing closing parenthesis (for parethesis balancing post processing).
2985              ~xS';
2986              // The regex is a non-anchored pattern and does not have a single fixed starting character.
2987              // Tell PCRE to spend more time optimizing since, when used on a page load, it will probably be used several times.
2988  
2989              $ret = preg_replace_callback( $url_clickable, '_make_url_clickable_cb', $ret );
2990  
2991              $ret = preg_replace_callback( '#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]+)#is', '_make_web_ftp_clickable_cb', $ret );
2992              $ret = preg_replace_callback( '#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret );
2993  
2994              $ret = substr( $ret, 1, -1 ); // Remove our whitespace padding.
2995              $r  .= $ret;
2996          }
2997      }
2998  
2999      // Cleanup of accidental links within links.
3000      return preg_replace( '#(<a([ \r\n\t]+[^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i', '$1$3</a>', $r );
3001  }
3002  
3003  /**
3004   * Breaks a string into chunks by splitting at whitespace characters.
3005   * The length of each returned chunk is as close to the specified length goal as possible,
3006   * with the caveat that each chunk includes its trailing delimiter.
3007   * Chunks longer than the goal are guaranteed to not have any inner whitespace.
3008   *
3009   * Joining the returned chunks with empty delimiters reconstructs the input string losslessly.
3010   *
3011   * Input string must have no null characters (or eventual transformations on output chunks must not care about null characters)
3012   *
3013   *     _split_str_by_whitespace( "1234 67890 1234 67890a cd 1234   890 123456789 1234567890a    45678   1 3 5 7 90 ", 10 ) ==
3014   *     array (
3015   *         0 => '1234 67890 ',  // 11 characters: Perfect split.
3016   *         1 => '1234 ',        //  5 characters: '1234 67890a' was too long.
3017   *         2 => '67890a cd ',   // 10 characters: '67890a cd 1234' was too long.
3018   *         3 => '1234   890 ',  // 11 characters: Perfect split.
3019   *         4 => '123456789 ',   // 10 characters: '123456789 1234567890a' was too long.
3020   *         5 => '1234567890a ', // 12 characters: Too long, but no inner whitespace on which to split.
3021   *         6 => '   45678   ',  // 11 characters: Perfect split.
3022   *         7 => '1 3 5 7 90 ',  // 11 characters: End of $string.
3023   *     );
3024   *
3025   * @since 3.4.0
3026   * @access private
3027   *
3028   * @param string $string The string to split.
3029   * @param int    $goal   The desired chunk length.
3030   * @return array Numeric array of chunks.
3031   */
3032  function _split_str_by_whitespace( $string, $goal ) {
3033      $chunks = array();
3034  
3035      $string_nullspace = strtr( $string, "\r\n\t\v\f ", "\000\000\000\000\000\000" );
3036  
3037      while ( $goal < strlen( $string_nullspace ) ) {
3038          $pos = strrpos( substr( $string_nullspace, 0, $goal + 1 ), "\000" );
3039  
3040          if ( false === $pos ) {
3041              $pos = strpos( $string_nullspace, "\000", $goal + 1 );
3042              if ( false === $pos ) {
3043                  break;
3044              }
3045          }
3046  
3047          $chunks[]         = substr( $string, 0, $pos + 1 );
3048          $string           = substr( $string, $pos + 1 );
3049          $string_nullspace = substr( $string_nullspace, $pos + 1 );
3050      }
3051  
3052      if ( $string ) {
3053          $chunks[] = $string;
3054      }
3055  
3056      return $chunks;
3057  }
3058  
3059  /**
3060   * Callback to add a rel attribute to HTML A element.
3061   *
3062   * Will remove already existing string before adding to prevent invalidating (X)HTML.
3063   *
3064   * @since 5.3.0
3065   *
3066   * @param array  $matches Single match.
3067   * @param string $rel     The rel attribute to add.
3068   * @return string HTML A element with the added rel attribute.
3069   */
3070  function wp_rel_callback( $matches, $rel ) {
3071      $text = $matches[1];
3072      $atts = wp_kses_hair( $matches[1], wp_allowed_protocols() );
3073  
3074      if ( ! empty( $atts['href'] ) ) {
3075          if ( in_array( strtolower( wp_parse_url( $atts['href']['value'], PHP_URL_SCHEME ) ), array( 'http', 'https' ), true ) ) {
3076              if ( strtolower( wp_parse_url( $atts['href']['value'], PHP_URL_HOST ) ) === strtolower( wp_parse_url( home_url(), PHP_URL_HOST ) ) ) {
3077                  return "<a $text>";
3078              }
3079          }
3080      }
3081  
3082      if ( ! empty( $atts['rel'] ) ) {
3083          $parts     = array_map( 'trim', explode( ' ', $atts['rel']['value'] ) );
3084          $rel_array = array_map( 'trim', explode( ' ', $rel ) );
3085          $parts     = array_unique( array_merge( $parts, $rel_array ) );
3086          $rel       = implode( ' ', $parts );
3087          unset( $atts['rel'] );
3088  
3089          $html = '';
3090          foreach ( $atts as $name => $value ) {
3091              if ( isset( $value['vless'] ) && 'y' === $value['vless'] ) {
3092                  $html .= $name . ' ';
3093              } else {
3094                  $html .= "{$name}=\"" . esc_attr( $value['value'] ) . '" ';
3095              }
3096          }
3097          $text = trim( $html );
3098      }
3099      return "<a $text rel=\"" . esc_attr( $rel ) . '">';
3100  }
3101  
3102  /**
3103   * Adds `rel="nofollow"` string to all HTML A elements in content.
3104   *
3105   * @since 1.5.0
3106   *
3107   * @param string $text Content that may contain HTML A elements.
3108   * @return string Converted content.
3109   */
3110  function wp_rel_nofollow( $text ) {
3111      // This is a pre-save filter, so text is already escaped.
3112      $text = stripslashes( $text );
3113      $text = preg_replace_callback(
3114          '|<a (.+?)>|i',
3115          function( $matches ) {
3116              return wp_rel_callback( $matches, 'nofollow' );
3117          },
3118          $text
3119      );
3120      return wp_slash( $text );
3121  }
3122  
3123  /**
3124   * Callback to add `rel="nofollow"` string to HTML A element.
3125   *
3126   * @since 2.3.0
3127   * @deprecated 5.3.0 Use wp_rel_callback()
3128   *
3129   * @param array $matches Single match.
3130   * @return string HTML A Element with `rel="nofollow"`.
3131   */
3132  function wp_rel_nofollow_callback( $matches ) {
3133      return wp_rel_callback( $matches, 'nofollow' );
3134  }
3135  
3136  /**
3137   * Adds `rel="nofollow ugc"` string to all HTML A elements in content.
3138   *
3139   * @since 5.3.0
3140   *
3141   * @param string $text Content that may contain HTML A elements.
3142   * @return string Converted content.
3143   */
3144  function wp_rel_ugc( $text ) {
3145      // This is a pre-save filter, so text is already escaped.
3146      $text = stripslashes( $text );
3147      $text = preg_replace_callback(
3148          '|<a (.+?)>|i',
3149          function( $matches ) {
3150              return wp_rel_callback( $matches, 'nofollow ugc' );
3151          },
3152          $text
3153      );
3154      return wp_slash( $text );
3155  }
3156  
3157  /**
3158   * Adds `rel="noopener"` to all HTML A elements that have a target.
3159   *
3160   * @since 5.1.0
3161   * @since 5.6.0 Removed 'noreferrer' relationship.
3162   *
3163   * @param string $text Content that may contain HTML A elements.
3164   * @return string Converted content.
3165   */
3166  function wp_targeted_link_rel( $text ) {
3167      // Don't run (more expensive) regex if no links with targets.
3168      if ( stripos( $text, 'target' ) === false || stripos( $text, '<a ' ) === false || is_serialized( $text ) ) {
3169          return $text;
3170      }
3171  
3172      $script_and_style_regex = '/<(script|style).*?<\/\\1>/si';
3173  
3174      preg_match_all( $script_and_style_regex, $text, $matches );
3175      $extra_parts = $matches[0];
3176      $html_parts  = preg_split( $script_and_style_regex, $text );
3177  
3178      foreach ( $html_parts as &$part ) {
3179          $part = preg_replace_callback( '|<a\s([^>]*target\s*=[^>]*)>|i', 'wp_targeted_link_rel_callback', $part );
3180      }
3181  
3182      $text = '';
3183      for ( $i = 0; $i < count( $html_parts ); $i++ ) {
3184          $text .= $html_parts[ $i ];
3185          if ( isset( $extra_parts[ $i ] ) ) {
3186              $text .= $extra_parts[ $i ];
3187          }
3188      }
3189  
3190      return $text;
3191  }
3192  
3193  /**
3194   * Callback to add `rel="noopener"` string to HTML A element.
3195   *
3196   * Will not duplicate an existing 'noopener' value to avoid invalidating the HTML.
3197   *
3198   * @since 5.1.0
3199   * @since 5.6.0 Removed 'noreferrer' relationship.
3200   *
3201   * @param array $matches Single match.
3202   * @return string HTML A Element with `rel="noopener"` in addition to any existing values.
3203   */
3204  function wp_targeted_link_rel_callback( $matches ) {
3205      $link_html          = $matches[1];
3206      $original_link_html = $link_html;
3207  
3208      // Consider the HTML escaped if there are no unescaped quotes.
3209      $is_escaped = ! preg_match( '/(^|[^\\\\])[\'"]/', $link_html );
3210      if ( $is_escaped ) {
3211          // Replace only the quotes so that they are parsable by wp_kses_hair(), leave the rest as is.
3212          $link_html = preg_replace( '/\\\\([\'"])/', '$1', $link_html );
3213      }
3214  
3215      $atts = wp_kses_hair( $link_html, wp_allowed_protocols() );
3216  
3217      /**
3218       * Filters the rel values that are added to links with `target` attribute.
3219       *
3220       * @since 5.1.0
3221       *
3222       * @param string $rel       The rel values.
3223       * @param string $link_html The matched content of the link tag including all HTML attributes.
3224       */
3225      $rel = apply_filters( 'wp_targeted_link_rel', 'noopener', $link_html );
3226  
3227      // Return early if no rel values to be added or if no actual target attribute.
3228      if ( ! $rel || ! isset( $atts['target'] ) ) {
3229          return "<a $original_link_html>";
3230      }
3231  
3232      if ( isset( $atts['rel'] ) ) {
3233          $all_parts = preg_split( '/\s/', "{$atts['rel']['value']} $rel", -1, PREG_SPLIT_NO_EMPTY );
3234          $rel       = implode( ' ', array_unique( $all_parts ) );
3235      }
3236  
3237      $atts['rel']['whole'] = 'rel="' . esc_attr( $rel ) . '"';
3238      $link_html            = implode( ' ', array_column( $atts, 'whole' ) );
3239  
3240      if ( $is_escaped ) {
3241          $link_html = preg_replace( '/[\'"]/', '\\\\$0', $link_html );
3242      }
3243  
3244      return "<a $link_html>";
3245  }
3246  
3247  /**
3248   * Adds all filters modifying the rel attribute of targeted links.
3249   *
3250   * @since 5.1.0
3251   */
3252  function wp_init_targeted_link_rel_filters() {
3253      $filters = array(
3254          'title_save_pre',
3255          'content_save_pre',
3256          'excerpt_save_pre',
3257          'content_filtered_save_pre',
3258          'pre_comment_content',
3259          'pre_term_description',
3260          'pre_link_description',
3261          'pre_link_notes',
3262          'pre_user_description',
3263      );
3264  
3265      foreach ( $filters as $filter ) {
3266          add_filter( $filter, 'wp_targeted_link_rel' );
3267      };
3268  }
3269  
3270  /**
3271   * Removes all filters modifying the rel attribute of targeted links.
3272   *
3273   * @since 5.1.0
3274   */
3275  function wp_remove_targeted_link_rel_filters() {
3276      $filters = array(
3277          'title_save_pre',
3278          'content_save_pre',
3279          'excerpt_save_pre',
3280          'content_filtered_save_pre',
3281          'pre_comment_content',
3282          'pre_term_description',
3283          'pre_link_description',
3284          'pre_link_notes',
3285          'pre_user_description',
3286      );
3287  
3288      foreach ( $filters as $filter ) {
3289          remove_filter( $filter, 'wp_targeted_link_rel' );
3290      };
3291  }
3292  
3293  /**
3294   * Convert one smiley code to the icon graphic file equivalent.
3295   *
3296   * Callback handler for convert_smilies().
3297   *
3298   * Looks up one smiley code in the $wpsmiliestrans global array and returns an
3299   * `<img>` string for that smiley.
3300   *
3301   * @since 2.8.0
3302   *
3303   * @global array $wpsmiliestrans
3304   *
3305   * @param array $matches Single match. Smiley code to convert to image.
3306   * @return string Image string for smiley.
3307   */
3308  function translate_smiley( $matches ) {
3309      global $wpsmiliestrans;
3310  
3311      if ( count( $matches ) == 0 ) {
3312          return '';
3313      }
3314  
3315      $smiley = trim( reset( $matches ) );
3316      $img    = $wpsmiliestrans[ $smiley ];
3317  
3318      $matches    = array();
3319      $ext        = preg_match( '/\.([^.]+)$/', $img, $matches ) ? strtolower( $matches[1] ) : false;
3320      $image_exts = array( 'jpg', 'jpeg', 'jpe', 'gif', 'png' );
3321  
3322      // Don't convert smilies that aren't images - they're probably emoji.
3323      if ( ! in_array( $ext, $image_exts, true ) ) {
3324          return $img;
3325      }
3326  
3327      /**
3328       * Filters the Smiley image URL before it's used in the image element.
3329       *
3330       * @since 2.9.0
3331       *
3332       * @param string $smiley_url URL for the smiley image.
3333       * @param string $img        Filename for the smiley image.
3334       * @param string $site_url   Site URL, as returned by site_url().
3335       */
3336      $src_url = apply_filters( 'smilies_src', includes_url( "images/smilies/$img" ), $img, site_url() );
3337  
3338      return sprintf( '<img src="%s" alt="%s" class="wp-smiley" style="height: 1em; max-height: 1em;" />', esc_url( $src_url ), esc_attr( $smiley ) );
3339  }
3340  
3341  /**
3342   * Convert text equivalent of smilies to images.
3343   *
3344   * Will only convert smilies if the option 'use_smilies' is true and the global
3345   * used in the function isn't empty.
3346   *
3347   * @since 0.71
3348   *
3349   * @global string|array $wp_smiliessearch
3350   *
3351   * @param string $text Content to convert smilies from text.
3352   * @return string Converted content with text smilies replaced with images.
3353   */
3354  function convert_smilies( $text ) {
3355      global $wp_smiliessearch;
3356      $output = '';
3357      if ( get_option( 'use_smilies' ) && ! empty( $wp_smiliessearch ) ) {
3358          // HTML loop taken from texturize function, could possible be consolidated.
3359          $textarr = preg_split( '/(<.*>)/U', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // Capture the tags as well as in between.
3360          $stop    = count( $textarr ); // Loop stuff.
3361  
3362          // Ignore proessing of specific tags.
3363          $tags_to_ignore       = 'code|pre|style|script|textarea';
3364          $ignore_block_element = '';
3365  
3366          for ( $i = 0; $i < $stop; $i++ ) {
3367              $content = $textarr[ $i ];
3368  
3369              // If we're in an ignore block, wait until we find its closing tag.
3370              if ( '' === $ignore_block_element && preg_match( '/^<(' . $tags_to_ignore . ')[^>]*>/', $content, $matches ) ) {
3371                  $ignore_block_element = $matches[1];
3372              }
3373  
3374              // If it's not a tag and not in ignore block.
3375              if ( '' === $ignore_block_element && strlen( $content ) > 0 && '<' !== $content[0] ) {
3376                  $content = preg_replace_callback( $wp_smiliessearch, 'translate_smiley', $content );
3377              }
3378  
3379              // Did we exit ignore block?
3380              if ( '' !== $ignore_block_element && '</' . $ignore_block_element . '>' === $content ) {
3381                  $ignore_block_element = '';
3382              }
3383  
3384              $output .= $content;
3385          }
3386      } else {
3387          // Return default text.
3388          $output = $text;
3389      }
3390      return $output;
3391  }
3392  
3393  /**
3394   * Verifies that an email is valid.
3395   *
3396   * Does not grok i18n domains. Not RFC compliant.
3397   *
3398   * @since 0.71
3399   *
3400   * @param string $email      Email address to verify.
3401   * @param bool   $deprecated Deprecated.
3402   * @return string|false Valid email address on success, false on failure.
3403   */
3404  function is_email( $email, $deprecated = false ) {
3405      if ( ! empty( $deprecated ) ) {
3406          _deprecated_argument( __FUNCTION__, '3.0.0' );
3407      }
3408  
3409      // Test for the minimum length the email can be.
3410      if ( strlen( $email ) < 6 ) {
3411          /**
3412           * Filters whether an email address is valid.
3413           *
3414           * This filter is evaluated under several different contexts, such as 'email_too_short',
3415           * 'email_no_at', 'local_invalid_chars', 'domain_period_sequence', 'domain_period_limits',
3416           * 'domain_no_periods', 'sub_hyphen_limits', 'sub_invalid_chars', or no specific context.
3417           *
3418           * @since 2.8.0
3419           *
3420           * @param string|false $is_email The email address if successfully passed the is_email() checks, false otherwise.
3421           * @param string       $email    The email address being checked.
3422           * @param string       $context  Context under which the email was tested.
3423           */
3424          return apply_filters( 'is_email', false, $email, 'email_too_short' );
3425      }
3426  
3427      // Test for an @ character after the first position.
3428      if ( strpos( $email, '@', 1 ) === false ) {
3429          /** This filter is documented in wp-includes/formatting.php */
3430          return apply_filters( 'is_email', false, $email, 'email_no_at' );
3431      }
3432  
3433      // Split out the local and domain parts.
3434      list( $local, $domain ) = explode( '@', $email, 2 );
3435  
3436      // LOCAL PART
3437      // Test for invalid characters.
3438      if ( ! preg_match( '/^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]+$/', $local ) ) {
3439          /** This filter is documented in wp-includes/formatting.php */
3440          return apply_filters( 'is_email', false, $email, 'local_invalid_chars' );
3441      }
3442  
3443      // DOMAIN PART
3444      // Test for sequences of periods.
3445      if ( preg_match( '/\.{2,}/', $domain ) ) {
3446          /** This filter is documented in wp-includes/formatting.php */
3447          return apply_filters( 'is_email', false, $email, 'domain_period_sequence' );
3448      }
3449  
3450      // Test for leading and trailing periods and whitespace.
3451      if ( trim( $domain, " \t\n\r\0\x0B." ) !== $domain ) {
3452          /** This filter is documented in wp-includes/formatting.php */
3453          return apply_filters( 'is_email', false, $email, 'domain_period_limits' );
3454      }
3455  
3456      // Split the domain into subs.
3457      $subs = explode( '.', $domain );
3458  
3459      // Assume the domain will have at least two subs.
3460      if ( 2 > count( $subs ) ) {
3461          /** This filter is documented in wp-includes/formatting.php */
3462          return apply_filters( 'is_email', false, $email, 'domain_no_periods' );
3463      }
3464  
3465      // Loop through each sub.
3466      foreach ( $subs as $sub ) {
3467          // Test for leading and trailing hyphens and whitespace.
3468          if ( trim( $sub, " \t\n\r\0\x0B-" ) !== $sub ) {
3469              /** This filter is documented in wp-includes/formatting.php */
3470              return apply_filters( 'is_email', false, $email, 'sub_hyphen_limits' );
3471          }
3472  
3473          // Test for invalid characters.
3474          if ( ! preg_match( '/^[a-z0-9-]+$/i', $sub ) ) {
3475              /** This filter is documented in wp-includes/formatting.php */
3476              return apply_filters( 'is_email', false, $email, 'sub_invalid_chars' );
3477          }
3478      }
3479  
3480      // Congratulations, your email made it!
3481      /** This filter is documented in wp-includes/formatting.php */
3482      return apply_filters( 'is_email', $email, $email, null );
3483  }
3484  
3485  /**
3486   * Convert to ASCII from email subjects.
3487   *
3488   * @since 1.2.0
3489   *
3490   * @param string $string Subject line
3491   * @return string Converted string to ASCII
3492   */
3493  function wp_iso_descrambler( $string ) {
3494      /* this may only work with iso-8859-1, I'm afraid */
3495      if ( ! preg_match( '#\=\?(.+)\?Q\?(.+)\?\=#i', $string, $matches ) ) {
3496          return $string;
3497      } else {
3498          $subject = str_replace( '_', ' ', $matches[2] );
3499          return preg_replace_callback( '#\=([0-9a-f]{2})#i', '_wp_iso_convert', $subject );
3500      }
3501  }
3502  
3503  /**
3504   * Helper function to convert hex encoded chars to ASCII
3505   *
3506   * @since 3.1.0
3507   * @access private
3508   *
3509   * @param array $match The preg_replace_callback matches array
3510   * @return string Converted chars
3511   */
3512  function _wp_iso_convert( $match ) {
3513      return chr( hexdec( strtolower( $match[1] ) ) );
3514  }
3515  
3516  /**
3517   * Given a date in the timezone of the site, returns that date in UTC.
3518   *
3519   * Requires and returns a date in the Y-m-d H:i:s format.
3520   * Return format can be overridden using the $format parameter.
3521   *
3522   * @since 1.2.0
3523   *
3524   * @param string $string The date to be converted, in the timezone of the site.
3525   * @param string $format The format string for the returned date. Default 'Y-m-d H:i:s'.
3526   * @return string Formatted version of the date, in UTC.
3527   */
3528  function get_gmt_from_date( $string, $format = 'Y-m-d H:i:s' ) {
3529      $datetime = date_create( $string, wp_timezone() );
3530  
3531      if ( false === $datetime ) {
3532          return gmdate( $format, 0 );
3533      }
3534  
3535      return $datetime->setTimezone( new DateTimeZone( 'UTC' ) )->format( $format );
3536  }
3537  
3538  /**
3539   * Given a date in UTC or GMT timezone, returns that date in the timezone of the site.
3540   *
3541   * Requires and returns a date in the Y-m-d H:i:s format.
3542   * Return format can be overridden using the $format parameter.
3543   *
3544   * @since 1.2.0
3545   *
3546   * @param string $string The date to be converted, in UTC or GMT timezone.
3547   * @param string $format The format string for the returned date. Default 'Y-m-d H:i:s'.
3548   * @return string Formatted version of the date, in the site's timezone.
3549   */
3550  function get_date_from_gmt( $string, $format = 'Y-m-d H:i:s' ) {
3551      $datetime = date_create( $string, new DateTimeZone( 'UTC' ) );
3552  
3553      if ( false === $datetime ) {
3554          return gmdate( $format, 0 );
3555      }
3556  
3557      return $datetime->setTimezone( wp_timezone() )->format( $format );
3558  }
3559  
3560  /**
3561   * Given an ISO 8601 timezone, returns its UTC offset in seconds.
3562   *
3563   * @since 1.5.0
3564   *
3565   * @param string $timezone Either 'Z' for 0 offset or '±hhmm'.
3566   * @return int|float The offset in seconds.
3567   */
3568  function iso8601_timezone_to_offset( $timezone ) {
3569      // $timezone is either 'Z' or '[+|-]hhmm'.
3570      if ( 'Z' === $timezone ) {
3571          $offset = 0;
3572      } else {
3573          $sign    = ( '+' === substr( $timezone, 0, 1 ) ) ? 1 : -1;
3574          $hours   = (int) substr( $timezone, 1, 2 );
3575          $minutes = (int) substr( $timezone, 3, 4 ) / 60;
3576          $offset  = $sign * HOUR_IN_SECONDS * ( $hours + $minutes );
3577      }
3578      return $offset;
3579  }
3580  
3581  /**
3582   * Given an ISO 8601 (Ymd\TH:i:sO) date, returns a MySQL DateTime (Y-m-d H:i:s) format used by post_date[_gmt].
3583   *
3584   * @since 1.5.0
3585   *
3586   * @param string $date_string Date and time in ISO 8601 format {@link https://en.wikipedia.org/wiki/ISO_8601}.
3587   * @param string $timezone    Optional. If set to 'gmt' returns the result in UTC. Default 'user'.
3588   * @return string|bool The date and time in MySQL DateTime format - Y-m-d H:i:s, or false on failure.
3589   */
3590  function iso8601_to_datetime( $date_string, $timezone = 'user' ) {
3591      $timezone    = strtolower( $timezone );
3592      $wp_timezone = wp_timezone();
3593      $datetime    = date_create( $date_string, $wp_timezone ); // Timezone is ignored if input has one.
3594  
3595      if ( false === $datetime ) {
3596          return false;
3597      }
3598  
3599      if ( 'gmt' === $timezone ) {
3600          return $datetime->setTimezone( new DateTimeZone( 'UTC' ) )->format( 'Y-m-d H:i:s' );
3601      }
3602  
3603      if ( 'user' === $timezone ) {
3604          return $datetime->setTimezone( $wp_timezone )->format( 'Y-m-d H:i:s' );
3605      }
3606  
3607      return false;
3608  }
3609  
3610  /**
3611   * Strips out all characters that are not allowable in an email.
3612   *
3613   * @since 1.5.0
3614   *
3615   * @param string $email Email address to filter.
3616   * @return string Filtered email address.
3617   */
3618  function sanitize_email( $email ) {
3619      // Test for the minimum length the email can be.
3620      if ( strlen( $email ) < 6 ) {
3621          /**
3622           * Filters a sanitized email address.
3623           *
3624           * This filter is evaluated under several contexts, including 'email_too_short',
3625           * 'email_no_at', 'local_invalid_chars', 'domain_period_sequence', 'domain_period_limits',
3626           * 'domain_no_periods', 'domain_no_valid_subs', or no context.
3627           *
3628           * @since 2.8.0
3629           *
3630           * @param string $sanitized_email The sanitized email address.
3631           * @param string $email           The email address, as provided to sanitize_email().
3632           * @param string|null $message    A message to pass to the user. null if email is sanitized.
3633           */
3634          return apply_filters( 'sanitize_email', '', $email, 'email_too_short' );
3635      }
3636  
3637      // Test for an @ character after the first position.
3638      if ( strpos( $email, '@', 1 ) === false ) {
3639          /** This filter is documented in wp-includes/formatting.php */
3640          return apply_filters( 'sanitize_email', '', $email, 'email_no_at' );
3641      }
3642  
3643      // Split out the local and domain parts.
3644      list( $local, $domain ) = explode( '@', $email, 2 );
3645  
3646      // LOCAL PART
3647      // Test for invalid characters.
3648      $local = preg_replace( '/[^a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]/', '', $local );
3649      if ( '' === $local ) {
3650          /** This filter is documented in wp-includes/formatting.php */
3651          return apply_filters( 'sanitize_email', '', $email, 'local_invalid_chars' );
3652      }
3653  
3654      // DOMAIN PART
3655      // Test for sequences of periods.
3656      $domain = preg_replace( '/\.{2,}/', '', $domain );
3657      if ( '' === $domain ) {
3658          /** This filter is documented in wp-includes/formatting.php */
3659          return apply_filters( 'sanitize_email', '', $email, 'domain_period_sequence' );
3660      }
3661  
3662      // Test for leading and trailing periods and whitespace.
3663      $domain = trim( $domain, " \t\n\r\0\x0B." );
3664      if ( '' === $domain ) {
3665          /** This filter is documented in wp-includes/formatting.php */
3666          return apply_filters( 'sanitize_email', '', $email, 'domain_period_limits' );
3667      }
3668  
3669      // Split the domain into subs.
3670      $subs = explode( '.', $domain );
3671  
3672      // Assume the domain will have at least two subs.
3673      if ( 2 > count( $subs ) ) {
3674          /** This filter is documented in wp-includes/formatting.php */
3675          return apply_filters( 'sanitize_email', '', $email, 'domain_no_periods' );
3676      }
3677  
3678      // Create an array that will contain valid subs.
3679      $new_subs = array();
3680  
3681      // Loop through each sub.
3682      foreach ( $subs as $sub ) {
3683          // Test for leading and trailing hyphens.
3684          $sub = trim( $sub, " \t\n\r\0\x0B-" );
3685  
3686          // Test for invalid characters.
3687          $sub = preg_replace( '/[^a-z0-9-]+/i', '', $sub );
3688  
3689          // If there's anything left, add it to the valid subs.
3690          if ( '' !== $sub ) {
3691              $new_subs[] = $sub;
3692          }
3693      }
3694  
3695      // If there aren't 2 or more valid subs.
3696      if ( 2 > count( $new_subs ) ) {
3697          /** This filter is documented in wp-includes/formatting.php */
3698          return apply_filters( 'sanitize_email', '', $email, 'domain_no_valid_subs' );
3699      }
3700  
3701      // Join valid subs into the new domain.
3702      $domain = implode( '.', $new_subs );
3703  
3704      // Put the email back together.
3705      $sanitized_email = $local . '@' . $domain;
3706  
3707      // Congratulations, your email made it!
3708      /** This filter is documented in wp-includes/formatting.php */
3709      return apply_filters( 'sanitize_email', $sanitized_email, $email, null );
3710  }
3711  
3712  /**
3713   * Determines the difference between two timestamps.
3714   *
3715   * The difference is returned in a human readable format such as "1 hour",
3716   * "5 mins", "2 days".
3717   *
3718   * @since 1.5.0
3719   * @since 5.3.0 Added support for showing a difference in seconds.
3720   *
3721   * @param int $from Unix timestamp from which the difference begins.
3722   * @param int $to   Optional. Unix timestamp to end the time difference. Default becomes time() if not set.
3723   * @return string Human readable time difference.
3724   */
3725  function human_time_diff( $from, $to = 0 ) {
3726      if ( empty( $to ) ) {
3727          $to = time();
3728      }
3729  
3730      $diff = (int) abs( $to - $from );
3731  
3732      if ( $diff < MINUTE_IN_SECONDS ) {
3733          $secs = $diff;
3734          if ( $secs <= 1 ) {
3735              $secs = 1;
3736          }
3737          /* translators: Time difference between two dates, in seconds. %s: Number of seconds. */
3738          $since = sprintf( _n( '%s second', '%s seconds', $secs ), $secs );
3739      } elseif ( $diff < HOUR_IN_SECONDS && $diff >= MINUTE_IN_SECONDS ) {
3740          $mins = round( $diff / MINUTE_IN_SECONDS );
3741          if ( $mins <= 1 ) {
3742              $mins = 1;
3743          }
3744          /* translators: Time difference between two dates, in minutes (min=minute). %s: Number of minutes. */
3745          $since = sprintf( _n( '%s min', '%s mins', $mins ), $mins );
3746      } elseif ( $diff < DAY_IN_SECONDS && $diff >= HOUR_IN_SECONDS ) {
3747          $hours = round( $diff / HOUR_IN_SECONDS );
3748          if ( $hours <= 1 ) {
3749              $hours = 1;
3750          }
3751          /* translators: Time difference between two dates, in hours. %s: Number of hours. */
3752          $since = sprintf( _n( '%s hour', '%s hours', $hours ), $hours );
3753      } elseif ( $diff < WEEK_IN_SECONDS && $diff >= DAY_IN_SECONDS ) {
3754          $days = round( $diff / DAY_IN_SECONDS );
3755          if ( $days <= 1 ) {
3756              $days = 1;
3757          }
3758          /* translators: Time difference between two dates, in days. %s: Number of days. */
3759          $since = sprintf( _n( '%s day', '%s days', $days ), $days );
3760      } elseif ( $diff < MONTH_IN_SECONDS && $diff >= WEEK_IN_SECONDS ) {
3761          $weeks = round( $diff / WEEK_IN_SECONDS );
3762          if ( $weeks <= 1 ) {
3763              $weeks = 1;
3764          }
3765          /* translators: Time difference between two dates, in weeks. %s: Number of weeks. */
3766          $since = sprintf( _n( '%s week', '%s weeks', $weeks ), $weeks );
3767      } elseif ( $diff < YEAR_IN_SECONDS && $diff >= MONTH_IN_SECONDS ) {
3768          $months = round( $diff / MONTH_IN_SECONDS );
3769          if ( $months <= 1 ) {
3770              $months = 1;
3771          }
3772          /* translators: Time difference between two dates, in months. %s: Number of months. */
3773          $since = sprintf( _n( '%s month', '%s months', $months ), $months );
3774      } elseif ( $diff >= YEAR_IN_SECONDS ) {
3775          $years = round( $diff / YEAR_IN_SECONDS );
3776          if ( $years <= 1 ) {
3777              $years = 1;
3778          }
3779          /* translators: Time difference between two dates, in years. %s: Number of years. */
3780          $since = sprintf( _n( '%s year', '%s years', $years ), $years );
3781      }
3782  
3783      /**
3784       * Filters the human readable difference between two timestamps.
3785       *
3786       * @since 4.0.0
3787       *
3788       * @param string $since The difference in human readable text.
3789       * @param int    $diff  The difference in seconds.
3790       * @param int    $from  Unix timestamp from which the difference begins.
3791       * @param int    $to    Unix timestamp to end the time difference.
3792       */
3793      return apply_filters( 'human_time_diff', $since, $diff, $from, $to );
3794  }
3795  
3796  /**
3797   * Generates an excerpt from the content, if needed.
3798   *
3799   * Returns a maximum of 55 words with an ellipsis appended if necessary.
3800   *
3801   * The 55 word limit can be modified by plugins/themes using the {@see 'excerpt_length'} filter
3802   * The ' [&hellip;]' string can be modified by plugins/themes using the {@see 'excerpt_more'} filter
3803   *
3804   * @since 1.5.0
3805   * @since 5.2.0 Added the `$post` parameter.
3806   *
3807   * @param string             $text Optional. The excerpt. If set to empty, an excerpt is generated.
3808   * @param WP_Post|object|int $post Optional. WP_Post instance or Post ID/object. Default null.
3809   * @return string The excerpt.
3810   */
3811  function wp_trim_excerpt( $text = '', $post = null ) {
3812      $raw_excerpt = $text;
3813  
3814      if ( '' === trim( $text ) ) {
3815          $post = get_post( $post );
3816          $text = get_the_content( '', false, $post );
3817  
3818          $text = strip_shortcodes( $text );
3819          $text = excerpt_remove_blocks( $text );
3820  
3821          /** This filter is documented in wp-includes/post-template.php */
3822          $text = apply_filters( 'the_content', $text );
3823          $text = str_replace( ']]>', ']]&gt;', $text );
3824  
3825          /* translators: Maximum number of words used in a post excerpt. */
3826          $excerpt_length = (int) _x( '55', 'excerpt_length' );
3827  
3828          /**
3829           * Filters the maximum number of words in a post excerpt.
3830           *
3831           * @since 2.7.0
3832           *
3833           * @param int $number The maximum number of words. Default 55.
3834           */
3835          $excerpt_length = (int) apply_filters( 'excerpt_length', $excerpt_length );
3836  
3837          /**
3838           * Filters the string in the "more" link displayed after a trimmed excerpt.
3839           *
3840           * @since 2.9.0
3841           *
3842           * @param string $more_string The string shown within the more link.
3843           */
3844          $excerpt_more = apply_filters( 'excerpt_more', ' ' . '[&hellip;]' );
3845          $text         = wp_trim_words( $text, $excerpt_length, $excerpt_more );
3846      }
3847  
3848      /**
3849       * Filters the trimmed excerpt string.
3850       *
3851       * @since 2.8.0
3852       *
3853       * @param string $text        The trimmed text.
3854       * @param string $raw_excerpt The text prior to trimming.
3855       */
3856      return apply_filters( 'wp_trim_excerpt', $text, $raw_excerpt );
3857  }
3858  
3859  /**
3860   * Trims text to a certain number of words.
3861   *
3862   * This function is localized. For languages that count 'words' by the individual
3863   * character (such as East Asian languages), the $num_words argument will apply
3864   * to the number of individual characters.
3865   *
3866   * @since 3.3.0
3867   *
3868   * @param string $text      Text to trim.
3869   * @param int    $num_words Number of words. Default 55.
3870   * @param string $more      Optional. What to append if $text needs to be trimmed. Default '&hellip;'.
3871   * @return string Trimmed text.
3872   */
3873  function wp_trim_words( $text, $num_words = 55, $more = null ) {
3874      if ( null === $more ) {
3875          $more = __( '&hellip;' );
3876      }
3877  
3878      $original_text = $text;
3879      $text          = wp_strip_all_tags( $text );
3880      $num_words     = (int) $num_words;
3881  
3882      /*
3883       * translators: If your word count is based on single characters (e.g. East Asian characters),
3884       * enter 'characters_excluding_spaces' or 'characters_including_spaces'. Otherwise, enter 'words'.
3885       * Do not translate into your own language.
3886       */
3887      if ( strpos( _x( 'words', 'Word count type. Do not translate!' ), 'characters' ) === 0 && preg_match( '/^utf\-?8$/i', get_option( 'blog_charset' ) ) ) {
3888          $text = trim( preg_replace( "/[\n\r\t ]+/", ' ', $text ), ' ' );
3889          preg_match_all( '/./u', $text, $words_array );
3890          $words_array = array_slice( $words_array[0], 0, $num_words + 1 );
3891          $sep         = '';
3892      } else {
3893          $words_array = preg_split( "/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY );
3894          $sep         = ' ';
3895      }
3896  
3897      if ( count( $words_array ) > $num_words ) {
3898          array_pop( $words_array );
3899          $text = implode( $sep, $words_array );
3900          $text = $text . $more;
3901      } else {
3902          $text = implode( $sep, $words_array );
3903      }
3904  
3905      /**
3906       * Filters the text content after words have been trimmed.
3907       *
3908       * @since 3.3.0
3909       *
3910       * @param string $text          The trimmed text.
3911       * @param int    $num_words     The number of words to trim the text to. Default 55.
3912       * @param string $more          An optional string to append to the end of the trimmed text, e.g. &hellip;.
3913       * @param string $original_text The text before it was trimmed.
3914       */
3915      return apply_filters( 'wp_trim_words', $text, $num_words, $more, $original_text );
3916  }
3917  
3918  /**
3919   * Converts named entities into numbered entities.
3920   *
3921   * @since 1.5.1
3922   *
3923   * @param string $text The text within which entities will be converted.
3924   * @return string Text with converted entities.
3925   */
3926  function ent2ncr( $text ) {
3927  
3928      /**
3929       * Filters text before named entities are converted into numbered entities.
3930       *
3931       * A non-null string must be returned for the filter to be evaluated.
3932       *
3933       * @since 3.3.0
3934       *
3935       * @param string|null $converted_text The text to be converted. Default null.
3936       * @param string      $text           The text prior to entity conversion.
3937       */
3938      $filtered = apply_filters( 'pre_ent2ncr', null, $text );
3939      if ( null !== $filtered ) {
3940          return $filtered;
3941      }
3942  
3943      $to_ncr = array(
3944          '&quot;'     => '&#34;',
3945          '&amp;'      => '&#38;',
3946          '&lt;'       => '&#60;',
3947          '&gt;'       => '&#62;',
3948          '|'          => '&#124;',
3949          '&nbsp;'     => '&#160;',
3950          '&iexcl;'    => '&#161;',
3951          '&cent;'     => '&#162;',
3952          '&pound;'    => '&#163;',
3953          '&curren;'   => '&#164;',
3954          '&yen;'      => '&#165;',
3955          '&brvbar;'   => '&#166;',
3956          '&brkbar;'   => '&#166;',
3957          '&sect;'     => '&#167;',
3958          '&uml;'      => '&#168;',
3959          '&die;'      => '&#168;',
3960          '&copy;'     => '&#169;',
3961          '&ordf;'     => '&#170;',
3962          '&laquo;'    => '&#171;',
3963          '&not;'      => '&#172;',
3964          '&shy;'      => '&#173;',
3965          '&reg;'      => '&#174;',
3966          '&macr;'     => '&#175;',
3967          '&hibar;'    => '&#175;',
3968          '&deg;'      => '&#176;',
3969          '&plusmn;'   => '&#177;',
3970          '&sup2;'     => '&#178;',
3971          '&sup3;'     => '&#179;',
3972          '&acute;'    => '&#180;',
3973          '&micro;'    => '&#181;',
3974          '&para;'     => '&#182;',
3975          '&middot;'   => '&#183;',
3976          '&cedil;'    => '&#184;',
3977          '&sup1;'     => '&#185;',
3978          '&ordm;'     => '&#186;',
3979          '&raquo;'    => '&#187;',
3980          '&frac14;'   => '&#188;',
3981          '&frac12;'   => '&#189;',
3982          '&frac34;'   => '&#190;',
3983          '&iquest;'   => '&#191;',
3984          '&Agrave;'   => '&#192;',
3985          '&Aacute;'   => '&#193;',
3986          '&Acirc;'    => '&#194;',
3987          '&Atilde;'   => '&#195;',
3988          '&Auml;'     => '&#196;',
3989          '&Aring;'    => '&#197;',
3990          '&AElig;'    => '&#198;',
3991          '&Ccedil;'   => '&#199;',
3992          '&Egrave;'   => '&#200;',
3993          '&Eacute;'   => '&#201;',
3994          '&Ecirc;'    => '&#202;',
3995          '&Euml;'     => '&#203;',
3996          '&Igrave;'   => '&#204;',
3997          '&Iacute;'   => '&#205;',
3998          '&Icirc;'    => '&#206;',
3999          '&Iuml;'     => '&#207;',
4000          '&ETH;'      => '&#208;',
4001          '&Ntilde;'   => '&#209;',
4002          '&Ograve;'   => '&#210;',
4003          '&Oacute;'   => '&#211;',
4004          '&Ocirc;'    => '&#212;',
4005          '&Otilde;'   => '&#213;',
4006          '&Ouml;'     => '&#214;',
4007          '&times;'    => '&#215;',
4008          '&Oslash;'   => '&#216;',
4009          '&Ugrave;'   => '&#217;',
4010          '&Uacute;'   => '&#218;',
4011          '&Ucirc;'    => '&#219;',
4012          '&Uuml;'     => '&#220;',
4013          '&Yacute;'   => '&#221;',
4014          '&THORN;'    => '&#222;',
4015          '&szlig;'    => '&#223;',
4016          '&agrave;'   => '&#224;',
4017          '&aacute;'   => '&#225;',
4018          '&acirc;'    => '&#226;',
4019          '&atilde;'   => '&#227;',
4020          '&auml;'     => '&#228;',
4021          '&aring;'    => '&#229;',
4022          '&aelig;'    => '&#230;',
4023          '&ccedil;'   => '&#231;',
4024          '&egrave;'   => '&#232;',
4025          '&eacute;'   => '&#233;',
4026          '&ecirc;'    => '&#234;',
4027          '&euml;'     => '&#235;',
4028          '&igrave;'   => '&#236;',
4029          '&iacute;'   => '&#237;',
4030          '&icirc;'    => '&#238;',
4031          '&iuml;'     => '&#239;',
4032          '&eth;'      => '&#240;',
4033          '&ntilde;'   => '&#241;',
4034          '&ograve;'   => '&#242;',
4035          '&oacute;'   => '&#243;',
4036          '&ocirc;'    => '&#244;',
4037          '&otilde;'   => '&#245;',
4038          '&ouml;'     => '&#246;',
4039          '&divide;'   => '&#247;',
4040          '&oslash;'   => '&#248;',
4041          '&ugrave;'   => '&#249;',
4042          '&uacute;'   => '&#250;',
4043          '&ucirc;'    => '&#251;',
4044          '&uuml;'     => '&#252;',
4045          '&yacute;'   => '&#253;',
4046          '&thorn;'    => '&#254;',
4047          '&yuml;'     => '&#255;',
4048          '&OElig;'    => '&#338;',
4049          '&oelig;'    => '&#339;',
4050          '&Scaron;'   => '&#352;',
4051          '&scaron;'   => '&#353;',
4052          '&Yuml;'     => '&#376;',
4053          '&fnof;'     => '&#402;',
4054          '&circ;'     => '&#710;',
4055          '&tilde;'    => '&#732;',
4056          '&Alpha;'    => '&#913;',
4057          '&Beta;'     => '&#914;',
4058          '&Gamma;'    => '&#915;',
4059          '&Delta;'    => '&#916;',
4060          '&Epsilon;'  => '&#917;',
4061          '&Zeta;'     => '&#918;',
4062          '&Eta;'      => '&#919;',
4063          '&Theta;'    => '&#920;',
4064          '&Iota;'     => '&#921;',
4065          '&Kappa;'    => '&#922;',
4066          '&Lambda;'   => '&#923;',
4067          '&Mu;'       => '&#924;',
4068          '&Nu;'       => '&#925;',
4069          '&Xi;'       => '&#926;',
4070          '&Omicron;'  => '&#927;',
4071          '&Pi;'       => '&#928;',
4072          '&Rho;'      => '&#929;',
4073          '&Sigma;'    => '&#931;',
4074          '&Tau;'      => '&#932;',
4075          '&Upsilon;'  => '&#933;',
4076          '&Phi;'      => '&#934;',
4077          '&Chi;'      => '&#935;',
4078          '&Psi;'      => '&#936;',
4079          '&Omega;'    => '&#937;',
4080          '&alpha;'    => '&#945;',
4081          '&beta;'     => '&#946;',
4082          '&gamma;'    => '&#947;',
4083          '&delta;'    => '&#948;',
4084          '&epsilon;'  => '&#949;',
4085          '&zeta;'     => '&#950;',
4086          '&eta;'      => '&#951;',
4087          '&theta;'    => '&#952;',
4088          '&iota;'     => '&#953;',
4089          '&kappa;'    => '&#954;',
4090          '&lambda;'   => '&#955;',
4091          '&mu;'       => '&#956;',
4092          '&nu;'       => '&#957;',
4093          '&xi;'       => '&#958;',
4094          '&omicron;'  => '&#959;',
4095          '&pi;'       => '&#960;',
4096          '&rho;'      => '&#961;',
4097          '&sigmaf;'   => '&#962;',
4098          '&sigma;'    => '&#963;',
4099          '&tau;'      => '&#964;',
4100          '&upsilon;'  => '&#965;',
4101          '&phi;'      => '&#966;',
4102          '&chi;'      => '&#967;',
4103          '&psi;'      => '&#968;',
4104          '&omega;'    => '&#969;',
4105          '&thetasym;' => '&#977;',
4106          '&upsih;'    => '&#978;',
4107          '&piv;'      => '&#982;',
4108          '&ensp;'     => '&#8194;',
4109          '&emsp;'     => '&#8195;',
4110          '&thinsp;'   => '&#8201;',
4111          '&zwnj;'     => '&#8204;',
4112          '&zwj;'      => '&#8205;',
4113          '&lrm;'      => '&#8206;',
4114          '&rlm;'      => '&#8207;',
4115          '&ndash;'    => '&#8211;',
4116          '&mdash;'    => '&#8212;',
4117          '&lsquo;'    => '&#8216;',
4118          '&rsquo;'    => '&#8217;',
4119          '&sbquo;'    => '&#8218;',
4120          '&ldquo;'    => '&#8220;',
4121          '&rdquo;'    => '&#8221;',
4122          '&bdquo;'    => '&#8222;',
4123          '&dagger;'   => '&#8224;',
4124          '&Dagger;'   => '&#8225;',
4125          '&bull;'     => '&#8226;',
4126          '&hellip;'   => '&#8230;',
4127          '&permil;'   => '&#8240;',
4128          '&prime;'    => '&#8242;',
4129          '&Prime;'    => '&#8243;',
4130          '&lsaquo;'   => '&#8249;',
4131          '&rsaquo;'   => '&#8250;',
4132          '&oline;'    => '&#8254;',
4133          '&frasl;'    => '&#8260;',
4134          '&euro;'     => '&#8364;',
4135          '&image;'    => '&#8465;',
4136          '&weierp;'   => '&#8472;',
4137          '&real;'     => '&#8476;',
4138          '&trade;'    => '&#8482;',
4139          '&alefsym;'  => '&#8501;',
4140          '&crarr;'    => '&#8629;',
4141          '&lArr;'     => '&#8656;',
4142          '&uArr;'     => '&#8657;',
4143          '&rArr;'     => '&#8658;',
4144          '&dArr;'     => '&#8659;',
4145          '&hArr;'     => '&#8660;',
4146          '&forall;'   => '&#8704;',
4147          '&part;'     => '&#8706;',
4148          '&exist;'    => '&#8707;',
4149          '&empty;'    => '&#8709;',
4150          '&nabla;'    => '&#8711;',
4151          '&isin;'     => '&#8712;',
4152          '&notin;'    => '&#8713;',
4153          '&ni;'       => '&#8715;',
4154          '&prod;'     => '&#8719;',
4155          '&sum;'      => '&#8721;',
4156          '&minus;'    => '&#8722;',
4157          '&lowast;'   => '&#8727;',
4158          '&radic;'    => '&#8730;',
4159          '&prop;'     => '&#8733;',
4160          '&infin;'    => '&#8734;',
4161          '&ang;'      => '&#8736;',
4162          '&and;'      => '&#8743;',
4163          '&or;'       => '&#8744;',
4164          '&cap;'      => '&#8745;',
4165          '&cup;'      => '&#8746;',
4166          '&int;'      => '&#8747;',
4167          '&there4;'   => '&#8756;',
4168          '&sim;'      => '&#8764;',
4169          '&cong;'     => '&#8773;',
4170          '&asymp;'    => '&#8776;',
4171          '&ne;'       => '&#8800;',
4172          '&equiv;'    => '&#8801;',
4173          '&le;'       => '&#8804;',
4174          '&ge;'       => '&#8805;',
4175          '&sub;'      => '&#8834;',
4176          '&sup;'      => '&#8835;',
4177          '&nsub;'     => '&#8836;',
4178          '&sube;'     => '&#8838;',
4179          '&supe;'     => '&#8839;',
4180          '&oplus;'    => '&#8853;',
4181          '&otimes;'   => '&#8855;',
4182          '&perp;'     => '&#8869;',
4183          '&sdot;'     => '&#8901;',
4184          '&lceil;'    => '&#8968;',
4185          '&rceil;'    => '&#8969;',
4186          '&lfloor;'   => '&#8970;',
4187          '&rfloor;'   => '&#8971;',
4188          '&lang;'     => '&#9001;',
4189          '&rang;'     => '&#9002;',
4190          '&larr;'     => '&#8592;',
4191          '&uarr;'     => '&#8593;',
4192          '&rarr;'     => '&#8594;',
4193          '&darr;'     => '&#8595;',
4194          '&harr;'     => '&#8596;',
4195          '&loz;'      => '&#9674;',
4196          '&spades;'   => '&#9824;',
4197          '&clubs;'    => '&#9827;',
4198          '&hearts;'   => '&#9829;',
4199          '&diams;'    => '&#9830;',
4200      );
4201  
4202      return str_replace( array_keys( $to_ncr ), array_values( $to_ncr ), $text );
4203  }
4204  
4205  /**
4206   * Formats text for the editor.
4207   *
4208   * Generally the browsers treat everything inside a textarea as text, but
4209   * it is still a good idea to HTML entity encode `<`, `>` and `&` in the content.
4210   *
4211   * The filter {@see 'format_for_editor'} is applied here. If `$text` is empty the
4212   * filter will be applied to an empty string.
4213   *
4214   * @since 4.3.0
4215   *
4216   * @see _WP_Editors::editor()
4217   *
4218   * @param string $text           The text to be formatted.
4219   * @param string $default_editor The default editor for the current user.
4220   *                               It is usually either 'html' or 'tinymce'.
4221   * @return string The formatted text after filter is applied.
4222   */
4223  function format_for_editor( $text, $default_editor = null ) {
4224      if ( $text ) {
4225          $text = htmlspecialchars( $text, ENT_NOQUOTES, get_option( 'blog_charset' ) );
4226      }
4227  
4228      /**
4229       * Filters the text after it is formatted for the editor.
4230       *
4231       * @since 4.3.0
4232       *
4233       * @param string $text           The formatted text.
4234       * @param string $default_editor The default editor for the current user.
4235       *                               It is usually either 'html' or 'tinymce'.
4236       */
4237      return apply_filters( 'format_for_editor', $text, $default_editor );
4238  }
4239  
4240  /**
4241   * Perform a deep string replace operation to ensure the values in $search are no longer present
4242   *
4243   * Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values
4244   * e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that
4245   * str_replace would return
4246   *
4247   * @since 2.8.1
4248   * @access private
4249   *
4250   * @param string|array $search  The value being searched for, otherwise known as the needle.
4251   *                              An array may be used to designate multiple needles.
4252   * @param string       $subject The string being searched and replaced on, otherwise known as the haystack.
4253   * @return string The string with the replaced values.
4254   */
4255  function _deep_replace( $search, $subject ) {
4256      $subject = (string) $subject;
4257  
4258      $count = 1;
4259      while ( $count ) {
4260          $subject = str_replace( $search, '', $subject, $count );
4261      }
4262  
4263      return $subject;
4264  }
4265  
4266  /**
4267   * Escapes data for use in a MySQL query.
4268   *
4269   * Usually you should prepare queries using wpdb::prepare().
4270   * Sometimes, spot-escaping is required or useful. One example
4271   * is preparing an array for use in an IN clause.
4272   *
4273   * NOTE: Since 4.8.3, '%' characters will be replaced with a placeholder string,
4274   * this prevents certain SQLi attacks from taking place. This change in behaviour
4275   * may cause issues for code that expects the return value of esc_sql() to be useable
4276   * for other purposes.
4277   *
4278   * @since 2.8.0
4279   *
4280   * @global wpdb $wpdb WordPress database abstraction object.
4281   *
4282   * @param string|array $data Unescaped data
4283   * @return string|array Escaped data
4284   */
4285  function esc_sql( $data ) {
4286      global $wpdb;
4287      return $wpdb->_escape( $data );
4288  }
4289  
4290  /**
4291   * Checks and cleans a URL.
4292   *
4293   * A number of characters are removed from the URL. If the URL is for displaying
4294   * (the default behaviour) ampersands are also replaced. The {@see 'clean_url'} filter
4295   * is applied to the returned cleaned URL.
4296   *
4297   * @since 2.8.0
4298   *
4299   * @param string   $url       The URL to be cleaned.
4300   * @param string[] $protocols Optional. An array of acceptable protocols.
4301   *                            Defaults to return value of wp_allowed_protocols().
4302   * @param string   $_context  Private. Use esc_url_raw() for database usage.
4303   * @return string The cleaned URL after the {@see 'clean_url'} filter is applied.
4304   *                An empty string is returned if `$url` specifies a protocol other than
4305   *                those in `$protocols`, or if `$url` contains an empty string.
4306   */
4307  function esc_url( $url, $protocols = null, $_context = 'display' ) {
4308      $original_url = $url;
4309  
4310      if ( '' === $url ) {
4311          return $url;
4312      }
4313  
4314      $url = str_replace( ' ', '%20', ltrim( $url ) );
4315      $url = preg_replace( '|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\[\]\\x80-\\xff]|i', '', $url );
4316  
4317      if ( '' === $url ) {
4318          return $url;
4319      }
4320  
4321      if ( 0 !== stripos( $url, 'mailto:' ) ) {
4322          $strip = array( '%0d', '%0a', '%0D', '%0A' );
4323          $url   = _deep_replace( $strip, $url );
4324      }
4325  
4326      $url = str_replace( ';//', '://', $url );
4327      /*
4328       * If the URL doesn't appear to contain a scheme, we presume
4329       * it needs http:// prepended (unless it's a relative link
4330       * starting with /, # or ?, or a PHP file).
4331       */
4332      if ( strpos( $url, ':' ) === false && ! in_array( $url[0], array( '/', '#', '?' ), true ) &&
4333          ! preg_match( '/^[a-z0-9-]+?\.php/i', $url ) ) {
4334          $url = 'http://' . $url;
4335      }
4336  
4337      // Replace ampersands and single quotes only when displaying.
4338      if ( 'display' === $_context ) {
4339          $url = wp_kses_normalize_entities( $url );
4340          $url = str_replace( '&amp;', '&#038;', $url );
4341          $url = str_replace( "'", '&#039;', $url );
4342      }
4343  
4344      if ( ( false !== strpos( $url, '[' ) ) || ( false !== strpos( $url, ']' ) ) ) {
4345  
4346          $parsed = wp_parse_url( $url );
4347          $front  = '';
4348  
4349          if ( isset( $parsed['scheme'] ) ) {
4350              $front .= $parsed['scheme'] . '://';
4351          } elseif ( '/' === $url[0] ) {
4352              $front .= '//';
4353          }
4354  
4355          if ( isset( $parsed['user'] ) ) {
4356              $front .= $parsed['user'];
4357          }
4358  
4359          if ( isset( $parsed['pass'] ) ) {
4360              $front .= ':' . $parsed['pass'];
4361          }
4362  
4363          if ( isset( $parsed['user'] ) || isset( $parsed['pass'] ) ) {
4364              $front .= '@';
4365          }
4366  
4367          if ( isset( $parsed['host'] ) ) {
4368              $front .= $parsed['host'];
4369          }
4370  
4371          if ( isset( $parsed['port'] ) ) {
4372              $front .= ':' . $parsed['port'];
4373          }
4374  
4375          $end_dirty = str_replace( $front, '', $url );
4376          $end_clean = str_replace( array( '[', ']' ), array( '%5B', '%5D' ), $end_dirty );
4377          $url       = str_replace( $end_dirty, $end_clean, $url );
4378  
4379      }
4380  
4381      if ( '/' === $url[0] ) {
4382          $good_protocol_url = $url;
4383      } else {
4384          if ( ! is_array( $protocols ) ) {
4385              $protocols = wp_allowed_protocols();
4386          }
4387          $good_protocol_url = wp_kses_bad_protocol( $url, $protocols );
4388          if ( strtolower( $good_protocol_url ) != strtolower( $url ) ) {
4389              return '';
4390          }
4391      }
4392  
4393      /**
4394       * Filters a string cleaned and escaped for output as a URL.
4395       *
4396       * @since 2.3.0
4397       *
4398       * @param string $good_protocol_url The cleaned URL to be returned.
4399       * @param string $original_url      The URL prior to cleaning.
4400       * @param string $_context          If 'display', replace ampersands and single quotes only.
4401       */
4402      return apply_filters( 'clean_url', $good_protocol_url, $original_url, $_context );
4403  }
4404  
4405  /**
4406   * Performs esc_url() for database usage.
4407   *
4408   * @since 2.8.0
4409   *
4410   * @see esc_url()
4411   *
4412   * @param string   $url       The URL to be cleaned.
4413   * @param string[] $protocols Optional. An array of acceptable protocols.
4414   *                            Defaults to return value of wp_allowed_protocols().
4415   * @return string The cleaned URL after esc_url() is run with the 'db' context.
4416   */
4417  function esc_url_raw( $url, $protocols = null ) {
4418      return esc_url( $url, $protocols, 'db' );
4419  }
4420  
4421  /**
4422   * Convert entities, while preserving already-encoded entities.
4423   *
4424   * @link https://www.php.net/htmlentities Borrowed from the PHP Manual user notes.
4425   *
4426   * @since 1.2.2
4427   *
4428   * @param string $myHTML The text to be converted.
4429   * @return string Converted text.
4430   */
4431  function htmlentities2( $myHTML ) {
4432      $translation_table              = get_html_translation_table( HTML_ENTITIES, ENT_QUOTES );
4433      $translation_table[ chr( 38 ) ] = '&';
4434      return preg_replace( '/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/', '&amp;', strtr( $myHTML, $translation_table ) );
4435  }
4436  
4437  /**
4438   * Escape single quotes, htmlspecialchar " < > &, and fix line endings.
4439   *
4440   * Escapes text strings for echoing in JS. It is intended to be used for inline JS
4441   * (in a tag attribute, for example onclick="..."). Note that the strings have to
4442   * be in single quotes. The {@see 'js_escape'} filter is also applied here.
4443   *
4444   * @since 2.8.0
4445   *
4446   * @param string $text The text to be escaped.
4447   * @return string Escaped text.
4448   */
4449  function esc_js( $text ) {
4450      $safe_text = wp_check_invalid_utf8( $text );
4451      $safe_text = _wp_specialchars( $safe_text, ENT_COMPAT );
4452      $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) );
4453      $safe_text = str_replace( "\r", '', $safe_text );
4454      $safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) );
4455      /**
4456       * Filters a string cleaned and escaped for output in JavaScript.
4457       *
4458       * Text passed to esc_js() is stripped of invalid or special characters,
4459       * and properly slashed for output.
4460       *
4461       * @since 2.0.6
4462       *
4463       * @param string $safe_text The text after it has been escaped.
4464       * @param string $text      The text prior to being escaped.
4465       */
4466      return apply_filters( 'js_escape', $safe_text, $text );
4467  }
4468  
4469  /**
4470   * Escaping for HTML blocks.
4471   *
4472   * @since 2.8.0
4473   *
4474   * @param string $text
4475   * @return string
4476   */
4477  function esc_html( $text ) {
4478      $safe_text = wp_check_invalid_utf8( $text );
4479      $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
4480      /**
4481       * Filters a string cleaned and escaped for output in HTML.
4482       *
4483       * Text passed to esc_html() is stripped of invalid or special characters
4484       * before output.
4485       *
4486       * @since 2.8.0
4487       *
4488       * @param string $safe_text The text after it has been escaped.
4489       * @param string $text      The text prior to being escaped.
4490       */
4491      return apply_filters( 'esc_html', $safe_text, $text );
4492  }
4493  
4494  /**
4495   * Escaping for HTML attributes.
4496   *
4497   * @since 2.8.0
4498   *
4499   * @param string $text
4500   * @return string
4501   */
4502  function esc_attr( $text ) {
4503      $safe_text = wp_check_invalid_utf8( $text );
4504      $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
4505      /**
4506       * Filters a string cleaned and escaped for output in an HTML attribute.
4507       *
4508       * Text passed to esc_attr() is stripped of invalid or special characters
4509       * before output.
4510       *
4511       * @since 2.0.6
4512       *
4513       * @param string $safe_text The text after it has been escaped.
4514       * @param string $text      The text prior to being escaped.
4515       */
4516      return apply_filters( 'attribute_escape', $safe_text, $text );
4517  }
4518  
4519  /**
4520   * Escaping for textarea values.
4521   *
4522   * @since 3.1.0
4523   *
4524   * @param string $text
4525   * @return string
4526   */
4527  function esc_textarea( $text ) {
4528      $safe_text = htmlspecialchars( $text, ENT_QUOTES, get_option( 'blog_charset' ) );
4529      /**
4530       * Filters a string cleaned and escaped for output in a textarea element.
4531       *
4532       * @since 3.1.0
4533       *
4534       * @param string $safe_text The text after it has been escaped.
4535       * @param string $text      The text prior to being escaped.
4536       */
4537      return apply_filters( 'esc_textarea', $safe_text, $text );
4538  }
4539  
4540  /**
4541   * Escaping for XML blocks.
4542   *
4543   * @since 5.5.0
4544   *
4545   * @param string $text Text to escape.
4546   * @return string Escaped text.
4547   */
4548  function esc_xml( $text ) {
4549      $safe_text = wp_check_invalid_utf8( $text );
4550  
4551      $cdata_regex = '\<\!\[CDATA\[.*?\]\]\>';
4552      $regex       = <<<EOF
4553  /
4554      (?=.*?{$cdata_regex})                 # lookahead that will match anything followed by a CDATA Section
4555      (?<non_cdata_followed_by_cdata>(.*?)) # the "anything" matched by the lookahead
4556      (?<cdata>({$cdata_regex}))            # the CDATA Section matched by the lookahead
4557  
4558  |                                          # alternative
4559  
4560      (?<non_cdata>(.*))                    # non-CDATA Section
4561  /sx
4562  EOF;
4563  
4564      $safe_text = (string) preg_replace_callback(
4565          $regex,
4566          static function( $matches ) {
4567              if ( ! $matches[0] ) {
4568                  return '';
4569              }
4570  
4571              if ( ! empty( $matches['non_cdata'] ) ) {
4572                  // escape HTML entities in the non-CDATA Section.
4573                  return _wp_specialchars( $matches['non_cdata'], ENT_XML1 );
4574              }
4575  
4576              // Return the CDATA Section unchanged, escape HTML entities in the rest.
4577              return _wp_specialchars( $matches['non_cdata_followed_by_cdata'], ENT_XML1 ) . $matches['cdata'];
4578          },
4579          $safe_text
4580      );
4581  
4582      /**
4583       * Filters a string cleaned and escaped for output in XML.
4584       *
4585       * Text passed to esc_xml() is stripped of invalid or special characters
4586       * before output. HTML named character references are converted to their
4587       * equivalent code points.
4588       *
4589       * @since 5.5.0
4590       *
4591       * @param string $safe_text The text after it has been escaped.
4592       * @param string $text      The text prior to being escaped.
4593       */
4594      return apply_filters( 'esc_xml', $safe_text, $text );
4595  }
4596  
4597  /**
4598   * Escape an HTML tag name.
4599   *
4600   * @since 2.5.0
4601   *
4602   * @param string $tag_name
4603   * @return string
4604   */
4605  function tag_escape( $tag_name ) {
4606      $safe_tag = strtolower( preg_replace( '/[^a-zA-Z0-9_:]/', '', $tag_name ) );
4607      /**
4608       * Filters a string cleaned and escaped for output as an HTML tag.
4609       *
4610       * @since 2.8.0
4611       *
4612       * @param string $safe_tag The tag name after it has been escaped.
4613       * @param string $tag_name The text before it was escaped.
4614       */
4615      return apply_filters( 'tag_escape', $safe_tag, $tag_name );
4616  }
4617  
4618  /**
4619   * Convert full URL paths to absolute paths.
4620   *
4621   * Removes the http or https protocols and the domain. Keeps the path '/' at the
4622   * beginning, so it isn't a true relative link, but from the web root base.
4623   *
4624   * @since 2.1.0
4625   * @since 4.1.0 Support was added for relative URLs.
4626   *
4627   * @param string $link Full URL path.
4628   * @return string Absolute path.
4629   */
4630  function wp_make_link_relative( $link ) {
4631      return preg_replace( '|^(https?:)?//[^/]+(/?.*)|i', '$2', $link );
4632  }
4633  
4634  /**
4635   * Sanitises various option values based on the nature of the option.
4636   *
4637   * This is basically a switch statement which will pass $value through a number
4638   * of functions depending on the $option.
4639   *
4640   * @since 2.0.5
4641   *
4642   * @global wpdb $wpdb WordPress database abstraction object.
4643   *
4644   * @param string $option The name of the option.
4645   * @param string $value  The unsanitised value.
4646   * @return string Sanitized value.
4647   */
4648  function sanitize_option( $option, $value ) {
4649      global $wpdb;
4650  
4651      $original_value = $value;
4652      $error          = '';
4653  
4654      switch ( $option ) {
4655          case 'admin_email':
4656          case 'new_admin_email':
4657              $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
4658              if ( is_wp_error( $value ) ) {
4659                  $error = $value->get_error_message();
4660              } else {
4661                  $value = sanitize_email( $value );
4662                  if ( ! is_email( $value ) ) {
4663                      $error = __( 'The email address entered did not appear to be a valid email address. Please enter a valid email address.' );
4664                  }
4665              }
4666              break;
4667  
4668          case 'thumbnail_size_w':
4669          case 'thumbnail_size_h':
4670          case 'medium_size_w':
4671          case 'medium_size_h':
4672          case 'medium_large_size_w':
4673          case 'medium_large_size_h':
4674          case 'large_size_w':
4675          case 'large_size_h':
4676          case 'mailserver_port':
4677          case 'comment_max_links':
4678          case 'page_on_front':
4679          case 'page_for_posts':
4680          case 'rss_excerpt_length':
4681          case 'default_category':
4682          case 'default_email_category':
4683          case 'default_link_category':
4684          case 'close_comments_days_old':
4685          case 'comments_per_page':
4686          case 'thread_comments_depth':
4687          case 'users_can_register':
4688          case 'start_of_week':
4689          case 'site_icon':
4690              $value = absint( $value );
4691              break;
4692  
4693          case 'posts_per_page':
4694          case 'posts_per_rss':
4695              $value = (int) $value;
4696              if ( empty( $value ) ) {
4697                  $value = 1;
4698              }
4699              if ( $value < -1 ) {
4700                  $value = abs( $value );
4701              }
4702              break;
4703  
4704          case 'default_ping_status':
4705          case 'default_comment_status':
4706              // Options that if not there have 0 value but need to be something like "closed".
4707              if ( '0' == $value || '' === $value ) {
4708                  $value = 'closed';
4709              }
4710              break;
4711  
4712          case 'blogdescription':
4713          case 'blogname':
4714              $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
4715              if ( $value !== $original_value ) {
4716                  $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', wp_encode_emoji( $original_value ) );
4717              }
4718  
4719              if ( is_wp_error( $value ) ) {
4720                  $error = $value->get_error_message();
4721              } else {
4722                  $value = esc_html( $value );
4723              }
4724              break;
4725  
4726          case 'blog_charset':
4727              $value = preg_replace( '/[^a-zA-Z0-9_-]/', '', $value ); // Strips slashes.
4728              break;
4729  
4730          case 'blog_public':
4731              // This is the value if the settings checkbox is not checked on POST. Don't rely on this.
4732              if ( null === $value ) {
4733                  $value = 1;
4734              } else {
4735                  $value = (int) $value;
4736              }
4737              break;
4738  
4739          case 'date_format':
4740          case 'time_format':
4741          case 'mailserver_url':
4742          case 'mailserver_login':
4743          case 'mailserver_pass':
4744          case 'upload_path':
4745              $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
4746              if ( is_wp_error( $value ) ) {
4747                  $error = $value->get_error_message();
4748              } else {
4749                  $value = strip_tags( $value );
4750                  $value = wp_kses_data( $value );
4751              }
4752              break;
4753  
4754          case 'ping_sites':
4755              $value = explode( "\n", $value );
4756              $value = array_filter( array_map( 'trim', $value ) );
4757              $value = array_filter( array_map( 'esc_url_raw', $value ) );
4758              $value = implode( "\n", $value );
4759              break;
4760  
4761          case 'gmt_offset':
4762              $value = preg_replace( '/[^0-9:.-]/', '', $value ); // Strips slashes.
4763              break;
4764  
4765          case 'siteurl':
4766              $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
4767              if ( is_wp_error( $value ) ) {
4768                  $error = $value->get_error_message();
4769              } else {
4770                  if ( preg_match( '#http(s?)://(.+)#i', $value ) ) {
4771                      $value = esc_url_raw( $value );
4772                  } else {
4773                      $error = __( 'The WordPress address you entered did not appear to be a valid URL. Please enter a valid URL.' );
4774                  }
4775              }
4776              break;
4777  
4778          case 'home':
4779              $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
4780              if ( is_wp_error( $value ) ) {
4781                  $error = $value->get_error_message();
4782              } else {
4783                  if ( preg_match( '#http(s?)://(.+)#i', $value ) ) {
4784                      $value = esc_url_raw( $value );
4785                  } else {
4786                      $error = __( 'The Site address you entered did not appear to be a valid URL. Please enter a valid URL.' );
4787                  }
4788              }
4789              break;
4790  
4791          case 'WPLANG':
4792              $allowed = get_available_languages();
4793              if ( ! is_multisite() && defined( 'WPLANG' ) && '' !== WPLANG && 'en_US' !== WPLANG ) {
4794                  $allowed[] = WPLANG;
4795              }
4796              if ( ! in_array( $value, $allowed, true ) && ! empty( $value ) ) {
4797                  $value = get_option( $option );
4798              }
4799              break;
4800  
4801          case 'illegal_names':
4802              $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
4803              if ( is_wp_error( $value ) ) {
4804                  $error = $value->get_error_message();
4805              } else {
4806                  if ( ! is_array( $value ) ) {
4807                      $value = explode( ' ', $value );
4808                  }
4809  
4810                  $value = array_values( array_filter( array_map( 'trim', $value ) ) );
4811  
4812                  if ( ! $value ) {
4813                      $value = '';
4814                  }
4815              }
4816              break;
4817  
4818          case 'limited_email_domains':
4819          case 'banned_email_domains':
4820              $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
4821              if ( is_wp_error( $value ) ) {
4822                  $error = $value->get_error_message();
4823              } else {
4824                  if ( ! is_array( $value ) ) {
4825                      $value = explode( "\n", $value );
4826                  }
4827  
4828                  $domains = array_values( array_filter( array_map( 'trim', $value ) ) );
4829                  $value   = array();
4830  
4831                  foreach ( $domains as $domain ) {
4832                      if ( ! preg_match( '/(--|\.\.)/', $domain ) && preg_match( '|^([a-zA-Z0-9-\.])+$|', $domain ) ) {
4833                          $value[] = $domain;
4834                      }
4835                  }
4836                  if ( ! $value ) {
4837                      $value = '';
4838                  }
4839              }
4840              break;
4841  
4842          case 'timezone_string':
4843              $allowed_zones = timezone_identifiers_list();
4844              if ( ! in_array( $value, $allowed_zones, true ) && ! empty( $value ) ) {
4845                  $error = __( 'The timezone you have entered is not valid. Please select a valid timezone.' );
4846              }
4847              break;
4848  
4849          case 'permalink_structure':
4850          case 'category_base':
4851          case 'tag_base':
4852              $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
4853              if ( is_wp_error( $value ) ) {
4854                  $error = $value->get_error_message();
4855              } else {
4856                  $value = esc_url_raw( $value );
4857                  $value = str_replace( 'http://', '', $value );
4858              }
4859  
4860              if ( 'permalink_structure' === $option && '' !== $value && ! preg_match( '/%[^\/%]+%/', $value ) ) {
4861                  $error = sprintf(
4862                      /* translators: %s: Documentation URL. */
4863                      __( 'A structure tag is required when using custom permalinks. <a href="%s">Learn more</a>' ),
4864                      __( 'https://wordpress.org/support/article/using-permalinks/#choosing-your-permalink-structure' )
4865                  );
4866              }
4867              break;
4868  
4869          case 'default_role':
4870              if ( ! get_role( $value ) && get_role( 'subscriber' ) ) {
4871                  $value = 'subscriber';
4872              }
4873              break;
4874  
4875          case 'moderation_keys':
4876          case 'disallowed_keys':
4877              $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
4878              if ( is_wp_error( $value ) ) {
4879                  $error = $value->get_error_message();
4880              } else {
4881                  $value = explode( "\n", $value );
4882                  $value = array_filter( array_map( 'trim', $value ) );
4883                  $value = array_unique( $value );
4884                  $value = implode( "\n", $value );
4885              }
4886              break;
4887      }
4888  
4889      if ( ! empty( $error ) ) {
4890          $value = get_option( $option );
4891          if ( function_exists( 'add_settings_error' ) ) {
4892              add_settings_error( $option, "invalid_{$option}", $error );
4893          }
4894      }
4895  
4896      /**
4897       * Filters an option value following sanitization.
4898       *
4899       * @since 2.3.0
4900       * @since 4.3.0 Added the `$original_value` parameter.
4901       *
4902       * @param string $value          The sanitized option value.
4903       * @param string $option         The option name.
4904       * @param string $original_value The original value passed to the function.
4905       */
4906      return apply_filters( "sanitize_option_{$option}", $value, $option, $original_value );
4907  }
4908  
4909  /**
4910   * Maps a function to all non-iterable elements of an array or an object.
4911   *
4912   * This is similar to `array_walk_recursive()` but acts upon objects too.
4913   *
4914   * @since 4.4.0
4915   *
4916   * @param mixed    $value    The array, object, or scalar.
4917   * @param callable $callback The function to map onto $value.
4918   * @return mixed The value with the callback applied to all non-arrays and non-objects inside it.
4919   */
4920  function map_deep( $value, $callback ) {
4921      if ( is_array( $value ) ) {
4922          foreach ( $value as $index => $item ) {
4923              $value[ $index ] = map_deep( $item, $callback );
4924          }
4925      } elseif ( is_object( $value ) ) {
4926          $object_vars = get_object_vars( $value );
4927          foreach ( $object_vars as $property_name => $property_value ) {
4928              $value->$property_name = map_deep( $property_value, $callback );
4929          }
4930      } else {
4931          $value = call_user_func( $callback, $value );
4932      }
4933  
4934      return $value;
4935  }
4936  
4937  /**
4938   * Parses a string into variables to be stored in an array.
4939   *
4940   * @since 2.2.1
4941   *
4942   * @param string $string The string to be parsed.
4943   * @param array  $array  Variables will be stored in this array.
4944   */
4945  function wp_parse_str( $string, &$array ) {
4946      parse_str( $string, $array );
4947  
4948      /**
4949       * Filters the array of variables derived from a parsed string.
4950       *
4951       * @since 2.3.0
4952       *
4953       * @param array $array The array populated with variables.
4954       */
4955      $array = apply_filters( 'wp_parse_str', $array );
4956  }
4957  
4958  /**
4959   * Convert lone less than signs.
4960   *
4961   * KSES already converts lone greater than signs.
4962   *
4963   * @since 2.3.0
4964   *
4965   * @param string $text Text to be converted.
4966   * @return string Converted text.
4967   */
4968  function wp_pre_kses_less_than( $text ) {
4969      return preg_replace_callback( '%<[^>]*?((?=<)|>|$)%', 'wp_pre_kses_less_than_callback', $text );
4970  }
4971  
4972  /**
4973   * Callback function used by preg_replace.
4974   *
4975   * @since 2.3.0
4976   *
4977   * @param array $matches Populated by matches to preg_replace.
4978   * @return string The text returned after esc_html if needed.
4979   */
4980  function wp_pre_kses_less_than_callback( $matches ) {
4981      if ( false === strpos( $matches[0], '>' ) ) {
4982          return esc_html( $matches[0] );
4983      }
4984      return $matches[0];
4985  }
4986  
4987  /**
4988   * Remove non-allowable HTML from parsed block attribute values when filtering
4989   * in the post context.
4990   *
4991   * @since 5.3.1
4992   *
4993   * @param string         $string            Content to be run through KSES.
4994   * @param array[]|string $allowed_html      An array of allowed HTML elements
4995   *                                          and attributes, or a context name
4996   *                                          such as 'post'.
4997   * @param string[]       $allowed_protocols Array of allowed URL protocols.
4998   * @return string Filtered text to run through KSES.
4999   */
5000  function wp_pre_kses_block_attributes( $string, $allowed_html, $allowed_protocols ) {
5001      /*
5002       * `filter_block_content` is expected to call `wp_kses`. Temporarily remove
5003       * the filter to avoid recursion.
5004       */
5005      remove_filter( 'pre_kses', 'wp_pre_kses_block_attributes', 10 );
5006      $string = filter_block_content( $string, $allowed_html, $allowed_protocols );
5007      add_filter( 'pre_kses', 'wp_pre_kses_block_attributes', 10, 3 );
5008  
5009      return $string;
5010  }
5011  
5012  /**
5013   * WordPress implementation of PHP sprintf() with filters.
5014   *
5015   * @since 2.5.0
5016   * @since 5.3.0 Formalized the existing and already documented `...$args` parameter
5017   *              by adding it to the function signature.
5018   *
5019   * @link https://www.php.net/sprintf
5020   *
5021   * @param string $pattern The string which formatted args are inserted.
5022   * @param mixed  ...$args Arguments to be formatted into the $pattern string.
5023   * @return string The formatted string.
5024   */
5025  function wp_sprintf( $pattern, ...$args ) {
5026      $len       = strlen( $pattern );
5027      $start     = 0;
5028      $result    = '';
5029      $arg_index = 0;
5030      while ( $len > $start ) {
5031          // Last character: append and break.
5032          if ( strlen( $pattern ) - 1 == $start ) {
5033              $result .= substr( $pattern, -1 );
5034              break;
5035          }
5036  
5037          // Literal %: append and continue.
5038          if ( '%%' === substr( $pattern, $start, 2 ) ) {
5039              $start  += 2;
5040              $result .= '%';
5041              continue;
5042          }
5043  
5044          // Get fragment before next %.
5045          $end = strpos( $pattern, '%', $start + 1 );
5046          if ( false === $end ) {
5047              $end = $len;
5048          }
5049          $fragment = substr( $pattern, $start, $end - $start );
5050  
5051          // Fragment has a specifier.
5052          if ( '%' === $pattern[ $start ] ) {
5053              // Find numbered arguments or take the next one in order.
5054              if ( preg_match( '/^%(\d+)\$/', $fragment, $matches ) ) {
5055                  $index    = $matches[1] - 1; // 0-based array vs 1-based sprintf() arguments.
5056                  $arg      = isset( $args[ $index ] ) ? $args[ $index ] : '';
5057                  $fragment = str_replace( "%{$matches[1]}$", '%', $fragment );
5058              } else {
5059                  $arg = isset( $args[ $arg_index ] ) ? $args[ $arg_index ] : '';
5060                  ++$arg_index;
5061              }
5062  
5063              /**
5064               * Filters a fragment from the pattern passed to wp_sprintf().
5065               *
5066               * If the fragment is unchanged, then sprintf() will be run on the fragment.
5067               *
5068               * @since 2.5.0
5069               *
5070               * @param string $fragment A fragment from the pattern.
5071               * @param string $arg      The argument.
5072               */
5073              $_fragment = apply_filters( 'wp_sprintf', $fragment, $arg );
5074              if ( $_fragment != $fragment ) {
5075                  $fragment = $_fragment;
5076              } else {
5077                  $fragment = sprintf( $fragment, (string) $arg );
5078              }
5079          }
5080  
5081          // Append to result and move to next fragment.
5082          $result .= $fragment;
5083          $start   = $end;
5084      }
5085  
5086      return $result;
5087  }
5088  
5089  /**
5090   * Localize list items before the rest of the content.
5091   *
5092   * The '%l' must be at the first characters can then contain the rest of the
5093   * content. The list items will have ', ', ', and', and ' and ' added depending
5094   * on the amount of list items in the $args parameter.
5095   *
5096   * @since 2.5.0
5097   *
5098   * @param string $pattern Content containing '%l' at the beginning.
5099   * @param array  $args    List items to prepend to the content and replace '%l'.
5100   * @return string Localized list items and rest of the content.
5101   */
5102  function wp_sprintf_l( $pattern, $args ) {
5103      // Not a match.
5104      if ( '%l' !== substr( $pattern, 0, 2 ) ) {
5105          return $pattern;
5106      }
5107  
5108      // Nothing to work with.
5109      if ( empty( $args ) ) {
5110          return '';
5111      }
5112  
5113      /**
5114       * Filters the translated delimiters used by wp_sprintf_l().
5115       * Placeholders (%s) are included to assist translators and then
5116       * removed before the array of strings reaches the filter.
5117       *
5118       * Please note: Ampersands and entities should be avoided here.
5119       *
5120       * @since 2.5.0
5121       *
5122       * @param array $delimiters An array of translated delimiters.
5123       */
5124      $l = apply_filters(
5125          'wp_sprintf_l',
5126          array(
5127              /* translators: Used to join items in a list with more than 2 items. */
5128              'between'          => sprintf( __( '%1$s, %2$s' ), '', '' ),
5129              /* translators: Used to join last two items in a list with more than 2 times. */
5130              'between_last_two' => sprintf( __( '%1$s, and %2$s' ), '', '' ),
5131              /* translators: Used to join items in a list with only 2 items. */
5132              'between_only_two' => sprintf( __( '%1$s and %2$s' ), '', '' ),
5133          )
5134      );
5135  
5136      $args   = (array) $args;
5137      $result = array_shift( $args );
5138      if ( count( $args ) == 1 ) {
5139          $result .= $l['between_only_two'] . array_shift( $args );
5140      }
5141  
5142      // Loop when more than two args.
5143      $i = count( $args );
5144      while ( $i ) {
5145          $arg = array_shift( $args );
5146          $i--;
5147          if ( 0 == $i ) {
5148              $result .= $l['between_last_two'] . $arg;
5149          } else {
5150              $result .= $l['between'] . $arg;
5151          }
5152      }
5153  
5154      return $result . substr( $pattern, 2 );
5155  }
5156  
5157  /**
5158   * Safely extracts not more than the first $count characters from HTML string.
5159   *
5160   * UTF-8, tags and entities safe prefix extraction. Entities inside will *NOT*
5161   * be counted as one character. For example &amp; will be counted as 4, &lt; as
5162   * 3, etc.
5163   *
5164   * @since 2.5.0
5165   *
5166   * @param string $str   String to get the excerpt from.
5167   * @param int    $count Maximum number of characters to take.
5168   * @param string $more  Optional. What to append if $str needs to be trimmed. Defaults to empty string.
5169   * @return string The excerpt.
5170   */
5171  function wp_html_excerpt( $str, $count, $more = null ) {
5172      if ( null === $more ) {
5173          $more = '';
5174      }
5175  
5176      $str     = wp_strip_all_tags( $str, true );
5177      $excerpt = mb_substr( $str, 0, $count );
5178  
5179      // Remove part of an entity at the end.
5180      $excerpt = preg_replace( '/&[^;\s]{0,6}$/', '', $excerpt );
5181      if ( $str != $excerpt ) {
5182          $excerpt = trim( $excerpt ) . $more;
5183      }
5184  
5185      return $excerpt;
5186  }
5187  
5188  /**
5189   * Add a Base url to relative links in passed content.
5190   *
5191   * By default it supports the 'src' and 'href' attributes. However this can be
5192   * changed via the 3rd param.
5193   *
5194   * @since 2.7.0
5195   *
5196   * @global string $_links_add_base
5197   *
5198   * @param string $content String to search for links in.
5199   * @param string $base    The base URL to prefix to links.
5200   * @param array  $attrs   The attributes which should be processed.
5201   * @return string The processed content.
5202   */
5203  function links_add_base_url( $content, $base, $attrs = array( 'src', 'href' ) ) {
5204      global $_links_add_base;
5205      $_links_add_base = $base;
5206      $attrs           = implode( '|', (array) $attrs );
5207      return preg_replace_callback( "!($attrs)=(['\"])(.+?)\\2!i", '_links_add_base', $content );
5208  }
5209  
5210  /**
5211   * Callback to add a base url to relative links in passed content.
5212   *
5213   * @since 2.7.0
5214   * @access private
5215   *
5216   * @global string $_links_add_base
5217   *
5218   * @param string $m The matched link.
5219   * @return string The processed link.
5220   */
5221  function _links_add_base( $m ) {
5222      global $_links_add_base;
5223      // 1 = attribute name  2 = quotation mark  3 = URL.
5224      return $m[1] . '=' . $m[2] .
5225          ( preg_match( '#^(\w{1,20}):#', $m[3], $protocol ) && in_array( $protocol[1], wp_allowed_protocols(), true ) ?
5226              $m[3] :
5227              WP_Http::make_absolute_url( $m[3], $_links_add_base )
5228          )
5229          . $m[2];
5230  }
5231  
5232  /**
5233   * Adds a Target attribute to all links in passed content.
5234   *
5235   * This function by default only applies to `<a>` tags, however this can be
5236   * modified by the 3rd param.
5237   *
5238   * *NOTE:* Any current target attributed will be stripped and replaced.
5239   *
5240   * @since 2.7.0
5241   *
5242   * @global string $_links_add_target
5243   *
5244   * @param string   $content String to search for links in.
5245   * @param string   $target  The Target to add to the links.
5246   * @param string[] $tags    An array of tags to apply to.
5247   * @return string The processed content.
5248   */
5249  function links_add_target( $content, $target = '_blank', $tags = array( 'a' ) ) {
5250      global $_links_add_target;
5251      $_links_add_target = $target;
5252      $tags              = implode( '|', (array) $tags );
5253      return preg_replace_callback( "!<($tags)((\s[^>]*)?)>!i", '_links_add_target', $content );
5254  }
5255  
5256  /**
5257   * Callback to add a target attribute to all links in passed content.
5258   *
5259   * @since 2.7.0
5260   * @access private
5261   *
5262   * @global string $_links_add_target
5263   *
5264   * @param string $m The matched link.
5265   * @return string The processed link.
5266   */
5267  function _links_add_target( $m ) {
5268      global $_links_add_target;
5269      $tag  = $m[1];
5270      $link = preg_replace( '|( target=([\'"])(.*?)\2)|i', '', $m[2] );
5271      return '<' . $tag . $link . ' target="' . esc_attr( $_links_add_target ) . '">';
5272  }
5273  
5274  /**
5275   * Normalize EOL characters and strip duplicate whitespace.
5276   *
5277   * @since 2.7.0
5278   *
5279   * @param string $str The string to normalize.
5280   * @return string The normalized string.
5281   */
5282  function normalize_whitespace( $str ) {
5283      $str = trim( $str );
5284      $str = str_replace( "\r", "\n", $str );
5285      $str = preg_replace( array( '/\n+/', '/[ \t]+/' ), array( "\n", ' ' ), $str );
5286      return $str;
5287  }
5288  
5289  /**
5290   * Properly strip all HTML tags including script and style
5291   *
5292   * This differs from strip_tags() because it removes the contents of
5293   * the `<script>` and `<style>` tags. E.g. `strip_tags( '<script>something</script>' )`
5294   * will return 'something'. wp_strip_all_tags will return ''
5295   *
5296   * @since 2.9.0
5297   *
5298   * @param string $string        String containing HTML tags
5299   * @param bool   $remove_breaks Optional. Whether to remove left over line breaks and white space chars
5300   * @return string The processed string.
5301   */
5302  function wp_strip_all_tags( $string, $remove_breaks = false ) {
5303      $string = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $string );
5304      $string = strip_tags( $string );
5305  
5306      if ( $remove_breaks ) {
5307          $string = preg_replace( '/[\r\n\t ]+/', ' ', $string );
5308      }
5309  
5310      return trim( $string );
5311  }
5312  
5313  /**
5314   * Sanitizes a string from user input or from the database.
5315   *
5316   * - Checks for invalid UTF-8,
5317   * - Converts single `<` characters to entities
5318   * - Strips all tags
5319   * - Removes line breaks, tabs, and extra whitespace
5320   * - Strips octets
5321   *
5322   * @since 2.9.0
5323   *
5324   * @see sanitize_textarea_field()
5325   * @see wp_check_invalid_utf8()
5326   * @see wp_strip_all_tags()
5327   *
5328   * @param string $str String to sanitize.
5329   * @return string Sanitized string.
5330   */
5331  function sanitize_text_field( $str ) {
5332      $filtered = _sanitize_text_fields( $str, false );
5333  
5334      /**
5335       * Filters a sanitized text field string.
5336       *
5337       * @since 2.9.0
5338       *
5339       * @param string $filtered The sanitized string.
5340       * @param string $str      The string prior to being sanitized.
5341       */
5342      return apply_filters( 'sanitize_text_field', $filtered, $str );
5343  }
5344  
5345  /**
5346   * Sanitizes a multiline string from user input or from the database.
5347   *
5348   * The function is like sanitize_text_field(), but preserves
5349   * new lines (\n) and other whitespace, which are legitimate
5350   * input in textarea elements.
5351   *
5352   * @see sanitize_text_field()
5353   *
5354   * @since 4.7.0
5355   *
5356   * @param string $str String to sanitize.
5357   * @return string Sanitized string.
5358   */
5359  function sanitize_textarea_field( $str ) {
5360