[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

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