PageRenderTime 411ms CodeModel.GetById 91ms app.highlight 216ms RepoModel.GetById 35ms app.codeStats 22ms

/wp-includes/formatting.php

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

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