[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

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

   1  <?php
   2  /**
   3   * Main WordPress Formatting API.
   4   *
   5   * Handles many functions for formatting output.
   6   *
   7   * @package WordPress
   8   */
   9  
  10  /**
  11   * Replaces common plain text characters 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   * Adds rel nofollow string to all HTML A elements in content.
3016   *
3017   * @since 1.5.0
3018   *
3019   * @param string $text Content that may contain HTML A elements.
3020   * @return string Converted content.
3021   */
3022  function wp_rel_nofollow( $text ) {
3023      // This is a pre save filter, so text is already escaped.
3024      $text = stripslashes( $text );
3025      $text = preg_replace_callback( '|<a (.+?)>|i', 'wp_rel_nofollow_callback', $text );
3026      return wp_slash( $text );
3027  }
3028  
3029  /**
3030   * Callback to add rel=nofollow string to HTML A element.
3031   *
3032   * Will remove already existing rel="nofollow" and rel='nofollow' from the
3033   * string to prevent from invalidating (X)HTML.
3034   *
3035   * @since 2.3.0
3036   *
3037   * @param array $matches Single Match
3038   * @return string HTML A Element with rel nofollow.
3039   */
3040  function wp_rel_nofollow_callback( $matches ) {
3041      $text = $matches[1];
3042      $atts = wp_kses_hair( $matches[1], wp_allowed_protocols() );
3043      $rel  = 'nofollow';
3044  
3045      if ( ! empty( $atts['href'] ) ) {
3046          if ( in_array( strtolower( wp_parse_url( $atts['href']['value'], PHP_URL_SCHEME ) ), array( 'http', 'https' ), true ) ) {
3047              if ( strtolower( wp_parse_url( $atts['href']['value'], PHP_URL_HOST ) ) === strtolower( wp_parse_url( home_url(), PHP_URL_HOST ) ) ) {
3048                  return "<a $text>";
3049              }
3050          }
3051      }
3052  
3053      if ( ! empty( $atts['rel'] ) ) {
3054          $parts = array_map( 'trim', explode( ' ', $atts['rel']['value'] ) );
3055          if ( false === array_search( 'nofollow', $parts ) ) {
3056              $parts[] = 'nofollow';
3057          }
3058          $rel = implode( ' ', $parts );
3059          unset( $atts['rel'] );
3060  
3061          $html = '';
3062          foreach ( $atts as $name => $value ) {
3063              if ( isset( $value['vless'] ) && 'y' === $value['vless'] ) {
3064                  $html .= $name . ' ';
3065              } else {
3066                  $html .= "{$name}=\"" . esc_attr( $value['value'] ) . '" ';
3067              }
3068          }
3069          $text = trim( $html );
3070      }
3071      return "<a $text rel=\"" . esc_attr( $rel ) . '">';
3072  }
3073  
3074  /**
3075   * Adds rel noreferrer and noopener to all HTML A elements that have a target.
3076   *
3077   * @since 5.1.0
3078   *
3079   * @param string $text Content that may contain HTML A elements.
3080   * @return string Converted content.
3081   */
3082  function wp_targeted_link_rel( $text ) {
3083      // Don't run (more expensive) regex if no links with targets.
3084      if ( stripos( $text, 'target' ) !== false && stripos( $text, '<a ' ) !== false ) {
3085          if ( ! is_serialized( $text ) ) {
3086              $text = preg_replace_callback( '|<a\s([^>]*target\s*=[^>]*)>|i', 'wp_targeted_link_rel_callback', $text );
3087          }
3088      }
3089  
3090      return $text;
3091  }
3092  
3093  /**
3094   * Callback to add rel="noreferrer noopener" string to HTML A element.
3095   *
3096   * Will not duplicate existing noreferrer and noopener values
3097   * to prevent from invalidating the HTML.
3098   *
3099   * @since 5.1.0
3100   *
3101   * @param array $matches Single Match
3102   * @return string HTML A Element with rel noreferrer noopener in addition to any existing values
3103   */
3104  function wp_targeted_link_rel_callback( $matches ) {
3105      $link_html = $matches[1];
3106      $rel_match = array();
3107  
3108      /**
3109       * Filters the rel values that are added to links with `target` attribute.
3110       *
3111       * @since 5.1.0
3112       *
3113       * @param string The rel values.
3114       * @param string $link_html The matched content of the link tag including all HTML attributes.
3115       */
3116      $rel = apply_filters( 'wp_targeted_link_rel', 'noopener noreferrer', $link_html );
3117  
3118      // Avoid additional regex if the filter removes rel values.
3119      if ( ! $rel ) {
3120          return "<a $link_html>";
3121      }
3122  
3123      // Value with delimiters, spaces around are optional.
3124      $attr_regex = '|rel\s*=\s*?(\\\\{0,1}["\'])(.*?)\\1|i';
3125      preg_match( $attr_regex, $link_html, $rel_match );
3126  
3127      if ( empty( $rel_match[0] ) ) {
3128          // No delimiters, try with a single value and spaces, because `rel =  va"lue` is totally fine...
3129          $attr_regex = '|rel\s*=(\s*)([^\s]*)|i';
3130          preg_match( $attr_regex, $link_html, $rel_match );
3131      }
3132  
3133      if ( ! empty( $rel_match[0] ) ) {
3134          $parts     = preg_split( '|\s+|', strtolower( $rel_match[2] ) );
3135          $parts     = array_map( 'esc_attr', $parts );
3136          $needed    = explode( ' ', $rel );
3137          $parts     = array_unique( array_merge( $parts, $needed ) );
3138          $delimiter = trim( $rel_match[1] ) ? $rel_match[1] : '"';
3139          $rel       = 'rel=' . $delimiter . trim( implode( ' ', $parts ) ) . $delimiter;
3140          $link_html = str_replace( $rel_match[0], $rel, $link_html );
3141      } elseif ( preg_match( '|target\s*=\s*?\\\\"|', $link_html ) ) {
3142          $link_html .= " rel=\\\"$rel\\\"";
3143      } elseif ( preg_match( '#(target|href)\s*=\s*?\'#', $link_html ) ) {
3144          $link_html .= " rel='$rel'";
3145      } else {
3146          $link_html .= " rel=\"$rel\"";
3147      }
3148  
3149      return "<a $link_html>";
3150  }
3151  
3152  /**
3153   * Adds all filters modifying the rel attribute of targeted links.
3154   *
3155   * @since 5.1.0
3156   */
3157  function wp_init_targeted_link_rel_filters() {
3158      $filters = array(
3159          'title_save_pre',
3160          'content_save_pre',
3161          'excerpt_save_pre',
3162          'content_filtered_save_pre',
3163          'pre_comment_content',
3164          'pre_term_description',
3165          'pre_link_description',
3166          'pre_link_notes',
3167          'pre_user_description',
3168      );
3169  
3170      foreach ( $filters as $filter ) {
3171          add_filter( $filter, 'wp_targeted_link_rel' );
3172      };
3173  }
3174  
3175  /**
3176   * Removes all filters modifying the rel attribute of targeted links.
3177   *
3178   * @since 5.1.0
3179   */
3180  function wp_remove_targeted_link_rel_filters() {
3181      $filters = array(
3182          'title_save_pre',
3183          'content_save_pre',
3184          'excerpt_save_pre',
3185          'content_filtered_save_pre',
3186          'pre_comment_content',
3187          'pre_term_description',
3188          'pre_link_description',
3189          'pre_link_notes',
3190          'pre_user_description',
3191      );
3192  
3193      foreach ( $filters as $filter ) {
3194          remove_filter( $filter, 'wp_targeted_link_rel' );
3195      };
3196  }
3197  
3198  /**
3199   * Convert one smiley code to the icon graphic file equivalent.
3200   *
3201   * Callback handler for convert_smilies().
3202   *
3203   * Looks up one smiley code in the $wpsmiliestrans global array and returns an
3204   * `<img>` string for that smiley.
3205   *
3206   * @since 2.8.0
3207   *
3208   * @global array $wpsmiliestrans
3209   *
3210   * @param array $matches Single match. Smiley code to convert to image.
3211   * @return string Image string for smiley.
3212   */
3213  function translate_smiley( $matches ) {
3214      global $wpsmiliestrans;
3215  
3216      if ( count( $matches ) == 0 ) {
3217          return '';
3218      }
3219  
3220      $smiley = trim( reset( $matches ) );
3221      $img    = $wpsmiliestrans[ $smiley ];
3222  
3223      $matches    = array();
3224      $ext        = preg_match( '/\.([^.]+)$/', $img, $matches ) ? strtolower( $matches[1] ) : false;
3225      $image_exts = array( 'jpg', 'jpeg', 'jpe', 'gif', 'png' );
3226  
3227      // Don't convert smilies that aren't images - they're probably emoji.
3228      if ( ! in_array( $ext, $image_exts ) ) {
3229          return $img;
3230      }
3231  
3232      /**
3233       * Filters the Smiley image URL before it's used in the image element.
3234       *
3235       * @since 2.9.0
3236       *
3237       * @param string $smiley_url URL for the smiley image.
3238       * @param string $img        Filename for the smiley image.
3239       * @param string $site_url   Site URL, as returned by site_url().
3240       */
3241      $src_url = apply_filters( 'smilies_src', includes_url( "images/smilies/$img" ), $img, site_url() );
3242  
3243      return sprintf( '<img src="%s" alt="%s" class="wp-smiley" style="height: 1em; max-height: 1em;" />', esc_url( $src_url ), esc_attr( $smiley ) );
3244  }
3245  
3246  /**
3247   * Convert text equivalent of smilies to images.
3248   *
3249   * Will only convert smilies if the option 'use_smilies' is true and the global
3250   * used in the function isn't empty.
3251   *
3252   * @since 0.71
3253   *
3254   * @global string|array $wp_smiliessearch
3255   *
3256   * @param string $text Content to convert smilies from text.
3257   * @return string Converted content with text smilies replaced with images.
3258   */
3259  function convert_smilies( $text ) {
3260      global $wp_smiliessearch;
3261      $output = '';
3262      if ( get_option( 'use_smilies' ) && ! empty( $wp_smiliessearch ) ) {
3263          // HTML loop taken from texturize function, could possible be consolidated
3264          $textarr = preg_split( '/(<.*>)/U', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // capture the tags as well as in between
3265          $stop    = count( $textarr );// loop stuff
3266  
3267          // Ignore proessing of specific tags
3268          $tags_to_ignore       = 'code|pre|style|script|textarea';
3269          $ignore_block_element = '';
3270  
3271          for ( $i = 0; $i < $stop; $i++ ) {
3272              $content = $textarr[ $i ];
3273  
3274              // If we're in an ignore block, wait until we find its closing tag
3275              if ( '' == $ignore_block_element && preg_match( '/^<(' . $tags_to_ignore . ')[^>]*>/', $content, $matches ) ) {
3276                  $ignore_block_element = $matches[1];
3277              }
3278  
3279              // If it's not a tag and not in ignore block
3280              if ( '' == $ignore_block_element && strlen( $content ) > 0 && '<' != $content[0] ) {
3281                  $content = preg_replace_callback( $wp_smiliessearch, 'translate_smiley', $content );
3282              }
3283  
3284              // did we exit ignore block
3285              if ( '' != $ignore_block_element && '</' . $ignore_block_element . '>' == $content ) {
3286                  $ignore_block_element = '';
3287              }
3288  
3289              $output .= $content;
3290          }
3291      } else {
3292          // return default text.
3293          $output = $text;
3294      }
3295      return $output;
3296  }
3297  
3298  /**
3299   * Verifies that an email is valid.
3300   *
3301   * Does not grok i18n domains. Not RFC compliant.
3302   *
3303   * @since 0.71
3304   *
3305   * @param string $email      Email address to verify.
3306   * @param bool   $deprecated Deprecated.
3307   * @return string|false Valid email address on success, false on failure.
3308   */
3309  function is_email( $email, $deprecated = false ) {
3310      if ( ! empty( $deprecated ) ) {
3311          _deprecated_argument( __FUNCTION__, '3.0.0' );
3312      }
3313  
3314      // Test for the minimum length the email can be
3315      if ( strlen( $email ) < 6 ) {
3316          /**
3317           * Filters whether an email address is valid.
3318           *
3319           * This filter is evaluated under several different contexts, such as 'email_too_short',
3320           * 'email_no_at', 'local_invalid_chars', 'domain_period_sequence', 'domain_period_limits',
3321           * 'domain_no_periods', 'sub_hyphen_limits', 'sub_invalid_chars', or no specific context.
3322           *
3323           * @since 2.8.0
3324           *
3325           * @param string|false $is_email The email address if successfully passed the is_email() checks, false otherwise.
3326           * @param string       $email    The email address being checked.
3327           * @param string       $context  Context under which the email was tested.
3328           */
3329          return apply_filters( 'is_email', false, $email, 'email_too_short' );
3330      }
3331  
3332      // Test for an @ character after the first position
3333      if ( strpos( $email, '@', 1 ) === false ) {
3334          /** This filter is documented in wp-includes/formatting.php */
3335          return apply_filters( 'is_email', false, $email, 'email_no_at' );
3336      }
3337  
3338      // Split out the local and domain parts
3339      list( $local, $domain ) = explode( '@', $email, 2 );
3340  
3341      // LOCAL PART
3342      // Test for invalid characters
3343      if ( ! preg_match( '/^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]+$/', $local ) ) {
3344          /** This filter is documented in wp-includes/formatting.php */
3345          return apply_filters( 'is_email', false, $email, 'local_invalid_chars' );
3346      }
3347  
3348      // DOMAIN PART
3349      // Test for sequences of periods
3350      if ( preg_match( '/\.{2,}/', $domain ) ) {
3351          /** This filter is documented in wp-includes/formatting.php */
3352          return apply_filters( 'is_email', false, $email, 'domain_period_sequence' );
3353      }
3354  
3355      // Test for leading and trailing periods and whitespace
3356      if ( trim( $domain, " \t\n\r\0\x0B." ) !== $domain ) {
3357          /** This filter is documented in wp-includes/formatting.php */
3358          return apply_filters( 'is_email', false, $email, 'domain_period_limits' );
3359      }
3360  
3361      // Split the domain into subs
3362      $subs = explode( '.', $domain );
3363  
3364      // Assume the domain will have at least two subs
3365      if ( 2 > count( $subs ) ) {
3366          /** This filter is documented in wp-includes/formatting.php */
3367          return apply_filters( 'is_email', false, $email, 'domain_no_periods' );
3368      }
3369  
3370      // Loop through each sub
3371      foreach ( $subs as $sub ) {
3372          // Test for leading and trailing hyphens and whitespace
3373          if ( trim( $sub, " \t\n\r\0\x0B-" ) !== $sub ) {
3374              /** This filter is documented in wp-includes/formatting.php */
3375              return apply_filters( 'is_email', false, $email, 'sub_hyphen_limits' );
3376          }
3377  
3378          // Test for invalid characters
3379          if ( ! preg_match( '/^[a-z0-9-]+$/i', $sub ) ) {
3380              /** This filter is documented in wp-includes/formatting.php */
3381              return apply_filters( 'is_email', false, $email, 'sub_invalid_chars' );
3382          }
3383      }
3384  
3385      // Congratulations your email made it!
3386      /** This filter is documented in wp-includes/formatting.php */
3387      return apply_filters( 'is_email', $email, $email, null );
3388  }
3389  
3390  /**
3391   * Convert to ASCII from email subjects.
3392   *
3393   * @since 1.2.0
3394   *
3395   * @param string $string Subject line
3396   * @return string Converted string to ASCII
3397   */
3398  function wp_iso_descrambler( $string ) {
3399      /* this may only work with iso-8859-1, I'm afraid */
3400      if ( ! preg_match( '#\=\?(.+)\?Q\?(.+)\?\=#i', $string, $matches ) ) {
3401          return $string;
3402      } else {
3403          $subject = str_replace( '_', ' ', $matches[2] );
3404          return preg_replace_callback( '#\=([0-9a-f]{2})#i', '_wp_iso_convert', $subject );
3405      }
3406  }
3407  
3408  /**
3409   * Helper function to convert hex encoded chars to ASCII
3410   *
3411   * @since 3.1.0
3412   * @access private
3413   *
3414   * @param array $match The preg_replace_callback matches array
3415   * @return string Converted chars
3416   */
3417  function _wp_iso_convert( $match ) {
3418      return chr( hexdec( strtolower( $match[1] ) ) );
3419  }
3420  
3421  /**
3422   * Returns a date in the GMT equivalent.
3423   *
3424   * Requires and returns a date in the Y-m-d H:i:s format.
3425   * Return format can be overridden using the $format parameter.
3426   *
3427   * @since 1.2.0
3428   *
3429   * @param string $string The date to be converted.
3430   * @param string $format The format string for the returned date. Default 'Y-m-d H:i:s'.
3431   * @return string GMT version of the date provided.
3432   */
3433  function get_gmt_from_date( $string, $format = 'Y-m-d H:i:s' ) {
3434      $datetime = date_create( $string, wp_timezone() );
3435  
3436      if ( false === $datetime ) {
3437          return gmdate( $format, 0 );
3438      }
3439  
3440      return $datetime->setTimezone( new DateTimeZone( 'UTC' ) )->format( $format );
3441  }
3442  
3443  /**
3444   * Converts a GMT date into the correct format for the blog.
3445   *
3446   * Requires and returns a date in the Y-m-d H:i:s format.
3447   * Return format can be overridden using the $format parameter.
3448   *
3449   * @since 1.2.0
3450   *
3451   * @param string $string The date to be converted.
3452   * @param string $format The format string for the returned date. Default 'Y-m-d H:i:s'.
3453   * @return string Formatted date relative to the timezone.
3454   */
3455  function get_date_from_gmt( $string, $format = 'Y-m-d H:i:s' ) {
3456      $datetime = date_create( $string, new DateTimeZone( 'UTC' ) );
3457  
3458      if ( false === $datetime ) {
3459          return gmdate( $format, 0 );
3460      }
3461  
3462      return $datetime->setTimezone( wp_timezone() )->format( $format );
3463  }
3464  
3465  /**
3466   * Computes an offset in seconds from an iso8601 timezone.
3467   *
3468   * @since 1.5.0
3469   *
3470   * @param string $timezone Either 'Z' for 0 offset or '±hhmm'.
3471   * @return int|float The offset in seconds.
3472   */
3473  function iso8601_timezone_to_offset( $timezone ) {
3474      // $timezone is either 'Z' or '[+|-]hhmm'
3475      if ( $timezone == 'Z' ) {
3476          $offset = 0;
3477      } else {
3478          $sign    = ( substr( $timezone, 0, 1 ) == '+' ) ? 1 : -1;
3479          $hours   = intval( substr( $timezone, 1, 2 ) );
3480          $minutes = intval( substr( $timezone, 3, 4 ) ) / 60;
3481          $offset  = $sign * HOUR_IN_SECONDS * ( $hours + $minutes );
3482      }
3483      return $offset;
3484  }
3485  
3486  /**
3487   * Converts an iso8601 (Ymd\TH:i:sO) date to MySQL DateTime (Y-m-d H:i:s) format used by post_date[_gmt].
3488   *
3489   * @since 1.5.0
3490   *
3491   * @param string $date_string Date and time in ISO 8601 format {@link https://en.wikipedia.org/wiki/ISO_8601}.
3492   * @param string $timezone    Optional. If set to 'gmt' returns the result in UTC. Default 'user'.
3493   * @return string|bool The date and time in MySQL DateTime format - Y-m-d H:i:s, or false on failure.
3494   */
3495  function iso8601_to_datetime( $date_string, $timezone = 'user' ) {
3496      $timezone    = strtolower( $timezone );
3497      $wp_timezone = wp_timezone();
3498      $datetime    = date_create( $date_string, $wp_timezone ); // Timezone is ignored if input has one.
3499  
3500      if ( false === $datetime ) {
3501          return false;
3502      }
3503  
3504      if ( 'gmt' === $timezone ) {
3505          return $datetime->setTimezone( new DateTimeZone( 'UTC' ) )->format( 'Y-m-d H:i:s' );
3506      }
3507  
3508      if ( 'user' === $timezone ) {
3509          return $datetime->setTimezone( $wp_timezone )->format( 'Y-m-d H:i:s' );
3510      }
3511  
3512      return false;
3513  }
3514  
3515  /**
3516   * Strips out all characters that are not allowable in an email.
3517   *
3518   * @since 1.5.0
3519   *
3520   * @param string $email Email address to filter.
3521   * @return string Filtered email address.
3522   */
3523  function sanitize_email( $email ) {
3524      // Test for the minimum length the email can be
3525      if ( strlen( $email ) < 6 ) {
3526          /**
3527           * Filters a sanitized email address.
3528           *
3529           * This filter is evaluated under several contexts, including 'email_too_short',
3530           * 'email_no_at', 'local_invalid_chars', 'domain_period_sequence', 'domain_period_limits',
3531           * 'domain_no_periods', 'domain_no_valid_subs', or no context.
3532           *
3533           * @since 2.8.0
3534           *
3535           * @param string $sanitized_email The sanitized email address.
3536           * @param string $email           The email address, as provided to sanitize_email().
3537           * @param string|null $message    A message to pass to the user. null if email is sanitized.
3538           */
3539          return apply_filters( 'sanitize_email', '', $email, 'email_too_short' );
3540      }
3541  
3542      // Test for an @ character after the first position
3543      if ( strpos( $email, '@', 1 ) === false ) {
3544          /** This filter is documented in wp-includes/formatting.php */
3545          return apply_filters( 'sanitize_email', '', $email, 'email_no_at' );
3546      }
3547  
3548      // Split out the local and domain parts
3549      list( $local, $domain ) = explode( '@', $email, 2 );
3550  
3551      // LOCAL PART
3552      // Test for invalid characters
3553      $local = preg_replace( '/[^a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]/', '', $local );
3554      if ( '' === $local ) {
3555          /** This filter is documented in wp-includes/formatting.php */
3556          return apply_filters( 'sanitize_email', '', $email, 'local_invalid_chars' );
3557      }
3558  
3559      // DOMAIN PART
3560      // Test for sequences of periods
3561      $domain = preg_replace( '/\.{2,}/', '', $domain );
3562      if ( '' === $domain ) {
3563          /** This filter is documented in wp-includes/formatting.php */
3564          return apply_filters( 'sanitize_email', '', $email, 'domain_period_sequence' );
3565      }
3566  
3567      // Test for leading and trailing periods and whitespace
3568      $domain = trim( $domain, " \t\n\r\0\x0B." );
3569      if ( '' === $domain ) {
3570          /** This filter is documented in wp-includes/formatting.php */
3571          return apply_filters( 'sanitize_email', '', $email, 'domain_period_limits' );
3572      }
3573  
3574      // Split the domain into subs
3575      $subs = explode( '.', $domain );
3576  
3577      // Assume the domain will have at least two subs
3578      if ( 2 > count( $subs ) ) {
3579          /** This filter is documented in wp-includes/formatting.php */
3580          return apply_filters( 'sanitize_email', '', $email, 'domain_no_periods' );
3581      }
3582  
3583      // Create an array that will contain valid subs
3584      $new_subs = array();
3585  
3586      // Loop through each sub
3587      foreach ( $subs as $sub ) {
3588          // Test for leading and trailing hyphens
3589          $sub = trim( $sub, " \t\n\r\0\x0B-" );
3590  
3591          // Test for invalid characters
3592          $sub = preg_replace( '/[^a-z0-9-]+/i', '', $sub );
3593  
3594          // If there's anything left, add it to the valid subs
3595          if ( '' !== $sub ) {
3596              $new_subs[] = $sub;
3597          }
3598      }
3599  
3600      // If there aren't 2 or more valid subs
3601      if ( 2 > count( $new_subs ) ) {
3602          /** This filter is documented in wp-includes/formatting.php */
3603          return apply_filters( 'sanitize_email', '', $email, 'domain_no_valid_subs' );
3604      }
3605  
3606      // Join valid subs into the new domain
3607      $domain = join( '.', $new_subs );
3608  
3609      // Put the email back together
3610      $sanitized_email = $local . '@' . $domain;
3611  
3612      // Congratulations your email made it!
3613      /** This filter is documented in wp-includes/formatting.php */
3614      return apply_filters( 'sanitize_email', $sanitized_email, $email, null );
3615  }
3616  
3617  /**
3618   * Determines the difference between two timestamps.
3619   *
3620   * The difference is returned in a human readable format such as "1 hour",
3621   * "5 mins", "2 days".
3622   *
3623   * @since 1.5.0
3624   * @since 5.3.0 Added support for showing a difference in seconds.
3625   *
3626   * @param int $from Unix timestamp from which the difference begins.
3627   * @param int $to   Optional. Unix timestamp to end the time difference. Default becomes time() if not set.
3628   * @return string Human readable time difference.
3629   */
3630  function human_time_diff( $from, $to = 0 ) {
3631      if ( empty( $to ) ) {
3632          $to = time();
3633      }
3634  
3635      $diff = (int) abs( $to - $from );
3636  
3637      if ( $diff < MINUTE_IN_SECONDS ) {
3638          $secs = $diff;
3639          if ( $secs <= 1 ) {
3640              $secs = 1;
3641          }
3642          /* translators: Time difference between two dates, in seconds. %s: Number of seconds. */
3643          $since = sprintf( _n( '%s second', '%s seconds', $secs ), $secs );
3644      } elseif ( $diff < HOUR_IN_SECONDS && $diff >= MINUTE_IN_SECONDS ) {
3645          $mins = round( $diff / MINUTE_IN_SECONDS );
3646          if ( $mins <= 1 ) {
3647              $mins = 1;
3648          }
3649          /* translators: Time difference between two dates, in minutes (min=minute). %s: Number of minutes. */
3650          $since = sprintf( _n( '%s min', '%s mins', $mins ), $mins );
3651      } elseif ( $diff < DAY_IN_SECONDS && $diff >= HOUR_IN_SECONDS ) {
3652          $hours = round( $diff / HOUR_IN_SECONDS );
3653          if ( $hours <= 1 ) {
3654              $hours = 1;
3655          }
3656          /* translators: Time difference between two dates, in hours. %s: Number of hours. */
3657          $since = sprintf( _n( '%s hour', '%s hours', $hours ), $hours );
3658      } elseif ( $diff < WEEK_IN_SECONDS && $diff >= DAY_IN_SECONDS ) {
3659          $days = round( $diff / DAY_IN_SECONDS );
3660          if ( $days <= 1 ) {
3661              $days = 1;
3662          }
3663          /* translators: Time difference between two dates, in days. %s: Number of days. */
3664          $since = sprintf( _n( '%s day', '%s days', $days ), $days );
3665      } elseif ( $diff < MONTH_IN_SECONDS && $diff >= WEEK_IN_SECONDS ) {
3666          $weeks = round( $diff / WEEK_IN_SECONDS );
3667          if ( $weeks <= 1 ) {
3668              $weeks = 1;
3669          }
3670          /* translators: Time difference between two dates, in weeks. %s: Number of weeks. */
3671          $since = sprintf( _n( '%s week', '%s weeks', $weeks ), $weeks );
3672      } elseif ( $diff < YEAR_IN_SECONDS && $diff >= MONTH_IN_SECONDS ) {
3673          $months = round( $diff / MONTH_IN_SECONDS );
3674          if ( $months <= 1 ) {
3675              $months = 1;
3676          }
3677          /* translators: Time difference between two dates, in months. %s: Number of months. */
3678          $since = sprintf( _n( '%s month', '%s months', $months ), $months );
3679      } elseif ( $diff >= YEAR_IN_SECONDS ) {
3680          $years = round( $diff / YEAR_IN_SECONDS );
3681          if ( $years <= 1 ) {
3682              $years = 1;
3683          }
3684          /* translators: Time difference between two dates, in years. %s: Number of years. */
3685          $since = sprintf( _n( '%s year', '%s years', $years ), $years );
3686      }
3687  
3688      /**
3689       * Filters the human readable difference between two timestamps.
3690       *
3691       * @since 4.0.0
3692       *
3693       * @param string $since The difference in human readable text.
3694       * @param int    $diff  The difference in seconds.
3695       * @param int    $from  Unix timestamp from which the difference begins.
3696       * @param int    $to    Unix timestamp to end the time difference.
3697       */
3698      return apply_filters( 'human_time_diff', $since, $diff, $from, $to );
3699  }
3700  
3701  /**
3702   * Generates an excerpt from the content, if needed.
3703   *
3704   * Returns a maximum of 55 words with an ellipsis appended if necessary.
3705   *
3706   * The 55 word limit can be modified by plugins/themes using the {@see 'excerpt_length'} filter
3707   * The ' [&hellip;]' string can be modified by plugins/themes using the {@see 'excerpt_more'} filter
3708   *
3709   * @since 1.5.0
3710   * @since 5.2.0 Added the `$post` parameter.
3711   *
3712   * @param string             $text Optional. The excerpt. If set to empty, an excerpt is generated.
3713   * @param WP_Post|object|int $post Optional. WP_Post instance or Post ID/object. Default is null.
3714   * @return string The excerpt.
3715   */
3716  function wp_trim_excerpt( $text = '', $post = null ) {
3717      $raw_excerpt = $text;
3718      if ( '' == $text ) {
3719          $post = get_post( $post );
3720          $text = get_the_content( '', false, $post );
3721  
3722          $text = strip_shortcodes( $text );
3723          $text = excerpt_remove_blocks( $text );
3724  
3725          /** This filter is documented in wp-includes/post-template.php */
3726          $text = apply_filters( 'the_content', $text );
3727          $text = str_replace( ']]>', ']]&gt;', $text );
3728  
3729          /* translators: Maximum number of words used in a post excerpt. */
3730          $excerpt_length = intval( _x( '55', 'excerpt_length' ) );
3731  
3732          /**
3733           * Filters the maximum number of words in a post excerpt.
3734           *
3735           * @since 2.7.0
3736           *
3737           * @param int $number The maximum number of words. Default 55.
3738           */
3739          $excerpt_length = (int) apply_filters( 'excerpt_length', $excerpt_length );
3740  
3741          /**
3742           * Filters the string in the "more" link displayed after a trimmed excerpt.
3743           *
3744           * @since 2.9.0
3745           *
3746           * @param string $more_string The string shown within the more link.
3747           */
3748          $excerpt_more = apply_filters( 'excerpt_more', ' ' . '[&hellip;]' );
3749          $text         = wp_trim_words( $text, $excerpt_length, $excerpt_more );
3750      }
3751  
3752      /**
3753       * Filters the trimmed excerpt string.
3754       *
3755       * @since 2.8.0
3756       *
3757       * @param string $text        The trimmed text.
3758       * @param string $raw_excerpt The text prior to trimming.
3759       */
3760      return apply_filters( 'wp_trim_excerpt', $text, $raw_excerpt );
3761  }
3762  
3763  /**
3764   * Trims text to a certain number of words.
3765   *
3766   * This function is localized. For languages that count 'words' by the individual
3767   * character (such as East Asian languages), the $num_words argument will apply
3768   * to the number of individual characters.
3769   *
3770   * @since 3.3.0
3771   *
3772   * @param string $text      Text to trim.
3773   * @param int    $num_words Number of words. Default 55.
3774   * @param string $more      Optional. What to append if $text needs to be trimmed. Default '&hellip;'.
3775   * @return string Trimmed text.
3776   */
3777  function wp_trim_words( $text, $num_words = 55, $more = null ) {
3778      if ( null === $more ) {
3779          $more = __( '&hellip;' );
3780      }
3781  
3782      $original_text = $text;
3783      $text          = wp_strip_all_tags( $text );
3784      $num_words     = (int) $num_words;
3785  
3786      /*
3787       * translators: If your word count is based on single characters (e.g. East Asian characters),
3788       * enter 'characters_excluding_spaces' or 'characters_including_spaces'. Otherwise, enter 'words'.
3789       * Do not translate into your own language.
3790       */
3791      if ( strpos( _x( 'words', 'Word count type. Do not translate!' ), 'characters' ) === 0 && preg_match( '/^utf\-?8$/i', get_option( 'blog_charset' ) ) ) {
3792          $text = trim( preg_replace( "/[\n\r\t ]+/", ' ', $text ), ' ' );
3793          preg_match_all( '/./u', $text, $words_array );
3794          $words_array = array_slice( $words_array[0], 0, $num_words + 1 );
3795          $sep         = '';
3796      } else {
3797          $words_array = preg_split( "/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY );
3798          $sep         = ' ';
3799      }
3800  
3801      if ( count( $words_array ) > $num_words ) {
3802          array_pop( $words_array );
3803          $text = implode( $sep, $words_array );
3804          $text = $text . $more;
3805      } else {
3806          $text = implode( $sep, $words_array );
3807      }
3808  
3809      /**
3810       * Filters the text content after words have been trimmed.
3811       *
3812       * @since 3.3.0
3813       *
3814       * @param string $text          The trimmed text.
3815       * @param int    $num_words     The number of words to trim the text to. Default 55.
3816       * @param string $more          An optional string to append to the end of the trimmed text, e.g. &hellip;.
3817       * @param string $original_text The text before it was trimmed.
3818       */
3819      return apply_filters( 'wp_trim_words', $text, $num_words, $more, $original_text );
3820  }
3821  
3822  /**
3823   * Converts named entities into numbered entities.
3824   *
3825   * @since 1.5.1
3826   *
3827   * @param string $text The text within which entities will be converted.
3828   * @return string Text with converted entities.
3829   */
3830  function ent2ncr( $text ) {
3831  
3832      /**
3833       * Filters text before named entities are converted into numbered entities.
3834       *
3835       * A non-null string must be returned for the filter to be evaluated.
3836       *
3837       * @since 3.3.0
3838       *
3839       * @param null   $converted_text The text to be converted. Default null.
3840       * @param string $text           The text prior to entity conversion.
3841       */
3842      $filtered = apply_filters( 'pre_ent2ncr', null, $text );
3843      if ( null !== $filtered ) {
3844          return $filtered;
3845      }
3846  
3847      $to_ncr = array(
3848          '&quot;'     => '&#34;',
3849          '&amp;'      => '&#38;',
3850          '&lt;'       => '&#60;',
3851          '&gt;'       => '&#62;',
3852          '|'          => '&#124;',
3853          '&nbsp;'     => '&#160;',
3854          '&iexcl;'    => '&#161;',
3855          '&cent;'     => '&#162;',
3856          '&pound;'    => '&#163;',
3857          '&curren;'   => '&#164;',
3858          '&yen;'      => '&#165;',
3859          '&brvbar;'   => '&#166;',
3860          '&brkbar;'   => '&#166;',
3861          '&sect;'     => '&#167;',
3862          '&uml;'      => '&#168;',
3863          '&die;'      => '&#168;',
3864          '&copy;'     => '&#169;',
3865          '&ordf;'     => '&#170;',
3866          '&laquo;'    => '&#171;',
3867          '&not;'      => '&#172;',
3868          '&shy;'      => '&#173;',
3869          '&reg;'      => '&#174;',
3870          '&macr;'     => '&#175;',
3871          '&hibar;'    => '&#175;',
3872          '&deg;'      => '&#176;',
3873          '&plusmn;'   => '&#177;',
3874          '&sup2;'     => '&#178;',
3875          '&sup3;'     => '&#179;',
3876          '&acute;'    => '&#180;',
3877          '&micro;'    => '&#181;',
3878          '&para;'     => '&#182;',
3879          '&middot;'   => '&#183;',
3880          '&cedil;'    => '&#184;',
3881          '&sup1;'     => '&#185;',
3882          '&ordm;'     => '&#186;',
3883          '&raquo;'    => '&#187;',
3884          '&frac14;'   => '&#188;',
3885          '&frac12;'   => '&#189;',
3886          '&frac34;'   => '&#190;',
3887          '&iquest;'   => '&#191;',
3888          '&Agrave;'   => '&#192;',
3889          '&Aacute;'   => '&#193;',
3890          '&Acirc;'    => '&#194;',
3891          '&Atilde;'   => '&#195;',
3892          '&Auml;'     => '&#196;',
3893          '&Aring;'    => '&#197;',
3894          '&AElig;'    => '&#198;',
3895          '&Ccedil;'   => '&#199;',
3896          '&Egrave;'   => '&#200;',
3897          '&Eacute;'   => '&#201;',
3898          '&Ecirc;'    => '&#202;',
3899          '&Euml;'     => '&#203;',
3900          '&Igrave;'   => '&#204;',
3901          '&Iacute;'   => '&#205;',
3902          '&Icirc;'    => '&#206;',
3903          '&Iuml;'     => '&#207;',
3904          '&ETH;'      => '&#208;',
3905          '&Ntilde;'   => '&#209;',
3906          '&Ograve;'   => '&#210;',
3907          '&Oacute;'   => '&#211;',
3908          '&Ocirc;'    => '&#212;',
3909          '&Otilde;'   => '&#213;',
3910          '&Ouml;'     => '&#214;',
3911          '&times;'    => '&#215;',
3912          '&Oslash;'   => '&#216;',
3913          '&Ugrave;'   => '&#217;',
3914          '&Uacute;'   => '&#218;',
3915          '&Ucirc;'    => '&#219;',
3916          '&Uuml;'     => '&#220;',
3917          '&Yacute;'   => '&#221;',
3918          '&THORN;'    => '&#222;',
3919          '&szlig;'    => '&#223;',
3920          '&agrave;'   => '&#224;',
3921          '&aacute;'   => '&#225;',
3922          '&acirc;'    => '&#226;',
3923          '&atilde;'   => '&#227;',
3924          '&auml;'     => '&#228;',
3925          '&aring;'    => '&#229;',
3926          '&aelig;'    => '&#230;',
3927          '&ccedil;'   => '&#231;',
3928          '&egrave;'   => '&#232;',
3929          '&eacute;'   => '&#233;',
3930          '&ecirc;'    => '&#234;',
3931          '&euml;'     => '&#235;',
3932          '&igrave;'   => '&#236;',
3933          '&iacute;'   => '&#237;',
3934          '&icirc;'    => '&#238;',
3935          '&iuml;'     => '&#239;',
3936          '&eth;'      => '&#240;',
3937          '&ntilde;'   => '&#241;',
3938          '&ograve;'   => '&#242;',
3939          '&oacute;'   => '&#243;',
3940          '&ocirc;'    => '&#244;',
3941          '&otilde;'   => '&#245;',
3942          '&ouml;'     => '&#246;',
3943          '&divide;'   => '&#247;',
3944          '&oslash;'   => '&#248;',
3945          '&ugrave;'   => '&#249;',
3946          '&uacute;'   => '&#250;',
3947          '&ucirc;'    => '&#251;',
3948          '&uuml;'     => '&#252;',
3949          '&yacute;'   => '&#253;',
3950          '&thorn;'    => '&#254;',
3951          '&yuml;'     => '&#255;',
3952          '&OElig;'    => '&#338;',
3953          '&oelig;'    => '&#339;',
3954          '&Scaron;'   => '&#352;',
3955          '&scaron;'   => '&#353;',
3956          '&Yuml;'     => '&#376;',
3957          '&fnof;'     => '&#402;',
3958          '&circ;'     => '&#710;',
3959          '&tilde;'    => '&#732;',
3960          '&Alpha;'    => '&#913;',
3961          '&Beta;'     => '&#914;',
3962          '&Gamma;'    => '&#915;',
3963          '&Delta;'    => '&#916;',
3964          '&Epsilon;'  => '&#917;',
3965          '&Zeta;'     => '&#918;',
3966          '&Eta;'      => '&#919;',
3967          '&Theta;'    => '&#920;',
3968          '&Iota;'     => '&#921;',
3969          '&Kappa;'    => '&#922;',
3970          '&Lambda;'   => '&#923;',
3971          '&Mu;'       => '&#924;',
3972          '&Nu;'       => '&#925;',
3973          '&Xi;'       => '&#926;',
3974          '&Omicron;'  => '&#927;',
3975          '&Pi;'       => '&#928;',
3976          '&Rho;'      => '&#929;',
3977          '&Sigma;'    => '&#931;',
3978          '&Tau;'      => '&#932;',
3979          '&Upsilon;'  => '&#933;',
3980          '&Phi;'      => '&#934;',
3981          '&Chi;'      => '&#935;',
3982          '&Psi;'      => '&#936;',
3983          '&Omega;'    => '&#937;',
3984          '&alpha;'    => '&#945;',
3985          '&beta;'     => '&#946;',
3986          '&gamma;'    => '&#947;',
3987          '&delta;'    => '&#948;',
3988          '&epsilon;'  => '&#949;',
3989          '&zeta;'     => '&#950;',
3990          '&eta;'      => '&#951;',
3991          '&theta;'    => '&#952;',
3992          '&iota;'     => '&#953;',
3993          '&kappa;'    => '&#954;',
3994          '&lambda;'   => '&#955;',
3995          '&mu;'       => '&#956;',
3996          '&nu;'       => '&#957;',
3997          '&xi;'       => '&#958;',
3998          '&omicron;'  => '&#959;',
3999          '&pi;'       => '&#960;',
4000          '&rho;'      => '&#961;',
4001          '&sigmaf;'   => '&#962;',
4002          '&sigma;'    => '&#963;',
4003          '&tau;'      => '&#964;',
4004          '&upsilon;'  => '&#965;',
4005          '&phi;'      => '&#966;',
4006          '&chi;'      => '&#967;',
4007          '&psi;'      => '&#968;',
4008          '&omega;'    => '&#969;',
4009          '&thetasym;' => '&#977;',
4010          '&upsih;'    => '&#978;',
4011          '&piv;'      => '&#982;',
4012          '&ensp;'     => '&#8194;',
4013          '&emsp;'     => '&#8195;',
4014          '&thinsp;'   => '&#8201;',
4015          '&zwnj;'     => '&#8204;',
4016          '&zwj;'      => '&#8205;',
4017          '&lrm;'      => '&#8206;',
4018          '&rlm;'      => '&#8207;',
4019          '&ndash;'    => '&#8211;',
4020          '&mdash;'    => '&#8212;',
4021          '&lsquo;'    => '&#8216;',
4022          '&rsquo;'    => '&#8217;',
4023          '&sbquo;'    => '&#8218;',
4024          '&ldquo;'    => '&#8220;',
4025          '&rdquo;'    => '&#8221;',
4026          '&bdquo;'    => '&#8222;',
4027          '&dagger;'   => '&#8224;',
4028          '&Dagger;'   => '&#8225;',
4029          '&bull;'     => '&#8226;',
4030          '&hellip;'   => '&#8230;',
4031          '&permil;'   => '&#8240;',
4032          '&prime;'    => '&#8242;',
4033          '&Prime;'    => '&#8243;',
4034          '&lsaquo;'   => '&#8249;',
4035          '&rsaquo;'   => '&#8250;',
4036          '&oline;'    => '&#8254;',
4037          '&frasl;'    => '&#8260;',
4038          '&euro;'     => '&#8364;',
4039          '&image;'    => '&#8465;',
4040          '&weierp;'   => '&#8472;',
4041          '&real;'     => '&#8476;',
4042          '&trade;'    => '&#8482;',
4043          '&alefsym;'  => '&#8501;',
4044          '&crarr;'    => '&#8629;',
4045          '&lArr;'     => '&#8656;',
4046          '&uArr;'     => '&#8657;',
4047          '&rArr;'     => '&#8658;',
4048          '&dArr;'     => '&#8659;',
4049          '&hArr;'     => '&#8660;',
4050          '&forall;'   => '&#8704;',
4051          '&part;'     => '&#8706;',
4052          '&exist;'    => '&#8707;',
4053          '&empty;'    => '&#8709;',
4054          '&nabla;'    => '&#8711;',
4055          '&isin;'     => '&#8712;',
4056          '&notin;'    => '&#8713;',
4057          '&ni;'       => '&#8715;',
4058          '&prod;'     => '&#8719;',
4059          '&sum;'      => '&#8721;',
4060          '&minus;'    => '&#8722;',
4061          '&lowast;'   => '&#8727;',
4062          '&radic;'    => '&#8730;',
4063          '&prop;'     => '&#8733;',
4064          '&infin;'    => '&#8734;',
4065          '&ang;'      => '&#8736;',
4066          '&and;'      => '&#8743;',
4067          '&or;'       => '&#8744;',
4068          '&cap;'      => '&#8745;',
4069          '&cup;'      => '&#8746;',
4070          '&int;'      => '&#8747;',
4071          '&there4;'   => '&#8756;',
4072          '&sim;'      => '&#8764;',
4073          '&cong;'     => '&#8773;',
4074          '&asymp;'    => '&#8776;',
4075          '&ne;'       => '&#8800;',
4076          '&equiv;'    => '&#8801;',
4077          '&le;'       => '&#8804;',
4078          '&ge;'       => '&#8805;',
4079          '&sub;'      => '&#8834;',
4080          '&sup;'      => '&#8835;',
4081          '&nsub;'     => '&#8836;',
4082          '&sube;'     => '&#8838;',
4083          '&supe;'     => '&#8839;',
4084          '&oplus;'    => '&#8853;',
4085          '&otimes;'   => '&#8855;',
4086          '&perp;'     => '&#8869;',
4087          '&sdot;'     => '&#8901;',
4088          '&lceil;'    => '&#8968;',
4089          '&rceil;'    => '&#8969;',
4090          '&lfloor;'   => '&#8970;',
4091          '&rfloor;'   => '&#8971;',
4092          '&lang;'     => '&#9001;',
4093          '&rang;'     => '&#9002;',
4094          '&larr;'     => '&#8592;',
4095          '&uarr;'     => '&#8593;',
4096          '&rarr;'     => '&#8594;',
4097          '&darr;'     => '&#8595;',
4098          '&harr;'     => '&#8596;',
4099          '&loz;'      => '&#9674;',
4100          '&spades;'   => '&#9824;',
4101          '&clubs;'    => '&#9827;',
4102          '&hearts;'   => '&#9829;',
4103          '&diams;'    => '&#9830;',
4104      );
4105  
4106      return str_replace( array_keys( $to_ncr ), array_values( $to_ncr ), $text );
4107  }
4108  
4109  /**
4110   * Formats text for the editor.
4111   *
4112   * Generally the browsers treat everything inside a textarea as text, but
4113   * it is still a good idea to HTML entity encode `<`, `>` and `&` in the content.
4114   *
4115   * The filter {@see 'format_for_editor'} is applied here. If `$text` is empty the
4116   * filter will be applied to an empty string.
4117   *
4118   * @since 4.3.0
4119   *
4120   * @see _WP_Editors::editor()
4121   *
4122   * @param string $text           The text to be formatted.
4123   * @param string $default_editor The default editor for the current user.
4124   *                               It is usually either 'html' or 'tinymce'.
4125   * @return string The formatted text after filter is applied.
4126   */
4127  function format_for_editor( $text, $default_editor = null ) {
4128      if ( $text ) {
4129          $text = htmlspecialchars( $text, ENT_NOQUOTES, get_option( 'blog_charset' ) );
4130      }
4131  
4132      /**
4133       * Filters the text after it is formatted for the editor.
4134       *
4135       * @since 4.3.0
4136       *
4137       * @param string $text           The formatted text.
4138       * @param string $default_editor The default editor for the current user.
4139       *                               It is usually either 'html' or 'tinymce'.
4140       */
4141      return apply_filters( 'format_for_editor', $text, $default_editor );
4142  }
4143  
4144  /**
4145   * Perform a deep string replace operation to ensure the values in $search are no longer present
4146   *
4147   * Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values
4148   * e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that
4149   * str_replace would return
4150   *
4151   * @since 2.8.1
4152   * @access private
4153   *
4154   * @param string|array $search  The value being searched for, otherwise known as the needle.
4155   *                              An array may be used to designate multiple needles.
4156   * @param string       $subject The string being searched and replaced on, otherwise known as the haystack.
4157   * @return string The string with the replaced values.
4158   */
4159  function _deep_replace( $search, $subject ) {
4160      $subject = (string) $subject;
4161  
4162      $count = 1;
4163      while ( $count ) {
4164          $subject = str_replace( $search, '', $subject, $count );
4165      }
4166  
4167      return $subject;
4168  }
4169  
4170  /**
4171   * Escapes data for use in a MySQL query.
4172   *
4173   * Usually you should prepare queries using wpdb::prepare().
4174   * Sometimes, spot-escaping is required or useful. One example
4175   * is preparing an array for use in an IN clause.
4176   *
4177   * NOTE: Since 4.8.3, '%' characters will be replaced with a placeholder string,
4178   * this prevents certain SQLi attacks from taking place. This change in behaviour
4179   * may cause issues for code that expects the return value of esc_sql() to be useable
4180   * for other purposes.
4181   *
4182   * @since 2.8.0
4183   *
4184   * @global wpdb $wpdb WordPress database abstraction object.
4185   *
4186   * @param string|array $data Unescaped data
4187   * @return string|array Escaped data
4188   */
4189  function esc_sql( $data ) {
4190      global $wpdb;
4191      return $wpdb->_escape( $data );
4192  }
4193  
4194  /**
4195   * Checks and cleans a URL.
4196   *
4197   * A number of characters are removed from the URL. If the URL is for displaying
4198   * (the default behaviour) ampersands are also replaced. The {@see 'clean_url'} filter
4199   * is applied to the returned cleaned URL.
4200   *
4201   * @since 2.8.0
4202   *
4203   * @param string $url       The URL to be cleaned.
4204   * @param array  $protocols Optional. An array of acceptable protocols.
4205   *                          Defaults to return value of wp_allowed_protocols()
4206   * @param string $_context  Private. Use esc_url_raw() for database usage.
4207   * @return string The cleaned $url after the {@see 'clean_url'} filter is applied.
4208   */
4209  function esc_url( $url, $protocols = null, $_context = 'display' ) {
4210      $original_url = $url;
4211  
4212      if ( '' == $url ) {
4213          return $url;
4214      }
4215  
4216      $url = str_replace( ' ', '%20', ltrim( $url ) );
4217      $url = preg_replace( '|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\[\]\\x80-\\xff]|i', '', $url );
4218  
4219      if ( '' === $url ) {
4220          return $url;
4221      }
4222  
4223      if ( 0 !== stripos( $url, 'mailto:' ) ) {
4224          $strip = array( '%0d', '%0a', '%0D', '%0A' );
4225          $url   = _deep_replace( $strip, $url );
4226      }
4227  
4228      $url = str_replace( ';//', '://', $url );
4229      /* If the URL doesn't appear to contain a scheme, we
4230       * presume it needs http:// prepended (unless a relative
4231       * link starting with /, # or ? or a php file).
4232       */
4233      if ( strpos( $url, ':' ) === false && ! in_array( $url[0], array( '/', '#', '?' ) ) &&
4234          ! preg_match( '/^[a-z0-9-]+?\.php/i', $url ) ) {
4235          $url = 'http://' . $url;
4236      }
4237  
4238      // Replace ampersands and single quotes only when displaying.
4239      if ( 'display' == $_context ) {
4240          $url = wp_kses_normalize_entities( $url );
4241          $url = str_replace( '&amp;', '&#038;', $url );
4242          $url = str_replace( "'", '&#039;', $url );
4243      }
4244  
4245      if ( ( false !== strpos( $url, '[' ) ) || ( false !== strpos( $url, ']' ) ) ) {
4246  
4247          $parsed = wp_parse_url( $url );
4248          $front  = '';
4249  
4250          if ( isset( $parsed['scheme'] ) ) {
4251              $front .= $parsed['scheme'] . '://';
4252          } elseif ( '/' === $url[0] ) {
4253              $front .= '//';
4254          }
4255  
4256          if ( isset( $parsed['user'] ) ) {
4257              $front .= $parsed['user'];
4258          }
4259  
4260          if ( isset( $parsed['pass'] ) ) {
4261              $front .= ':' . $parsed['pass'];
4262          }
4263  
4264          if ( isset( $parsed['user'] ) || isset( $parsed['pass'] ) ) {
4265              $front .= '@';
4266          }
4267  
4268          if ( isset( $parsed['host'] ) ) {
4269              $front .= $parsed['host'];
4270          }
4271  
4272          if ( isset( $parsed['port'] ) ) {
4273              $front .= ':' . $parsed['port'];
4274          }
4275  
4276          $end_dirty = str_replace( $front, '', $url );
4277          $end_clean = str_replace( array( '[', ']' ), array( '%5B', '%5D' ), $end_dirty );
4278          $url       = str_replace( $end_dirty, $end_clean, $url );
4279  
4280      }
4281  
4282      if ( '/' === $url[0] ) {
4283          $good_protocol_url = $url;
4284      } else {
4285          if ( ! is_array( $protocols ) ) {
4286              $protocols = wp_allowed_protocols();
4287          }
4288          $good_protocol_url = wp_kses_bad_protocol( $url, $protocols );
4289          if ( strtolower( $good_protocol_url ) != strtolower( $url ) ) {
4290              return '';
4291          }
4292      }
4293  
4294      /**
4295       * Filters a string cleaned and escaped for output as a URL.
4296       *
4297       * @since 2.3.0
4298       *
4299       * @param string $good_protocol_url The cleaned URL to be returned.
4300       * @param string $original_url      The URL prior to cleaning.
4301       * @param string $_context          If 'display', replace ampersands and single quotes only.
4302       */
4303      return apply_filters( 'clean_url', $good_protocol_url, $original_url, $_context );
4304  }
4305  
4306  /**
4307   * Performs esc_url() for database usage.
4308   *
4309   * @since 2.8.0
4310   *
4311   * @param string $url       The URL to be cleaned.
4312   * @param array  $protocols An array of acceptable protocols.
4313   * @return string The cleaned URL.
4314   */
4315  function esc_url_raw( $url, $protocols = null ) {
4316      return esc_url( $url, $protocols, 'db' );
4317  }
4318  
4319  /**
4320   * Convert entities, while preserving already-encoded entities.
4321   *
4322   * @link https://secure.php.net/htmlentities Borrowed from the PHP Manual user notes.
4323   *
4324   * @since 1.2.2
4325   *
4326   * @param string $myHTML The text to be converted.
4327   * @return string Converted text.
4328   */
4329  function htmlentities2( $myHTML ) {
4330      $translation_table              = get_html_translation_table( HTML_ENTITIES, ENT_QUOTES );
4331      $translation_table[ chr( 38 ) ] = '&';
4332      return preg_replace( '/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/', '&amp;', strtr( $myHTML, $translation_table ) );
4333  }
4334  
4335  /**
4336   * Escape single quotes, htmlspecialchar " < > &, and fix line endings.
4337   *
4338   * Escapes text strings for echoing in JS. It is intended to be used for inline JS
4339   * (in a tag attribute, for example onclick="..."). Note that the strings have to
4340   * be in single quotes. The {@see 'js_escape'} filter is also applied here.
4341   *
4342   * @since 2.8.0
4343   *
4344   * @param string $text The text to be escaped.
4345   * @return string Escaped text.
4346   */
4347  function esc_js( $text ) {
4348      $safe_text = wp_check_invalid_utf8( $text );
4349      $safe_text = _wp_specialchars( $safe_text, ENT_COMPAT );
4350      $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) );
4351      $safe_text = str_replace( "\r", '', $safe_text );
4352      $safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) );
4353      /**
4354       * Filters a string cleaned and escaped for output in JavaScript.
4355       *
4356       * Text passed to esc_js() is stripped of invalid or special characters,
4357       * and properly slashed for output.
4358       *
4359       * @since 2.0.6
4360       *
4361       * @param string $safe_text The text after it has been escaped.
4362       * @param string $text      The text prior to being escaped.
4363       */
4364      return apply_filters( 'js_escape', $safe_text, $text );
4365  }
4366  
4367  /**
4368   * Escaping for HTML blocks.
4369   *
4370   * @since 2.8.0
4371   *
4372   * @param string $text
4373   * @return string
4374   */
4375  function esc_html( $text ) {
4376      $safe_text = wp_check_invalid_utf8( $text );
4377      $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
4378      /**
4379       * Filters a string cleaned and escaped for output in HTML.
4380       *
4381       * Text passed to esc_html() is stripped of invalid or special characters
4382       * before output.
4383       *
4384       * @since 2.8.0
4385       *
4386       * @param string $safe_text The text after it has been escaped.
4387       * @param string $text      The text prior to being escaped.
4388       */
4389      return apply_filters( 'esc_html', $safe_text, $text );
4390  }
4391  
4392  /**
4393   * Escaping for HTML attributes.
4394   *
4395   * @since 2.8.0
4396   *
4397   * @param string $text
4398   * @return string
4399   */
4400  function esc_attr( $text ) {
4401      $safe_text = wp_check_invalid_utf8( $text );
4402      $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
4403      /**
4404       * Filters a string cleaned and escaped for output in an HTML attribute.
4405       *
4406       * Text passed to esc_attr() is stripped of invalid or special characters
4407       * before output.
4408       *
4409       * @since 2.0.6
4410       *
4411       * @param string $safe_text The text after it has been escaped.
4412       * @param string $text      The text prior to being escaped.
4413       */
4414      return apply_filters( 'attribute_escape', $safe_text, $text );
4415  }
4416  
4417  /**
4418   * Escaping for textarea values.
4419   *
4420   * @since 3.1.0
4421   *
4422   * @param string $text
4423   * @return string
4424   */
4425  function esc_textarea( $text ) {
4426      $safe_text = htmlspecialchars( $text, ENT_QUOTES, get_option( 'blog_charset' ) );
4427      /**
4428       * Filters a string cleaned and escaped for output in a textarea element.
4429       *
4430       * @since 3.1.0
4431       *
4432       * @param string $safe_text The text after it has been escaped.
4433       * @param string $text      The text prior to being escaped.
4434       */
4435      return apply_filters( 'esc_textarea', $safe_text, $text );
4436  }
4437  
4438  /**
4439   * Escape an HTML tag name.
4440   *
4441   * @since 2.5.0
4442   *
4443   * @param string $tag_name
4444   * @return string
4445   */
4446  function tag_escape( $tag_name ) {
4447      $safe_tag = strtolower( preg_replace( '/[^a-zA-Z0-9_:]/', '', $tag_name ) );
4448      /**
4449       * Filters a string cleaned and escaped for output as an HTML tag.
4450       *
4451       * @since 2.8.0
4452       *
4453       * @param string $safe_tag The tag name after it has been escaped.
4454       * @param string $tag_name The text before it was escaped.
4455       */
4456      return apply_filters( 'tag_escape', $safe_tag, $tag_name );
4457  }
4458  
4459  /**
4460   * Convert full URL paths to absolute paths.
4461   *
4462   * Removes the http or https protocols and the domain. Keeps the path '/' at the
4463   * beginning, so it isn't a true relative link, but from the web root base.
4464   *
4465   * @since 2.1.0
4466   * @since 4.1.0 Support was added for relative URLs.
4467   *
4468   * @param string $link Full URL path.
4469   * @return string Absolute path.
4470   */
4471  function wp_make_link_relative( $link ) {
4472      return preg_replace( '|^(https?:)?//[^/]+(/?.*)|i', '$2', $link );
4473  }
4474  
4475  /**
4476   * Sanitises various option values based on the nature of the option.
4477   *
4478   * This is basically a switch statement which will pass $value through a number
4479   * of functions depending on the $option.
4480   *
4481   * @since 2.0.5
4482   *
4483   * @global wpdb $wpdb WordPress database abstraction object.
4484   *
4485   * @param string $option The name of the option.
4486   * @param string $value  The unsanitised value.
4487   * @return string Sanitized value.
4488   */
4489  function sanitize_option( $option, $value ) {
4490      global $wpdb;
4491  
4492      $original_value = $value;
4493      $error          = '';
4494  
4495      switch ( $option ) {
4496          case 'admin_email':
4497          case 'new_admin_email':
4498              $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
4499              if ( is_wp_error( $value ) ) {
4500                  $error = $value->get_error_message();
4501              } else {
4502                  $value = sanitize_email( $value );
4503                  if ( ! is_email( $value ) ) {
4504                      $error = __( 'The email address entered did not appear to be a valid email address. Please enter a valid email address.' );
4505                  }
4506              }
4507              break;
4508  
4509          case 'thumbnail_size_w':
4510          case 'thumbnail_size_h':
4511          case 'medium_size_w':
4512          case 'medium_size_h':
4513          case 'medium_large_size_w':
4514          case 'medium_large_size_h':
4515          case 'large_size_w':
4516          case 'large_size_h':
4517          case 'mailserver_port':
4518          case 'comment_max_links':
4519          case 'page_on_front':
4520          case 'page_for_posts':
4521          case 'rss_excerpt_length':
4522          case 'default_category':
4523          case 'default_email_category':
4524          case 'default_link_category':
4525          case 'close_comments_days_old':
4526          case 'comments_per_page':
4527          case 'thread_comments_depth':
4528          case 'users_can_register':
4529          case 'start_of_week':
4530          case 'site_icon':
4531              $value = absint( $value );
4532              break;
4533  
4534          case 'posts_per_page':
4535          case 'posts_per_rss':
4536              $value = (int) $value;
4537              if ( empty( $value ) ) {
4538                  $value = 1;
4539              }
4540              if ( $value < -1 ) {
4541                  $value = abs( $value );
4542              }
4543              break;
4544  
4545          case 'default_ping_status':
4546          case 'default_comment_status':
4547              // Options that if not there have 0 value but need to be something like "closed"
4548              if ( $value == '0' || $value == '' ) {
4549                  $value = 'closed';
4550              }
4551              break;
4552  
4553          case 'blogdescription':
4554          case 'blogname':
4555              $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
4556              if ( $value !== $original_value ) {
4557                  $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', wp_encode_emoji( $original_value ) );
4558              }
4559  
4560              if ( is_wp_error( $value ) ) {
4561                  $error = $value->get_error_message();
4562              } else {
4563                  $value = esc_html( $value );
4564              }
4565              break;
4566  
4567          case 'blog_charset':
4568              $value = preg_replace( '/[^a-zA-Z0-9_-]/', '', $value ); // strips slashes
4569              break;
4570  
4571          case 'blog_public':
4572              // This is the value if the settings checkbox is not checked on POST. Don't rely on this.
4573              if ( null === $value ) {
4574                  $value = 1;
4575              } else {
4576                  $value = intval( $value );
4577              }
4578              break;
4579  
4580          case 'date_format':
4581          case 'time_format':
4582          case 'mailserver_url':
4583          case 'mailserver_login':
4584          case 'mailserver_pass':
4585          case 'upload_path':
4586              $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
4587              if ( is_wp_error( $value ) ) {
4588                  $error = $value->get_error_message();
4589              } else {
4590                  $value = strip_tags( $value );
4591                  $value = wp_kses_data( $value );
4592              }
4593              break;
4594  
4595          case 'ping_sites':
4596              $value = explode( "\n", $value );
4597              $value = array_filter( array_map( 'trim', $value ) );
4598              $value = array_filter( array_map( 'esc_url_raw', $value ) );
4599              $value = implode( "\n", $value );
4600              break;
4601  
4602          case 'gmt_offset':
4603              $value = preg_replace( '/[^0-9:.-]/', '', $value ); // strips slashes
4604              break;
4605  
4606          case 'siteurl':
4607              $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
4608              if ( is_wp_error( $value ) ) {
4609                  $error = $value->get_error_message();
4610              } else {
4611                  if ( preg_match( '#http(s?)://(.+)#i', $value ) ) {
4612                      $value = esc_url_raw( $value );
4613                  } else {
4614                      $error = __( 'The WordPress address you entered did not appear to be a valid URL. Please enter a valid URL.' );
4615                  }
4616              }
4617              break;
4618  
4619          case 'home':
4620              $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
4621              if ( is_wp_error( $value ) ) {
4622                  $error = $value->get_error_message();
4623              } else {
4624                  if ( preg_match( '#http(s?)://(.+)#i', $value ) ) {
4625                      $value = esc_url_raw( $value );
4626                  } else {
4627                      $error = __( 'The Site address you entered did not appear to be a valid URL. Please enter a valid URL.' );
4628                  }
4629              }
4630              break;
4631  
4632          case 'WPLANG':
4633              $allowed = get_available_languages();
4634              if ( ! is_multisite() && defined( 'WPLANG' ) && '' !== WPLANG && 'en_US' !== WPLANG ) {
4635                  $allowed[] = WPLANG;
4636              }
4637              if ( ! in_array( $value, $allowed ) && ! empty( $value ) ) {
4638                  $value = get_option( $option );
4639              }
4640              break;
4641  
4642          case 'illegal_names':
4643              $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
4644              if ( is_wp_error( $value ) ) {
4645                  $error = $value->get_error_message();
4646              } else {
4647                  if ( ! is_array( $value ) ) {
4648                      $value = explode( ' ', $value );
4649                  }
4650  
4651                  $value = array_values( array_filter( array_map( 'trim', $value ) ) );
4652  
4653                  if ( ! $value ) {
4654                      $value = '';
4655                  }
4656              }
4657              break;
4658  
4659          case 'limited_email_domains':
4660          case 'banned_email_domains':
4661              $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
4662              if ( is_wp_error( $value ) ) {
4663                  $error = $value->get_error_message();
4664              } else {
4665                  if ( ! is_array( $value ) ) {
4666                      $value = explode( "\n", $value );
4667                  }
4668  
4669                  $domains = array_values( array_filter( array_map( 'trim', $value ) ) );
4670                  $value   = array();
4671  
4672                  foreach ( $domains as $domain ) {
4673                      if ( ! preg_match( '/(--|\.\.)/', $domain ) && preg_match( '|^([a-zA-Z0-9-\.])+$|', $domain ) ) {
4674                          $value[] = $domain;
4675                      }
4676                  }
4677                  if ( ! $value ) {
4678                      $value = '';
4679                  }
4680              }
4681              break;
4682  
4683          case 'timezone_string':
4684              $allowed_zones = timezone_identifiers_list();
4685              if ( ! in_array( $value, $allowed_zones ) && ! empty( $value ) ) {
4686                  $error = __( 'The timezone you have entered is not valid. Please select a valid timezone.' );
4687              }
4688              break;
4689  
4690          case 'permalink_structure':
4691          case 'category_base':
4692          case 'tag_base':
4693              $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
4694              if ( is_wp_error( $value ) ) {
4695                  $error = $value->get_error_message();
4696              } else {
4697                  $value = esc_url_raw( $value );
4698                  $value = str_replace( 'http://', '', $value );
4699              }
4700  
4701              if ( 'permalink_structure' === $option && '' !== $value && ! preg_match( '/%[^\/%]+%/', $value ) ) {
4702                  $error = sprintf(
4703                      /* translators: %s: Documentation URL. */
4704                      __( 'A structure tag is required when using custom permalinks. <a href="%s">Learn more</a>' ),
4705                      __( 'https://wordpress.org/support/article/using-permalinks/#choosing-your-permalink-structure' )
4706                  );
4707              }
4708              break;
4709  
4710          case 'default_role':
4711              if ( ! get_role( $value ) && get_role( 'subscriber' ) ) {
4712                  $value = 'subscriber';
4713              }
4714              break;
4715  
4716          case 'moderation_keys':
4717          case 'blacklist_keys':
4718              $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
4719              if ( is_wp_error( $value ) ) {
4720                  $error = $value->get_error_message();
4721              } else {
4722                  $value = explode( "\n", $value );
4723                  $value = array_filter( array_map( 'trim', $value ) );
4724                  $value = array_unique( $value );
4725                  $value = implode( "\n", $value );
4726              }
4727              break;
4728      }
4729  
4730      if ( ! empty( $error ) ) {
4731          $value = get_option( $option );
4732          if ( function_exists( 'add_settings_error' ) ) {
4733              add_settings_error( $option, "invalid_{$option}", $error );
4734          }
4735      }
4736  
4737      /**
4738       * Filters an option value following sanitization.
4739       *
4740       * @since 2.3.0
4741       * @since 4.3.0 Added the `$original_value` parameter.
4742       *
4743       * @param string $value          The sanitized option value.
4744       * @param string $option         The option name.
4745       * @param string $original_value The original value passed to the function.
4746       */
4747      return apply_filters( "sanitize_option_{$option}", $value, $option, $original_value );
4748  }
4749  
4750  /**
4751   * Maps a function to all non-iterable elements of an array or an object.
4752   *
4753   * This is similar to `array_walk_recursive()` but acts upon objects too.
4754   *
4755   * @since 4.4.0
4756   *
4757   * @param mixed    $value    The array, object, or scalar.
4758   * @param callable $callback The function to map onto $value.
4759   * @return mixed The value with the callback applied to all non-arrays and non-objects inside it.
4760   */
4761  function map_deep( $value, $callback ) {
4762      if ( is_array( $value ) ) {
4763          foreach ( $value as $index => $item ) {
4764              $value[ $index ] = map_deep( $item, $callback );
4765          }
4766      } elseif ( is_object( $value ) ) {
4767          $object_vars = get_object_vars( $value );
4768          foreach ( $object_vars as $property_name => $property_value ) {
4769              $value->$property_name = map_deep( $property_value, $callback );
4770          }
4771      } else {
4772          $value = call_user_func( $callback, $value );
4773      }
4774  
4775      return $value;
4776  }
4777  
4778  /**
4779   * Parses a string into variables to be stored in an array.
4780   *
4781   *
4782   * @since 2.2.1
4783   *
4784   * @param string $string The string to be parsed.
4785   * @param array  $array  Variables will be stored in this array.
4786   */
4787  function wp_parse_str( $string, &$array ) {
4788      parse_str( $string, $array );
4789  
4790      /**
4791       * Filters the array of variables derived from a parsed string.
4792       *
4793       * @since 2.3.0
4794       *
4795       * @param array $array The array populated with variables.
4796       */
4797      $array = apply_filters( 'wp_parse_str', $array );
4798  }
4799  
4800  /**
4801   * Convert lone less than signs.
4802   *
4803   * KSES already converts lone greater than signs.
4804   *
4805   * @since 2.3.0
4806   *
4807   * @param string $text Text to be converted.
4808   * @return string Converted text.
4809   */
4810  function wp_pre_kses_less_than( $text ) {
4811      return preg_replace_callback( '%<[^>]*?((?=<)|>|$)%', 'wp_pre_kses_less_than_callback', $text );
4812  }
4813  
4814  /**
4815   * Callback function used by preg_replace.
4816   *
4817   * @since 2.3.0
4818   *
4819   * @param array $matches Populated by matches to preg_replace.
4820   * @return string The text returned after esc_html if needed.
4821   */
4822  function wp_pre_kses_less_than_callback( $matches ) {
4823      if ( false === strpos( $matches[0], '>' ) ) {
4824          return esc_html( $matches[0] );
4825      }
4826      return $matches[0];
4827  }
4828  
4829  /**
4830   * WordPress implementation of PHP sprintf() with filters.
4831   *
4832   * @since 2.5.0
4833   * @link https://secure.php.net/sprintf
4834   *
4835   * @param string $pattern The string which formatted args are inserted.
4836   * @param mixed  ...$args Arguments to be formatted into the $pattern string.
4837   * @return string The formatted string.
4838   */
4839  function wp_sprintf( $pattern, ...$args ) {
4840      $len       = strlen( $pattern );
4841      $start     = 0;
4842      $result    = '';
4843      $arg_index = 0;
4844      while ( $len > $start ) {
4845          // Last character: append and break
4846          if ( strlen( $pattern ) - 1 == $start ) {
4847              $result .= substr( $pattern, -1 );
4848              break;
4849          }
4850  
4851          // Literal %: append and continue
4852          if ( substr( $pattern, $start, 2 ) == '%%' ) {
4853              $start  += 2;
4854              $result .= '%';
4855              continue;
4856          }
4857  
4858          // Get fragment before next %
4859          $end = strpos( $pattern, '%', $start + 1 );
4860          if ( false === $end ) {
4861              $end = $len;
4862          }
4863          $fragment = substr( $pattern, $start, $end - $start );
4864  
4865          // Fragment has a specifier
4866          if ( $pattern[ $start ] == '%' ) {
4867              // Find numbered arguments or take the next one in order
4868              if ( preg_match( '/^%(\d+)\$/', $fragment, $matches ) ) {
4869                  $index    = $matches[1] - 1; // 0-based array vs 1-based sprintf arguments.
4870                  $arg      = isset( $args[ $index ] ) ? $args[ $index ] : '';
4871                  $fragment = str_replace( "%{$matches[1]}$", '%', $fragment );
4872              } else {
4873                  $arg = isset( $args[ $arg_index ] ) ? $args[ $arg_index ] : '';
4874                  ++$arg_index;
4875              }
4876  
4877              /**
4878               * Filters a fragment from the pattern passed to wp_sprintf().
4879               *
4880               * If the fragment is unchanged, then sprintf() will be run on the fragment.
4881               *
4882               * @since 2.5.0
4883               *
4884               * @param string $fragment A fragment from the pattern.
4885               * @param string $arg      The argument.
4886               */
4887              $_fragment = apply_filters( 'wp_sprintf', $fragment, $arg );
4888              if ( $_fragment != $fragment ) {
4889                  $fragment = $_fragment;
4890              } else {
4891                  $fragment = sprintf( $fragment, strval( $arg ) );
4892              }
4893          }
4894  
4895          // Append to result and move to next fragment
4896          $result .= $fragment;
4897          $start   = $end;
4898      }
4899      return $result;
4900  }
4901  
4902  /**
4903   * Localize list items before the rest of the content.
4904   *
4905   * The '%l' must be at the first characters can then contain the rest of the
4906   * content. The list items will have ', ', ', and', and ' and ' added depending
4907   * on the amount of list items in the $args parameter.
4908   *
4909   * @since 2.5.0
4910   *
4911   * @param string $pattern Content containing '%l' at the beginning.
4912   * @param array  $args    List items to prepend to the content and replace '%l'.
4913   * @return string Localized list items and rest of the content.
4914   */
4915  function wp_sprintf_l( $pattern, $args ) {
4916      // Not a match
4917      if ( substr( $pattern, 0, 2 ) != '%l' ) {
4918          return $pattern;
4919      }
4920  
4921      // Nothing to work with
4922      if ( empty( $args ) ) {
4923          return '';
4924      }
4925  
4926      /**
4927       * Filters the translated delimiters used by wp_sprintf_l().
4928       * Placeholders (%s) are included to assist translators and then
4929       * removed before the array of strings reaches the filter.
4930       *
4931       * Please note: Ampersands and entities should be avoided here.
4932       *
4933       * @since 2.5.0
4934       *
4935       * @param array $delimiters An array of translated delimiters.
4936       */
4937      $l = apply_filters(
4938          'wp_sprintf_l',
4939          array(
4940              /* translators: Used to join items in a list with more than 2 items. */
4941              'between'          => sprintf( __( '%1$s, %2$s' ), '', '' ),
4942              /* translators: Used to join last two items in a list with more than 2 times. */
4943              'between_last_two' => sprintf( __( '%1$s, and %2$s' ), '', '' ),
4944              /* translators: Used to join items in a list with only 2 items. */
4945              'between_only_two' => sprintf( __( '%1$s and %2$s' ), '', '' ),
4946          )
4947      );
4948  
4949      $args   = (array) $args;
4950      $result = array_shift( $args );
4951      if ( count( $args ) == 1 ) {
4952          $result .= $l['between_only_two'] . array_shift( $args );
4953      }
4954      // Loop when more than two args
4955      $i = count( $args );
4956      while ( $i ) {
4957          $arg = array_shift( $args );
4958          $i--;
4959          if ( 0 == $i ) {
4960              $result .= $l['between_last_two'] . $arg;
4961          } else {
4962              $result .= $l['between'] . $arg;
4963          }
4964      }
4965      return $result . substr( $pattern, 2 );
4966  }
4967  
4968  /**
4969   * Safely extracts not more than the first $count characters from html string.
4970   *
4971   * UTF-8, tags and entities safe prefix extraction. Entities inside will *NOT*
4972   * be counted as one character. For example &amp; will be counted as 4, &lt; as
4973   * 3, etc.
4974   *
4975   * @since 2.5.0
4976   *
4977   * @param string $str   String to get the excerpt from.
4978   * @param int    $count Maximum number of characters to take.
4979   * @param string $more  Optional. What to append if $str needs to be trimmed. Defaults to empty string.
4980   * @return string The excerpt.
4981   */
4982  function wp_html_excerpt( $str, $count, $more = null ) {
4983      if ( null === $more ) {
4984          $more = '';
4985      }
4986      $str     = wp_strip_all_tags( $str, true );
4987      $excerpt = mb_substr( $str, 0, $count );
4988      // remove part of an entity at the end
4989      $excerpt = preg_replace( '/&[^;\s]{0,6}$/', '', $excerpt );
4990      if ( $str != $excerpt ) {
4991          $excerpt = trim( $excerpt ) . $more;
4992      }
4993      return $excerpt;
4994  }
4995  
4996  /**
4997   * Add a Base url to relative links in passed content.
4998   *
4999   * By default it supports the 'src' and 'href' attributes. However this can be
5000   * changed via the 3rd param.
5001   *
5002   * @since 2.7.0
5003   *
5004   * @global string $_links_add_base
5005   *
5006   * @param string $content String to search for links in.
5007   * @param string $base    The base URL to prefix to links.
5008   * @param array  $attrs   The attributes which should be processed.
5009   * @return string The processed content.
5010   */
5011  function links_add_base_url( $content, $base, $attrs = array( 'src', 'href' ) ) {
5012      global $_links_add_base;
5013      $_links_add_base = $base;
5014      $attrs           = implode( '|', (array) $attrs );
5015      return preg_replace_callback( "!($attrs)=(['\"])(.+?)\\2!i", '_links_add_base', $content );
5016  }
5017  
5018  /**
5019   * Callback to add a base url to relative links in passed content.
5020   *
5021   * @since 2.7.0
5022   * @access private
5023   *
5024   * @global string $_links_add_base
5025   *
5026   * @param string $m The matched link.
5027   * @return string The processed link.
5028   */
5029  function _links_add_base( $m ) {
5030      global $_links_add_base;
5031      //1 = attribute name  2 = quotation mark  3 = URL
5032      return $m[1] . '=' . $m[2] .
5033          ( preg_match( '#^(\w{1,20}):#', $m[3], $protocol ) && in_array( $protocol[1], wp_allowed_protocols() ) ?
5034              $m[3] :
5035              WP_Http::make_absolute_url( $m[3], $_links_add_base )
5036          )
5037          . $m[2];
5038  }
5039  
5040  /**
5041   * Adds a Target attribute to all links in passed content.
5042   *
5043   * This function by default only applies to `<a>` tags, however this can be
5044   * modified by the 3rd param.
5045   *
5046   * *NOTE:* Any current target attributed will be stripped and replaced.
5047   *
5048   * @since 2.7.0
5049   *
5050   * @global string $_links_add_target
5051   *
5052   * @param string $content String to search for links in.
5053   * @param string $target  The Target to add to the links.
5054   * @param array  $tags    An array of tags to apply to.
5055   * @return string The processed content.
5056   */
5057  function links_add_target( $content, $target = '_blank', $tags = array( 'a' ) ) {
5058      global $_links_add_target;
5059      $_links_add_target = $target;
5060      $tags              = implode( '|', (array) $tags );
5061      return preg_replace_callback( "!<($tags)([^>]*)>!i", '_links_add_target', $content );
5062  }
5063  
5064  /**
5065   * Callback to add a target attribute to all links in passed content.
5066   *
5067   * @since 2.7.0
5068   * @access private
5069   *
5070   * @global string $_links_add_target
5071   *
5072   * @param string $m The matched link.
5073   * @return string The processed link.
5074   */
5075  function _links_add_target( $m ) {
5076      global $_links_add_target;
5077      $tag  = $m[1];
5078      $link = preg_replace( '|( target=([\'"])(.*?)\2)|i', '', $m[2] );
5079      return '<' . $tag . $link . ' target="' . esc_attr( $_links_add_target ) . '">';
5080  }
5081  
5082  /**
5083   * Normalize EOL characters and strip duplicate whitespace.
5084   *
5085   * @since 2.7.0
5086   *
5087   * @param string $str The string to normalize.
5088   * @return string The normalized string.
5089   */
5090  function normalize_whitespace( $str ) {
5091      $str = trim( $str );
5092      $str = str_replace( "\r", "\n", $str );
5093      $str = preg_replace( array( '/\n+/', '/[ \t]+/' ), array( "\n", ' ' ), $str );
5094      return $str;
5095  }
5096  
5097  /**
5098   * Properly strip all HTML tags including script and style
5099   *
5100   * This differs from strip_tags() because it removes the contents of
5101   * the `<script>` and `<style>` tags. E.g. `strip_tags( '<script>something</script>' )`
5102   * will return 'something'. wp_strip_all_tags will return ''
5103   *
5104   * @since 2.9.0
5105   *
5106   * @param string $string        String containing HTML tags
5107   * @param bool   $remove_breaks Optional. Whether to remove left over line breaks and white space chars
5108   * @return string The processed string.
5109   */
5110  function wp_strip_all_tags( $string, $remove_breaks = false ) {
5111      $string = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $string );
5112      $string = strip_tags( $string );
5113  
5114      if ( $remove_breaks ) {
5115          $string = preg_replace( '/[\r\n\t ]+/', ' ', $string );
5116      }
5117  
5118      return trim( $string );
5119  }
5120  
5121  /**
5122   * Sanitizes a string from user input or from the database.
5123   *
5124   * - Checks for invalid UTF-8,
5125   * - Converts single `<` characters to entities
5126   * - Strips all tags
5127   * - Removes line breaks, tabs, and extra whitespace
5128   * - Strips octets
5129   *
5130   * @since 2.9.0
5131   *
5132   * @see sanitize_textarea_field()
5133   * @see wp_check_invalid_utf8()
5134   * @see wp_strip_all_tags()
5135   *
5136   * @param string $str String to sanitize.
5137   * @return string Sanitized string.
5138   */
5139  function sanitize_text_field( $str ) {
5140      $filtered = _sanitize_text_fields( $str, false );
5141  
5142      /**
5143       * Filters a sanitized text field string.
5144       *
5145       * @since 2.9.0
5146       *
5147       * @param string $filtered The sanitized string.
5148       * @param string $str      The string prior to being sanitized.
5149       */
5150      return apply_filters( 'sanitize_text_field', $filtered, $str );
5151  }
5152  
5153  /**
5154   * Sanitizes a multiline string from user input or from the database.
5155   *
5156   * The function is like sanitize_text_field(), but preserves
5157   * new lines (\n) and other whitespace, which are legitimate
5158   * input in textarea elements.
5159   *
5160   * @see sanitize_text_field()
5161   *
5162   * @since 4.7.0
5163   *
5164   * @param string $str String to sanitize.
5165   * @return string Sanitized string.
5166   */
5167  function sanitize_textarea_field( $str ) {
5168      $filtered = _sanitize_text_fields( $str, true );
5169  
5170      /**
5171       * Filters a sanitized textarea field string.
5172       *
5173       * @since 4.7.0
5174       *
5175       * @param string $filtered The sanitized string.
5176       * @param string $str      The string prior to being sanitized.
5177       */
5178      return apply_filters( 'sanitize_textarea_field', $filtered, $str );
5179  }
5180  
5181  /**
5182   * Internal helper function to sanitize a string from user input or from the db
5183   *
5184   * @since 4.7.0
5185   * @access private
5186   *
5187   * @param string $str String to sanitize.
5188   * @param bool $keep_newlines optional Whether to keep newlines. Default: false.
5189   * @return string Sanitized string.
5190   */
5191  function _sanitize_text_fields( $str, $keep_newlines = false ) {
5192      if ( is_object( $str ) || is_array( $str ) ) {
5193          return '';
5194      }
5195  
5196      $str = (string) $str;
5197  
5198      $filtered = wp_check_invalid_utf8( $str );
5199  
5200      if ( strpos( $filtered, '<' ) !== false ) {
5201          $filtered = wp_pre_kses_less_than( $filtered );
5202          // This will strip extra whitespace for us.
5203          $filtered = wp_strip_all_tags( $filtered, false );
5204  
5205          // Use html entities in a special case to make sure no later
5206          // newline stripping stage could lead to a functional tag
5207          $filtered = str_replace( "<\n", "&lt;\n", $filtered );
5208      }
5209  
5210      if ( ! $keep_newlines ) {
5211          $filtered = preg_replace( '/[\r\n\t ]+/', ' ', $filtered );
5212      }
5213      $filtered = trim( $filtered );
5214  
5215      $found = false;
5216      while ( preg_match( '/%[a-f0-9]{2}/i', $filtered, $match ) ) {
5217          $filtered = str_replace( $match[0], '', $filtered );
5218          $found    = true;
5219      }
5220  
5221      if ( $found ) {
5222          // Strip out the whitespace that may now exist after removing the octets.
5223          $filtered = trim(