PageRenderTime 126ms CodeModel.GetById 38ms app.highlight 72ms RepoModel.GetById 1ms app.codeStats 1ms

/wp-includes/formatting.php

https://github.com/yanickouellet/WordPress
PHP | 3393 lines | 2143 code | 268 blank | 982 comment | 277 complexity | 591d4f3358331c593515e14508b5dcd9 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   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 */
  29function wptexturize($text) {
  30	global $wp_cockneyreplace;
  31	static $static_characters, $static_replacements, $dynamic_characters, $dynamic_replacements,
  32		$default_no_texturize_tags, $default_no_texturize_shortcodes;
  33
  34	// No need to set up these static variables more than once
  35	if ( ! isset( $static_characters ) ) {
  36		/* translators: opening curly double quote */
  37		$opening_quote = _x( '&#8220;', 'opening curly double quote' );
  38		/* translators: closing curly double quote */
  39		$closing_quote = _x( '&#8221;', 'closing curly double quote' );
  40
  41		/* translators: apostrophe, for example in 'cause or can't */
  42		$apos = _x( '&#8217;', 'apostrophe' );
  43
  44		/* translators: prime, for example in 9' (nine feet) */
  45		$prime = _x( '&#8242;', 'prime' );
  46		/* translators: double prime, for example in 9" (nine inches) */
  47		$double_prime = _x( '&#8243;', 'double prime' );
  48
  49		/* translators: opening curly single quote */
  50		$opening_single_quote = _x( '&#8216;', 'opening curly single quote' );
  51		/* translators: closing curly single quote */
  52		$closing_single_quote = _x( '&#8217;', 'closing curly single quote' );
  53
  54		/* translators: en dash */
  55		$en_dash = _x( '&#8211;', 'en dash' );
  56		/* translators: em dash */
  57		$em_dash = _x( '&#8212;', 'em dash' );
  58
  59		$default_no_texturize_tags = array('pre', 'code', 'kbd', 'style', 'script', 'tt');
  60		$default_no_texturize_shortcodes = array('code');
  61
  62		// if a plugin has provided an autocorrect array, use it
  63		if ( isset($wp_cockneyreplace) ) {
  64			$cockney = array_keys($wp_cockneyreplace);
  65			$cockneyreplace = array_values($wp_cockneyreplace);
  66		} elseif ( "'" != $apos ) { // Only bother if we're doing a replacement.
  67			$cockney = array( "'tain't", "'twere", "'twas", "'tis", "'twill", "'til", "'bout", "'nuff", "'round", "'cause" );
  68			$cockneyreplace = array( $apos . "tain" . $apos . "t", $apos . "twere", $apos . "twas", $apos . "tis", $apos . "twill", $apos . "til", $apos . "bout", $apos . "nuff", $apos . "round", $apos . "cause" );
  69		} else {
  70			$cockney = $cockneyreplace = array();
  71		}
  72
  73		$static_characters = array_merge( array( '---', ' -- ', '--', ' - ', 'xn&#8211;', '...', '``', '\'\'', ' (tm)' ), $cockney );
  74		$static_replacements = array_merge( array( $em_dash, ' ' . $em_dash . ' ', $en_dash, ' ' . $en_dash . ' ', 'xn--', '&#8230;', $opening_quote, $closing_quote, ' &#8482;' ), $cockneyreplace );
  75
  76		$dynamic = array();
  77		if ( "'" != $apos ) {
  78			$dynamic[ '/\'(\d\d(?:&#8217;|\')?s)/' ] = $apos . '$1'; // '99's
  79			$dynamic[ '/\'(\d)/'                   ] = $apos . '$1'; // '99
  80		}
  81		if ( "'" != $opening_single_quote )
  82			$dynamic[ '/(\s|\A|[([{<]|")\'/'       ] = '$1' . $opening_single_quote; // opening single quote, even after (, {, <, [
  83		if ( '"' != $double_prime )
  84			$dynamic[ '/(\d)"/'                    ] = '$1' . $double_prime; // 9" (double prime)
  85		if ( "'" != $prime )
  86			$dynamic[ '/(\d)\'/'                   ] = '$1' . $prime; // 9' (prime)
  87		if ( "'" != $apos )
  88			$dynamic[ '/(\S)\'([^\'\s])/'          ] = '$1' . $apos . '$2'; // apostrophe in a word
  89		if ( '"' != $opening_quote )
  90			$dynamic[ '/(\s|\A|[([{<])"(?!\s)/'    ] = '$1' . $opening_quote . '$2'; // opening double quote, even after (, {, <, [
  91		if ( '"' != $closing_quote )
  92			$dynamic[ '/"(\s|\S|\Z)/'              ] = $closing_quote . '$1'; // closing double quote
  93		if ( "'" != $closing_single_quote )
  94			$dynamic[ '/\'([\s.]|\Z)/'             ] = $closing_single_quote . '$1'; // closing single quote
  95
  96		$dynamic[ '/\b(\d+)x(\d+)\b/'              ] = '$1&#215;$2'; // 9x9 (times)
  97
  98		$dynamic_characters = array_keys( $dynamic );
  99		$dynamic_replacements = array_values( $dynamic );
 100	}
 101
 102	// Transform into regexp sub-expression used in _wptexturize_pushpop_element
 103	// Must do this every time in case plugins use these filters in a context sensitive manner
 104	$no_texturize_tags = '(' . implode('|', apply_filters('no_texturize_tags', $default_no_texturize_tags) ) . ')';
 105	$no_texturize_shortcodes = '(' . implode('|', apply_filters('no_texturize_shortcodes', $default_no_texturize_shortcodes) ) . ')';
 106
 107	$no_texturize_tags_stack = array();
 108	$no_texturize_shortcodes_stack = array();
 109
 110	$textarr = preg_split('/(<.*>|\[.*\])/Us', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
 111
 112	foreach ( $textarr as &$curl ) {
 113		if ( empty( $curl ) )
 114			continue;
 115
 116		// Only call _wptexturize_pushpop_element if first char is correct tag opening
 117		$first = $curl[0];
 118		if ( '<' === $first ) {
 119			_wptexturize_pushpop_element($curl, $no_texturize_tags_stack, $no_texturize_tags, '<', '>');
 120		} elseif ( '[' === $first ) {
 121			_wptexturize_pushpop_element($curl, $no_texturize_shortcodes_stack, $no_texturize_shortcodes, '[', ']');
 122		} elseif ( empty($no_texturize_shortcodes_stack) && empty($no_texturize_tags_stack) ) {
 123			// This is not a tag, nor is the texturization disabled static strings
 124			$curl = str_replace($static_characters, $static_replacements, $curl);
 125			// regular expressions
 126			$curl = preg_replace($dynamic_characters, $dynamic_replacements, $curl);
 127		}
 128		$curl = preg_replace('/&([^#])(?![a-zA-Z1-4]{1,8};)/', '&#038;$1', $curl);
 129	}
 130	return implode( '', $textarr );
 131}
 132
 133/**
 134 * Search for disabled element tags. Push element to stack on tag open and pop
 135 * on tag close. Assumes first character of $text is tag opening.
 136 *
 137 * @since 2.9.0
 138 * @access private
 139 *
 140 * @param string $text Text to check. First character is assumed to be $opening
 141 * @param array $stack Array used as stack of opened tag elements
 142 * @param string $disabled_elements Tags to match against formatted as regexp sub-expression
 143 * @param string $opening Tag opening character, assumed to be 1 character long
 144 * @param string $closing Tag closing character
 145 */
 146function _wptexturize_pushpop_element($text, &$stack, $disabled_elements, $opening = '<', $closing = '>') {
 147	// Check if it is a closing tag -- otherwise assume opening tag
 148	if (strncmp($opening . '/', $text, 2)) {
 149		// Opening? Check $text+1 against disabled elements
 150		if (preg_match('/^' . $disabled_elements . '\b/', substr($text, 1), $matches)) {
 151			/*
 152			 * This disables texturize until we find a closing tag of our type
 153			 * (e.g. <pre>) even if there was invalid nesting before that
 154			 *
 155			 * Example: in the case <pre>sadsadasd</code>"baba"</pre>
 156			 *          "baba" won't be texturize
 157			 */
 158
 159			array_push($stack, $matches[1]);
 160		}
 161	} else {
 162		// Closing? Check $text+2 against disabled elements
 163		$c = preg_quote($closing, '/');
 164		if (preg_match('/^' . $disabled_elements . $c . '/', substr($text, 2), $matches)) {
 165			$last = array_pop($stack);
 166
 167			// Make sure it matches the opening tag
 168			if ($last != $matches[1])
 169				array_push($stack, $last);
 170		}
 171	}
 172}
 173
 174/**
 175 * Replaces double line-breaks with paragraph elements.
 176 *
 177 * A group of regex replaces used to identify text formatted with newlines and
 178 * replace double line-breaks with HTML paragraph tags. The remaining
 179 * line-breaks after conversion become <<br />> tags, unless $br is set to '0'
 180 * or 'false'.
 181 *
 182 * @since 0.71
 183 *
 184 * @param string $pee The text which has to be formatted.
 185 * @param bool $br Optional. If set, this will convert all remaining line-breaks after paragraphing. Default true.
 186 * @return string Text which has been converted into correct paragraph tags.
 187 */
 188function wpautop($pee, $br = true) {
 189	$pre_tags = array();
 190
 191	if ( trim($pee) === '' )
 192		return '';
 193
 194	$pee = $pee . "\n"; // just to make things a little easier, pad the end
 195
 196	if ( strpos($pee, '<pre') !== false ) {
 197		$pee_parts = explode( '</pre>', $pee );
 198		$last_pee = array_pop($pee_parts);
 199		$pee = '';
 200		$i = 0;
 201
 202		foreach ( $pee_parts as $pee_part ) {
 203			$start = strpos($pee_part, '<pre');
 204
 205			// Malformed html?
 206			if ( $start === false ) {
 207				$pee .= $pee_part;
 208				continue;
 209			}
 210
 211			$name = "<pre wp-pre-tag-$i></pre>";
 212			$pre_tags[$name] = substr( $pee_part, $start ) . '</pre>';
 213
 214			$pee .= substr( $pee_part, 0, $start ) . $name;
 215			$i++;
 216		}
 217
 218		$pee .= $last_pee;
 219	}
 220
 221	$pee = preg_replace('|<br />\s*<br />|', "\n\n", $pee);
 222	// Space things out a little
 223	$allblocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|option|form|map|area|blockquote|address|math|style|p|h[1-6]|hr|fieldset|noscript|legend|section|article|aside|hgroup|header|footer|nav|figure|figcaption|details|menu|summary)';
 224	$pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee);
 225	$pee = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $pee);
 226	$pee = str_replace(array("\r\n", "\r"), "\n", $pee); // cross-platform newlines
 227	if ( strpos($pee, '<object') !== false ) {
 228		$pee = preg_replace('|\s*<param([^>]*)>\s*|', "<param$1>", $pee); // no pee inside object/embed
 229		$pee = preg_replace('|\s*</embed>\s*|', '</embed>', $pee);
 230	}
 231	$pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates
 232	// make paragraphs, including one at the end
 233	$pees = preg_split('/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY);
 234	$pee = '';
 235	foreach ( $pees as $tinkle )
 236		$pee .= '<p>' . trim($tinkle, "\n") . "</p>\n";
 237	$pee = preg_replace('|<p>\s*</p>|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace
 238	$pee = preg_replace('!<p>([^<]+)</(div|address|form)>!', "<p>$1</p></$2>", $pee);
 239	$pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee); // don't pee all over a tag
 240	$pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee); // problem with nested lists
 241	$pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee);
 242	$pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee);
 243	$pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)!', "$1", $pee);
 244	$pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
 245	if ( $br ) {
 246		$pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', '_autop_newline_preservation_helper', $pee);
 247		$pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee); // optionally make line breaks
 248		$pee = str_replace('<WPPreserveNewline />', "\n", $pee);
 249	}
 250	$pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', "$1", $pee);
 251	$pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee);
 252	$pee = preg_replace( "|\n</p>$|", '</p>', $pee );
 253
 254	if ( !empty($pre_tags) )
 255		$pee = str_replace(array_keys($pre_tags), array_values($pre_tags), $pee);
 256
 257	return $pee;
 258}
 259
 260/**
 261 * Newline preservation help function for wpautop
 262 *
 263 * @since 3.1.0
 264 * @access private
 265 *
 266 * @param array $matches preg_replace_callback matches array
 267 * @return string
 268 */
 269function _autop_newline_preservation_helper( $matches ) {
 270	return str_replace("\n", "<WPPreserveNewline />", $matches[0]);
 271}
 272
 273/**
 274 * Don't auto-p wrap shortcodes that stand alone
 275 *
 276 * Ensures that shortcodes are not wrapped in <<p>>...<</p>>.
 277 *
 278 * @since 2.9.0
 279 *
 280 * @param string $pee The content.
 281 * @return string The filtered content.
 282 */
 283function shortcode_unautop( $pee ) {
 284	global $shortcode_tags;
 285
 286	if ( empty( $shortcode_tags ) || !is_array( $shortcode_tags ) ) {
 287		return $pee;
 288	}
 289
 290	$tagregexp = join( '|', array_map( 'preg_quote', array_keys( $shortcode_tags ) ) );
 291
 292	$pattern =
 293		  '/'
 294		. '<p>'                              // Opening paragraph
 295		. '\\s*+'                            // Optional leading whitespace
 296		. '('                                // 1: The shortcode
 297		.     '\\['                          // Opening bracket
 298		.     "($tagregexp)"                 // 2: Shortcode name
 299		.     '(?![\\w-])'                   // Not followed by word character or hyphen
 300		                                     // Unroll the loop: Inside the opening shortcode tag
 301		.     '[^\\]\\/]*'                   // Not a closing bracket or forward slash
 302		.     '(?:'
 303		.         '\\/(?!\\])'               // A forward slash not followed by a closing bracket
 304		.         '[^\\]\\/]*'               // Not a closing bracket or forward slash
 305		.     ')*?'
 306		.     '(?:'
 307		.         '\\/\\]'                   // Self closing tag and closing bracket
 308		.     '|'
 309		.         '\\]'                      // Closing bracket
 310		.         '(?:'                      // Unroll the loop: Optionally, anything between the opening and closing shortcode tags
 311		.             '[^\\[]*+'             // Not an opening bracket
 312		.             '(?:'
 313		.                 '\\[(?!\\/\\2\\])' // An opening bracket not followed by the closing shortcode tag
 314		.                 '[^\\[]*+'         // Not an opening bracket
 315		.             ')*+'
 316		.             '\\[\\/\\2\\]'         // Closing shortcode tag
 317		.         ')?'
 318		.     ')'
 319		. ')'
 320		. '\\s*+'                            // optional trailing whitespace
 321		. '<\\/p>'                           // closing paragraph
 322		. '/s';
 323
 324	return preg_replace( $pattern, '$1', $pee );
 325}
 326
 327/**
 328 * Checks to see if a string is utf8 encoded.
 329 *
 330 * NOTE: This function checks for 5-Byte sequences, UTF8
 331 *       has Bytes Sequences with a maximum length of 4.
 332 *
 333 * @author bmorel at ssi dot fr (modified)
 334 * @since 1.2.1
 335 *
 336 * @param string $str The string to be checked
 337 * @return bool True if $str fits a UTF-8 model, false otherwise.
 338 */
 339function seems_utf8($str) {
 340	$length = strlen($str);
 341	for ($i=0; $i < $length; $i++) {
 342		$c = ord($str[$i]);
 343		if ($c < 0x80) $n = 0; # 0bbbbbbb
 344		elseif (($c & 0xE0) == 0xC0) $n=1; # 110bbbbb
 345		elseif (($c & 0xF0) == 0xE0) $n=2; # 1110bbbb
 346		elseif (($c & 0xF8) == 0xF0) $n=3; # 11110bbb
 347		elseif (($c & 0xFC) == 0xF8) $n=4; # 111110bb
 348		elseif (($c & 0xFE) == 0xFC) $n=5; # 1111110b
 349		else return false; # Does not match any model
 350		for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
 351			if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))
 352				return false;
 353		}
 354	}
 355	return true;
 356}
 357
 358/**
 359 * Converts a number of special characters into their HTML entities.
 360 *
 361 * Specifically deals with: &, <, >, ", and '.
 362 *
 363 * $quote_style can be set to ENT_COMPAT to encode " to
 364 * &quot;, or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded.
 365 *
 366 * @since 1.2.2
 367 * @access private
 368 *
 369 * @param string $string The text which is to be encoded.
 370 * @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.
 371 * @param string $charset Optional. The character encoding of the string. Default is false.
 372 * @param boolean $double_encode Optional. Whether to encode existing html entities. Default is false.
 373 * @return string The encoded text with HTML entities.
 374 */
 375function _wp_specialchars( $string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false ) {
 376	$string = (string) $string;
 377
 378	if ( 0 === strlen( $string ) )
 379		return '';
 380
 381	// Don't bother if there are no specialchars - saves some processing
 382	if ( ! preg_match( '/[&<>"\']/', $string ) )
 383		return $string;
 384
 385	// Account for the previous behaviour of the function when the $quote_style is not an accepted value
 386	if ( empty( $quote_style ) )
 387		$quote_style = ENT_NOQUOTES;
 388	elseif ( ! in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) )
 389		$quote_style = ENT_QUOTES;
 390
 391	// Store the site charset as a static to avoid multiple calls to wp_load_alloptions()
 392	if ( ! $charset ) {
 393		static $_charset;
 394		if ( ! isset( $_charset ) ) {
 395			$alloptions = wp_load_alloptions();
 396			$_charset = isset( $alloptions['blog_charset'] ) ? $alloptions['blog_charset'] : '';
 397		}
 398		$charset = $_charset;
 399	}
 400
 401	if ( in_array( $charset, array( 'utf8', 'utf-8', 'UTF8' ) ) )
 402		$charset = 'UTF-8';
 403
 404	$_quote_style = $quote_style;
 405
 406	if ( $quote_style === 'double' ) {
 407		$quote_style = ENT_COMPAT;
 408		$_quote_style = ENT_COMPAT;
 409	} elseif ( $quote_style === 'single' ) {
 410		$quote_style = ENT_NOQUOTES;
 411	}
 412
 413	// Handle double encoding ourselves
 414	if ( $double_encode ) {
 415		$string = @htmlspecialchars( $string, $quote_style, $charset );
 416	} else {
 417		// Decode &amp; into &
 418		$string = wp_specialchars_decode( $string, $_quote_style );
 419
 420		// Guarantee every &entity; is valid or re-encode the &
 421		$string = wp_kses_normalize_entities( $string );
 422
 423		// Now re-encode everything except &entity;
 424		$string = preg_split( '/(&#?x?[0-9a-z]+;)/i', $string, -1, PREG_SPLIT_DELIM_CAPTURE );
 425
 426		for ( $i = 0; $i < count( $string ); $i += 2 )
 427			$string[$i] = @htmlspecialchars( $string[$i], $quote_style, $charset );
 428
 429		$string = implode( '', $string );
 430	}
 431
 432	// Backwards compatibility
 433	if ( 'single' === $_quote_style )
 434		$string = str_replace( "'", '&#039;', $string );
 435
 436	return $string;
 437}
 438
 439/**
 440 * Converts a number of HTML entities into their special characters.
 441 *
 442 * Specifically deals with: &, <, >, ", and '.
 443 *
 444 * $quote_style can be set to ENT_COMPAT to decode " entities,
 445 * or ENT_QUOTES to do both " and '. Default is ENT_NOQUOTES where no quotes are decoded.
 446 *
 447 * @since 2.8.0
 448 *
 449 * @param string $string The text which is to be decoded.
 450 * @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.
 451 * @return string The decoded text without HTML entities.
 452 */
 453function wp_specialchars_decode( $string, $quote_style = ENT_NOQUOTES ) {
 454	$string = (string) $string;
 455
 456	if ( 0 === strlen( $string ) ) {
 457		return '';
 458	}
 459
 460	// Don't bother if there are no entities - saves a lot of processing
 461	if ( strpos( $string, '&' ) === false ) {
 462		return $string;
 463	}
 464
 465	// Match the previous behaviour of _wp_specialchars() when the $quote_style is not an accepted value
 466	if ( empty( $quote_style ) ) {
 467		$quote_style = ENT_NOQUOTES;
 468	} elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
 469		$quote_style = ENT_QUOTES;
 470	}
 471
 472	// More complete than get_html_translation_table( HTML_SPECIALCHARS )
 473	$single = array( '&#039;'  => '\'', '&#x27;' => '\'' );
 474	$single_preg = array( '/&#0*39;/'  => '&#039;', '/&#x0*27;/i' => '&#x27;' );
 475	$double = array( '&quot;' => '"', '&#034;'  => '"', '&#x22;' => '"' );
 476	$double_preg = array( '/&#0*34;/'  => '&#034;', '/&#x0*22;/i' => '&#x22;' );
 477	$others = array( '&lt;'   => '<', '&#060;'  => '<', '&gt;'   => '>', '&#062;'  => '>', '&amp;'  => '&', '&#038;'  => '&', '&#x26;' => '&' );
 478	$others_preg = array( '/&#0*60;/'  => '&#060;', '/&#0*62;/'  => '&#062;', '/&#0*38;/'  => '&#038;', '/&#x0*26;/i' => '&#x26;' );
 479
 480	if ( $quote_style === ENT_QUOTES ) {
 481		$translation = array_merge( $single, $double, $others );
 482		$translation_preg = array_merge( $single_preg, $double_preg, $others_preg );
 483	} elseif ( $quote_style === ENT_COMPAT || $quote_style === 'double' ) {
 484		$translation = array_merge( $double, $others );
 485		$translation_preg = array_merge( $double_preg, $others_preg );
 486	} elseif ( $quote_style === 'single' ) {
 487		$translation = array_merge( $single, $others );
 488		$translation_preg = array_merge( $single_preg, $others_preg );
 489	} elseif ( $quote_style === ENT_NOQUOTES ) {
 490		$translation = $others;
 491		$translation_preg = $others_preg;
 492	}
 493
 494	// Remove zero padding on numeric entities
 495	$string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string );
 496
 497	// Replace characters according to translation table
 498	return strtr( $string, $translation );
 499}
 500
 501/**
 502 * Checks for invalid UTF8 in a string.
 503 *
 504 * @since 2.8.0
 505 *
 506 * @param string $string The text which is to be checked.
 507 * @param boolean $strip Optional. Whether to attempt to strip out invalid UTF8. Default is false.
 508 * @return string The checked text.
 509 */
 510function wp_check_invalid_utf8( $string, $strip = false ) {
 511	$string = (string) $string;
 512
 513	if ( 0 === strlen( $string ) ) {
 514		return '';
 515	}
 516
 517	// Store the site charset as a static to avoid multiple calls to get_option()
 518	static $is_utf8;
 519	if ( !isset( $is_utf8 ) ) {
 520		$is_utf8 = in_array( get_option( 'blog_charset' ), array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ) );
 521	}
 522	if ( !$is_utf8 ) {
 523		return $string;
 524	}
 525
 526	// Check for support for utf8 in the installed PCRE library once and store the result in a static
 527	static $utf8_pcre;
 528	if ( !isset( $utf8_pcre ) ) {
 529		$utf8_pcre = @preg_match( '/^./u', 'a' );
 530	}
 531	// We can't demand utf8 in the PCRE installation, so just return the string in those cases
 532	if ( !$utf8_pcre ) {
 533		return $string;
 534	}
 535
 536	// preg_match fails when it encounters invalid UTF8 in $string
 537	if ( 1 === @preg_match( '/^./us', $string ) ) {
 538		return $string;
 539	}
 540
 541	// Attempt to strip the bad chars if requested (not recommended)
 542	if ( $strip && function_exists( 'iconv' ) ) {
 543		return iconv( 'utf-8', 'utf-8', $string );
 544	}
 545
 546	return '';
 547}
 548
 549/**
 550 * Encode the Unicode values to be used in the URI.
 551 *
 552 * @since 1.5.0
 553 *
 554 * @param string $utf8_string
 555 * @param int $length Max length of the string
 556 * @return string String with Unicode encoded for URI.
 557 */
 558function utf8_uri_encode( $utf8_string, $length = 0 ) {
 559	$unicode = '';
 560	$values = array();
 561	$num_octets = 1;
 562	$unicode_length = 0;
 563
 564	$string_length = strlen( $utf8_string );
 565	for ($i = 0; $i < $string_length; $i++ ) {
 566
 567		$value = ord( $utf8_string[ $i ] );
 568
 569		if ( $value < 128 ) {
 570			if ( $length && ( $unicode_length >= $length ) )
 571				break;
 572			$unicode .= chr($value);
 573			$unicode_length++;
 574		} else {
 575			if ( count( $values ) == 0 ) $num_octets = ( $value < 224 ) ? 2 : 3;
 576
 577			$values[] = $value;
 578
 579			if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length )
 580				break;
 581			if ( count( $values ) == $num_octets ) {
 582				if ($num_octets == 3) {
 583					$unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]) . '%' . dechex($values[2]);
 584					$unicode_length += 9;
 585				} else {
 586					$unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]);
 587					$unicode_length += 6;
 588				}
 589
 590				$values = array();
 591				$num_octets = 1;
 592			}
 593		}
 594	}
 595
 596	return $unicode;
 597}
 598
 599/**
 600 * Converts all accent characters to ASCII characters.
 601 *
 602 * If there are no accent characters, then the string given is just returned.
 603 *
 604 * @since 1.2.1
 605 *
 606 * @param string $string Text that might have accent characters
 607 * @return string Filtered string with replaced "nice" characters.
 608 */
 609function remove_accents($string) {
 610	if ( !preg_match('/[\x80-\xff]/', $string) )
 611		return $string;
 612
 613	if (seems_utf8($string)) {
 614		$chars = array(
 615		// Decompositions for Latin-1 Supplement
 616		chr(194).chr(170) => 'a', chr(194).chr(186) => 'o',
 617		chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
 618		chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
 619		chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
 620		chr(195).chr(134) => 'AE',chr(195).chr(135) => 'C',
 621		chr(195).chr(136) => 'E', chr(195).chr(137) => 'E',
 622		chr(195).chr(138) => 'E', chr(195).chr(139) => 'E',
 623		chr(195).chr(140) => 'I', chr(195).chr(141) => 'I',
 624		chr(195).chr(142) => 'I', chr(195).chr(143) => 'I',
 625		chr(195).chr(144) => 'D', chr(195).chr(145) => 'N',
 626		chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
 627		chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
 628		chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
 629		chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
 630		chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
 631		chr(195).chr(158) => 'TH',chr(195).chr(159) => 's',
 632		chr(195).chr(160) => 'a', chr(195).chr(161) => 'a',
 633		chr(195).chr(162) => 'a', chr(195).chr(163) => 'a',
 634		chr(195).chr(164) => 'a', chr(195).chr(165) => 'a',
 635		chr(195).chr(166) => 'ae',chr(195).chr(167) => 'c',
 636		chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
 637		chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
 638		chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
 639		chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
 640		chr(195).chr(176) => 'd', chr(195).chr(177) => 'n',
 641		chr(195).chr(178) => 'o', chr(195).chr(179) => 'o',
 642		chr(195).chr(180) => 'o', chr(195).chr(181) => 'o',
 643		chr(195).chr(182) => 'o', chr(195).chr(184) => 'o',
 644		chr(195).chr(185) => 'u', chr(195).chr(186) => 'u',
 645		chr(195).chr(187) => 'u', chr(195).chr(188) => 'u',
 646		chr(195).chr(189) => 'y', chr(195).chr(190) => 'th',
 647		chr(195).chr(191) => 'y', chr(195).chr(152) => 'O',
 648		// Decompositions for Latin Extended-A
 649		chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
 650		chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
 651		chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
 652		chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
 653		chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
 654		chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
 655		chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
 656		chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
 657		chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
 658		chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
 659		chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
 660		chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
 661		chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
 662		chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
 663		chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
 664		chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
 665		chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
 666		chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
 667		chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
 668		chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
 669		chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
 670		chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
 671		chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
 672		chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
 673		chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
 674		chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
 675		chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
 676		chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
 677		chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
 678		chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
 679		chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
 680		chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
 681		chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
 682		chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
 683		chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
 684		chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
 685		chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
 686		chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
 687		chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
 688		chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
 689		chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
 690		chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
 691		chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
 692		chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
 693		chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
 694		chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
 695		chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
 696		chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
 697		chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
 698		chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
 699		chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
 700		chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
 701		chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
 702		chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
 703		chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
 704		chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
 705		chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
 706		chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
 707		chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
 708		chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
 709		chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
 710		chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
 711		chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
 712		chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
 713		// Decompositions for Latin Extended-B
 714		chr(200).chr(152) => 'S', chr(200).chr(153) => 's',
 715		chr(200).chr(154) => 'T', chr(200).chr(155) => 't',
 716		// Euro Sign
 717		chr(226).chr(130).chr(172) => 'E',
 718		// GBP (Pound) Sign
 719		chr(194).chr(163) => '',
 720		// Vowels with diacritic (Vietnamese)
 721		// unmarked
 722		chr(198).chr(160) => 'O', chr(198).chr(161) => 'o',
 723		chr(198).chr(175) => 'U', chr(198).chr(176) => 'u',
 724		// grave accent
 725		chr(225).chr(186).chr(166) => 'A', chr(225).chr(186).chr(167) => 'a',
 726		chr(225).chr(186).chr(176) => 'A', chr(225).chr(186).chr(177) => 'a',
 727		chr(225).chr(187).chr(128) => 'E', chr(225).chr(187).chr(129) => 'e',
 728		chr(225).chr(187).chr(146) => 'O', chr(225).chr(187).chr(147) => 'o',
 729		chr(225).chr(187).chr(156) => 'O', chr(225).chr(187).chr(157) => 'o',
 730		chr(225).chr(187).chr(170) => 'U', chr(225).chr(187).chr(171) => 'u',
 731		chr(225).chr(187).chr(178) => 'Y', chr(225).chr(187).chr(179) => 'y',
 732		// hook
 733		chr(225).chr(186).chr(162) => 'A', chr(225).chr(186).chr(163) => 'a',
 734		chr(225).chr(186).chr(168) => 'A', chr(225).chr(186).chr(169) => 'a',
 735		chr(225).chr(186).chr(178) => 'A', chr(225).chr(186).chr(179) => 'a',
 736		chr(225).chr(186).chr(186) => 'E', chr(225).chr(186).chr(187) => 'e',
 737		chr(225).chr(187).chr(130) => 'E', chr(225).chr(187).chr(131) => 'e',
 738		chr(225).chr(187).chr(136) => 'I', chr(225).chr(187).chr(137) => 'i',
 739		chr(225).chr(187).chr(142) => 'O', chr(225).chr(187).chr(143) => 'o',
 740		chr(225).chr(187).chr(148) => 'O', chr(225).chr(187).chr(149) => 'o',
 741		chr(225).chr(187).chr(158) => 'O', chr(225).chr(187).chr(159) => 'o',
 742		chr(225).chr(187).chr(166) => 'U', chr(225).chr(187).chr(167) => 'u',
 743		chr(225).chr(187).chr(172) => 'U', chr(225).chr(187).chr(173) => 'u',
 744		chr(225).chr(187).chr(182) => 'Y', chr(225).chr(187).chr(183) => 'y',
 745		// tilde
 746		chr(225).chr(186).chr(170) => 'A', chr(225).chr(186).chr(171) => 'a',
 747		chr(225).chr(186).chr(180) => 'A', chr(225).chr(186).chr(181) => 'a',
 748		chr(225).chr(186).chr(188) => 'E', chr(225).chr(186).chr(189) => 'e',
 749		chr(225).chr(187).chr(132) => 'E', chr(225).chr(187).chr(133) => 'e',
 750		chr(225).chr(187).chr(150) => 'O', chr(225).chr(187).chr(151) => 'o',
 751		chr(225).chr(187).chr(160) => 'O', chr(225).chr(187).chr(161) => 'o',
 752		chr(225).chr(187).chr(174) => 'U', chr(225).chr(187).chr(175) => 'u',
 753		chr(225).chr(187).chr(184) => 'Y', chr(225).chr(187).chr(185) => 'y',
 754		// acute accent
 755		chr(225).chr(186).chr(164) => 'A', chr(225).chr(186).chr(165) => 'a',
 756		chr(225).chr(186).chr(174) => 'A', chr(225).chr(186).chr(175) => 'a',
 757		chr(225).chr(186).chr(190) => 'E', chr(225).chr(186).chr(191) => 'e',
 758		chr(225).chr(187).chr(144) => 'O', chr(225).chr(187).chr(145) => 'o',
 759		chr(225).chr(187).chr(154) => 'O', chr(225).chr(187).chr(155) => 'o',
 760		chr(225).chr(187).chr(168) => 'U', chr(225).chr(187).chr(169) => 'u',
 761		// dot below
 762		chr(225).chr(186).chr(160) => 'A', chr(225).chr(186).chr(161) => 'a',
 763		chr(225).chr(186).chr(172) => 'A', chr(225).chr(186).chr(173) => 'a',
 764		chr(225).chr(186).chr(182) => 'A', chr(225).chr(186).chr(183) => 'a',
 765		chr(225).chr(186).chr(184) => 'E', chr(225).chr(186).chr(185) => 'e',
 766		chr(225).chr(187).chr(134) => 'E', chr(225).chr(187).chr(135) => 'e',
 767		chr(225).chr(187).chr(138) => 'I', chr(225).chr(187).chr(139) => 'i',
 768		chr(225).chr(187).chr(140) => 'O', chr(225).chr(187).chr(141) => 'o',
 769		chr(225).chr(187).chr(152) => 'O', chr(225).chr(187).chr(153) => 'o',
 770		chr(225).chr(187).chr(162) => 'O', chr(225).chr(187).chr(163) => 'o',
 771		chr(225).chr(187).chr(164) => 'U', chr(225).chr(187).chr(165) => 'u',
 772		chr(225).chr(187).chr(176) => 'U', chr(225).chr(187).chr(177) => 'u',
 773		chr(225).chr(187).chr(180) => 'Y', chr(225).chr(187).chr(181) => 'y',
 774		// Vowels with diacritic (Chinese, Hanyu Pinyin)
 775		chr(201).chr(145) => 'a',
 776		// macron
 777		chr(199).chr(149) => 'U', chr(199).chr(150) => 'u',
 778		// acute accent
 779		chr(199).chr(151) => 'U', chr(199).chr(152) => 'u',
 780		// caron
 781		chr(199).chr(141) => 'A', chr(199).chr(142) => 'a',
 782		chr(199).chr(143) => 'I', chr(199).chr(144) => 'i',
 783		chr(199).chr(145) => 'O', chr(199).chr(146) => 'o',
 784		chr(199).chr(147) => 'U', chr(199).chr(148) => 'u',
 785		chr(199).chr(153) => 'U', chr(199).chr(154) => 'u',
 786		// grave accent
 787		chr(199).chr(155) => 'U', chr(199).chr(156) => 'u',
 788		);
 789
 790		// Used for locale-specific rules
 791		$locale = get_locale();
 792
 793		if ( 'de_DE' == $locale ) {
 794			$chars[ chr(195).chr(132) ] = 'Ae';
 795			$chars[ chr(195).chr(164) ] = 'ae';
 796			$chars[ chr(195).chr(150) ] = 'Oe';
 797			$chars[ chr(195).chr(182) ] = 'oe';
 798			$chars[ chr(195).chr(156) ] = 'Ue';
 799			$chars[ chr(195).chr(188) ] = 'ue';
 800			$chars[ chr(195).chr(159) ] = 'ss';
 801		}
 802
 803		$string = strtr($string, $chars);
 804	} else {
 805		// Assume ISO-8859-1 if not UTF-8
 806		$chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
 807			.chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
 808			.chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
 809			.chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
 810			.chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
 811			.chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
 812			.chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
 813			.chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
 814			.chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
 815			.chr(252).chr(253).chr(255);
 816
 817		$chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";
 818
 819		$string = strtr($string, $chars['in'], $chars['out']);
 820		$double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
 821		$double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
 822		$string = str_replace($double_chars['in'], $double_chars['out'], $string);
 823	}
 824
 825	return $string;
 826}
 827
 828/**
 829 * Sanitizes a filename, replacing whitespace with dashes.
 830 *
 831 * Removes special characters that are illegal in filenames on certain
 832 * operating systems and special characters requiring special escaping
 833 * to manipulate at the command line. Replaces spaces and consecutive
 834 * dashes with a single dash. Trims period, dash and underscore from beginning
 835 * and end of filename.
 836 *
 837 * @since 2.1.0
 838 *
 839 * @param string $filename The filename to be sanitized
 840 * @return string The sanitized filename
 841 */
 842function sanitize_file_name( $filename ) {
 843	$filename_raw = $filename;
 844	$special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", chr(0));
 845	$special_chars = apply_filters('sanitize_file_name_chars', $special_chars, $filename_raw);
 846	$filename = str_replace($special_chars, '', $filename);
 847	$filename = preg_replace('/[\s-]+/', '-', $filename);
 848	$filename = trim($filename, '.-_');
 849
 850	// Split the filename into a base and extension[s]
 851	$parts = explode('.', $filename);
 852
 853	// Return if only one extension
 854	if ( count($parts) <= 2 )
 855		return apply_filters('sanitize_file_name', $filename, $filename_raw);
 856
 857	// Process multiple extensions
 858	$filename = array_shift($parts);
 859	$extension = array_pop($parts);
 860	$mimes = get_allowed_mime_types();
 861
 862	// Loop over any intermediate extensions. Munge them with a trailing underscore if they are a 2 - 5 character
 863	// long alpha string not in the extension whitelist.
 864	foreach ( (array) $parts as $part) {
 865		$filename .= '.' . $part;
 866
 867		if ( preg_match("/^[a-zA-Z]{2,5}\d?$/", $part) ) {
 868			$allowed = false;
 869			foreach ( $mimes as $ext_preg => $mime_match ) {
 870				$ext_preg = '!^(' . $ext_preg . ')$!i';
 871				if ( preg_match( $ext_preg, $part ) ) {
 872					$allowed = true;
 873					break;
 874				}
 875			}
 876			if ( !$allowed )
 877				$filename .= '_';
 878		}
 879	}
 880	$filename .= '.' . $extension;
 881
 882	return apply_filters('sanitize_file_name', $filename, $filename_raw);
 883}
 884
 885/**
 886 * Sanitizes a username, stripping out unsafe characters.
 887 *
 888 * Removes tags, octets, entities, and if strict is enabled, will only keep
 889 * alphanumeric, _, space, ., -, @. After sanitizing, it passes the username,
 890 * raw username (the username in the parameter), and the value of $strict as
 891 * parameters for the 'sanitize_user' filter.
 892 *
 893 * @since 2.0.0
 894 * @uses apply_filters() Calls 'sanitize_user' hook on username, raw username,
 895 *		and $strict parameter.
 896 *
 897 * @param string $username The username to be sanitized.
 898 * @param bool $strict If set limits $username to specific characters. Default false.
 899 * @return string The sanitized username, after passing through filters.
 900 */
 901function sanitize_user( $username, $strict = false ) {
 902	$raw_username = $username;
 903	$username = wp_strip_all_tags( $username );
 904	$username = remove_accents( $username );
 905	// Kill octets
 906	$username = preg_replace( '|%([a-fA-F0-9][a-fA-F0-9])|', '', $username );
 907	$username = preg_replace( '/&.+?;/', '', $username ); // Kill entities
 908
 909	// If strict, reduce to ASCII for max portability.
 910	if ( $strict )
 911		$username = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $username );
 912
 913	$username = trim( $username );
 914	// Consolidate contiguous whitespace
 915	$username = preg_replace( '|\s+|', ' ', $username );
 916
 917	return apply_filters( 'sanitize_user', $username, $raw_username, $strict );
 918}
 919
 920/**
 921 * Sanitizes a string key.
 922 *
 923 * Keys are used as internal identifiers. Lowercase alphanumeric characters, dashes and underscores are allowed.
 924 *
 925 * @since 3.0.0
 926 *
 927 * @param string $key String key
 928 * @return string Sanitized key
 929 */
 930function sanitize_key( $key ) {
 931	$raw_key = $key;
 932	$key = strtolower( $key );
 933	$key = preg_replace( '/[^a-z0-9_\-]/', '', $key );
 934	return apply_filters( 'sanitize_key', $key, $raw_key );
 935}
 936
 937/**
 938 * Sanitizes a title, or returns a fallback title.
 939 *
 940 * Specifically, HTML and PHP tags are stripped. Further actions can be added
 941 * via the plugin API. If $title is empty and $fallback_title is set, the latter
 942 * will be used.
 943 *
 944 * @since 1.0.0
 945 *
 946 * @param string $title The string to be sanitized.
 947 * @param string $fallback_title Optional. A title to use if $title is empty.
 948 * @param string $context Optional. The operation for which the string is sanitized
 949 * @return string The sanitized string.
 950 */
 951function sanitize_title( $title, $fallback_title = '', $context = 'save' ) {
 952	$raw_title = $title;
 953
 954	if ( 'save' == $context )
 955		$title = remove_accents($title);
 956
 957	$title = apply_filters('sanitize_title', $title, $raw_title, $context);
 958
 959	if ( '' === $title || false === $title )
 960		$title = $fallback_title;
 961
 962	return $title;
 963}
 964
 965/**
 966 * Sanitizes a title with the 'query' context.
 967 *
 968 * Used for querying the database for a value from URL.
 969 *
 970 * @since 3.1.0
 971 * @uses sanitize_title()
 972 *
 973 * @param string $title The string to be sanitized.
 974 * @return string The sanitized string.
 975 */
 976function sanitize_title_for_query( $title ) {
 977	return sanitize_title( $title, '', 'query' );
 978}
 979
 980/**
 981 * Sanitizes a title, replacing whitespace and a few other characters with dashes.
 982 *
 983 * Limits the output to alphanumeric characters, underscore (_) and dash (-).
 984 * Whitespace becomes a dash.
 985 *
 986 * @since 1.2.0
 987 *
 988 * @param string $title The title to be sanitized.
 989 * @param string $raw_title Optional. Not used.
 990 * @param string $context Optional. The operation for which the string is sanitized.
 991 * @return string The sanitized title.
 992 */
 993function sanitize_title_with_dashes( $title, $raw_title = '', $context = 'display' ) {
 994	$title = strip_tags($title);
 995	// Preserve escaped octets.
 996	$title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
 997	// Remove percent signs that are not part of an octet.
 998	$title = str_replace('%', '', $title);
 999	// Restore octets.
1000	$title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
1001
1002	if (seems_utf8($title)) {
1003		if (function_exists('mb_strtolower')) {
1004			$title = mb_strtolower($title, 'UTF-8');
1005		}
1006		$title = utf8_uri_encode($title, 200);
1007	}
1008
1009	$title = strtolower($title);
1010	$title = preg_replace('/&.+?;/', '', $title); // kill entities
1011	$title = str_replace('.', '-', $title);
1012
1013	if ( 'save' == $context ) {
1014		// Convert nbsp, ndash and mdash to hyphens
1015		$title = str_replace( array( '%c2%a0', '%e2%80%93', '%e2%80%94' ), '-', $title );
1016
1017		// Strip these characters entirely
1018		$title = str_replace( array(
1019			// iexcl and iquest
1020			'%c2%a1', '%c2%bf',
1021			// angle quotes
1022			'%c2%ab', '%c2%bb', '%e2%80%b9', '%e2%80%ba',
1023			// curly quotes
1024			'%e2%80%98', '%e2%80%99', '%e2%80%9c', '%e2%80%9d',
1025			'%e2%80%9a', '%e2%80%9b', '%e2%80%9e', '%e2%80%9f',
1026			// copy, reg, deg, hellip and trade
1027			'%c2%a9', '%c2%ae', '%c2%b0', '%e2%80%a6', '%e2%84%a2',
1028			// acute accents
1029			'%c2%b4', '%cb%8a', '%cc%81', '%cd%81',
1030			// grave accent, macron, caron
1031			'%cc%80', '%cc%84', '%cc%8c',
1032		), '', $title );
1033
1034		// Convert times to x
1035		$title = str_replace( '%c3%97', 'x', $title );
1036	}
1037
1038	$title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
1039	$title = preg_replace('/\s+/', '-', $title);
1040	$title = preg_replace('|-+|', '-', $title);
1041	$title = trim($title, '-');
1042
1043	return $title;
1044}
1045
1046/**
1047 * Ensures a string is a valid SQL order by clause.
1048 *
1049 * Accepts one or more columns, with or without ASC/DESC, and also accepts
1050 * RAND().
1051 *
1052 * @since 2.5.1
1053 *
1054 * @param string $orderby Order by string to be checked.
1055 * @return string|bool Returns the order by clause if it is a match, false otherwise.
1056 */
1057function sanitize_sql_orderby( $orderby ){
1058	preg_match('/^\s*([a-z0-9_]+(\s+(ASC|DESC))?(\s*,\s*|\s*$))+|^\s*RAND\(\s*\)\s*$/i', $orderby, $obmatches);
1059	if ( !$obmatches )
1060		return false;
1061	return $orderby;
1062}
1063
1064/**
1065 * Sanitizes an HTML classname to ensure it only contains valid characters.
1066 *
1067 * Strips the string down to A-Z,a-z,0-9,_,-. If this results in an empty
1068 * string then it will return the alternative value supplied.
1069 *
1070 * @todo Expand to support the full range of CDATA that a class attribute can contain.
1071 *
1072 * @since 2.8.0
1073 *
1074 * @param string $class The classname to be sanitized
1075 * @param string $fallback Optional. The value to return if the sanitization end's up as an empty string.
1076 * 	Defaults to an empty string.
1077 * @return string The sanitized value
1078 */
1079function sanitize_html_class( $class, $fallback = '' ) {
1080	//Strip out any % encoded octets
1081	$sanitized = preg_replace( '|%[a-fA-F0-9][a-fA-F0-9]|', '', $class );
1082
1083	//Limit to A-Z,a-z,0-9,_,-
1084	$sanitized = preg_replace( '/[^A-Za-z0-9_-]/', '', $sanitized );
1085
1086	if ( '' == $sanitized )
1087		$sanitized = $fallback;
1088
1089	return apply_filters( 'sanitize_html_class', $sanitized, $class, $fallback );
1090}
1091
1092/**
1093 * Converts a number of characters from a string.
1094 *
1095 * Metadata tags <<title>> and <<category>> are removed, <<br>> and <<hr>> are
1096 * converted into correct XHTML and Unicode characters are converted to the
1097 * valid range.
1098 *
1099 * @since 0.71
1100 *
1101 * @param string $content String of characters to be converted.
1102 * @param string $deprecated Not used.
1103 * @return string Converted string.
1104 */
1105function convert_chars($content, $deprecated = '') {
1106	if ( !empty( $deprecated ) )
1107		_deprecated_argument( __FUNCTION__, '0.71' );
1108
1109	// Translation of invalid Unicode references range to valid range
1110	$wp_htmltranswinuni = array(
1111	'&#128;' => '&#8364;', // the Euro sign
1112	'&#129;' => '',
1113	'&#130;' => '&#8218;', // these are Windows CP1252 specific characters
1114	'&#131;' => '&#402;',  // they would look weird on non-Windows browsers
1115	'&#132;' => '&#8222;',
1116	'&#133;' => '&#8230;',
1117	'&#134;' => '&#8224;',
1118	'&#135;' => '&#8225;',
1119	'&#136;' => '&#710;',
1120	'&#137;' => '&#8240;',
1121	'&#138;' => '&#352;',
1122	'&#139;' => '&#8249;',
1123	'&#140;' => '&#338;',
1124	'&#141;' => '',
1125	'&#142;' => '&#381;',
1126	'&#143;' => '',
1127	'&#144;' => '',
1128	'&#145;' => '&#8216;',
1129	'&#146;' => '&#8217;',
1130	'&#147;' => '&#8220;',
1131	'&#148;' => '&#8221;',
1132	'&#149;' => '&#8226;',
1133	'&#150;' => '&#8211;',
1134	'&#151;' => '&#8212;',
1135	'&#152;' => '&#732;',
1136	'&#153;' => '&#8482;',
1137	'&#154;' => '&#353;',
1138	'&#155;' => '&#8250;',
1139	'&#156;' => '&#339;',
1140	'&#157;' => '',
1141	'&#158;' => '&#382;',
1142	'&#159;' => '&#376;'
1143	);
1144
1145	// Remove metadata tags
1146	$content = preg_replace('/<title>(.+?)<\/title>/','',$content);
1147	$content = preg_replace('/<category>(.+?)<\/category>/','',$content);
1148
1149	// Converts lone & characters into &#38; (a.k.a. &amp;)
1150	$content = preg_replace('/&([^#])(?![a-z1-4]{1,8};)/i', '&#038;$1', $content);
1151
1152	// Fix Word pasting
1153	$content = strtr($content, $wp_htmltranswinuni);
1154
1155	// Just a little XHTML help
1156	$content = str_replace('<br>', '<br />', $content);
1157	$content = str_replace('<hr>', '<hr />', $content);
1158
1159	return $content;
1160}
1161
1162/**
1163 * Balances tags if forced to, or if the 'use_balanceTags' option is set to true.
1164 *
1165 * @since 0.71
1166 *
1167 * @param string $text Text to be balanced
1168 * @param bool $force If true, forces balancing, ignoring the value of the option. Default false.
1169 * @return string Balanced text
1170 */
1171function balanceTags( $text, $force = false ) {
1172	if ( $force || get_option('use_balanceTags') == 1 )
1173		return force_balance_tags( $text );
1174	else
1175		return $text;
1176}
1177
1178/**
1179 * Balances tags of string using a modified stack.
1180 *
1181 * @since 2.0.4
1182 *
1183 * @author Leonard Lin <leonard@acm.org>
1184 * @license GPL
1185 * @copyright November 4, 2001
1186 * @version 1.1
1187 * @todo Make better - change loop condition to $text in 1.2
1188 * @internal Modified by Scott Reilly (coffee2code) 02 Aug 2004
1189 *		1.1  Fixed handling of append/stack pop order of end text
1190 *			 Added Cleaning Hooks
1191 *		1.0  First Version
1192 *
1193 * @param string $text Text to be balanced.
1194 * @return string Balanced text.
1195 */
1196function force_balance_tags( $text ) {
1197	$tagstack = array();
1198	$stacksize = 0;
1199	$tagqueue = '';
1200	$newtext = '';
1201	// Known single-entity/self-closing tags
1202	$single_tags = array( 'area', 'base', 'basefont', 'br', 'col', 'command', 'embed', 'frame', 'hr', 'img', 'input', 'isindex', 'link', 'meta', 'param', 'source' );
1203	// Tags that can be immediately nested within themselves
1204	$nestable_tags = array( 'blockquote', 'div', 'object', 'q', 'span' );
1205
1206	// WP bug fix for comments - in case you REALLY meant to type '< !--'
1207	$text = str_replace('< !--', '<    !--', $text);
1208	// WP bug fix for LOVE <3 (and other situations with '<' before a number)
1209	$text = preg_replace('#<([0-9]{1})#', '&lt;$1', $text);
1210
1211	while ( preg_match("/<(\/?[\w:]*)\s*([^>]*)>/", $text, $regex) ) {
1212		$newtext .= $tagqueue;
1213
1214		$i = strpos($text, $regex[0]);
1215		$l = strlen($regex[0]);
1216
1217		// clear the shifter
1218		$tagqueue = '';
1219		// Pop or Push
1220		if ( isset($regex[1][0]) && '/' == $regex[1][0] ) { // End Tag
1221			$tag = strtolower(substr($regex[1],1));
1222			// if too many closing tags
1223			if( $stacksize <= 0 ) {
1224				$tag = '';
1225				// or close to be safe $tag = '/' . $tag;
1226			}
1227			// if stacktop value = tag close value then pop
1228			else if ( $tagstack[$stacksize - 1] == $tag ) { // found closing tag
1229				$tag = '</' . $tag . '>'; // Close Tag
1230				// Pop
1231				array_pop( $tagstack );
1232				$stacksize--;
1233			} else { // closing tag not at top, search for it
1234				for ( $j = $stacksize-1; $j >= 0; $j-- ) {
1235					if ( $tagstack[$j] == $tag ) {
1236					// add tag to tagqueue
1237						for ( $k = $stacksize-1; $k >= $j; $k--) {
1238							$tagqueue .= '</' . array_pop( $tagstack ) . '>';
1239							$stacksize--;
1240						}
1241						break;
1242					}
1243				}
1244				$tag = '';
1245			}
1246		} else { // Begin Tag
1247			$tag = strtolower($regex[1]);
1248
1249			// Tag Cleaning
1250
1251			// If it's an empty tag "< >", do nothing
1252			if ( '' == $tag ) {
1253				// do nothing
1254			}
1255			// ElseIf it presents itself as a self-closing tag...
1256			elseif ( substr( $regex[2], -1 ) == '/' ) {
1257				// ...but it isn't a known single-entity self-closing tag, then don't let it be treated as such and
1258				// immediately close it with a closing tag (the tag will encapsulate no text as a result)
1259				if ( ! in_array( $tag, $single_tags ) )
1260					$regex[2] = trim( substr( $regex[2], 0, -1 ) ) . "></$tag";
1261			}
1262			// ElseIf it's a known single-entity tag but it doesn't close itself, do so
1263			elseif ( in_array($tag, $single_tags) ) {
1264				$regex[2] .= '/';
1265			}
1266			// Else it's not a single-entity tag
1267			else {
1268				// If the top of the stack is the same as the tag we want to push, close previous tag
1269				if ( $stacksize > 0 && !in_array($tag, $nestable_tags) && $tagstack[$stacksize - 1] == $tag ) {
1270					$tagqueue = '</' . array_pop( $tagstack ) . '>';
1271					$stacksize--;
1272				}
1273				$stacksize = array_push( $tagstack, $tag );
1274			}
1275
1276			// Attributes
1277			$attributes = $regex[2];
1278			if( ! empty( $attributes ) && $attributes[0] != '>' )
1279				$attributes = ' ' . $attributes;
1280
1281			$tag = '<' . $tag . $attributes . '>';
1282			//If already queuing a close tag, then put this tag on, too
1283			if ( !empty($tagqueue) ) {
1284				$tagqueue .= $tag;
1285				$tag = '';
1286			}
1287		}
1288		$newtext .= substr($text, 0, $i) . $tag;
1289		$text = substr($text, $i + $l);
1290	}
1291
1292	// Clear Tag Queue
1293	$newtext .= $tagqueue;
1294
1295	// Add Remaining text
1296	$newtext .= $text;
1297
1298	// Empty Stack
1299	while( $x = array_pop($tagstack) )
1300		$newtext .= '</' . $x . '>'; // Add remaining tags to close
1301
1302	// WP fix for the bug with HTML comments
1303	$newtext = str_replace("< !--","<!--",$newtext);
1304	$newtext = str_replace("<    !--","< !--",$newtext);
1305
1306	return $newtext;
1307}
1308
1309/**
1310 * Acts on text which is about to be edited.
1311 *
1312 * The $content is run through esc_textarea(), which uses htmlspecialchars()
1313 * to convert special characters to HTML entities. If $richedit is set to true,
1314 * it is simply a holder for the 'format_to_edit' filter.
1315 *
1316 * @since 0.71
1317 *
1318 * @param string $content The text about to be edited.
1319 * @param bool $richedit Whether the $content should not pass through htmlspecialchars(). Default false (meaning it will be passed).
1320 * @return string The text after the filter (and possibly htmlspecialchars()) has been run.
1321 */
1322function format_to_edit( $content, $richedit = false ) {
1323	$content = apply_filters( 'format_to_edit', $content );
1324	if (

Large files files are truncated, but you can click here to view the full file