[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

title

Body

[close]

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

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