[ Index ]

PHP Cross Reference of Wordpress 2.9.1

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   * <code>
  15   * 'cause today's effort makes it worth tomorrow's "holiday"...
  16   * </code>
  17   * Becomes:
  18   * <code>
  19   * &#8217;cause today&#8217;s effort makes it worth tomorrow&#8217;s &#8220;holiday&#8221;&#8230;
  20   * </code>
  21   * Code within certain html blocks are skipped.
  22   *
  23   * @since 0.71
  24   * @uses $wp_cockneyreplace Array of formatted entities for certain common phrases
  25   *
  26   * @param string $text The text to be formatted
  27   * @return string The string replaced with html entities
  28   */
  29  function wptexturize($text) {
  30      global $wp_cockneyreplace;
  31      static $static_setup = false, $opening_quote, $closing_quote, $default_no_texturize_tags, $default_no_texturize_shortcodes, $static_characters, $static_replacements, $dynamic_characters, $dynamic_replacements;
  32      $output = '';
  33      $curl = '';
  34      $textarr = preg_split('/(<.*>|\[.*\])/Us', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
  35      $stop = count($textarr);
  36      
  37      // No need to setup these variables more than once
  38      if (!$static_setup) {
  39          /* translators: opening curly quote */
  40          $opening_quote = _x('&#8220;', 'opening curly quote');
  41          /* translators: closing curly quote */
  42          $closing_quote = _x('&#8221;', 'closing curly quote');
  43  
  44          $default_no_texturize_tags = array('pre', 'code', 'kbd', 'style', 'script', 'tt');
  45          $default_no_texturize_shortcodes = array('code');
  46  
  47          // if a plugin has provided an autocorrect array, use it
  48          if ( isset($wp_cockneyreplace) ) {
  49              $cockney = array_keys($wp_cockneyreplace);
  50              $cockneyreplace = array_values($wp_cockneyreplace);
  51          } else {
  52              $cockney = array("'tain't","'twere","'twas","'tis","'twill","'til","'bout","'nuff","'round","'cause");
  53              $cockneyreplace = array("&#8217;tain&#8217;t","&#8217;twere","&#8217;twas","&#8217;tis","&#8217;twill","&#8217;til","&#8217;bout","&#8217;nuff","&#8217;round","&#8217;cause");
  54          }
  55  
  56          $static_characters = array_merge(array('---', ' -- ', '--', ' - ', 'xn&#8211;', '...', '``', '\'s', '\'\'', ' (tm)'), $cockney);
  57          $static_replacements = array_merge(array('&#8212;', ' &#8212; ', '&#8211;', ' &#8211; ', 'xn--', '&#8230;', $opening_quote, '&#8217;s', $closing_quote, ' &#8482;'), $cockneyreplace);
  58  
  59          $dynamic_characters = array('/\'(\d\d(?:&#8217;|\')?s)/', '/(\s|\A|[([{<]|")\'/', '/(\d+)"/', '/(\d+)\'/', '/(\S)\'([^\'\s])/', '/(\s|\A|[([{<])"(?!\s)/', '/"(\s|\S|\Z)/', '/\'([\s.]|\Z)/', '/(\d+)x(\d+)/');
  60          $dynamic_replacements = array('&#8217;$1','$1&#8216;', '$1&#8243;', '$1&#8242;', '$1&#8217;$2', '$1' . $opening_quote . '$2', $closing_quote . '$1', '&#8217;$1', '$1&#215;$2');
  61  
  62          $static_setup = true;
  63      }
  64  
  65      // Transform into regexp sub-expression used in _wptexturize_pushpop_element
  66      // Must do this everytime in case plugins use these filters in a context sensitive manner
  67      $no_texturize_tags = '(' . implode('|', apply_filters('no_texturize_tags', $default_no_texturize_tags) ) . ')';
  68      $no_texturize_shortcodes = '(' . implode('|', apply_filters('no_texturize_shortcodes', $default_no_texturize_shortcodes) ) . ')';
  69  
  70      $no_texturize_tags_stack = array();
  71      $no_texturize_shortcodes_stack = array();
  72  
  73      for ( $i = 0; $i < $stop; $i++ ) {
  74          $curl = $textarr[$i];
  75  
  76          if ( !empty($curl) && '<' != $curl{0} && '[' != $curl{0}
  77                  && empty($no_texturize_shortcodes_stack) && empty($no_texturize_tags_stack)) { 
  78              // This is not a tag, nor is the texturization disabled
  79              // static strings
  80              $curl = str_replace($static_characters, $static_replacements, $curl);
  81              // regular expressions
  82              $curl = preg_replace($dynamic_characters, $dynamic_replacements, $curl);
  83          } elseif (!empty($curl)) {
  84              /*
  85               * Only call _wptexturize_pushpop_element if first char is correct
  86               * tag opening
  87               */
  88              if ('<' == $curl{0})
  89                  _wptexturize_pushpop_element($curl, $no_texturize_tags_stack, $no_texturize_tags, '<', '>');
  90              elseif ('[' == $curl{0})
  91                  _wptexturize_pushpop_element($curl, $no_texturize_shortcodes_stack, $no_texturize_shortcodes, '[', ']');
  92          }
  93  
  94          $curl = preg_replace('/&([^#])(?![a-zA-Z1-4]{1,8};)/', '&#038;$1', $curl);
  95          $output .= $curl;
  96      }
  97  
  98      return $output;
  99  }
 100  
 101  /**
 102   * Search for disabled element tags. Push element to stack on tag open and pop
 103   * on tag close. Assumes first character of $text is tag opening.
 104   *
 105   * @access private
 106   * @since 2.9.0
 107   *
 108   * @param string $text Text to check. First character is assumed to be $opening
 109   * @param array $stack Array used as stack of opened tag elements
 110   * @param string $disabled_elements Tags to match against formatted as regexp sub-expression
 111   * @param string $opening Tag opening character, assumed to be 1 character long
 112   * @param string $opening Tag closing  character
 113   * @return object
 114   */
 115  function _wptexturize_pushpop_element($text, &$stack, $disabled_elements, $opening = '<', $closing = '>') {
 116      // Check if it is a closing tag -- otherwise assume opening tag
 117      if (strncmp($opening . '/', $text, 2)) {
 118          // Opening? Check $text+1 against disabled elements
 119          if (preg_match('/^' . $disabled_elements . '\b/', substr($text, 1), $matches)) {
 120              /*
 121               * This disables texturize until we find a closing tag of our type
 122               * (e.g. <pre>) even if there was invalid nesting before that
 123               * 
 124               * Example: in the case <pre>sadsadasd</code>"baba"</pre>
 125               *          "baba" won't be texturize
 126               */
 127  
 128              array_push($stack, $matches[1]);
 129          }
 130      } else {
 131          // Closing? Check $text+2 against disabled elements
 132          $c = preg_quote($closing, '/');
 133          if (preg_match('/^' . $disabled_elements . $c . '/', substr($text, 2), $matches)) {
 134              $last = array_pop($stack);
 135  
 136              // Make sure it matches the opening tag
 137              if ($last != $matches[1])
 138                  array_push($stack, $last);
 139          }
 140      }
 141  }
 142  
 143  /**
 144   * Accepts matches array from preg_replace_callback in wpautop() or a string.
 145   *
 146   * Ensures that the contents of a <<pre>>...<</pre>> HTML block are not
 147   * converted into paragraphs or line-breaks.
 148   *
 149   * @since 1.2.0
 150   *
 151   * @param array|string $matches The array or string
 152   * @return string The pre block without paragraph/line-break conversion.
 153   */
 154  function clean_pre($matches) {
 155      if ( is_array($matches) )
 156          $text = $matches[1] . $matches[2] . "</pre>";
 157      else
 158          $text = $matches;
 159  
 160      $text = str_replace('<br />', '', $text);
 161      $text = str_replace('<p>', "\n", $text);
 162      $text = str_replace('</p>', '', $text);
 163  
 164      return $text;
 165  }
 166  
 167  /**
 168   * Replaces double line-breaks with paragraph elements.
 169   *
 170   * A group of regex replaces used to identify text formatted with newlines and
 171   * replace double line-breaks with HTML paragraph tags. The remaining
 172   * line-breaks after conversion become <<br />> tags, unless $br is set to '0'
 173   * or 'false'.
 174   *
 175   * @since 0.71
 176   *
 177   * @param string $pee The text which has to be formatted.
 178   * @param int|bool $br Optional. If set, this will convert all remaining line-breaks after paragraphing. Default true.
 179   * @return string Text which has been converted into correct paragraph tags.
 180   */
 181  function wpautop($pee, $br = 1) {
 182  
 183      if ( trim($pee) === '' )
 184          return '';
 185      $pee = $pee . "\n"; // just to make things a little easier, pad the end
 186      $pee = preg_replace('|<br />\s*<br />|', "\n\n", $pee);
 187      // Space things out a little
 188      $allblocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|form|map|area|blockquote|address|math|style|input|p|h[1-6]|hr|fieldset|legend)';
 189      $pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee);
 190      $pee = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $pee);
 191      $pee = str_replace(array("\r\n", "\r"), "\n", $pee); // cross-platform newlines
 192      if ( strpos($pee, '<object') !== false ) {
 193          $pee = preg_replace('|\s*<param([^>]*)>\s*|', "<param$1>", $pee); // no pee inside object/embed
 194          $pee = preg_replace('|\s*</embed>\s*|', '</embed>', $pee);
 195      }
 196      $pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates
 197      // make paragraphs, including one at the end
 198      $pees = preg_split('/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY);
 199      $pee = '';
 200      foreach ( $pees as $tinkle )
 201          $pee .= '<p>' . trim($tinkle, "\n") . "</p>\n";
 202      $pee = preg_replace('|<p>\s*</p>|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace
 203      $pee = preg_replace('!<p>([^<]+)</(div|address|form)>!', "<p>$1</p></$2>", $pee);
 204      $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee); // don't pee all over a tag
 205      $pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee); // problem with nested lists
 206      $pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee);
 207      $pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee);
 208      $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)!', "$1", $pee);
 209      $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
 210      if ($br) {
 211          $pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', create_function('$matches', 'return str_replace("\n", "<WPPreserveNewline />", $matches[0]);'), $pee);
 212          $pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee); // optionally make line breaks
 213          $pee = str_replace('<WPPreserveNewline />', "\n", $pee);
 214      }
 215      $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', "$1", $pee);
 216      $pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee);
 217      if (strpos($pee, '<pre') !== false)
 218          $pee = preg_replace_callback('!(<pre[^>]*>)(.*?)</pre>!is', 'clean_pre', $pee );
 219      $pee = preg_replace( "|\n</p>$|", '</p>', $pee );
 220  
 221      return $pee;
 222  }
 223  
 224  /**
 225   * Don't auto-p wrap shortcodes that stand alone
 226   *
 227   * Ensures that shortcodes are not wrapped in <<p>>...<</p>>.
 228   *
 229   * @since 2.9.0
 230   *
 231   * @param string $pee The content.
 232   * @return string The filtered content.
 233   */
 234  function shortcode_unautop($pee) {
 235      global $shortcode_tags;
 236  
 237      if ( !empty($shortcode_tags) && is_array($shortcode_tags) ) {
 238          $tagnames = array_keys($shortcode_tags);
 239          $tagregexp = join( '|', array_map('preg_quote', $tagnames) );
 240          $pee = preg_replace('/<p>\\s*?(\\[(' . $tagregexp . ')\\b.*?\\/?\\](?:.+?\\[\\/\\2\\])?)\\s*<\\/p>/s', '$1', $pee);
 241      }
 242  
 243      return $pee;
 244  }
 245  
 246  /**
 247   * Checks to see if a string is utf8 encoded.
 248   *
 249   * NOTE: This function checks for 5-Byte sequences, UTF8
 250   *       has Bytes Sequences with a maximum length of 4.
 251   *
 252   * @author bmorel at ssi dot fr (modified)
 253   * @since 1.2.1
 254   *
 255   * @param string $str The string to be checked
 256   * @return bool True if $str fits a UTF-8 model, false otherwise.
 257   */
 258  function seems_utf8($str) {
 259      $length = strlen($str);
 260      for ($i=0; $i < $length; $i++) {
 261          $c = ord($str[$i]);
 262          if ($c < 0x80) $n = 0; # 0bbbbbbb
 263          elseif (($c & 0xE0) == 0xC0) $n=1; # 110bbbbb
 264          elseif (($c & 0xF0) == 0xE0) $n=2; # 1110bbbb
 265          elseif (($c & 0xF8) == 0xF0) $n=3; # 11110bbb
 266          elseif (($c & 0xFC) == 0xF8) $n=4; # 111110bb
 267          elseif (($c & 0xFE) == 0xFC) $n=5; # 1111110b
 268          else return false; # Does not match any model
 269          for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
 270              if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))
 271                  return false;
 272          }
 273      }
 274      return true;
 275  }
 276  
 277  /**
 278   * Converts a number of special characters into their HTML entities.
 279   *
 280   * Specifically deals with: &, <, >, ", and '.
 281   *
 282   * $quote_style can be set to ENT_COMPAT to encode " to
 283   * &quot;, or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded.
 284   *
 285   * @since 1.2.2
 286   *
 287   * @param string $string The text which is to be encoded.
 288   * @param mixed $quote_style Optional. Converts double quotes if set to ENT_COMPAT, both single and double if set to ENT_QUOTES or none if set to ENT_NOQUOTES. Also compatible with old values; converting single quotes if set to 'single', double if set to 'double' or both if otherwise set. Default is ENT_NOQUOTES.
 289   * @param string $charset Optional. The character encoding of the string. Default is false.
 290   * @param boolean $double_encode Optional. Whether or not to encode existing html entities. Default is false.
 291   * @return string The encoded text with HTML entities.
 292   */
 293  function _wp_specialchars( $string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false ) {
 294      $string = (string) $string;
 295  
 296      if ( 0 === strlen( $string ) ) {
 297          return '';
 298      }
 299  
 300      // Don't bother if there are no specialchars - saves some processing
 301      if ( !preg_match( '/[&<>"\']/', $string ) ) {
 302          return $string;
 303      }
 304  
 305      // Account for the previous behaviour of the function when the $quote_style is not an accepted value
 306      if ( empty( $quote_style ) ) {
 307          $quote_style = ENT_NOQUOTES;
 308      } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
 309          $quote_style = ENT_QUOTES;
 310      }
 311  
 312      // Store the site charset as a static to avoid multiple calls to wp_load_alloptions()
 313      if ( !$charset ) {
 314          static $_charset;
 315          if ( !isset( $_charset ) ) {
 316              $alloptions = wp_load_alloptions();
 317              $_charset = isset( $alloptions['blog_charset'] ) ? $alloptions['blog_charset'] : '';
 318          }
 319          $charset = $_charset;
 320      }
 321      if ( in_array( $charset, array( 'utf8', 'utf-8', 'UTF8' ) ) ) {
 322          $charset = 'UTF-8';
 323      }
 324  
 325      $_quote_style = $quote_style;
 326  
 327      if ( $quote_style === 'double' ) {
 328          $quote_style = ENT_COMPAT;
 329          $_quote_style = ENT_COMPAT;
 330      } elseif ( $quote_style === 'single' ) {
 331          $quote_style = ENT_NOQUOTES;
 332      }
 333  
 334      // Handle double encoding ourselves
 335      if ( !$double_encode ) {
 336          $string = wp_specialchars_decode( $string, $_quote_style );
 337          $string = preg_replace( '/&(#?x?[0-9a-z]+);/i', '|wp_entity|$1|/wp_entity|', $string );
 338      }
 339  
 340      $string = @htmlspecialchars( $string, $quote_style, $charset );
 341  
 342      // Handle double encoding ourselves
 343      if ( !$double_encode ) {
 344          $string = str_replace( array( '|wp_entity|', '|/wp_entity|' ), array( '&', ';' ), $string );
 345      }
 346  
 347      // Backwards compatibility
 348      if ( 'single' === $_quote_style ) {
 349          $string = str_replace( "'", '&#039;', $string );
 350      }
 351  
 352      return $string;
 353  }
 354  
 355  /**
 356   * Converts a number of HTML entities into their special characters.
 357   *
 358   * Specifically deals with: &, <, >, ", and '.
 359   *
 360   * $quote_style can be set to ENT_COMPAT to decode " entities,
 361   * or ENT_QUOTES to do both " and '. Default is ENT_NOQUOTES where no quotes are decoded.
 362   *
 363   * @since 2.8
 364   *
 365   * @param string $string The text which is to be decoded.
 366   * @param mixed $quote_style Optional. Converts double quotes if set to ENT_COMPAT, both single and double if set to ENT_QUOTES or none if set to ENT_NOQUOTES. Also compatible with old _wp_specialchars() values; converting single quotes if set to 'single', double if set to 'double' or both if otherwise set. Default is ENT_NOQUOTES.
 367   * @return string The decoded text without HTML entities.
 368   */
 369  function wp_specialchars_decode( $string, $quote_style = ENT_NOQUOTES ) {
 370      $string = (string) $string;
 371  
 372      if ( 0 === strlen( $string ) ) {
 373          return '';
 374      }
 375  
 376      // Don't bother if there are no entities - saves a lot of processing
 377      if ( strpos( $string, '&' ) === false ) {
 378          return $string;
 379      }
 380  
 381      // Match the previous behaviour of _wp_specialchars() when the $quote_style is not an accepted value
 382      if ( empty( $quote_style ) ) {
 383          $quote_style = ENT_NOQUOTES;
 384      } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
 385          $quote_style = ENT_QUOTES;
 386      }
 387  
 388      // More complete than get_html_translation_table( HTML_SPECIALCHARS )
 389      $single = array( '&#039;'  => '\'', '&#x27;' => '\'' );
 390      $single_preg = array( '/&#0*39;/'  => '&#039;', '/&#x0*27;/i' => '&#x27;' );
 391      $double = array( '&quot;' => '"', '&#034;'  => '"', '&#x22;' => '"' );
 392      $double_preg = array( '/&#0*34;/'  => '&#034;', '/&#x0*22;/i' => '&#x22;' );
 393      $others = array( '&lt;'   => '<', '&#060;'  => '<', '&gt;'   => '>', '&#062;'  => '>', '&amp;'  => '&', '&#038;'  => '&', '&#x26;' => '&' );
 394      $others_preg = array( '/&#0*60;/'  => '&#060;', '/&#0*62;/'  => '&#062;', '/&#0*38;/'  => '&#038;', '/&#x0*26;/i' => '&#x26;' );
 395  
 396      if ( $quote_style === ENT_QUOTES ) {
 397          $translation = array_merge( $single, $double, $others );
 398          $translation_preg = array_merge( $single_preg, $double_preg, $others_preg );
 399      } elseif ( $quote_style === ENT_COMPAT || $quote_style === 'double' ) {
 400          $translation = array_merge( $double, $others );
 401          $translation_preg = array_merge( $double_preg, $others_preg );
 402      } elseif ( $quote_style === 'single' ) {
 403          $translation = array_merge( $single, $others );
 404          $translation_preg = array_merge( $single_preg, $others_preg );
 405      } elseif ( $quote_style === ENT_NOQUOTES ) {
 406          $translation = $others;
 407          $translation_preg = $others_preg;
 408      }
 409  
 410      // Remove zero padding on numeric entities
 411      $string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string );
 412  
 413      // Replace characters according to translation table
 414      return strtr( $string, $translation );
 415  }
 416  
 417  /**
 418   * Checks for invalid UTF8 in a string.
 419   *
 420   * @since 2.8
 421   *
 422   * @param string $string The text which is to be checked.
 423   * @param boolean $strip Optional. Whether to attempt to strip out invalid UTF8. Default is false.
 424   * @return string The checked text.
 425   */
 426  function wp_check_invalid_utf8( $string, $strip = false ) {
 427      $string = (string) $string;
 428  
 429      if ( 0 === strlen( $string ) ) {
 430          return '';
 431      }
 432  
 433      // Store the site charset as a static to avoid multiple calls to get_option()
 434      static $is_utf8;
 435      if ( !isset( $is_utf8 ) ) {
 436          $is_utf8 = in_array( get_option( 'blog_charset' ), array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ) );
 437      }
 438      if ( !$is_utf8 ) {
 439          return $string;
 440      }
 441  
 442      // Check for support for utf8 in the installed PCRE library once and store the result in a static
 443      static $utf8_pcre;
 444      if ( !isset( $utf8_pcre ) ) {
 445          $utf8_pcre = @preg_match( '/^./u', 'a' );
 446      }
 447      // We can't demand utf8 in the PCRE installation, so just return the string in those cases
 448      if ( !$utf8_pcre ) {
 449          return $string;
 450      }
 451  
 452      // preg_match fails when it encounters invalid UTF8 in $string
 453      if ( 1 === @preg_match( '/^./us', $string ) ) {
 454          return $string;
 455      }
 456  
 457      // Attempt to strip the bad chars if requested (not recommended)
 458      if ( $strip && function_exists( 'iconv' ) ) {
 459          return iconv( 'utf-8', 'utf-8', $string );
 460      }
 461  
 462      return '';
 463  }
 464  
 465  /**
 466   * Encode the Unicode values to be used in the URI.
 467   *
 468   * @since 1.5.0
 469   *
 470   * @param string $utf8_string
 471   * @param int $length Max length of the string
 472   * @return string String with Unicode encoded for URI.
 473   */
 474  function utf8_uri_encode( $utf8_string, $length = 0 ) {
 475      $unicode = '';
 476      $values = array();
 477      $num_octets = 1;
 478      $unicode_length = 0;
 479  
 480      $string_length = strlen( $utf8_string );
 481      for ($i = 0; $i < $string_length; $i++ ) {
 482  
 483          $value = ord( $utf8_string[ $i ] );
 484  
 485          if ( $value < 128 ) {
 486              if ( $length && ( $unicode_length >= $length ) )
 487                  break;
 488              $unicode .= chr($value);
 489              $unicode_length++;
 490          } else {
 491              if ( count( $values ) == 0 ) $num_octets = ( $value < 224 ) ? 2 : 3;
 492  
 493              $values[] = $value;
 494  
 495              if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length )
 496                  break;
 497              if ( count( $values ) == $num_octets ) {
 498                  if ($num_octets == 3) {
 499                      $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]) . '%' . dechex($values[2]);
 500                      $unicode_length += 9;
 501                  } else {
 502                      $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]);
 503                      $unicode_length += 6;
 504                  }
 505  
 506                  $values = array();
 507                  $num_octets = 1;
 508              }
 509          }
 510      }
 511  
 512      return $unicode;
 513  }
 514  
 515  /**
 516   * Converts all accent characters to ASCII characters.
 517   *
 518   * If there are no accent characters, then the string given is just returned.
 519   *
 520   * @since 1.2.1
 521   *
 522   * @param string $string Text that might have accent characters
 523   * @return string Filtered string with replaced "nice" characters.
 524   */
 525  function remove_accents($string) {
 526      if ( !preg_match('/[\x80-\xff]/', $string) )
 527          return $string;
 528  
 529      if (seems_utf8($string)) {
 530          $chars = array(
 531          // Decompositions for Latin-1 Supplement
 532          chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
 533          chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
 534          chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
 535          chr(195).chr(135) => 'C', chr(195).chr(136) => 'E',
 536          chr(195).chr(137) => 'E', chr(195).chr(138) => 'E',
 537          chr(195).chr(139) => 'E', chr(195).chr(140) => 'I',
 538          chr(195).chr(141) => 'I', chr(195).chr(142) => 'I',
 539          chr(195).chr(143) => 'I', chr(195).chr(145) => 'N',
 540          chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
 541          chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
 542          chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
 543          chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
 544          chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
 545          chr(195).chr(159) => 's', chr(195).chr(160) => 'a',
 546          chr(195).chr(161) => 'a', chr(195).chr(162) => 'a',
 547          chr(195).chr(163) => 'a', chr(195).chr(164) => 'a',
 548          chr(195).chr(165) => 'a', chr(195).chr(167) => 'c',
 549          chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
 550          chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
 551          chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
 552          chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
 553          chr(195).chr(177) => 'n', chr(195).chr(178) => 'o',
 554          chr(195).chr(179) => 'o', chr(195).chr(180) => 'o',
 555          chr(195).chr(181) => 'o', chr(195).chr(182) => 'o',
 556          chr(195).chr(182) => 'o', chr(195).chr(185) => 'u',
 557          chr(195).chr(186) => 'u', chr(195).chr(187) => 'u',
 558          chr(195).chr(188) => 'u', chr(195).chr(189) => 'y',
 559          chr(195).chr(191) => 'y',
 560          // Decompositions for Latin Extended-A
 561          chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
 562          chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
 563          chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
 564          chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
 565          chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
 566          chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
 567          chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
 568          chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
 569          chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
 570          chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
 571          chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
 572          chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
 573          chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
 574          chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
 575          chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
 576          chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
 577          chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
 578          chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
 579          chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
 580          chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
 581          chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
 582          chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
 583          chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
 584          chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
 585          chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
 586          chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
 587          chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
 588          chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
 589          chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
 590          chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
 591          chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
 592          chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
 593          chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
 594          chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
 595          chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
 596          chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
 597          chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
 598          chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
 599          chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
 600          chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
 601          chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
 602          chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
 603          chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
 604          chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
 605          chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
 606          chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
 607          chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
 608          chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
 609          chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
 610          chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
 611          chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
 612          chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
 613          chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
 614          chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
 615          chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
 616          chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
 617          chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
 618          chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
 619          chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
 620          chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
 621          chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
 622          chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
 623          chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
 624          chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
 625          // Euro Sign
 626          chr(226).chr(130).chr(172) => 'E',
 627          // GBP (Pound) Sign
 628          chr(194).chr(163) => '');
 629  
 630          $string = strtr($string, $chars);
 631      } else {
 632          // Assume ISO-8859-1 if not UTF-8
 633          $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
 634              .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
 635              .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
 636              .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
 637              .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
 638              .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
 639              .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
 640              .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
 641              .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
 642              .chr(252).chr(253).chr(255);
 643  
 644          $chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";
 645  
 646          $string = strtr($string, $chars['in'], $chars['out']);
 647          $double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
 648          $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
 649          $string = str_replace($double_chars['in'], $double_chars['out'], $string);
 650      }
 651  
 652      return $string;
 653  }
 654  
 655  /**
 656   * Sanitizes a filename replacing whitespace with dashes
 657   *
 658   * Removes special characters that are illegal in filenames on certain
 659   * operating systems and special characters requiring special escaping
 660   * to manipulate at the command line. Replaces spaces and consecutive
 661   * dashes with a single dash. Trim period, dash and underscore from beginning
 662   * and end of filename.
 663   *
 664   * @since 2.1.0
 665   *
 666   * @param string $filename The filename to be sanitized
 667   * @return string The sanitized filename
 668   */
 669  function sanitize_file_name( $filename ) {
 670      $filename_raw = $filename;
 671      $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", chr(0));
 672      $special_chars = apply_filters('sanitize_file_name_chars', $special_chars, $filename_raw);
 673      $filename = str_replace($special_chars, '', $filename);
 674      $filename = preg_replace('/[\s-]+/', '-', $filename);
 675      $filename = trim($filename, '.-_');
 676  
 677      // Split the filename into a base and extension[s]
 678      $parts = explode('.', $filename);
 679  
 680      // Return if only one extension
 681      if ( count($parts) <= 2 )
 682          return apply_filters('sanitize_file_name', $filename, $filename_raw);
 683  
 684      // Process multiple extensions
 685      $filename = array_shift($parts);
 686      $extension = array_pop($parts);
 687      $mimes = get_allowed_mime_types();
 688  
 689      // Loop over any intermediate extensions.  Munge them with a trailing underscore if they are a 2 - 5 character
 690      // long alpha string not in the extension whitelist.
 691      foreach ( (array) $parts as $part) {
 692          $filename .= '.' . $part;
 693          
 694          if ( preg_match("/^[a-zA-Z]{2,5}\d?$/", $part) ) {
 695              $allowed = false;
 696              foreach ( $mimes as $ext_preg => $mime_match ) {
 697                  $ext_preg = '!(^' . $ext_preg . ')$!i';
 698                  if ( preg_match( $ext_preg, $part ) ) {
 699                      $allowed = true;
 700                      break;
 701                  }
 702              }
 703              if ( !$allowed )
 704                  $filename .= '_';
 705          }
 706      }
 707      $filename .= '.' . $extension;
 708  
 709      return apply_filters('sanitize_file_name', $filename, $filename_raw);
 710  }
 711  
 712  /**
 713   * Sanitize username stripping out unsafe characters.
 714   *
 715   * If $strict is true, only alphanumeric characters (as well as _, space, ., -,
 716   * @) are returned.
 717   * Removes tags, octets, entities, and if strict is enabled, will remove all
 718   * non-ASCII characters. After sanitizing, it passes the username, raw username
 719   * (the username in the parameter), and the strict parameter as parameters for
 720   * the filter.
 721   *
 722   * @since 2.0.0
 723   * @uses apply_filters() Calls 'sanitize_user' hook on username, raw username,
 724   *        and $strict parameter.
 725   *
 726   * @param string $username The username to be sanitized.
 727   * @param bool $strict If set limits $username to specific characters. Default false.
 728   * @return string The sanitized username, after passing through filters.
 729   */
 730  function sanitize_user( $username, $strict = false ) {
 731      $raw_username = $username;
 732      $username = wp_strip_all_tags($username);
 733      // Kill octets
 734      $username = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '', $username);
 735      $username = preg_replace('/&.+?;/', '', $username); // Kill entities
 736  
 737      // If strict, reduce to ASCII for max portability.
 738      if ( $strict )
 739          $username = preg_replace('|[^a-z0-9 _.\-@]|i', '', $username);
 740  
 741      // Consolidate contiguous whitespace
 742      $username = preg_replace('|\s+|', ' ', $username);
 743  
 744      return apply_filters('sanitize_user', $username, $raw_username, $strict);
 745  }
 746  
 747  /**
 748   * Sanitizes title or use fallback title.
 749   *
 750   * Specifically, HTML and PHP tags are stripped. Further actions can be added
 751   * via the plugin API. If $title is empty and $fallback_title is set, the latter
 752   * will be used.
 753   *
 754   * @since 1.0.0
 755   *
 756   * @param string $title The string to be sanitized.
 757   * @param string $fallback_title Optional. A title to use if $title is empty.
 758   * @return string The sanitized string.
 759   */
 760  function sanitize_title($title, $fallback_title = '') {
 761      $raw_title = $title;
 762      $title = strip_tags($title);
 763      $title = apply_filters('sanitize_title', $title, $raw_title);
 764  
 765      if ( '' === $title || false === $title )
 766          $title = $fallback_title;
 767  
 768      return $title;
 769  }
 770  
 771  /**
 772   * Sanitizes title, replacing whitespace with dashes.
 773   *
 774   * Limits the output to alphanumeric characters, underscore (_) and dash (-).
 775   * Whitespace becomes a dash.
 776   *
 777   * @since 1.2.0
 778   *
 779   * @param string $title The title to be sanitized.
 780   * @return string The sanitized title.
 781   */
 782  function sanitize_title_with_dashes($title) {
 783      $title = strip_tags($title);
 784      // Preserve escaped octets.
 785      $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
 786      // Remove percent signs that are not part of an octet.
 787      $title = str_replace('%', '', $title);
 788      // Restore octets.
 789      $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
 790  
 791      $title = remove_accents($title);
 792      if (seems_utf8($title)) {
 793          if (function_exists('mb_strtolower')) {
 794              $title = mb_strtolower($title, 'UTF-8');
 795          }
 796          $title = utf8_uri_encode($title, 200);
 797      }
 798  
 799      $title = strtolower($title);
 800      $title = preg_replace('/&.+?;/', '', $title); // kill entities
 801      $title = str_replace('.', '-', $title);
 802      $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
 803      $title = preg_replace('/\s+/', '-', $title);
 804      $title = preg_replace('|-+|', '-', $title);
 805      $title = trim($title, '-');
 806  
 807      return $title;
 808  }
 809  
 810  /**
 811   * Ensures a string is a valid SQL order by clause.
 812   *
 813   * Accepts one or more columns, with or without ASC/DESC, and also accepts
 814   * RAND().
 815   *
 816   * @since 2.5.1
 817   *
 818   * @param string $orderby Order by string to be checked.
 819   * @return string|false Returns the order by clause if it is a match, false otherwise.
 820   */
 821  function sanitize_sql_orderby( $orderby ){
 822      preg_match('/^\s*([a-z0-9_]+(\s+(ASC|DESC))?(\s*,\s*|\s*$))+|^\s*RAND\(\s*\)\s*$/i', $orderby, $obmatches);
 823      if ( !$obmatches )
 824          return false;
 825      return $orderby;
 826  }
 827  
 828  /**
 829   * Santizes a html classname to ensure it only contains valid characters
 830   *
 831   * Strips the string down to A-Z,a-z,0-9,'-' if this results in an empty
 832   * string then it will return the alternative value supplied.
 833   *
 834   * @todo Expand to support the full range of CDATA that a class attribute can contain.
 835   *
 836   * @since 2.8.0
 837   *
 838   * @param string $class The classname to be sanitized
 839   * @param string $fallback The value to return if the sanitization end's up as an empty string.
 840   * @return string The sanitized value
 841   */
 842  function sanitize_html_class($class, $fallback){
 843      //Strip out any % encoded octets
 844      $sanitized = preg_replace('|%[a-fA-F0-9][a-fA-F0-9]|', '', $class);
 845  
 846      //Limit to A-Z,a-z,0-9,'-'
 847      $sanitized = preg_replace('/[^A-Za-z0-9-]/', '', $sanitized);
 848  
 849      if ('' == $sanitized)
 850          $sanitized = $fallback;
 851  
 852      return apply_filters('sanitize_html_class',$sanitized, $class, $fallback);
 853  }
 854  
 855  /**
 856   * Converts a number of characters from a string.
 857   *
 858   * Metadata tags <<title>> and <<category>> are removed, <<br>> and <<hr>> are
 859   * converted into correct XHTML and Unicode characters are converted to the
 860   * valid range.
 861   *
 862   * @since 0.71
 863   *
 864   * @param string $content String of characters to be converted.
 865   * @param string $deprecated Not used.
 866   * @return string Converted string.
 867   */
 868  function convert_chars($content, $deprecated = '') {
 869      // Translation of invalid Unicode references range to valid range
 870      $wp_htmltranswinuni = array(
 871      '&#128;' => '&#8364;', // the Euro sign
 872      '&#129;' => '',
 873      '&#130;' => '&#8218;', // these are Windows CP1252 specific characters
 874      '&#131;' => '&#402;',  // they would look weird on non-Windows browsers
 875      '&#132;' => '&#8222;',
 876      '&#133;' => '&#8230;',
 877      '&#134;' => '&#8224;',
 878      '&#135;' => '&#8225;',
 879      '&#136;' => '&#710;',
 880      '&#137;' => '&#8240;',
 881      '&#138;' => '&#352;',
 882      '&#139;' => '&#8249;',
 883      '&#140;' => '&#338;',
 884      '&#141;' => '',
 885      '&#142;' => '&#382;',
 886      '&#143;' => '',
 887      '&#144;' => '',
 888      '&#145;' => '&#8216;',
 889      '&#146;' => '&#8217;',
 890      '&#147;' => '&#8220;',
 891      '&#148;' => '&#8221;',
 892      '&#149;' => '&#8226;',
 893      '&#150;' => '&#8211;',
 894      '&#151;' => '&#8212;',
 895      '&#152;' => '&#732;',
 896      '&#153;' => '&#8482;',
 897      '&#154;' => '&#353;',
 898      '&#155;' => '&#8250;',
 899      '&#156;' => '&#339;',
 900      '&#157;' => '',
 901      '&#158;' => '',
 902      '&#159;' => '&#376;'
 903      );
 904  
 905      // Remove metadata tags
 906      $content = preg_replace('/<title>(.+?)<\/title>/','',$content);
 907      $content = preg_replace('/<category>(.+?)<\/category>/','',$content);
 908  
 909      // Converts lone & characters into &#38; (a.k.a. &amp;)
 910      $content = preg_replace('/&([^#])(?![a-z1-4]{1,8};)/i', '&#038;$1', $content);
 911  
 912      // Fix Word pasting
 913      $content = strtr($content, $wp_htmltranswinuni);
 914  
 915      // Just a little XHTML help
 916      $content = str_replace('<br>', '<br />', $content);
 917      $content = str_replace('<hr>', '<hr />', $content);
 918  
 919      return $content;
 920  }
 921  
 922  /**
 923   * Callback used to change %uXXXX to &#YYY; syntax
 924   *
 925   * @since 2.8?
 926   *
 927   * @param array $matches Single Match
 928   * @return string An HTML entity
 929   */
 930  function funky_javascript_callback($matches) {
 931      return "&#".base_convert($matches[1],16,10).";";
 932  }
 933  
 934  /**
 935   * Fixes javascript bugs in browsers.
 936   *
 937   * Converts unicode characters to HTML numbered entities.
 938   *
 939   * @since 1.5.0
 940   * @uses $is_macIE
 941   * @uses $is_winIE
 942   *
 943   * @param string $text Text to be made safe.
 944   * @return string Fixed text.
 945   */
 946  function funky_javascript_fix($text) {
 947      // Fixes for browsers' javascript bugs
 948      global $is_macIE, $is_winIE;
 949  
 950      if ( $is_winIE || $is_macIE )
 951          $text =  preg_replace_callback("/\%u([0-9A-F]{4,4})/",
 952                             "funky_javascript_callback",
 953                             $text);
 954  
 955      return $text;
 956  }
 957  
 958  /**
 959   * Will only balance the tags if forced to and the option is set to balance tags.
 960   *
 961   * The option 'use_balanceTags' is used for whether the tags will be balanced.
 962   * Both the $force parameter and 'use_balanceTags' option will have to be true
 963   * before the tags will be balanced.
 964   *
 965   * @since 0.71
 966   *
 967   * @param string $text Text to be balanced
 968   * @param bool $force Forces balancing, ignoring the value of the option. Default false.
 969   * @return string Balanced text
 970   */
 971  function balanceTags( $text, $force = false ) {
 972      if ( !$force && get_option('use_balanceTags') == 0 )
 973          return $text;
 974      return force_balance_tags( $text );
 975  }
 976  
 977  /**
 978   * Balances tags of string using a modified stack.
 979   *
 980   * @since 2.0.4
 981   *
 982   * @author Leonard Lin <leonard@acm.org>
 983   * @license GPL v2.0
 984   * @copyright November 4, 2001
 985   * @version 1.1
 986   * @todo Make better - change loop condition to $text in 1.2
 987   * @internal Modified by Scott Reilly (coffee2code) 02 Aug 2004
 988   *        1.1  Fixed handling of append/stack pop order of end text
 989   *             Added Cleaning Hooks
 990   *        1.0  First Version
 991   *
 992   * @param string $text Text to be balanced.
 993   * @return string Balanced text.
 994   */
 995  function force_balance_tags( $text ) {
 996      $tagstack = array(); $stacksize = 0; $tagqueue = ''; $newtext = '';
 997      $single_tags = array('br', 'hr', 'img', 'input'); //Known single-entity/self-closing tags
 998      $nestable_tags = array('blockquote', 'div', 'span'); //Tags that can be immediately nested within themselves
 999  
1000      # WP bug fix for comments - in case you REALLY meant to type '< !--'
1001      $text = str_replace('< !--', '<    !--', $text);
1002      # WP bug fix for LOVE <3 (and other situations with '<' before a number)
1003      $text = preg_replace('#<([0-9]{1})#', '&lt;$1', $text);
1004  
1005      while (preg_match("/<(\/?\w*)\s*([^>]*)>/",$text,$regex)) {
1006          $newtext .= $tagqueue;
1007  
1008          $i = strpos($text,$regex[0]);
1009          $l = strlen($regex[0]);
1010  
1011          // clear the shifter
1012          $tagqueue = '';
1013          // Pop or Push
1014          if ( isset($regex[1][0]) && '/' == $regex[1][0] ) { // End Tag
1015              $tag = strtolower(substr($regex[1],1));
1016              // if too many closing tags
1017              if($stacksize <= 0) {
1018                  $tag = '';
1019                  //or close to be safe $tag = '/' . $tag;
1020              }
1021              // if stacktop value = tag close value then pop
1022              else if ($tagstack[$stacksize - 1] == $tag) { // found closing tag
1023                  $tag = '</' . $tag . '>'; // Close Tag
1024                  // Pop
1025                  array_pop ($tagstack);
1026                  $stacksize--;
1027              } else { // closing tag not at top, search for it
1028                  for ($j=$stacksize-1;$j>=0;$j--) {
1029                      if ($tagstack[$j] == $tag) {
1030                      // add tag to tagqueue
1031                          for ($k=$stacksize-1;$k>=$j;$k--){
1032                              $tagqueue .= '</' . array_pop ($tagstack) . '>';
1033                              $stacksize--;
1034                          }
1035                          break;
1036                      }
1037                  }
1038                  $tag = '';
1039              }
1040          } else { // Begin Tag
1041              $tag = strtolower($regex[1]);
1042  
1043              // Tag Cleaning
1044  
1045              // If self-closing or '', don't do anything.
1046              if((substr($regex[2],-1) == '/') || ($tag == '')) {
1047              }
1048              // ElseIf it's a known single-entity tag but it doesn't close itself, do so
1049              elseif ( in_array($tag, $single_tags) ) {
1050                  $regex[2] .= '/';
1051              } else {    // Push the tag onto the stack
1052                  // If the top of the stack is the same as the tag we want to push, close previous tag
1053                  if (($stacksize > 0) && !in_array($tag, $nestable_tags) && ($tagstack[$stacksize - 1] == $tag)) {
1054                      $tagqueue = '</' . array_pop ($tagstack) . '>';
1055                      $stacksize--;
1056                  }
1057                  $stacksize = array_push ($tagstack, $tag);
1058              }
1059  
1060              // Attributes
1061              $attributes = $regex[2];
1062              if($attributes) {
1063                  $attributes = ' '.$attributes;
1064              }
1065              $tag = '<'.$tag.$attributes.'>';
1066              //If already queuing a close tag, then put this tag on, too
1067              if ($tagqueue) {
1068                  $tagqueue .= $tag;
1069                  $tag = '';
1070              }
1071          }
1072          $newtext .= substr($text,0,$i) . $tag;
1073          $text = substr($text,$i+$l);
1074      }
1075  
1076      // Clear Tag Queue
1077      $newtext .= $tagqueue;
1078  
1079      // Add Remaining text
1080      $newtext .= $text;
1081  
1082      // Empty Stack
1083      while($x = array_pop($tagstack)) {
1084          $newtext .= '</' . $x . '>'; // Add remaining tags to close
1085      }
1086  
1087      // WP fix for the bug with HTML comments
1088      $newtext = str_replace("< !--","<!--",$newtext);
1089      $newtext = str_replace("<    !--","< !--",$newtext);
1090  
1091      return $newtext;
1092  }
1093  
1094  /**
1095   * Acts on text which is about to be edited.
1096   *
1097   * Unless $richedit is set, it is simply a holder for the 'format_to_edit'
1098   * filter. If $richedit is set true htmlspecialchars() will be run on the
1099   * content, converting special characters to HTMl entities.
1100   *
1101   * @since 0.71
1102   *
1103   * @param string $content The text about to be edited.
1104   * @param bool $richedit Whether or not the $content should pass through htmlspecialchars(). Default false.
1105   * @return string The text after the filter (and possibly htmlspecialchars()) has been run.
1106   */
1107  function format_to_edit($content, $richedit = false) {
1108      $content = apply_filters('format_to_edit', $content);
1109      if (! $richedit )
1110          $content = htmlspecialchars($content);
1111      return $content;
1112  }
1113  
1114  /**
1115   * Holder for the 'format_to_post' filter.
1116   *
1117   * @since 0.71
1118   *
1119   * @param string $content The text to pass through the filter.
1120   * @return string Text returned from the 'format_to_post' filter.
1121   */
1122  function format_to_post($content) {
1123      $content = apply_filters('format_to_post', $content);
1124      return $content;
1125  }
1126  
1127  /**
1128   * Add leading zeros when necessary.
1129   *
1130   * If you set the threshold to '4' and the number is '10', then you will get
1131   * back '0010'. If you set the number to '4' and the number is '5000', then you
1132   * will get back '5000'.
1133   *
1134   * Uses sprintf to append the amount of zeros based on the $threshold parameter
1135   * and the size of the number. If the number is large enough, then no zeros will
1136   * be appended.
1137   *
1138   * @since 0.71
1139   *
1140   * @param mixed $number Number to append zeros to if not greater than threshold.
1141   * @param int $threshold Digit places number needs to be to not have zeros added.
1142   * @return string Adds leading zeros to number if needed.
1143   */
1144  function zeroise($number, $threshold) {
1145      return sprintf('%0'.$threshold.'s', $number);
1146  }
1147  
1148  /**
1149   * Adds backslashes before letters and before a number at the start of a string.
1150   *
1151   * @since 0.71
1152   *
1153   * @param string $string Value to which backslashes will be added.
1154   * @return string String with backslashes inserted.
1155   */
1156  function backslashit($string) {
1157      $string = preg_replace('/^([0-9])/', '\\\\\\\\\1', $string);
1158      $string = preg_replace('/([a-z])/i', '\\\\\1', $string);
1159      return $string;
1160  }
1161  
1162  /**
1163   * Appends a trailing slash.
1164   *
1165   * Will remove trailing slash if it exists already before adding a trailing
1166   * slash. This prevents double slashing a string or path.
1167   *
1168   * The primary use of this is for paths and thus should be used for paths. It is
1169   * not restricted to paths and offers no specific path support.
1170   *
1171   * @since 1.2.0
1172   * @uses untrailingslashit() Unslashes string if it was slashed already.
1173   *
1174   * @param string $string What to add the trailing slash to.
1175   * @return string String with trailing slash added.
1176   */
1177  function trailingslashit($string) {
1178      return untrailingslashit($string) . '/';
1179  }
1180  
1181  /**
1182   * Removes trailing slash if it exists.
1183   *
1184   * The primary use of this is for paths and thus should be used for paths. It is
1185   * not restricted to paths and offers no specific path support.
1186   *
1187   * @since 2.2.0
1188   *
1189   * @param string $string What to remove the trailing slash from.
1190   * @return string String without the trailing slash.
1191   */
1192  function untrailingslashit($string) {
1193      return rtrim($string, '/');
1194  }
1195  
1196  /**
1197   * Adds slashes to escape strings.
1198   *
1199   * Slashes will first be removed if magic_quotes_gpc is set, see {@link
1200   * http://www.php.net/magic_quotes} for more details.
1201   *
1202   * @since 0.71
1203   *
1204   * @param string $gpc The string returned from HTTP request data.
1205   * @return string Returns a string escaped with slashes.
1206   */
1207  function addslashes_gpc($gpc) {
1208      global $wpdb;
1209  
1210      if (get_magic_quotes_gpc()) {
1211          $gpc = stripslashes($gpc);
1212      }
1213  
1214      return esc_sql($gpc);
1215  }
1216  
1217  /**
1218   * Navigates through an array and removes slashes from the values.
1219   *
1220   * If an array is passed, the array_map() function causes a callback to pass the
1221   * value back to the function. The slashes from this value will removed.
1222   *
1223   * @since 2.0.0
1224   *
1225   * @param array|string $value The array or string to be striped.
1226   * @return array|string Stripped array (or string in the callback).
1227   */
1228  function stripslashes_deep($value) {
1229      $value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value);
1230      return $value;
1231  }
1232  
1233  /**
1234   * Navigates through an array and encodes the values to be used in a URL.
1235   *
1236   * Uses a callback to pass the value of the array back to the function as a
1237   * string.
1238   *
1239   * @since 2.2.0
1240   *
1241   * @param array|string $value The array or string to be encoded.
1242   * @return array|string $value The encoded array (or string from the callback).
1243   */
1244  function urlencode_deep($value) {
1245      $value = is_array($value) ? array_map('urlencode_deep', $value) : urlencode($value);
1246      return $value;
1247  }
1248  
1249  /**
1250   * Converts email addresses characters to HTML entities to block spam bots.
1251   *
1252   * @since 0.71
1253   *
1254   * @param string $emailaddy Email address.
1255   * @param int $mailto Optional. Range from 0 to 1. Used for encoding.
1256   * @return string Converted email address.
1257   */
1258  function antispambot($emailaddy, $mailto=0) {
1259      $emailNOSPAMaddy = '';
1260      srand ((float) microtime() * 1000000);
1261      for ($i = 0; $i < strlen($emailaddy); $i = $i + 1) {
1262          $j = floor(rand(0, 1+$mailto));
1263          if ($j==0) {
1264              $emailNOSPAMaddy .= '&#'.ord(substr($emailaddy,$i,1)).';';
1265          } elseif ($j==1) {
1266              $emailNOSPAMaddy .= substr($emailaddy,$i,1);
1267          } elseif ($j==2) {
1268              $emailNOSPAMaddy .= '%'.zeroise(dechex(ord(substr($emailaddy, $i, 1))), 2);
1269          }
1270      }
1271      $emailNOSPAMaddy = str_replace('@','&#64;',$emailNOSPAMaddy);
1272      return $emailNOSPAMaddy;
1273  }
1274  
1275  /**
1276   * Callback to convert URI match to HTML A element.
1277   *
1278   * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1279   * make_clickable()}.
1280   *
1281   * @since 2.3.2
1282   * @access private
1283   *
1284   * @param array $matches Single Regex Match.
1285   * @return string HTML A element with URI address.
1286   */
1287  function _make_url_clickable_cb($matches) {
1288      $url = $matches[2];
1289  
1290      $url = esc_url($url);
1291      if ( empty($url) )
1292          return $matches[0];
1293  
1294      return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>";
1295  }
1296  
1297  /**
1298   * Callback to convert URL match to HTML A element.
1299   *
1300   * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1301   * make_clickable()}.
1302   *
1303   * @since 2.3.2
1304   * @access private
1305   *
1306   * @param array $matches Single Regex Match.
1307   * @return string HTML A element with URL address.
1308   */
1309  function _make_web_ftp_clickable_cb($matches) {
1310      $ret = '';
1311      $dest = $matches[2];
1312      $dest = 'http://' . $dest;
1313      $dest = esc_url($dest);
1314      if ( empty($dest) )
1315          return $matches[0];
1316  
1317      // removed trailing [.,;:)] from URL
1318      if ( in_array( substr($dest, -1), array('.', ',', ';', ':', ')') ) === true ) {
1319          $ret = substr($dest, -1);
1320          $dest = substr($dest, 0, strlen($dest)-1);
1321      }
1322      return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>$ret";
1323  }
1324  
1325  /**
1326   * Callback to convert email address match to HTML A element.
1327   *
1328   * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1329   * make_clickable()}.
1330   *
1331   * @since 2.3.2
1332   * @access private
1333   *
1334   * @param array $matches Single Regex Match.
1335   * @return string HTML A element with email address.
1336   */
1337  function _make_email_clickable_cb($matches) {
1338      $email = $matches[2] . '@' . $matches[3];
1339      return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
1340  }
1341  
1342  /**
1343   * Convert plaintext URI to HTML links.
1344   *
1345   * Converts URI, www and ftp, and email addresses. Finishes by fixing links
1346   * within links.
1347   *
1348   * @since 0.71
1349   *
1350   * @param string $ret Content to convert URIs.
1351   * @return string Content with converted URIs.
1352   */
1353  function make_clickable($ret) {
1354      $ret = ' ' . $ret;
1355      // in testing, using arrays here was found to be faster
1356      $ret = preg_replace_callback('#(?<=[\s>])(\()?([\w]+?://(?:[\w\\x80-\\xff\#$%&~/=?@\[\](+-]|[.,;:](?![\s<]|(\))?([\s]|$))|(?(1)\)(?![\s<.,;:]|$)|\)))+)#is', '_make_url_clickable_cb', $ret);
1357      $ret = preg_replace_callback('#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]+)#is', '_make_web_ftp_clickable_cb', $ret);
1358      $ret = preg_replace_callback('#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret);
1359      // this one is not in an array because we need it to run last, for cleanup of accidental links within links
1360      $ret = preg_replace("#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i", "$1$3</a>", $ret);
1361      $ret = trim($ret);
1362      return $ret;
1363  }
1364  
1365  /**
1366   * Adds rel nofollow string to all HTML A elements in content.
1367   *
1368   * @since 1.5.0
1369   *
1370   * @param string $text Content that may contain HTML A elements.
1371   * @return string Converted content.
1372   */
1373  function wp_rel_nofollow( $text ) {
1374      global $wpdb;
1375      // This is a pre save filter, so text is already escaped.
1376      $text = stripslashes($text);
1377      $text = preg_replace_callback('|<a (.+?)>|i', 'wp_rel_nofollow_callback', $text);
1378      $text = esc_sql($text);
1379      return $text;
1380  }
1381  
1382  /**
1383   * Callback to used to add rel=nofollow string to HTML A element.
1384   *
1385   * Will remove already existing rel="nofollow" and rel='nofollow' from the
1386   * string to prevent from invalidating (X)HTML.
1387   *
1388   * @since 2.3.0
1389   *
1390   * @param array $matches Single Match
1391   * @return string HTML A Element with rel nofollow.
1392   */
1393  function wp_rel_nofollow_callback( $matches ) {
1394      $text = $matches[1];
1395      $text = str_replace(array(' rel="nofollow"', " rel='nofollow'"), '', $text);
1396      return "<a $text rel=\"nofollow\">";
1397  }
1398  
1399  
1400  /**
1401   * Convert one smiley code to the icon graphic file equivalent.
1402   *
1403   * Looks up one smiley code in the $wpsmiliestrans global array and returns an
1404   * <img> string for that smiley.
1405   *
1406   * @global array $wpsmiliestrans
1407   * @since 2.8.0
1408   *
1409   * @param string $smiley Smiley code to convert to image.
1410   * @return string Image string for smiley.
1411   */
1412  function translate_smiley($smiley) {
1413      global $wpsmiliestrans;
1414  
1415      if (count($smiley) == 0) {
1416          return '';
1417      }
1418  
1419      $siteurl = get_option( 'siteurl' );
1420  
1421      $smiley = trim(reset($smiley));
1422      $img = $wpsmiliestrans[$smiley];
1423      $smiley_masked = esc_attr($smiley);
1424  
1425      $srcurl = apply_filters('smilies_src', "$siteurl/wp-includes/images/smilies/$img", $img, $siteurl);
1426  
1427      return " <img src='$srcurl' alt='$smiley_masked' class='wp-smiley' /> ";
1428  }
1429  
1430  
1431  /**
1432   * Convert text equivalent of smilies to images.
1433   *
1434   * Will only convert smilies if the option 'use_smilies' is true and the global
1435   * used in the function isn't empty.
1436   *
1437   * @since 0.71
1438   * @uses $wp_smiliessearch
1439   *
1440   * @param string $text Content to convert smilies from text.
1441   * @return string Converted content with text smilies replaced with images.
1442   */
1443  function convert_smilies($text) {
1444      global $wp_smiliessearch;
1445      $output = '';
1446      if ( get_option('use_smilies') && !empty($wp_smiliessearch) ) {
1447          // HTML loop taken from texturize function, could possible be consolidated
1448          $textarr = preg_split("/(<.*>)/U", $text, -1, PREG_SPLIT_DELIM_CAPTURE); // capture the tags as well as in between
1449          $stop = count($textarr);// loop stuff
1450          for ($i = 0; $i < $stop; $i++) {
1451              $content = $textarr[$i];
1452              if ((strlen($content) > 0) && ('<' != $content{0})) { // If it's not a tag
1453                  $content = preg_replace_callback($wp_smiliessearch, 'translate_smiley', $content);
1454              }
1455              $output .= $content;
1456          }
1457      } else {
1458          // return default text.
1459          $output = $text;
1460      }
1461      return $output;
1462  }
1463  
1464  /**
1465   * Verifies that an email is valid.
1466   *
1467   * Does not grok i18n domains. Not RFC compliant.
1468   *
1469   * @since 0.71
1470   *
1471   * @param string $email Email address to verify.
1472   * @param boolean $check_dns Whether to check the DNS for the domain using checkdnsrr().
1473   * @return string|bool Either false or the valid email address.
1474   */
1475  function is_email( $email, $check_dns = false ) {
1476      // Test for the minimum length the email can be
1477      if ( strlen( $email ) < 3 ) {
1478          return apply_filters( 'is_email', false, $email, 'email_too_short' );
1479      }
1480  
1481      // Test for an @ character after the first position
1482      if ( strpos( $email, '@', 1 ) === false ) {
1483          return apply_filters( 'is_email', false, $email, 'email_no_at' );
1484      }
1485  
1486      // Split out the local and domain parts
1487      list( $local, $domain ) = explode( '@', $email, 2 );
1488  
1489      // LOCAL PART
1490      // Test for invalid characters
1491      if ( !preg_match( '/^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]+$/', $local ) ) {
1492          return apply_filters( 'is_email', false, $email, 'local_invalid_chars' );
1493      }
1494  
1495      // DOMAIN PART
1496      // Test for sequences of periods
1497      if ( preg_match( '/\.{2,}/', $domain ) ) {
1498          return apply_filters( 'is_email', false, $email, 'domain_period_sequence' );
1499      }
1500  
1501      // Test for leading and trailing periods and whitespace
1502      if ( trim( $domain, " \t\n\r\0\x0B." ) !== $domain ) {
1503          return apply_filters( 'is_email', false, $email, 'domain_period_limits' );
1504      }
1505  
1506      // Split the domain into subs
1507      $subs = explode( '.', $domain );
1508  
1509      // Assume the domain will have at least two subs
1510      if ( 2 > count( $subs ) ) {
1511          return apply_filters( 'is_email', false, $email, 'domain_no_periods' );
1512      }
1513  
1514      // Loop through each sub
1515      foreach ( $subs as $sub ) {
1516          // Test for leading and trailing hyphens and whitespace
1517          if ( trim( $sub, " \t\n\r\0\x0B-" ) !== $sub ) {
1518              return apply_filters( 'is_email', false, $email, 'sub_hyphen_limits' );
1519          }
1520  
1521          // Test for invalid characters
1522          if ( !preg_match('/^[a-z0-9-]+$/i', $sub ) ) {
1523              return apply_filters( 'is_email', false, $email, 'sub_invalid_chars' );
1524          }
1525      }
1526  
1527      // DNS
1528      // Check the domain has a valid MX and A resource record
1529      if ( $check_dns && function_exists( 'checkdnsrr' ) && !( checkdnsrr( $domain . '.', 'MX' ) || checkdnsrr( $domain . '.', 'A' ) ) ) {
1530          return apply_filters( 'is_email', false, $email, 'dns_no_rr' );
1531      }
1532  
1533      // Congratulations your email made it!
1534      return apply_filters( 'is_email', $email, $email, null );
1535  }
1536  
1537  /**
1538   * Convert to ASCII from email subjects.
1539   *
1540   * @since 1.2.0
1541   * @usedby wp_mail() handles charsets in email subjects
1542   *
1543   * @param string $string Subject line
1544   * @return string Converted string to ASCII
1545   */
1546  function wp_iso_descrambler($string) {
1547      /* this may only work with iso-8859-1, I'm afraid */
1548      if (!preg_match('#\=\?(.+)\?Q\?(.+)\?\=#i', $string, $matches)) {
1549          return $string;
1550      } else {
1551          $subject = str_replace('_', ' ', $matches[2]);
1552          $subject = preg_replace_callback('#\=([0-9a-f]{2})#i', create_function('$match', 'return chr(hexdec(strtolower($match[1])));'), $subject);
1553          return $subject;
1554      }
1555  }
1556  
1557  /**
1558   * Returns a date in the GMT equivalent.
1559   *
1560   * Requires and returns a date in the Y-m-d H:i:s format. Simply subtracts the
1561   * value of the 'gmt_offset' option. Return format can be overridden using the
1562   * $format parameter
1563   *
1564   * @since 1.2.0
1565   *
1566   * @uses get_option() to retrieve the the value of 'gmt_offset'.
1567   * @param string $string The date to be converted.
1568   * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
1569   * @return string GMT version of the date provided.
1570   */
1571  function get_gmt_from_date($string, $format = 'Y-m-d H:i:s') {
1572      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);
1573      $string_time = gmmktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]);
1574      $string_gmt = gmdate($format, $string_time - get_option('gmt_offset') * 3600);
1575      return $string_gmt;
1576  }
1577  
1578  /**
1579   * Converts a GMT date into the correct format for the blog.
1580   *
1581   * Requires and returns in the Y-m-d H:i:s format. Simply adds the value of
1582   * gmt_offset.Return format can be overridden using the $format parameter
1583   *
1584   * @since 1.2.0
1585   *
1586   * @param string $string The date to be converted.
1587   * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
1588   * @return string Formatted date relative to the GMT offset.
1589   */
1590  function get_date_from_gmt($string, $format = 'Y-m-d H:i:s') {
1591      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);
1592      $string_time = gmmktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]);
1593      $string_localtime = gmdate($format, $string_time + get_option('gmt_offset')*3600);
1594      return $string_localtime;
1595  }
1596  
1597  /**
1598   * Computes an offset in seconds from an iso8601 timezone.
1599   *
1600   * @since 1.5.0
1601   *
1602   * @param string $timezone Either 'Z' for 0 offset or '±hhmm'.
1603   * @return int|float The offset in seconds.
1604   */
1605  function iso8601_timezone_to_offset($timezone) {
1606      // $timezone is either 'Z' or '[+|-]hhmm'
1607      if ($timezone == 'Z') {
1608          $offset = 0;
1609      } else {
1610          $sign    = (substr($timezone, 0, 1) == '+') ? 1 : -1;
1611          $hours   = intval(substr($timezone, 1, 2));
1612          $minutes = intval(substr($timezone, 3, 4)) / 60;
1613          $offset  = $sign * 3600 * ($hours + $minutes);
1614      }
1615      return $offset;
1616  }
1617  
1618  /**
1619   * Converts an iso8601 date to MySQL DateTime format used by post_date[_gmt].
1620   *
1621   * @since 1.5.0
1622   *
1623   * @param string $date_string Date and time in ISO 8601 format {@link http://en.wikipedia.org/wiki/ISO_8601}.
1624   * @param string $timezone Optional. If set to GMT returns the time minus gmt_offset. Default is 'user'.
1625   * @return string The date and time in MySQL DateTime format - Y-m-d H:i:s.
1626   */
1627  function iso8601_to_datetime($date_string, $timezone = 'user') {
1628      $timezone = strtolower($timezone);
1629  
1630      if ($timezone == 'gmt') {
1631  
1632          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);
1633  
1634          if (!empty($date_bits[7])) { // we have a timezone, so let's compute an offset
1635              $offset = iso8601_timezone_to_offset($date_bits[7]);
1636          } else { // we don't have a timezone, so we assume user local timezone (not server's!)
1637              $offset = 3600 * get_option('gmt_offset');
1638          }
1639  
1640          $timestamp = gmmktime($date_bits[4], $date_bits[5], $date_bits[6], $date_bits[2], $date_bits[3], $date_bits[1]);
1641          $timestamp -= $offset;
1642  
1643          return gmdate('Y-m-d H:i:s', $timestamp);
1644  
1645      } else if ($timezone == 'user') {
1646          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);
1647      }
1648  }
1649  
1650  /**
1651   * Adds a element attributes to open links in new windows.
1652   *
1653   * Comment text in popup windows should be filtered through this. Right now it's
1654   * a moderately dumb function, ideally it would detect whether a target or rel
1655   * attribute was already there and adjust its actions accordingly.
1656   *
1657   * @since 0.71
1658   *
1659   * @param string $text Content to replace links to open in a new window.
1660   * @return string Content that has filtered links.
1661   */
1662  function popuplinks($text) {
1663      $text = preg_replace('/<a (.+?)>/i', "<a $1 target='_blank' rel='external'>", $text);
1664      return $text;
1665  }
1666  
1667  /**
1668   * Strips out all characters that are not allowable in an email.
1669   *
1670   * @since 1.5.0
1671   *
1672   * @param string $email Email address to filter.
1673   * @return string Filtered email address.
1674   */
1675  function sanitize_email( $email ) {
1676      // Test for the minimum length the email can be
1677      if ( strlen( $email ) < 3 ) {
1678          return apply_filters( 'sanitize_email', '', $email, 'email_too_short' );
1679      }
1680  
1681      // Test for an @ character after the first position
1682      if ( strpos( $email, '@', 1 ) === false ) {
1683          return apply_filters( 'sanitize_email', '', $email, 'email_no_at' );
1684      }
1685  
1686      // Split out the local and domain parts
1687      list( $local, $domain ) = explode( '@', $email, 2 );
1688  
1689      // LOCAL PART
1690      // Test for invalid characters
1691      $local = preg_replace( '/[^a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]/', '', $local );
1692      if ( '' === $local ) {
1693          return apply_filters( 'sanitize_email', '', $email, 'local_invalid_chars' );
1694      }
1695  
1696      // DOMAIN PART
1697      // Test for sequences of periods
1698      $domain = preg_replace( '/\.{2,}/', '', $domain );
1699      if ( '' === $domain ) {
1700          return apply_filters( 'sanitize_email', '', $email, 'domain_period_sequence' );
1701      }
1702  
1703      // Test for leading and trailing periods and whitespace
1704      $domain = trim( $domain, " \t\n\r\0\x0B." );
1705      if ( '' === $domain ) {
1706          return apply_filters( 'sanitize_email', '', $email, 'domain_period_limits' );
1707      }
1708  
1709      // Split the domain into subs
1710      $subs = explode( '.', $domain );
1711  
1712      // Assume the domain will have at least two subs
1713      if ( 2 > count( $subs ) ) {
1714          return apply_filters( 'sanitize_email', '', $email, 'domain_no_periods' );
1715      }
1716  
1717      // Create an array that will contain valid subs
1718      $new_subs = array();
1719  
1720      // Loop through each sub
1721      foreach ( $subs as $sub ) {
1722          // Test for leading and trailing hyphens
1723          $sub = trim( $sub, " \t\n\r\0\x0B-" );
1724  
1725          // Test for invalid characters
1726          $sub = preg_replace( '/^[^a-z0-9-]+$/i', '', $sub );
1727  
1728          // If there's anything left, add it to the valid subs
1729          if ( '' !== $sub ) {
1730              $new_subs[] = $sub;
1731          }
1732      }
1733  
1734      // If there aren't 2 or more valid subs
1735      if ( 2 > count( $new_subs ) ) {
1736          return apply_filters( 'sanitize_email', '', $email, 'domain_no_valid_subs' );
1737      }
1738  
1739      // Join valid subs into the new domain
1740      $domain = join( '.', $new_subs );
1741  
1742      // Put the email back together
1743      $email = $local . '@' . $domain;
1744  
1745      // Congratulations your email made it!
1746      return apply_filters( 'sanitize_email', $email, $email, null );
1747  }
1748  
1749  /**
1750   * Determines the difference between two timestamps.
1751   *
1752   * The difference is returned in a human readable format such as "1 hour",
1753   * "5 mins", "2 days".
1754   *
1755   * @since 1.5.0
1756   *
1757   * @param int $from Unix timestamp from which the difference begins.
1758   * @param int $to Optional. Unix timestamp to end the time difference. Default becomes time() if not set.
1759   * @return string Human readable time difference.
1760   */
1761  function human_time_diff( $from, $to = '' ) {
1762      if ( empty($to) )
1763          $to = time();
1764      $diff = (int) abs($to - $from);
1765      if ($diff <= 3600) {
1766          $mins = round($diff / 60);
1767          if ($mins <= 1) {
1768              $mins = 1;
1769          }
1770          $since = sprintf(_n('%s min', '%s mins', $mins), $mins);
1771      } else if (($diff <= 86400) && ($diff > 3600)) {
1772          $hours = round($diff / 3600);
1773          if ($hours <= 1) {
1774              $hours = 1;
1775          }
1776          $since = sprintf(_n('%s hour', '%s hours', $hours), $hours);
1777      } elseif ($diff >= 86400) {
1778          $days = round($diff / 86400);
1779          if ($days <= 1) {
1780              $days = 1;
1781          }
1782          $since = sprintf(_n('%s day', '%s days', $days), $days);
1783      }
1784      return $since;
1785  }
1786  
1787  /**
1788   * Generates an excerpt from the content, if needed.
1789   *
1790   * The excerpt word amount will be 55 words and if the amount is greater than
1791   * that, then the string ' [...]' will be appended to the excerpt. If the string
1792   * is less than 55 words, then the content will be returned as is.
1793   *
1794   * The 55 word limit can be modified by plugins/themes using the excerpt_length filter
1795   * The ' [...]' string can be modified by plugins/themes using the excerpt_more filter
1796   *
1797   * @since 1.5.0
1798   *
1799   * @param string $text The excerpt. If set to empty an excerpt is generated.
1800   * @return string The excerpt.
1801   */
1802  function wp_trim_excerpt($text) {
1803      $raw_excerpt = $text;
1804      if ( '' == $text ) {
1805          $text = get_the_content('');
1806  
1807          $text = strip_shortcodes( $text );
1808  
1809          $text = apply_filters('the_content', $text);
1810          $text = str_replace(']]>', ']]&gt;', $text);
1811          $text = strip_tags($text);
1812          $excerpt_length = apply_filters('excerpt_length', 55);
1813          $excerpt_more = apply_filters('excerpt_more', ' ' . '[...]');
1814          $words = explode(' ', $text, $excerpt_length + 1);
1815          if (count($words) > $excerpt_length) {
1816              array_pop($words);
1817              $text = implode(' ', $words);
1818              $text = $text . $excerpt_more;
1819          }
1820      }
1821      return apply_filters('wp_trim_excerpt', $text, $raw_excerpt);
1822  }
1823  
1824  /**
1825   * Converts named entities into numbered entities.
1826   *
1827   * @since 1.5.1
1828   *
1829   * @param string $text The text within which entities will be converted.
1830   * @return string Text with converted entities.
1831   */
1832  function ent2ncr($text) {
1833      $to_ncr = array(
1834          '&quot;' => '&#34;',
1835          '&amp;' => '&#38;',
1836          '&frasl;' => '&#47;',
1837          '&lt;' => '&#60;',
1838          '&gt;' => '&#62;',
1839          '|' => '&#124;',
1840          '&nbsp;' => '&#160;',
1841          '&iexcl;' => '&#161;',
1842          '&cent;' => '&#162;',
1843          '&pound;' => '&#163;',
1844          '&curren;' => '&#164;',
1845          '&yen;' => '&#165;',
1846          '&brvbar;' => '&#166;',
1847          '&brkbar;' => '&#166;',
1848          '&sect;' => '&#167;',
1849          '&uml;' => '&#168;',
1850          '&die;' => '&#168;',
1851          '&copy;' => '&#169;',
1852          '&ordf;' => '&#170;',
1853          '&laquo;' => '&#171;',
1854          '&not;' => '&#172;',
1855          '&shy;' => '&#173;',
1856          '&reg;' => '&#174;',
1857          '&macr;' => '&#175;',
1858          '&hibar;' => '&#175;',
1859          '&deg;' => '&#176;',
1860          '&plusmn;' => '&#177;',
1861          '&sup2;' => '&#178;',
1862          '&sup3;' => '&#179;',
1863          '&acute;' => '&#180;',
1864          '&micro;' => '&#181;',
1865          '&para;' => '&#182;',
1866          '&middot;' => '&#183;',
1867          '&cedil;' => '&#184;',
1868          '&sup1;' => '&#185;',
1869          '&ordm;' => '&#186;',
1870          '&raquo;' => '&#187;',
1871          '&frac14;' => '&#188;',
1872          '&frac12;' => '&#189;',
1873          '&frac34;' => '&#190;',
1874          '&iquest;' => '&#191;',
1875          '&Agrave;' => '&#192;',
1876          '&Aacute;' => '&#193;',
1877          '&Acirc;' => '&#194;',
1878          '&Atilde;' => '&#195;',
1879          '&Auml;' => '&#196;',
1880          '&Aring;' => '&#197;',
1881          '&AElig;' => '&#198;',
1882          '&Ccedil;' => '&#199;',
1883          '&Egrave;' => '&#200;',
1884          '&Eacute;' => '&#201;',
1885          '&Ecirc;' => '&#202;',
1886          '&Euml;' => '&#203;',
1887          '&Igrave;' => '&#204;',
1888          '&Iacute;' => '&#205;',
1889          '&Icirc;' => '&#206;',
1890          '&Iuml;' => '&#207;',
1891          '&ETH;' => '&#208;',
1892          '&Ntilde;' => '&#209;',
1893          '&Ograve;' => '&#210;',
1894          '&Oacute;' => '&#211;',
1895          '&Ocirc;' => '&#212;',
1896          '&Otilde;' => '&#213;',
1897          '&Ouml;' => '&#214;',
1898          '&times;' => '&#215;',
1899          '&Oslash;' => '&#216;',
1900          '&Ugrave;' => '&#217;',
1901          '&Uacute;' => '&#218;',
1902          '&Ucirc;' => '&#219;',
1903          '&Uuml;' => '&#220;',
1904          '&Yacute;' => '&#221;',
1905          '&THORN;' => '&#222;',
1906          '&szlig;' => '&#223;',
1907          '&agrave;' => '&#224;',
1908          '&aacute;' => '&#225;',
1909          '&acirc;' => '&#226;',
1910          '&atilde;' => '&#227;',
1911          '&auml;' => '&#228;',
1912          '&aring;' => '&#229;',
1913          '&aelig;' => '&#230;',
1914          '&ccedil;' => '&#231;',
1915          '&egrave;' => '&#232;',
1916          '&eacute;' => '&#233;',
1917          '&ecirc;' => '&#234;',
1918          '&euml;' => '&#235;',
1919          '&igrave;' => '&#236;',
1920          '&iacute;' => '&#237;',
1921          '&icirc;' => '&#238;',
1922          '&iuml;' => '&#239;',
1923          '&eth;' => '&#240;',
1924          '&ntilde;' => '&#241;',
1925          '&ograve;' => '&#242;',
1926          '&oacute;' => '&#243;',
1927          '&ocirc;' => '&#244;',
1928          '&otilde;' => '&#245;',
1929          '&ouml;' => '&#246;',
1930          '&divide;' => '&#247;',
1931          '&oslash;' => '&#248;',
1932          '&ugrave;' => '&#249;',
1933          '&uacute;' => '&#250;',
1934          '&ucirc;' => '&#251;',
1935          '&uuml;' => '&#252;',
1936          '&yacute;' => '&#253;',
1937          '&thorn;' => '&#254;',
1938          '&yuml;' => '&#255;',
1939          '&OElig;' => '&#338;',
1940          '&oelig;' => '&#339;',
1941          '&Scaron;' => '&#352;',
1942          '&scaron;' => '&#353;',
1943          '&Yuml;' => '&#376;',
1944          '&fnof;' => '&#402;',
1945          '&circ;' => '&#710;',
1946          '&tilde;' => '&#732;',
1947          '&Alpha;' => '&#913;',
1948          '&Beta;' => '&#914;',
1949          '&Gamma;' => '&#915;',
1950          '&Delta;' => '&#916;',
1951          '&Epsilon;' => '&#917;',
1952          '&Zeta;' => '&#918;',
1953          '&Eta;' => '&#919;',
1954          '&Theta;' => '&#920;',
1955          '&Iota;' => '&#921;',
1956          '&Kappa;' => '&#922;',
1957          '&Lambda;' => '&#923;',
1958          '&Mu;' => '&#924;',
1959          '&Nu;' => '&#925;',
1960          '&Xi;' => '&#926;',
1961          '&Omicron;' => '&#927;',
1962          '&Pi;' => '&#928;',
1963          '&Rho;' => '&#929;',
1964          '&Sigma;' => '&#931;',
1965          '&Tau;' => '&#932;',
1966          '&Upsilon;' => '&#933;',
1967          '&Phi;' => '&#934;',
1968          '&Chi;' => '&#935;',
1969          '&Psi;' => '&#936;',
1970          '&Omega;' => '&#937;',
1971          '&alpha;' => '&#945;',
1972          '&beta;' => '&#946;',
1973          '&gamma;' => '&#947;',
1974          '&delta;' => '&#948;',
1975          '&epsilon;' => '&#949;',
1976          '&zeta;' => '&#950;',
1977          '&eta;' => '&#951;',
1978          '&theta;' => '&#952;',
1979          '&iota;' => '&#953;',
1980          '&kappa;' => '&#954;',
1981          '&lambda;' => '&#955;',
1982          '&mu;' => '&#956;',
1983          '&nu;' => '&#957;',
1984          '&xi;' => '&#958;',
1985          '&omicron;' => '&#959;',
1986          '&pi;' => '&#960;',
1987          '&rho;' => '&#961;',
1988          '&sigmaf;' => '&#962;',
1989          '&sigma;' => '&#963;',
1990          '&tau;' => '&#964;',
1991          '&upsilon;' => '&#965;',
1992          '&phi;' => '&#966;',
1993          '&chi;' => '&#967;',
1994          '&psi;' => '&#968;',
1995          '&omega;' => '&#969;',
1996          '&thetasym;' => '&#977;',
1997          '&upsih;' => '&#978;',
1998          '&piv;' => '&#982;',
1999          '&ensp;' => '&#8194;',
2000          '&emsp;' => '&#8195;',
2001          '&thinsp;' => '&#8201;',
2002          '&zwnj;' => '&#8204;',
2003          '&zwj;' => '&#8205;',
2004          '&lrm;' => '&#8206;',
2005          '&rlm;' => '&#8207;',
2006          '&ndash;' => '&#8211;',
2007          '&mdash;' => '&#8212;',
2008          '&lsquo;' => '&#8216;',
2009          '&rsquo;' => '&#8217;',
2010          '&sbquo;' => '&#8218;',
2011          '&ldquo;' => '&#8220;',
2012          '&rdquo;' => '&#8221;',
2013          '&bdquo;' => '&#8222;',
2014          '&dagger;' => '&#8224;',
2015          '&Dagger;' => '&#8225;',
2016          '&bull;' => '&#8226;',
2017          '&hellip;' => '&#8230;',
2018          '&permil;' => '&#8240;',
2019          '&prime;' => '&#8242;',
2020          '&Prime;' => '&#8243;',
2021          '&lsaquo;' => '&#8249;',
2022          '&rsaquo;' => '&#8250;',
2023          '&oline;' => '&#8254;',
2024          '&frasl;' => '&#8260;',
2025          '&euro;' => '&#8364;',
2026          '&image;' => '&#8465;',
2027          '&weierp;' => '&#8472;',
2028          '&real;' => '&#8476;',
2029          '&trade;' => '&#8482;',
2030          '&alefsym;' => '&#8501;',
2031          '&crarr;' => '&#8629;',
2032          '&lArr;' => '&#8656;',
2033          '&uArr;' => '&#8657;',
2034          '&rArr;' => '&#8658;',
2035          '&dArr;' => '&#8659;',
2036          '&hArr;' => '&#8660;',
2037          '&forall;' => '&#8704;',
2038          '&part;' => '&#8706;',
2039          '&exist;' => '&#8707;',
2040          '&empty;' => '&#8709;',
2041          '&nabla;' => '&#8711;',
2042          '&isin;' => '&#8712;',
2043          '&notin;' => '&#8713;',
2044          '&ni;' => '&#8715;',
2045          '&prod;' => '&#8719;',
2046          '&sum;' => '&#8721;',
2047          '&minus;' => '&#8722;',
2048          '&lowast;' => '&#8727;',
2049          '&radic;' => '&#8730;',
2050          '&prop;' => '&#8733;',
2051          '&infin;' => '&#8734;',
2052          '&ang;' => '&#8736;',
2053          '&and;' => '&#8743;',
2054          '&or;' => '&#8744;',
2055          '&cap;' => '&#8745;',
2056          '&cup;' => '&#8746;',
2057          '&int;' => '&#8747;',
2058          '&there4;' => '&#8756;',
2059          '&sim;' => '&#8764;',
2060          '&cong;' => '&#8773;',
2061          '&asymp;' => '&#8776;',
2062          '&ne;' => '&#8800;',
2063          '&equiv;' => '&#8801;',
2064          '&le;' => '&#8804;',
2065          '&ge;' => '&#8805;',
2066          '&sub;' => '&#8834;',
2067          '&sup;' => '&#8835;',
2068          '&nsub;' => '&#8836;',
2069          '&sube;' => '&#8838;',
2070          '&supe;' => '&#8839;',
2071          '&oplus;' => '&#8853;',
2072          '&otimes;' => '&#8855;',
2073          '&perp;' => '&#8869;',
2074          '&sdot;' => '&#8901;',
2075          '&lceil;' => '&#8968;',
2076          '&rceil;' => '&#8969;',
2077          '&lfloor;' => '&#8970;',
2078          '&rfloor;' => '&#8971;',
2079          '&lang;' => '&#9001;',
2080          '&rang;' => '&#9002;',
2081          '&larr;' => '&#8592;',
2082          '&uarr;' => '&#8593;',
2083          '&rarr;' => '&#8594;',
2084          '&darr;' => '&#8595;',
2085          '&harr;' => '&#8596;',
2086          '&loz;' => '&#9674;',
2087          '&spades;' => '&#9824;',
2088          '&clubs;' => '&#9827;',
2089          '&hearts;' => '&#9829;',
2090          '&diams;' => '&#9830;'
2091      );
2092  
2093      return str_replace( array_keys($to_ncr), array_values($to_ncr), $text );
2094  }
2095  
2096  /**
2097   * Formats text for the rich text editor.
2098   *
2099   * The filter 'richedit_pre' is applied here. If $text is empty the filter will
2100   * be applied to an empty string.
2101   *
2102   * @since 2.0.0
2103   *
2104   * @param string $text The text to be formatted.
2105   * @return string The formatted text after filter is applied.
2106   */
2107  function wp_richedit_pre($text) {
2108      // Filtering a blank results in an annoying <br />\n
2109      if ( empty($text) ) return apply_filters('richedit_pre', '');
2110  
2111      $output = convert_chars($text);
2112      $output = wpautop($output);
2113      $output = htmlspecialchars($output, ENT_NOQUOTES);
2114  
2115      return apply_filters('richedit_pre', $output);
2116  }
2117  
2118  /**
2119   * Formats text for the HTML editor.
2120   *
2121   * Unless $output is empty it will pass through htmlspecialchars before the
2122   * 'htmledit_pre' filter is applied.
2123   *
2124   * @since 2.5.0
2125   *
2126   * @param string $output The text to be formatted.
2127   * @return string Formatted text after filter applied.
2128   */
2129  function wp_htmledit_pre($output) {
2130      if ( !empty($output) )
2131          $output = htmlspecialchars($output, ENT_NOQUOTES); // convert only < > &
2132  
2133      return apply_filters('htmledit_pre', $output);
2134  }
2135  
2136  /**
2137   * Checks and cleans a URL.
2138   *
2139   * A number of characters are removed from the URL. If the URL is for displaying
2140   * (the default behaviour) amperstands are also replaced. The 'esc_url' filter
2141   * is applied to the returned cleaned URL.
2142   *
2143   * @since 1.2.0
2144   * @uses wp_kses_bad_protocol() To only permit protocols in the URL set
2145   *        via $protocols or the common ones set in the function.
2146   *
2147   * @param string $url The URL to be cleaned.
2148   * @param array $protocols Optional. An array of acceptable protocols.
2149   *        Defaults to 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet' if not set.
2150   * @param string $context Optional. How the URL will be used. Default is 'display'.
2151   * @return string The cleaned $url after the 'cleaned_url' filter is applied.
2152   */
2153  function clean_url( $url, $protocols = null, $context = 'display' ) {
2154      $original_url = $url;
2155  
2156      if ('' == $url) return $url;
2157      $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);
2158      $strip = array('%0d', '%0a', '%0D', '%0A');
2159      $url = _deep_replace($strip, $url);
2160      $url = str_replace(';//', '://', $url);
2161      /* If the URL doesn't appear to contain a scheme, we
2162       * presume it needs http:// appended (unless a relative
2163       * link starting with / or a php file).
2164       */
2165      if ( strpos($url, ':') === false &&
2166          substr( $url, 0, 1 ) != '/' && substr( $url, 0, 1 ) != '#' && !preg_match('/^[a-z0-9-]+?\.php/i', $url) )
2167          $url = 'http://' . $url;
2168  
2169      // Replace ampersands and single quotes only when displaying.
2170      if ( 'display' == $context ) {
2171          $url = preg_replace('/&([^#])(?![a-z]{2,8};)/', '&#038;$1', $url);
2172          $url = str_replace( "'", '&#039;', $url );
2173      }
2174  
2175      if ( !is_array($protocols) )
2176          $protocols = array('http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet');
2177      if ( wp_kses_bad_protocol( $url, $protocols ) != $url )
2178          return '';
2179  
2180      return apply_filters('clean_url', $url, $original_url, $context);
2181  }
2182  
2183  /**
2184   * Perform a deep string replace operation to ensure the values in $search are no longer present
2185   *
2186   * Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values
2187   * e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that
2188   * str_replace would return
2189   *
2190   * @since 2.8.1
2191   * @access private
2192   *
2193   * @param string|array $search
2194   * @param string $subject
2195   * @return string The processed string
2196   */
2197  function _deep_replace($search, $subject){
2198      $found = true;
2199      while($found) {
2200          $found = false;
2201          foreach( (array) $search as $val ) {
2202              while(strpos($subject, $val) !== false) {
2203                  $found = true;
2204                  $subject = str_replace($val, '', $subject);
2205              }
2206          }
2207      }
2208  
2209      return $subject;
2210  }
2211  
2212  /**
2213   * Escapes data for use in a MySQL query
2214   *
2215   * This is just a handy shortcut for $wpdb->escape(), for completeness' sake
2216   *
2217   * @since 2.8.0
2218   * @param string $sql Unescaped SQL data
2219   * @return string The cleaned $sql
2220   */
2221  function esc_sql( $sql ) {
2222      global $wpdb;
2223      return $wpdb->escape( $sql );
2224  }
2225  
2226  
2227  /**
2228   * Checks and cleans a URL.
2229   *
2230   * A number of characters are removed from the URL. If the URL is for displaying
2231   * (the default behaviour) amperstands are also replaced. The 'esc_url' filter
2232   * is applied to the returned cleaned URL.
2233   *
2234   * @since 2.8.0
2235   * @uses esc_url()
2236   * @uses wp_kses_bad_protocol() To only permit protocols in the URL set
2237   *        via $protocols or the common ones set in the function.
2238   *
2239   * @param string $url The URL to be cleaned.
2240   * @param array $protocols Optional. An array of acceptable protocols.
2241   *        Defaults to 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet' if not set.
2242   * @return string The cleaned $url after the 'cleaned_url' filter is applied.
2243   */
2244  function esc_url( $url, $protocols = null ) {
2245      return clean_url( $url, $protocols, 'display' );
2246  }
2247  
2248  /**
2249   * Performs esc_url() for database usage.
2250   *
2251   * @see esc_url()
2252   * @see esc_url()
2253   *
2254   * @since 2.8.0
2255   *
2256   * @param string $url The URL to be cleaned.
2257   * @param array $protocols An array of acceptable protocols.
2258   * @return string The cleaned URL.
2259   */
2260  function esc_url_raw( $url, $protocols = null ) {
2261      return clean_url( $url, $protocols, 'db' );
2262  }
2263  
2264  /**
2265   * Performs esc_url() for database or redirect usage.
2266   *
2267   * @see esc_url()
2268   * @deprecated 2.8.0
2269   *
2270   * @since 2.3.1
2271   *
2272   * @param string $url The URL to be cleaned.
2273   * @param array $protocols An array of acceptable protocols.
2274   * @return string The cleaned URL.
2275   */
2276  function sanitize_url( $url, $protocols = null ) {
2277      return clean_url( $url, $protocols, 'db' );
2278  }
2279  
2280  /**
2281   * Convert entities, while preserving already-encoded entities.
2282   *
2283   * @link http://www.php.net/htmlentities Borrowed from the PHP Manual user notes.
2284   *
2285   * @since 1.2.2
2286   *
2287   * @param string $myHTML The text to be converted.
2288   * @return string Converted text.
2289   */
2290  function htmlentities2($myHTML) {
2291      $translation_table = get_html_translation_table( HTML_ENTITIES, ENT_QUOTES );
2292      $translation_table[chr(38)] = '&';
2293      return preg_replace( "/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/", "&amp;", strtr($myHTML, $translation_table) );
2294  }
2295  
2296  /**
2297   * Escape single quotes, htmlspecialchar " < > &, and fix line endings.
2298   *
2299   * Escapes text strings for echoing in JS, both inline (for example in onclick="...")
2300   * and inside <script> tag. Note that the strings have to be in single quotes.
2301   * The filter 'js_escape' is also applied here.
2302   *
2303   * @since 2.8.0
2304   *
2305   * @param string $text The text to be escaped.
2306   * @return string Escaped text.
2307   */
2308  function esc_js( $text ) {
2309      $safe_text = wp_check_invalid_utf8( $text );
2310      $safe_text = _wp_specialchars( $safe_text, ENT_COMPAT );
2311      $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) );
2312      $safe_text = str_replace( "\r", '', $safe_text );
2313      $safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) );
2314      return apply_filters( 'js_escape', $safe_text, $text );
2315  }
2316  
2317  /**
2318   * Escape single quotes, specialchar double quotes, and fix line endings.
2319   *
2320   * The filter 'js_escape' is also applied by esc_js()
2321   *
2322   * @since 2.0.4
2323   *
2324   * @deprecated 2.8.0
2325   * @see esc_js()
2326   *
2327   * @param string $text The text to be escaped.
2328   * @return string Escaped text.
2329   */
2330  function js_escape( $text ) {
2331      return esc_js( $text );
2332  }
2333  
2334  /**
2335   * Escaping for HTML blocks.
2336   *
2337   * @since 2.8.0
2338   *
2339   * @param string $text
2340   * @return string
2341   */
2342  function esc_html( $text ) {
2343      $safe_text = wp_check_invalid_utf8( $text );
2344      $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
2345      return apply_filters( 'esc_html', $safe_text, $text );
2346  }
2347  
2348  /**
2349   * Escaping for HTML blocks
2350   * @deprecated 2.8.0
2351   * @see esc_html()
2352   */
2353  function wp_specialchars( $string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false ) {
2354      if ( func_num_args() > 1 ) { // Maintain backwards compat for people passing additional args
2355          $args = func_get_args();
2356          return call_user_func_array( '_wp_specialchars', $args );
2357      } else {
2358          return esc_html( $string );
2359      }
2360  }
2361  
2362  /**
2363   * Escaping for HTML attributes.
2364   *
2365   * @since 2.8.0
2366   *
2367   * @param string $text
2368   * @return string
2369   */
2370  function esc_attr( $text ) {
2371      $safe_text = wp_check_invalid_utf8( $text );
2372      $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
2373      return apply_filters( 'attribute_escape', $safe_text, $text );
2374  }
2375  
2376  /**
2377   * Escaping for HTML attributes.
2378   *
2379   * @since 2.0.6
2380   *
2381   * @deprecated 2.8.0
2382   * @see esc_attr()
2383   *
2384   * @param string $text
2385   * @return string
2386   */
2387  function attribute_escape( $text ) {
2388      return esc_attr( $text );
2389  }
2390  
2391  /**
2392   * Escape a HTML tag name.
2393   *
2394   * @since 2.5.0
2395   *
2396   * @param string $tag_name
2397   * @return string
2398   */
2399  function tag_escape($tag_name) {
2400      $safe_tag = strtolower( preg_replace('/[^a-zA-Z_:]/', '', $tag_name) );
2401      return apply_filters('tag_escape', $safe_tag, $tag_name);
2402  }
2403  
2404  /**
2405   * Escapes text for SQL LIKE special characters % and _.
2406   *
2407   * @since 2.5.0
2408   *
2409   * @param string $text The text to be escaped.
2410   * @return string text, safe for inclusion in LIKE query.
2411   */
2412  function like_escape($text) {
2413      return str_replace(array("%", "_"), array("\\%", "\\_"), $text);
2414  }
2415  
2416  /**
2417   * Convert full URL paths to absolute paths.
2418   *
2419   * Removes the http or https protocols and the domain. Keeps the path '/' at the
2420   * beginning, so it isn't a true relative link, but from the web root base.
2421   *
2422   * @since 2.1.0
2423   *
2424   * @param string $link Full URL path.
2425   * @return string Absolute path.
2426   */
2427  function wp_make_link_relative( $link ) {
2428      return preg_replace( '|https?://[^/]+(/.*)|i', '$1', $link );
2429  }
2430  
2431  /**
2432   * Sanitises various option values based on the nature of the option.
2433   *
2434   * This is basically a switch statement which will pass $value through a number
2435   * of functions depending on the $option.
2436   *
2437   * @since 2.0.5
2438   *
2439   * @param string $option The name of the option.
2440   * @param string $value The unsanitised value.
2441   * @return string Sanitized value.
2442   */
2443  function sanitize_option($option, $value) {
2444  
2445      switch ($option) {
2446          case 'admin_email':
2447              $value = sanitize_email($value);
2448              break;
2449  
2450          case 'thumbnail_size_w':
2451          case 'thumbnail_size_h':
2452          case 'medium_size_w':
2453          case 'medium_size_h':
2454          case 'large_size_w':
2455          case 'large_size_h':
2456          case 'embed_size_h':
2457          case 'default_post_edit_rows':
2458          case 'mailserver_port':
2459          case 'comment_max_links':
2460          case 'page_on_front':
2461          case 'rss_excerpt_length':
2462          case 'default_category':
2463          case 'default_email_category':
2464          case 'default_link_category':
2465          case 'close_comments_days_old':
2466          case 'comments_per_page':
2467          case 'thread_comments_depth':
2468          case 'users_can_register':
2469              $value = absint( $value );
2470              break;
2471  
2472          case 'embed_size_w':
2473              if ( '' !== $value )
2474                  $value = absint( $value );
2475              break;
2476  
2477          case 'posts_per_page':
2478          case 'posts_per_rss':
2479              $value = (int) $value;
2480              if ( empty($value) ) $value = 1;
2481              if ( $value < -1 ) $value = abs($value);
2482              break;
2483  
2484          case 'default_ping_status':
2485          case 'default_comment_status':
2486              // Options that if not there have 0 value but need to be something like "closed"
2487              if ( $value == '0' || $value == '')
2488                  $value = 'closed';
2489              break;
2490  
2491          case 'blogdescription':
2492          case 'blogname':
2493              $value = addslashes($value);
2494              $value = wp_filter_post_kses( $value ); // calls stripslashes then addslashes
2495              $value = stripslashes($value);
2496              $value = esc_html( $value );
2497              break;
2498  
2499          case 'blog_charset':
2500              $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value); // strips slashes
2501              break;
2502  
2503          case 'date_format':
2504          case 'time_format':
2505          case 'mailserver_url':
2506          case 'mailserver_login':
2507          case 'mailserver_pass':
2508          case 'ping_sites':
2509          case 'upload_path':
2510              $value = strip_tags($value);
2511              $value = addslashes($value);
2512              $value = wp_filter_kses($value); // calls stripslashes then addslashes
2513              $value = stripslashes($value);
2514              break;
2515  
2516          case 'gmt_offset':
2517              $value = preg_replace('/[^0-9:.-]/', '', $value); // strips slashes
2518              break;
2519  
2520          case 'siteurl':
2521          case 'home':
2522              $value = stripslashes($value);
2523              $value = esc_url($value);
2524              break;
2525          default :
2526              $value = apply_filters("sanitize_option_{$option}", $value, $option);
2527              break;
2528      }
2529  
2530      return $value;
2531  }
2532  
2533  /**
2534   * Parses a string into variables to be stored in an array.
2535   *
2536   * Uses {@link http://www.php.net/parse_str parse_str()} and stripslashes if
2537   * {@link http://www.php.net/magic_quotes magic_quotes_gpc} is on.
2538   *
2539   * @since 2.2.1
2540   * @uses apply_filters() for the 'wp_parse_str' filter.
2541   *
2542   * @param string $string The string to be parsed.
2543   * @param array $array Variables will be stored in this array.
2544   */
2545  function wp_parse_str( $string, &$array ) {
2546      parse_str( $string, $array );
2547      if ( get_magic_quotes_gpc() )
2548          $array = stripslashes_deep( $array );
2549      $array = apply_filters( 'wp_parse_str', $array );
2550  }
2551  
2552  /**
2553   * Convert lone less than signs.
2554   *
2555   * KSES already converts lone greater than signs.
2556   *
2557   * @uses wp_pre_kses_less_than_callback in the callback function.
2558   * @since 2.3.0
2559   *
2560   * @param string $text Text to be converted.
2561   * @return string Converted text.
2562   */
2563  function wp_pre_kses_less_than( $text ) {
2564      return preg_replace_callback('%<[^>]*?((?=<)|>|$)%', 'wp_pre_kses_less_than_callback', $text);
2565  }
2566  
2567  /**
2568   * Callback function used by preg_replace.
2569   *
2570   * @uses esc_html to format the $matches text.
2571   * @since 2.3.0
2572   *
2573   * @param array $matches Populated by matches to preg_replace.
2574   * @return string The text returned after esc_html if needed.
2575   */
2576  function wp_pre_kses_less_than_callback( $matches ) {
2577      if ( false === strpos($matches[0], '>') )
2578          return esc_html($matches[0]);
2579      return $matches[0];
2580  }
2581  
2582  /**
2583   * WordPress implementation of PHP sprintf() with filters.
2584   *
2585   * @since 2.5.0
2586   * @link http://www.php.net/sprintf
2587   *
2588   * @param string $pattern The string which formatted args are inserted.
2589   * @param mixed $args,... Arguments to be formatted into the $pattern string.
2590   * @return string The formatted string.
2591   */
2592  function wp_sprintf( $pattern ) {
2593      $args = func_get_args( );
2594      $len = strlen($pattern);
2595      $start = 0;
2596      $result = '';
2597      $arg_index = 0;
2598      while ( $len > $start ) {
2599          // Last character: append and break
2600          if ( strlen($pattern) - 1 == $start ) {
2601              $result .= substr($pattern, -1);
2602              break;
2603          }
2604  
2605          // Literal %: append and continue
2606          if ( substr($pattern, $start, 2) == '%%' ) {
2607              $start += 2;
2608              $result .= '%';
2609              continue;
2610          }
2611  
2612          // Get fragment before next %
2613          $end = strpos($pattern, '%', $start + 1);
2614          if ( false === $end )
2615              $end = $len;
2616          $fragment = substr($pattern, $start, $end - $start);
2617  
2618          // Fragment has a specifier
2619          if ( $pattern{$start} == '%' ) {
2620              // Find numbered arguments or take the next one in order
2621              if ( preg_match('/^%(\d+)\$/', $fragment, $matches) ) {
2622                  $arg = isset($args[$matches[1]]) ? $args[$matches[1]] : '';
2623                  $fragment = str_replace("%{$matches[1]}$", '%', $fragment);
2624              } else {
2625                  ++$arg_index;
2626                  $arg = isset($args[$arg_index]) ? $args[$arg_index] : '';
2627              }
2628  
2629              // Apply filters OR sprintf
2630              $_fragment = apply_filters( 'wp_sprintf', $fragment, $arg );
2631              if ( $_fragment != $fragment )
2632                  $fragment = $_fragment;
2633              else
2634                  $fragment = sprintf($fragment, strval($arg) );
2635          }
2636  
2637          // Append to result and move to next fragment
2638          $result .= $fragment;
2639          $start = $end;
2640      }
2641      return $result;
2642  }
2643  
2644  /**
2645   * Localize list items before the rest of the content.
2646   *
2647   * The '%l' must be at the first characters can then contain the rest of the
2648   * content. The list items will have ', ', ', and', and ' and ' added depending
2649   * on the amount of list items in the $args parameter.
2650   *
2651   * @since 2.5.0
2652   *
2653   * @param string $pattern Content containing '%l' at the beginning.
2654   * @param array $args List items to prepend to the content and replace '%l'.
2655   * @return string Localized list items and rest of the content.
2656   */
2657  function wp_sprintf_l($pattern, $args) {
2658      // Not a match
2659      if ( substr($pattern, 0, 2) != '%l' )
2660          return $pattern;
2661  
2662      // Nothing to work with
2663      if ( empty($args) )
2664          return '';
2665  
2666      // Translate and filter the delimiter set (avoid ampersands and entities here)
2667      $l = apply_filters('wp_sprintf_l', array(
2668          /* translators: used between list items, there is a space after the coma */
2669          'between'          => __(', '),
2670          /* translators: used between list items, there is a space after the and */
2671          'between_last_two' => __(', and '),
2672          /* translators: used between only two list items, there is a space after the and */
2673          'between_only_two' => __(' and '),
2674          ));
2675  
2676      $args = (array) $args;
2677      $result = array_shift($args);
2678      if ( count($args) == 1 )
2679          $result .= $l['between_only_two'] . array_shift($args);
2680      // Loop when more than two args
2681      $i = count($args);
2682      while ( $i ) {
2683          $arg = array_shift($args);
2684          $i--;
2685          if ( 0 == $i )
2686              $result .= $l['between_last_two'] . $arg;
2687          else
2688              $result .= $l['between'] . $arg;
2689      }
2690      return $result . substr($pattern, 2);
2691  }
2692  
2693  /**
2694   * Safely extracts not more than the first $count characters from html string.
2695   *
2696   * UTF-8, tags and entities safe prefix extraction. Entities inside will *NOT*
2697   * be counted as one character. For example &amp; will be counted as 4, &lt; as
2698   * 3, etc.
2699   *
2700   * @since 2.5.0
2701   *
2702   * @param integer $str String to get the excerpt from.
2703   * @param integer $count Maximum number of characters to take.
2704   * @return string The excerpt.
2705   */
2706  function wp_html_excerpt( $str, $count ) {
2707      $str = wp_strip_all_tags( $str, true );
2708      $str = mb_substr( $str, 0, $count );
2709      // remove part of an entity at the end
2710      $str = preg_replace( '/&[^;\s]{0,6}$/', '', $str );
2711      return $str;
2712  }
2713  
2714  /**
2715   * Add a Base url to relative links in passed content.
2716   *
2717   * By default it supports the 'src' and 'href' attributes. However this can be
2718   * changed via the 3rd param.
2719   *
2720   * @since 2.7.0
2721   *
2722   * @param string $content String to search for links in.
2723   * @param string $base The base URL to prefix to links.
2724   * @param array $attrs The attributes which should be processed.
2725   * @return string The processed content.
2726   */
2727  function links_add_base_url( $content, $base, $attrs = array('src', 'href') ) {
2728      $attrs = implode('|', (array)$attrs);
2729      return preg_replace_callback("!($attrs)=(['\"])(.+?)\\2!i",
2730              create_function('$m', 'return _links_add_base($m, "' . $base . '");'),
2731              $content);
2732  }
2733  
2734  /**
2735   * Callback to add a base url to relative links in passed content.
2736   *
2737   * @since 2.7.0
2738   * @access private
2739   *
2740   * @param string $m The matched link.
2741   * @param string $base The base URL to prefix to links.
2742   * @return string The processed link.
2743   */
2744  function _links_add_base($m, $base) {
2745      //1 = attribute name  2 = quotation mark  3 = URL
2746      return $m[1] . '=' . $m[2] .
2747          (strpos($m[3], 'http://') === false ?
2748              path_join($base, $m[3]) :
2749              $m[3])
2750          . $m[2];
2751  }
2752  
2753  /**
2754   * Adds a Target attribute to all links in passed content.
2755   *
2756   * This function by default only applies to <a> tags, however this can be
2757   * modified by the 3rd param.
2758   *
2759   * <b>NOTE:</b> Any current target attributed will be striped and replaced.
2760   *
2761   * @since 2.7.0
2762   *
2763   * @param string $content String to search for links in.
2764   * @param string $target The Target to add to the links.
2765   * @param array $tags An array of tags to apply to.
2766   * @return string The processed content.
2767   */
2768  function links_add_target( $content, $target = '_blank', $tags = array('a') ) {
2769      $tags = implode('|', (array)$tags);
2770      return preg_replace_callback("!<($tags)(.+?)>!i",
2771              create_function('$m', 'return _links_add_target($m, "' . $target . '");'),
2772              $content);
2773  }
2774  
2775  /**
2776   * Callback to add a target attribute to all links in passed content.
2777   *
2778   * @since 2.7.0
2779   * @access private
2780   *
2781   * @param string $m The matched link.
2782   * @param string $target The Target to add to the links.
2783   * @return string The processed link.
2784   */
2785  function _links_add_target( $m, $target ) {
2786      $tag = $m[1];
2787      $link = preg_replace('|(target=[\'"](.*?)[\'"])|i', '', $m[2]);
2788      return '<' . $tag . $link . ' target="' . $target . '">';
2789  }
2790  
2791  // normalize EOL characters and strip duplicate whitespace
2792  function normalize_whitespace( $str ) {
2793      $str  = trim($str);
2794      $str  = str_replace("\r", "\n", $str);
2795      $str  = preg_replace( array( '/\n+/', '/[ \t]+/' ), array( "\n", ' ' ), $str );
2796      return $str;
2797  }
2798  
2799  /**
2800   * Properly strip all HTML tags including script and style
2801   *
2802   * @since 2.9.0
2803   *
2804   * @param string $string String containing HTML tags
2805   * @param bool $remove_breaks optional Whether to remove left over line breaks and white space chars
2806   * @return string The processed string.
2807   */
2808  function wp_strip_all_tags($string, $remove_breaks = false) {
2809      $string = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $string );
2810      $string = strip_tags($string);
2811  
2812      if ( $remove_breaks )
2813          $string = preg_replace('/[\r\n\t ]+/', ' ', $string);
2814  
2815      return trim($string);
2816  }
2817  
2818  /**
2819   * Sanitize a string from user input or from the db
2820   *
2821   * check for invalid UTF-8,
2822   * Convert single < characters to entity,
2823   * strip all tags,
2824   * remove line breaks, tabs and extra whitre space,
2825   * strip octets.
2826   *
2827   * @since 2.9
2828   *
2829   * @param string $str
2830   * @return string
2831   */
2832  function sanitize_text_field($str) {
2833      $filtered = wp_check_invalid_utf8( $str );
2834  
2835      if ( strpos($filtered, '<') !== false ) {
2836          $filtered = wp_pre_kses_less_than( $filtered );
2837          $filtered = wp_strip_all_tags( $filtered, true );
2838      } else {
2839           $filtered = trim( preg_replace('/[\r\n\t ]+/', ' ', $filtered) );
2840      }
2841  
2842      $match = array();
2843      while ( preg_match('/%[a-f0-9]{2}/i', $filtered, $match) )
2844          $filtered = str_replace($match[0], '', $filtered);
2845  
2846      return apply_filters('sanitize_text_field', $filtered, $str);
2847  }
2848  
2849  ?>


Generated: Fri Jan 8 00:19:48 2010 Cross-referenced by PHPXref 0.7