3 * Main WordPress Formatting API.
5 * Handles many functions for formatting output.
11 * Replaces common plain text characters into formatted entities
15 * 'cause today's effort makes it worth tomorrow's "holiday"...
19 * ’cause today’s effort makes it worth tomorrow’s “holiday”…
21 * Code within certain html blocks are skipped.
24 * @uses $wp_cockneyreplace Array of formatted entities for certain common phrases
26 * @param string $text The text to be formatted
27 * @param bool $reset Set to true for unit testing. Translated patterns will reset.
28 * @return string The string replaced with html entities
30 function wptexturize($text, $reset = false) {
31 global $wp_cockneyreplace, $shortcode_tags;
32 static $static_characters, $static_replacements, $dynamic_characters, $dynamic_replacements,
33 $default_no_texturize_tags, $default_no_texturize_shortcodes, $run_texturize = true;
35 // If there's nothing to do, just stop.
36 if ( empty( $text ) || false === $run_texturize ) {
40 // Set up static variables. Run once only.
41 if ( $reset || ! isset( $static_characters ) ) {
43 * Filter whether to skip running wptexturize().
45 * Passing false to the filter will effectively short-circuit wptexturize().
46 * returning the original text passed to the function instead.
48 * The filter runs only once, the first time wptexturize() is called.
54 * @param bool $run_texturize Whether to short-circuit wptexturize().
56 $run_texturize = apply_filters( 'run_wptexturize', $run_texturize );
57 if ( false === $run_texturize ) {
61 /* translators: opening curly double quote */
62 $opening_quote = _x( '“', 'opening curly double quote' );
63 /* translators: closing curly double quote */
64 $closing_quote = _x( '”', 'closing curly double quote' );
66 /* translators: apostrophe, for example in 'cause or can't */
67 $apos = _x( '’', 'apostrophe' );
69 /* translators: prime, for example in 9' (nine feet) */
70 $prime = _x( '′', 'prime' );
71 /* translators: double prime, for example in 9" (nine inches) */
72 $double_prime = _x( '″', 'double prime' );
74 /* translators: opening curly single quote */
75 $opening_single_quote = _x( '‘', 'opening curly single quote' );
76 /* translators: closing curly single quote */
77 $closing_single_quote = _x( '’', 'closing curly single quote' );
79 /* translators: en dash */
80 $en_dash = _x( '–', 'en dash' );
81 /* translators: em dash */
82 $em_dash = _x( '—', 'em dash' );
84 $default_no_texturize_tags = array('pre', 'code', 'kbd', 'style', 'script', 'tt');
85 $default_no_texturize_shortcodes = array('code');
87 // if a plugin has provided an autocorrect array, use it
88 if ( isset($wp_cockneyreplace) ) {
89 $cockney = array_keys($wp_cockneyreplace);
90 $cockneyreplace = array_values($wp_cockneyreplace);
91 } elseif ( "'" != $apos ) { // Only bother if we're doing a replacement.
92 $cockney = array( "'tain't", "'twere", "'twas", "'tis", "'twill", "'til", "'bout", "'nuff", "'round", "'cause" );
93 $cockneyreplace = array( $apos . "tain" . $apos . "t", $apos . "twere", $apos . "twas", $apos . "tis", $apos . "twill", $apos . "til", $apos . "bout", $apos . "nuff", $apos . "round", $apos . "cause" );
95 $cockney = $cockneyreplace = array();
98 $static_characters = array_merge( array( '...', '``', '\'\'', ' (tm)' ), $cockney );
99 $static_replacements = array_merge( array( '…', $opening_quote, $closing_quote, ' ™' ), $cockneyreplace );
102 // Pattern-based replacements of characters.
103 // Sort the remaining patterns into several arrays for performance tuning.
104 $dynamic_characters = array( 'apos' => array(), 'quote' => array(), 'dash' => array() );
105 $dynamic_replacements = array( 'apos' => array(), 'quote' => array(), 'dash' => array() );
107 $spaces = wp_spaces_regexp();
109 // '99' and '99" are ambiguous among other patterns; assume it's an abbreviated year at the end of a quotation.
110 if ( "'" !== $apos || "'" !== $closing_single_quote ) {
111 $dynamic[ '/\'(\d\d)\'(?=\Z|[.,)}\-\]]|>|' . $spaces . ')/' ] = $apos . '$1' . $closing_single_quote;
113 if ( "'" !== $apos || '"' !== $closing_quote ) {
114 $dynamic[ '/\'(\d\d)"(?=\Z|[.,)}\-\]]|>|' . $spaces . ')/' ] = $apos . '$1' . $closing_quote;
117 // '99 '99s '99's (apostrophe) But never '9 or '99% or '999 or '99.0.
118 if ( "'" !== $apos ) {
119 $dynamic[ '/\'(?=\d\d(?:\Z|(?![%\d]|[.,]\d)))/' ] = $apos;
122 // Quoted Numbers like '0.42'
123 if ( "'" !== $opening_single_quote && "'" !== $closing_single_quote ) {
124 $dynamic[ '/(?<=\A|' . $spaces . ')\'(\d[.,\d]*)\'/' ] = $opening_single_quote . '$1' . $closing_single_quote;
127 // Single quote at start, or preceded by (, {, <, [, ", -, or spaces.
128 if ( "'" !== $opening_single_quote ) {
129 $dynamic[ '/(?<=\A|[([{"\-]|<|' . $spaces . ')\'/' ] = $opening_single_quote;
132 // Apostrophe in a word. No spaces, double apostrophes, or other punctuation.
133 if ( "'" !== $apos ) {
134 $dynamic[ '/(?<!' . $spaces . ')\'(?!\Z|[.,:;"\'(){}[\]\-]|&[lg]t;|' . $spaces . ')/' ] = $apos;
138 if ( "'" !== $prime ) {
139 $dynamic[ '/(?<=\d)\'/' ] = $prime;
142 // Single quotes followed by spaces or ending punctuation.
143 if ( "'" !== $closing_single_quote ) {
144 $dynamic[ '/\'(?=\Z|[.,)}\-\]]|>|' . $spaces . ')/' ] = $closing_single_quote;
147 $dynamic_characters['apos'] = array_keys( $dynamic );
148 $dynamic_replacements['apos'] = array_values( $dynamic );
151 // Quoted Numbers like "42"
152 if ( '"' !== $opening_quote && '"' !== $closing_quote ) {
153 $dynamic[ '/(?<=\A|' . $spaces . ')"(\d[.,\d]*)"/' ] = $opening_quote . '$1' . $closing_quote;
157 if ( '"' !== $double_prime ) {
158 $dynamic[ '/(?<=\d)"/' ] = $double_prime;
161 // Double quote at start, or preceded by (, {, <, [, -, or spaces, and not followed by spaces.
162 if ( '"' !== $opening_quote ) {
163 $dynamic[ '/(?<=\A|[([{\-]|<|' . $spaces . ')"(?!' . $spaces . ')/' ] = $opening_quote;
166 // Any remaining double quotes.
167 if ( '"' !== $closing_quote ) {
168 $dynamic[ '/"/' ] = $closing_quote;
171 $dynamic_characters['quote'] = array_keys( $dynamic );
172 $dynamic_replacements['quote'] = array_values( $dynamic );
176 $dynamic[ '/---/' ] = $em_dash;
177 $dynamic[ '/(?<=' . $spaces . ')--(?=' . $spaces . ')/' ] = $em_dash;
178 $dynamic[ '/(?<!xn)--/' ] = $en_dash;
179 $dynamic[ '/(?<=' . $spaces . ')-(?=' . $spaces . ')/' ] = $en_dash;
181 $dynamic_characters['dash'] = array_keys( $dynamic );
182 $dynamic_replacements['dash'] = array_values( $dynamic );
185 // Must do this every time in case plugins use these filters in a context sensitive manner
187 * Filter the list of HTML elements not to texturize.
191 * @param array $default_no_texturize_tags An array of HTML element names.
193 $no_texturize_tags = apply_filters( 'no_texturize_tags', $default_no_texturize_tags );
195 * Filter the list of shortcodes not to texturize.
199 * @param array $default_no_texturize_shortcodes An array of shortcode names.
201 $no_texturize_shortcodes = apply_filters( 'no_texturize_shortcodes', $default_no_texturize_shortcodes );
203 $no_texturize_tags_stack = array();
204 $no_texturize_shortcodes_stack = array();
206 // Look for shortcodes and HTML elements.
208 $tagnames = array_keys( $shortcode_tags );
209 $tagregexp = join( '|', array_map( 'preg_quote', $tagnames ) );
210 $tagregexp = "(?:$tagregexp)(?![\\w-])"; // Excerpt of get_shortcode_regex().
213 '!' // Start of comment, after the <.
214 . '(?:' // Unroll the loop: Consume everything until --> is found.
215 . '-(?!->)' // Dash not followed by end of comment.
216 . '[^\-]*+' // Consume non-dashes.
217 . ')*+' // Loop possessively.
218 . '-->'; // End of comment.
220 $regex = '/(' // Capture the entire match.
221 . '<' // Find start of element.
222 . '(?(?=!--)' // Is this a comment?
223 . $comment_regex // Find end of comment
225 . '[^>]+>' // Find end of element
228 . '\[' // Find start of shortcode.
229 . '[\/\[]?' // Shortcodes may begin with [/ or [[
230 . $tagregexp // Only match registered shortcodes, because performance.
232 . '[^\[\]<>]+' // Shortcodes do not contain other shortcodes. Quantifier critical.
234 . '<[^\[\]>]*>' // HTML elements permitted. Prevents matching ] before >.
235 . ')*+' // Possessive critical.
236 . '\]' // Find end of shortcode.
237 . '\]?' // Shortcodes may end with ]]
240 $textarr = preg_split( $regex, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY );
242 foreach ( $textarr as &$curl ) {
243 // Only call _wptexturize_pushpop_element if $curl is a delimiter.
245 if ( '<' === $first && '>' === substr( $curl, -1 ) ) {
246 // This is an HTML delimiter.
248 if ( '<!--' !== substr( $curl, 0, 4 ) ) {
249 _wptexturize_pushpop_element( $curl, $no_texturize_tags_stack, $no_texturize_tags );
252 } elseif ( '' === trim( $curl ) ) {
253 // This is a newline between delimiters. Performance improves when we check this.
257 } elseif ( '[' === $first && 1 === preg_match( '/^\[\/?' . $tagregexp . '(?:[^\[\]<>]+|<[^\[\]>]*>)*+\]$/', $curl ) ) {
258 // This is a shortcode delimiter.
260 _wptexturize_pushpop_element( $curl, $no_texturize_shortcodes_stack, $no_texturize_shortcodes );
262 } elseif ( '[' === $first && 1 === preg_match( '/^\[[\/\[]?' . $tagregexp . '(?:[^\[\]<>]+|<[^\[\]>]*>)*+\]\]?$/', $curl ) ) {
263 // This is an escaped shortcode delimiter.
266 // Do not push to the shortcodes stack.
270 } elseif ( empty( $no_texturize_shortcodes_stack ) && empty( $no_texturize_tags_stack ) ) {
271 // This is neither a delimiter, nor is this content inside of no_texturize pairs. Do texturize.
273 $curl = str_replace( $static_characters, $static_replacements, $curl );
275 if ( false !== strpos( $curl, "'" ) ) {
276 $curl = preg_replace( $dynamic_characters['apos'], $dynamic_replacements['apos'], $curl );
278 if ( false !== strpos( $curl, '"' ) ) {
279 $curl = preg_replace( $dynamic_characters['quote'], $dynamic_replacements['quote'], $curl );
281 if ( false !== strpos( $curl, '-' ) ) {
282 $curl = preg_replace( $dynamic_characters['dash'], $dynamic_replacements['dash'], $curl );
285 // 9x9 (times), but never 0x9999
286 if ( 1 === preg_match( '/(?<=\d)x-?\d/', $curl ) ) {
287 // Searching for a digit is 10 times more expensive than for the x, so we avoid doing this one!
288 $curl = preg_replace( '/\b(\d(?(?<=0)[\d\.,]+|[\d\.,]*))x(-?\d[\d\.,]*)\b/', '$1×$2', $curl );
292 $text = implode( '', $textarr );
294 // Replace each & with & unless it already looks like an entity.
295 $text = preg_replace('/&(?!#(?:\d+|x[a-f0-9]+);|[a-z1-4]{1,8};)/i', '&', $text);
301 * Search for disabled element tags. Push element to stack on tag open and pop
304 * Assumes first char of $text is tag opening and last char is tag closing.
305 * Assumes second char of $text is optionally '/' to indicate closing as in </html>.
310 * @param string $text Text to check. Must be a tag like <html> or [shortcode].
311 * @param array $stack List of open tag elements.
312 * @param array $disabled_elements The tag names to match against. Spaces are not allowed in tag names.
314 function _wptexturize_pushpop_element($text, &$stack, $disabled_elements) {
315 // Is it an opening tag or closing tag?
316 if ( '/' !== $text[1] ) {
319 } elseif ( 0 == count( $stack ) ) {
320 // Stack is empty. Just stop.
323 $opening_tag = false;
327 // Parse out the tag name.
328 $space = strpos( $text, ' ' );
329 if ( FALSE === $space ) {
332 $space -= $name_offset;
334 $tag = substr( $text, $name_offset, $space );
336 // Handle disabled tags.
337 if ( in_array( $tag, $disabled_elements ) ) {
338 if ( $opening_tag ) {
340 * This disables texturize until we find a closing tag of our type
341 * (e.g. <pre>) even if there was invalid nesting before that
343 * Example: in the case <pre>sadsadasd</code>"baba"</pre>
344 * "baba" won't be texturize
347 array_push( $stack, $tag );
348 } elseif ( end( $stack ) == $tag ) {
355 * Replaces double line-breaks with paragraph elements.
357 * A group of regex replaces used to identify text formatted with newlines and
358 * replace double line-breaks with HTML paragraph tags. The remaining
359 * line-breaks after conversion become <<br />> tags, unless $br is set to '0'
364 * @param string $pee The text which has to be formatted.
365 * @param bool $br Optional. If set, this will convert all remaining line-breaks after paragraphing. Default true.
366 * @return string Text which has been converted into correct paragraph tags.
368 function wpautop($pee, $br = true) {
371 if ( trim($pee) === '' )
374 $pee = $pee . "\n"; // just to make things a little easier, pad the end
376 if ( strpos($pee, '<pre') !== false ) {
377 $pee_parts = explode( '</pre>', $pee );
378 $last_pee = array_pop($pee_parts);
382 foreach ( $pee_parts as $pee_part ) {
383 $start = strpos($pee_part, '<pre');
386 if ( $start === false ) {
391 $name = "<pre wp-pre-tag-$i></pre>";
392 $pre_tags[$name] = substr( $pee_part, $start ) . '</pre>';
394 $pee .= substr( $pee_part, 0, $start ) . $name;
401 $pee = preg_replace('|<br />\s*<br />|', "\n\n", $pee);
402 // Space things out a little
403 $allblocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|form|map|area|blockquote|address|math|style|p|h[1-6]|hr|fieldset|legend|section|article|aside|hgroup|header|footer|nav|figure|details|menu|summary)';
404 $pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee);
405 $pee = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $pee);
406 $pee = str_replace(array("\r\n", "\r"), "\n", $pee); // cross-platform newlines
408 if ( strpos( $pee, '<option' ) !== false ) {
409 // no P/BR around option
410 $pee = preg_replace( '|\s*<option|', '<option', $pee );
411 $pee = preg_replace( '|</option>\s*|', '</option>', $pee );
414 if ( strpos( $pee, '</object>' ) !== false ) {
415 // no P/BR around param and embed
416 $pee = preg_replace( '|(<object[^>]*>)\s*|', '$1', $pee );
417 $pee = preg_replace( '|\s*</object>|', '</object>', $pee );
418 $pee = preg_replace( '%\s*(</?(?:param|embed)[^>]*>)\s*%', '$1', $pee );
421 if ( strpos( $pee, '<source' ) !== false || strpos( $pee, '<track' ) !== false ) {
422 // no P/BR around source and track
423 $pee = preg_replace( '%([<\[](?:audio|video)[^>\]]*[>\]])\s*%', '$1', $pee );
424 $pee = preg_replace( '%\s*([<\[]/(?:audio|video)[>\]])%', '$1', $pee );
425 $pee = preg_replace( '%\s*(<(?:source|track)[^>]*>)\s*%', '$1', $pee );
428 $pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates
429 // make paragraphs, including one at the end
430 $pees = preg_split('/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY);
433 foreach ( $pees as $tinkle ) {
434 $pee .= '<p>' . trim($tinkle, "\n") . "</p>\n";
437 $pee = preg_replace('|<p>\s*</p>|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace
438 $pee = preg_replace('!<p>([^<]+)</(div|address|form)>!', "<p>$1</p></$2>", $pee);
439 $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee); // don't pee all over a tag
440 $pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee); // problem with nested lists
441 $pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee);
442 $pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee);
443 $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)!', "$1", $pee);
444 $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
447 $pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', '_autop_newline_preservation_helper', $pee);
448 $pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee); // optionally make line breaks
449 $pee = str_replace('<WPPreserveNewline />', "\n", $pee);
452 $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', "$1", $pee);
453 $pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee);
454 $pee = preg_replace( "|\n</p>$|", '</p>', $pee );
456 if ( !empty($pre_tags) )
457 $pee = str_replace(array_keys($pre_tags), array_values($pre_tags), $pee);
463 * Newline preservation help function for wpautop
468 * @param array $matches preg_replace_callback matches array
471 function _autop_newline_preservation_helper( $matches ) {
472 return str_replace("\n", "<WPPreserveNewline />", $matches[0]);
476 * Don't auto-p wrap shortcodes that stand alone
478 * Ensures that shortcodes are not wrapped in <<p>>...<</p>>.
482 * @param string $pee The content.
483 * @return string The filtered content.
485 function shortcode_unautop( $pee ) {
486 global $shortcode_tags;
488 if ( empty( $shortcode_tags ) || !is_array( $shortcode_tags ) ) {
492 $tagregexp = join( '|', array_map( 'preg_quote', array_keys( $shortcode_tags ) ) );
493 $spaces = wp_spaces_regexp();
497 . '<p>' // Opening paragraph
498 . '(?:' . $spaces . ')*+' // Optional leading whitespace
499 . '(' // 1: The shortcode
500 . '\\[' // Opening bracket
501 . "($tagregexp)" // 2: Shortcode name
502 . '(?![\\w-])' // Not followed by word character or hyphen
503 // Unroll the loop: Inside the opening shortcode tag
504 . '[^\\]\\/]*' // Not a closing bracket or forward slash
506 . '\\/(?!\\])' // A forward slash not followed by a closing bracket
507 . '[^\\]\\/]*' // Not a closing bracket or forward slash
510 . '\\/\\]' // Self closing tag and closing bracket
512 . '\\]' // Closing bracket
513 . '(?:' // Unroll the loop: Optionally, anything between the opening and closing shortcode tags
514 . '[^\\[]*+' // Not an opening bracket
516 . '\\[(?!\\/\\2\\])' // An opening bracket not followed by the closing shortcode tag
517 . '[^\\[]*+' // Not an opening bracket
519 . '\\[\\/\\2\\]' // Closing shortcode tag
523 . '(?:' . $spaces . ')*+' // optional trailing whitespace
524 . '<\\/p>' // closing paragraph
527 return preg_replace( $pattern, '$1', $pee );
531 * Checks to see if a string is utf8 encoded.
533 * NOTE: This function checks for 5-Byte sequences, UTF8
534 * has Bytes Sequences with a maximum length of 4.
536 * @author bmorel at ssi dot fr (modified)
539 * @param string $str The string to be checked
540 * @return bool True if $str fits a UTF-8 model, false otherwise.
542 function seems_utf8($str) {
543 mbstring_binary_safe_encoding();
544 $length = strlen($str);
545 reset_mbstring_encoding();
546 for ($i=0; $i < $length; $i++) {
548 if ($c < 0x80) $n = 0; # 0bbbbbbb
549 elseif (($c & 0xE0) == 0xC0) $n=1; # 110bbbbb
550 elseif (($c & 0xF0) == 0xE0) $n=2; # 1110bbbb
551 elseif (($c & 0xF8) == 0xF0) $n=3; # 11110bbb
552 elseif (($c & 0xFC) == 0xF8) $n=4; # 111110bb
553 elseif (($c & 0xFE) == 0xFC) $n=5; # 1111110b
554 else return false; # Does not match any model
555 for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
556 if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))
564 * Converts a number of special characters into their HTML entities.
566 * Specifically deals with: &, <, >, ", and '.
568 * $quote_style can be set to ENT_COMPAT to encode " to
569 * ", or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded.
574 * @param string $string The text which is to be encoded.
575 * @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.
576 * @param string $charset Optional. The character encoding of the string. Default is false.
577 * @param boolean $double_encode Optional. Whether to encode existing html entities. Default is false.
578 * @return string The encoded text with HTML entities.
580 function _wp_specialchars( $string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false ) {
581 $string = (string) $string;
583 if ( 0 === strlen( $string ) )
586 // Don't bother if there are no specialchars - saves some processing
587 if ( ! preg_match( '/[&<>"\']/', $string ) )
590 // Account for the previous behaviour of the function when the $quote_style is not an accepted value
591 if ( empty( $quote_style ) )
592 $quote_style = ENT_NOQUOTES;
593 elseif ( ! in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) )
594 $quote_style = ENT_QUOTES;
596 // Store the site charset as a static to avoid multiple calls to wp_load_alloptions()
599 if ( ! isset( $_charset ) ) {
600 $alloptions = wp_load_alloptions();
601 $_charset = isset( $alloptions['blog_charset'] ) ? $alloptions['blog_charset'] : '';
603 $charset = $_charset;
606 if ( in_array( $charset, array( 'utf8', 'utf-8', 'UTF8' ) ) )
609 $_quote_style = $quote_style;
611 if ( $quote_style === 'double' ) {
612 $quote_style = ENT_COMPAT;
613 $_quote_style = ENT_COMPAT;
614 } elseif ( $quote_style === 'single' ) {
615 $quote_style = ENT_NOQUOTES;
618 // Handle double encoding ourselves
619 if ( $double_encode ) {
620 $string = @htmlspecialchars( $string, $quote_style, $charset );
622 // Decode & into &
623 $string = wp_specialchars_decode( $string, $_quote_style );
625 // Guarantee every &entity; is valid or re-encode the &
626 $string = wp_kses_normalize_entities( $string );
628 // Now re-encode everything except &entity;
629 $string = preg_split( '/(&#?x?[0-9a-z]+;)/i', $string, -1, PREG_SPLIT_DELIM_CAPTURE );
631 for ( $i = 0; $i < count( $string ); $i += 2 )
632 $string[$i] = @htmlspecialchars( $string[$i], $quote_style, $charset );
634 $string = implode( '', $string );
637 // Backwards compatibility
638 if ( 'single' === $_quote_style )
639 $string = str_replace( "'", ''', $string );
645 * Converts a number of HTML entities into their special characters.
647 * Specifically deals with: &, <, >, ", and '.
649 * $quote_style can be set to ENT_COMPAT to decode " entities,
650 * or ENT_QUOTES to do both " and '. Default is ENT_NOQUOTES where no quotes are decoded.
654 * @param string $string The text which is to be decoded.
655 * @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.
656 * @return string The decoded text without HTML entities.
658 function wp_specialchars_decode( $string, $quote_style = ENT_NOQUOTES ) {
659 $string = (string) $string;
661 if ( 0 === strlen( $string ) ) {
665 // Don't bother if there are no entities - saves a lot of processing
666 if ( strpos( $string, '&' ) === false ) {
670 // Match the previous behaviour of _wp_specialchars() when the $quote_style is not an accepted value
671 if ( empty( $quote_style ) ) {
672 $quote_style = ENT_NOQUOTES;
673 } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
674 $quote_style = ENT_QUOTES;
677 // More complete than get_html_translation_table( HTML_SPECIALCHARS )
678 $single = array( ''' => '\'', ''' => '\'' );
679 $single_preg = array( '/�*39;/' => ''', '/�*27;/i' => ''' );
680 $double = array( '"' => '"', '"' => '"', '"' => '"' );
681 $double_preg = array( '/�*34;/' => '"', '/�*22;/i' => '"' );
682 $others = array( '<' => '<', '<' => '<', '>' => '>', '>' => '>', '&' => '&', '&' => '&', '&' => '&' );
683 $others_preg = array( '/�*60;/' => '<', '/�*62;/' => '>', '/�*38;/' => '&', '/�*26;/i' => '&' );
685 if ( $quote_style === ENT_QUOTES ) {
686 $translation = array_merge( $single, $double, $others );
687 $translation_preg = array_merge( $single_preg, $double_preg, $others_preg );
688 } elseif ( $quote_style === ENT_COMPAT || $quote_style === 'double' ) {
689 $translation = array_merge( $double, $others );
690 $translation_preg = array_merge( $double_preg, $others_preg );
691 } elseif ( $quote_style === 'single' ) {
692 $translation = array_merge( $single, $others );
693 $translation_preg = array_merge( $single_preg, $others_preg );
694 } elseif ( $quote_style === ENT_NOQUOTES ) {
695 $translation = $others;
696 $translation_preg = $others_preg;
699 // Remove zero padding on numeric entities
700 $string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string );
702 // Replace characters according to translation table
703 return strtr( $string, $translation );
707 * Checks for invalid UTF8 in a string.
711 * @param string $string The text which is to be checked.
712 * @param boolean $strip Optional. Whether to attempt to strip out invalid UTF8. Default is false.
713 * @return string The checked text.
715 function wp_check_invalid_utf8( $string, $strip = false ) {
716 $string = (string) $string;
718 if ( 0 === strlen( $string ) ) {
722 // Store the site charset as a static to avoid multiple calls to get_option()
724 if ( !isset( $is_utf8 ) ) {
725 $is_utf8 = in_array( get_option( 'blog_charset' ), array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ) );
731 // Check for support for utf8 in the installed PCRE library once and store the result in a static
733 if ( !isset( $utf8_pcre ) ) {
734 $utf8_pcre = @preg_match( '/^./u', 'a' );
736 // We can't demand utf8 in the PCRE installation, so just return the string in those cases
741 // preg_match fails when it encounters invalid UTF8 in $string
742 if ( 1 === @preg_match( '/^./us', $string ) ) {
746 // Attempt to strip the bad chars if requested (not recommended)
747 if ( $strip && function_exists( 'iconv' ) ) {
748 return iconv( 'utf-8', 'utf-8', $string );
755 * Encode the Unicode values to be used in the URI.
759 * @param string $utf8_string
760 * @param int $length Max length of the string
761 * @return string String with Unicode encoded for URI.
763 function utf8_uri_encode( $utf8_string, $length = 0 ) {
769 mbstring_binary_safe_encoding();
770 $string_length = strlen( $utf8_string );
771 reset_mbstring_encoding();
773 for ($i = 0; $i < $string_length; $i++ ) {
775 $value = ord( $utf8_string[ $i ] );
777 if ( $value < 128 ) {
778 if ( $length && ( $unicode_length >= $length ) )
780 $unicode .= chr($value);
783 if ( count( $values ) == 0 ) $num_octets = ( $value < 224 ) ? 2 : 3;
787 if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length )
789 if ( count( $values ) == $num_octets ) {
790 if ($num_octets == 3) {
791 $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]) . '%' . dechex($values[2]);
792 $unicode_length += 9;
794 $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]);
795 $unicode_length += 6;
808 * Converts all accent characters to ASCII characters.
810 * If there are no accent characters, then the string given is just returned.
814 * @param string $string Text that might have accent characters
815 * @return string Filtered string with replaced "nice" characters.
817 function remove_accents($string) {
818 if ( !preg_match('/[\x80-\xff]/', $string) )
821 if (seems_utf8($string)) {
823 // Decompositions for Latin-1 Supplement
824 chr(194).chr(170) => 'a', chr(194).chr(186) => 'o',
825 chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
826 chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
827 chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
828 chr(195).chr(134) => 'AE',chr(195).chr(135) => 'C',
829 chr(195).chr(136) => 'E', chr(195).chr(137) => 'E',
830 chr(195).chr(138) => 'E', chr(195).chr(139) => 'E',
831 chr(195).chr(140) => 'I', chr(195).chr(141) => 'I',
832 chr(195).chr(142) => 'I', chr(195).chr(143) => 'I',
833 chr(195).chr(144) => 'D', chr(195).chr(145) => 'N',
834 chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
835 chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
836 chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
837 chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
838 chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
839 chr(195).chr(158) => 'TH',chr(195).chr(159) => 's',
840 chr(195).chr(160) => 'a', chr(195).chr(161) => 'a',
841 chr(195).chr(162) => 'a', chr(195).chr(163) => 'a',
842 chr(195).chr(164) => 'a', chr(195).chr(165) => 'a',
843 chr(195).chr(166) => 'ae',chr(195).chr(167) => 'c',
844 chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
845 chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
846 chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
847 chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
848 chr(195).chr(176) => 'd', chr(195).chr(177) => 'n',
849 chr(195).chr(178) => 'o', chr(195).chr(179) => 'o',
850 chr(195).chr(180) => 'o', chr(195).chr(181) => 'o',
851 chr(195).chr(182) => 'o', chr(195).chr(184) => 'o',
852 chr(195).chr(185) => 'u', chr(195).chr(186) => 'u',
853 chr(195).chr(187) => 'u', chr(195).chr(188) => 'u',
854 chr(195).chr(189) => 'y', chr(195).chr(190) => 'th',
855 chr(195).chr(191) => 'y', chr(195).chr(152) => 'O',
856 // Decompositions for Latin Extended-A
857 chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
858 chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
859 chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
860 chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
861 chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
862 chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
863 chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
864 chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
865 chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
866 chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
867 chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
868 chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
869 chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
870 chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
871 chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
872 chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
873 chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
874 chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
875 chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
876 chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
877 chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
878 chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
879 chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
880 chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
881 chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
882 chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
883 chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
884 chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
885 chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
886 chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
887 chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
888 chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
889 chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
890 chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
891 chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
892 chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
893 chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
894 chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
895 chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
896 chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
897 chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
898 chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
899 chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
900 chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
901 chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
902 chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
903 chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
904 chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
905 chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
906 chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
907 chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
908 chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
909 chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
910 chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
911 chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
912 chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
913 chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
914 chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
915 chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
916 chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
917 chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
918 chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
919 chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
920 chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
921 // Decompositions for Latin Extended-B
922 chr(200).chr(152) => 'S', chr(200).chr(153) => 's',
923 chr(200).chr(154) => 'T', chr(200).chr(155) => 't',
925 chr(226).chr(130).chr(172) => 'E',
927 chr(194).chr(163) => '',
928 // Vowels with diacritic (Vietnamese)
930 chr(198).chr(160) => 'O', chr(198).chr(161) => 'o',
931 chr(198).chr(175) => 'U', chr(198).chr(176) => 'u',
933 chr(225).chr(186).chr(166) => 'A', chr(225).chr(186).chr(167) => 'a',
934 chr(225).chr(186).chr(176) => 'A', chr(225).chr(186).chr(177) => 'a',
935 chr(225).chr(187).chr(128) => 'E', chr(225).chr(187).chr(129) => 'e',
936 chr(225).chr(187).chr(146) => 'O', chr(225).chr(187).chr(147) => 'o',
937 chr(225).chr(187).chr(156) => 'O', chr(225).chr(187).chr(157) => 'o',
938 chr(225).chr(187).chr(170) => 'U', chr(225).chr(187).chr(171) => 'u',
939 chr(225).chr(187).chr(178) => 'Y', chr(225).chr(187).chr(179) => 'y',
941 chr(225).chr(186).chr(162) => 'A', chr(225).chr(186).chr(163) => 'a',
942 chr(225).chr(186).chr(168) => 'A', chr(225).chr(186).chr(169) => 'a',
943 chr(225).chr(186).chr(178) => 'A', chr(225).chr(186).chr(179) => 'a',
944 chr(225).chr(186).chr(186) => 'E', chr(225).chr(186).chr(187) => 'e',
945 chr(225).chr(187).chr(130) => 'E', chr(225).chr(187).chr(131) => 'e',
946 chr(225).chr(187).chr(136) => 'I', chr(225).chr(187).chr(137) => 'i',
947 chr(225).chr(187).chr(142) => 'O', chr(225).chr(187).chr(143) => 'o',
948 chr(225).chr(187).chr(148) => 'O', chr(225).chr(187).chr(149) => 'o',
949 chr(225).chr(187).chr(158) => 'O', chr(225).chr(187).chr(159) => 'o',
950 chr(225).chr(187).chr(166) => 'U', chr(225).chr(187).chr(167) => 'u',
951 chr(225).chr(187).chr(172) => 'U', chr(225).chr(187).chr(173) => 'u',
952 chr(225).chr(187).chr(182) => 'Y', chr(225).chr(187).chr(183) => 'y',
954 chr(225).chr(186).chr(170) => 'A', chr(225).chr(186).chr(171) => 'a',
955 chr(225).chr(186).chr(180) => 'A', chr(225).chr(186).chr(181) => 'a',
956 chr(225).chr(186).chr(188) => 'E', chr(225).chr(186).chr(189) => 'e',
957 chr(225).chr(187).chr(132) => 'E', chr(225).chr(187).chr(133) => 'e',
958 chr(225).chr(187).chr(150) => 'O', chr(225).chr(187).chr(151) => 'o',
959 chr(225).chr(187).chr(160) => 'O', chr(225).chr(187).chr(161) => 'o',
960 chr(225).chr(187).chr(174) => 'U', chr(225).chr(187).chr(175) => 'u',
961 chr(225).chr(187).chr(184) => 'Y', chr(225).chr(187).chr(185) => 'y',
963 chr(225).chr(186).chr(164) => 'A', chr(225).chr(186).chr(165) => 'a',
964 chr(225).chr(186).chr(174) => 'A', chr(225).chr(186).chr(175) => 'a',
965 chr(225).chr(186).chr(190) => 'E', chr(225).chr(186).chr(191) => 'e',
966 chr(225).chr(187).chr(144) => 'O', chr(225).chr(187).chr(145) => 'o',
967 chr(225).chr(187).chr(154) => 'O', chr(225).chr(187).chr(155) => 'o',
968 chr(225).chr(187).chr(168) => 'U', chr(225).chr(187).chr(169) => 'u',
970 chr(225).chr(186).chr(160) => 'A', chr(225).chr(186).chr(161) => 'a',
971 chr(225).chr(186).chr(172) => 'A', chr(225).chr(186).chr(173) => 'a',
972 chr(225).chr(186).chr(182) => 'A', chr(225).chr(186).chr(183) => 'a',
973 chr(225).chr(186).chr(184) => 'E', chr(225).chr(186).chr(185) => 'e',
974 chr(225).chr(187).chr(134) => 'E', chr(225).chr(187).chr(135) => 'e',
975 chr(225).chr(187).chr(138) => 'I', chr(225).chr(187).chr(139) => 'i',
976 chr(225).chr(187).chr(140) => 'O', chr(225).chr(187).chr(141) => 'o',
977 chr(225).chr(187).chr(152) => 'O', chr(225).chr(187).chr(153) => 'o',
978 chr(225).chr(187).chr(162) => 'O', chr(225).chr(187).chr(163) => 'o',
979 chr(225).chr(187).chr(164) => 'U', chr(225).chr(187).chr(165) => 'u',
980 chr(225).chr(187).chr(176) => 'U', chr(225).chr(187).chr(177) => 'u',
981 chr(225).chr(187).chr(180) => 'Y', chr(225).chr(187).chr(181) => 'y',
982 // Vowels with diacritic (Chinese, Hanyu Pinyin)
983 chr(201).chr(145) => 'a',
985 chr(199).chr(149) => 'U', chr(199).chr(150) => 'u',
987 chr(199).chr(151) => 'U', chr(199).chr(152) => 'u',
989 chr(199).chr(141) => 'A', chr(199).chr(142) => 'a',
990 chr(199).chr(143) => 'I', chr(199).chr(144) => 'i',
991 chr(199).chr(145) => 'O', chr(199).chr(146) => 'o',
992 chr(199).chr(147) => 'U', chr(199).chr(148) => 'u',
993 chr(199).chr(153) => 'U', chr(199).chr(154) => 'u',
995 chr(199).chr(155) => 'U', chr(199).chr(156) => 'u',
998 // Used for locale-specific rules
999 $locale = get_locale();
1001 if ( 'de_DE' == $locale ) {
1002 $chars[ chr(195).chr(132) ] = 'Ae';
1003 $chars[ chr(195).chr(164) ] = 'ae';
1004 $chars[ chr(195).chr(150) ] = 'Oe';
1005 $chars[ chr(195).chr(182) ] = 'oe';
1006 $chars[ chr(195).chr(156) ] = 'Ue';
1007 $chars[ chr(195).chr(188) ] = 'ue';
1008 $chars[ chr(195).chr(159) ] = 'ss';
1009 } elseif ( 'da_DK' === $locale ) {
1010 $chars[ chr(195).chr(134) ] = 'Ae';
1011 $chars[ chr(195).chr(166) ] = 'ae';
1012 $chars[ chr(195).chr(152) ] = 'Oe';
1013 $chars[ chr(195).chr(184) ] = 'oe';
1014 $chars[ chr(195).chr(133) ] = 'Aa';
1015 $chars[ chr(195).chr(165) ] = 'aa';
1018 $string = strtr($string, $chars);
1020 // Assume ISO-8859-1 if not UTF-8
1021 $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
1022 .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
1023 .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
1024 .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
1025 .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
1026 .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
1027 .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
1028 .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
1029 .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
1030 .chr(252).chr(253).chr(255);
1032 $chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";
1034 $string = strtr($string, $chars['in'], $chars['out']);
1035 $double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
1036 $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
1037 $string = str_replace($double_chars['in'], $double_chars['out'], $string);
1044 * Sanitizes a filename, replacing whitespace with dashes.
1046 * Removes special characters that are illegal in filenames on certain
1047 * operating systems and special characters requiring special escaping
1048 * to manipulate at the command line. Replaces spaces and consecutive
1049 * dashes with a single dash. Trims period, dash and underscore from beginning
1050 * and end of filename.
1054 * @param string $filename The filename to be sanitized
1055 * @return string The sanitized filename
1057 function sanitize_file_name( $filename ) {
1058 $filename_raw = $filename;
1059 $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", chr(0));
1061 * Filter the list of characters to remove from a filename.
1065 * @param array $special_chars Characters to remove.
1066 * @param string $filename_raw Filename as it was passed into sanitize_file_name().
1068 $special_chars = apply_filters( 'sanitize_file_name_chars', $special_chars, $filename_raw );
1069 $filename = preg_replace( "#\x{00a0}#siu", ' ', $filename );
1070 $filename = str_replace($special_chars, '', $filename);
1071 $filename = str_replace( array( '%20', '+' ), '-', $filename );
1072 $filename = preg_replace('/[\s-]+/', '-', $filename);
1073 $filename = trim($filename, '.-_');
1075 // Split the filename into a base and extension[s]
1076 $parts = explode('.', $filename);
1078 // Return if only one extension
1079 if ( count( $parts ) <= 2 ) {
1081 * Filter a sanitized filename string.
1085 * @param string $filename Sanitized filename.
1086 * @param string $filename_raw The filename prior to sanitization.
1088 return apply_filters( 'sanitize_file_name', $filename, $filename_raw );
1091 // Process multiple extensions
1092 $filename = array_shift($parts);
1093 $extension = array_pop($parts);
1094 $mimes = get_allowed_mime_types();
1097 * Loop over any intermediate extensions. Postfix them with a trailing underscore
1098 * if they are a 2 - 5 character long alpha string not in the extension whitelist.
1100 foreach ( (array) $parts as $part) {
1101 $filename .= '.' . $part;
1103 if ( preg_match("/^[a-zA-Z]{2,5}\d?$/", $part) ) {
1105 foreach ( $mimes as $ext_preg => $mime_match ) {
1106 $ext_preg = '!^(' . $ext_preg . ')$!i';
1107 if ( preg_match( $ext_preg, $part ) ) {
1116 $filename .= '.' . $extension;
1117 /** This filter is documented in wp-includes/formatting.php */
1118 return apply_filters('sanitize_file_name', $filename, $filename_raw);
1122 * Sanitizes a username, stripping out unsafe characters.
1124 * Removes tags, octets, entities, and if strict is enabled, will only keep
1125 * alphanumeric, _, space, ., -, @. After sanitizing, it passes the username,
1126 * raw username (the username in the parameter), and the value of $strict as
1127 * parameters for the 'sanitize_user' filter.
1131 * @param string $username The username to be sanitized.
1132 * @param bool $strict If set limits $username to specific characters. Default false.
1133 * @return string The sanitized username, after passing through filters.
1135 function sanitize_user( $username, $strict = false ) {
1136 $raw_username = $username;
1137 $username = wp_strip_all_tags( $username );
1138 $username = remove_accents( $username );
1140 $username = preg_replace( '|%([a-fA-F0-9][a-fA-F0-9])|', '', $username );
1141 $username = preg_replace( '/&.+?;/', '', $username ); // Kill entities
1143 // If strict, reduce to ASCII for max portability.
1145 $username = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $username );
1147 $username = trim( $username );
1148 // Consolidate contiguous whitespace
1149 $username = preg_replace( '|\s+|', ' ', $username );
1152 * Filter a sanitized username string.
1156 * @param string $username Sanitized username.
1157 * @param string $raw_username The username prior to sanitization.
1158 * @param bool $strict Whether to limit the sanitization to specific characters. Default false.
1160 return apply_filters( 'sanitize_user', $username, $raw_username, $strict );
1164 * Sanitizes a string key.
1166 * Keys are used as internal identifiers. Lowercase alphanumeric characters, dashes and underscores are allowed.
1170 * @param string $key String key
1171 * @return string Sanitized key
1173 function sanitize_key( $key ) {
1175 $key = strtolower( $key );
1176 $key = preg_replace( '/[^a-z0-9_\-]/', '', $key );
1179 * Filter a sanitized key string.
1183 * @param string $key Sanitized key.
1184 * @param string $raw_key The key prior to sanitization.
1186 return apply_filters( 'sanitize_key', $key, $raw_key );
1190 * Sanitizes a title, or returns a fallback title.
1192 * Specifically, HTML and PHP tags are stripped. Further actions can be added
1193 * via the plugin API. If $title is empty and $fallback_title is set, the latter
1198 * @param string $title The string to be sanitized.
1199 * @param string $fallback_title Optional. A title to use if $title is empty.
1200 * @param string $context Optional. The operation for which the string is sanitized
1201 * @return string The sanitized string.
1203 function sanitize_title( $title, $fallback_title = '', $context = 'save' ) {
1204 $raw_title = $title;
1206 if ( 'save' == $context )
1207 $title = remove_accents($title);
1210 * Filter a sanitized title string.
1214 * @param string $title Sanitized title.
1215 * @param string $raw_title The title prior to sanitization.
1216 * @param string $context The context for which the title is being sanitized.
1218 $title = apply_filters( 'sanitize_title', $title, $raw_title, $context );
1220 if ( '' === $title || false === $title )
1221 $title = $fallback_title;
1227 * Sanitizes a title with the 'query' context.
1229 * Used for querying the database for a value from URL.
1232 * @uses sanitize_title()
1234 * @param string $title The string to be sanitized.
1235 * @return string The sanitized string.
1237 function sanitize_title_for_query( $title ) {
1238 return sanitize_title( $title, '', 'query' );
1242 * Sanitizes a title, replacing whitespace and a few other characters with dashes.
1244 * Limits the output to alphanumeric characters, underscore (_) and dash (-).
1245 * Whitespace becomes a dash.
1249 * @param string $title The title to be sanitized.
1250 * @param string $raw_title Optional. Not used.
1251 * @param string $context Optional. The operation for which the string is sanitized.
1252 * @return string The sanitized title.
1254 function sanitize_title_with_dashes( $title, $raw_title = '', $context = 'display' ) {
1255 $title = strip_tags($title);
1256 // Preserve escaped octets.
1257 $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
1258 // Remove percent signs that are not part of an octet.
1259 $title = str_replace('%', '', $title);
1261 $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
1263 if (seems_utf8($title)) {
1264 if (function_exists('mb_strtolower')) {
1265 $title = mb_strtolower($title, 'UTF-8');
1267 $title = utf8_uri_encode($title, 200);
1270 $title = strtolower($title);
1271 $title = preg_replace('/&.+?;/', '', $title); // kill entities
1272 $title = str_replace('.', '-', $title);
1274 if ( 'save' == $context ) {
1275 // Convert nbsp, ndash and mdash to hyphens
1276 $title = str_replace( array( '%c2%a0', '%e2%80%93', '%e2%80%94' ), '-', $title );
1278 // Strip these characters entirely
1279 $title = str_replace( array(
1283 '%c2%ab', '%c2%bb', '%e2%80%b9', '%e2%80%ba',
1285 '%e2%80%98', '%e2%80%99', '%e2%80%9c', '%e2%80%9d',
1286 '%e2%80%9a', '%e2%80%9b', '%e2%80%9e', '%e2%80%9f',
1287 // copy, reg, deg, hellip and trade
1288 '%c2%a9', '%c2%ae', '%c2%b0', '%e2%80%a6', '%e2%84%a2',
1290 '%c2%b4', '%cb%8a', '%cc%81', '%cd%81',
1291 // grave accent, macron, caron
1292 '%cc%80', '%cc%84', '%cc%8c',
1295 // Convert times to x
1296 $title = str_replace( '%c3%97', 'x', $title );
1299 $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
1300 $title = preg_replace('/\s+/', '-', $title);
1301 $title = preg_replace('|-+|', '-', $title);
1302 $title = trim($title, '-');
1308 * Ensures a string is a valid SQL order by clause.
1310 * Accepts one or more columns, with or without ASC/DESC, and also accepts
1315 * @param string $orderby Order by string to be checked.
1316 * @return string|bool Returns the order by clause if it is a match, false otherwise.
1318 function sanitize_sql_orderby( $orderby ){
1319 preg_match('/^\s*([a-z0-9_]+(\s+(ASC|DESC))?(\s*,\s*|\s*$))+|^\s*RAND\(\s*\)\s*$/i', $orderby, $obmatches);
1326 * Sanitizes an HTML classname to ensure it only contains valid characters.
1328 * Strips the string down to A-Z,a-z,0-9,_,-. If this results in an empty
1329 * string then it will return the alternative value supplied.
1331 * @todo Expand to support the full range of CDATA that a class attribute can contain.
1335 * @param string $class The classname to be sanitized
1336 * @param string $fallback Optional. The value to return if the sanitization ends up as an empty string.
1337 * Defaults to an empty string.
1338 * @return string The sanitized value
1340 function sanitize_html_class( $class, $fallback = '' ) {
1341 //Strip out any % encoded octets
1342 $sanitized = preg_replace( '|%[a-fA-F0-9][a-fA-F0-9]|', '', $class );
1344 //Limit to A-Z,a-z,0-9,_,-
1345 $sanitized = preg_replace( '/[^A-Za-z0-9_-]/', '', $sanitized );
1347 if ( '' == $sanitized )
1348 $sanitized = $fallback;
1351 * Filter a sanitized HTML class string.
1355 * @param string $sanitized The sanitized HTML class.
1356 * @param string $class HTML class before sanitization.
1357 * @param string $fallback The fallback string.
1359 return apply_filters( 'sanitize_html_class', $sanitized, $class, $fallback );
1363 * Converts a number of characters from a string.
1365 * Metadata tags <<title>> and <<category>> are removed, <<br>> and <<hr>> are
1366 * converted into correct XHTML and Unicode characters are converted to the
1371 * @param string $content String of characters to be converted.
1372 * @param string $deprecated Not used.
1373 * @return string Converted string.
1375 function convert_chars($content, $deprecated = '') {
1376 if ( !empty( $deprecated ) )
1377 _deprecated_argument( __FUNCTION__, '0.71' );
1379 // Translation of invalid Unicode references range to valid range
1380 $wp_htmltranswinuni = array(
1381 '€' => '€', // the Euro sign
1383 '‚' => '‚', // these are Windows CP1252 specific characters
1384 'ƒ' => 'ƒ', // they would look weird on non-Windows browsers
1385 '„' => '„',
1386 '…' => '…',
1387 '†' => '†',
1388 '‡' => '‡',
1389 'ˆ' => 'ˆ',
1390 '‰' => '‰',
1391 'Š' => 'Š',
1392 '‹' => '‹',
1393 'Œ' => 'Œ',
1395 'Ž' => 'Ž',
1398 '‘' => '‘',
1399 '’' => '’',
1400 '“' => '“',
1401 '”' => '”',
1402 '•' => '•',
1403 '–' => '–',
1404 '—' => '—',
1405 '˜' => '˜',
1406 '™' => '™',
1407 'š' => 'š',
1408 '›' => '›',
1409 'œ' => 'œ',
1411 'ž' => 'ž',
1412 'Ÿ' => 'Ÿ'
1415 // Remove metadata tags
1416 $content = preg_replace('/<title>(.+?)<\/title>/','',$content);
1417 $content = preg_replace('/<category>(.+?)<\/category>/','',$content);
1419 // Converts lone & characters into & (a.k.a. &)
1420 $content = preg_replace('/&([^#])(?![a-z1-4]{1,8};)/i', '&$1', $content);
1423 $content = strtr($content, $wp_htmltranswinuni);
1425 // Just a little XHTML help
1426 $content = str_replace('<br>', '<br />', $content);
1427 $content = str_replace('<hr>', '<hr />', $content);
1433 * Balances tags if forced to, or if the 'use_balanceTags' option is set to true.
1437 * @param string $text Text to be balanced
1438 * @param bool $force If true, forces balancing, ignoring the value of the option. Default false.
1439 * @return string Balanced text
1441 function balanceTags( $text, $force = false ) {
1442 if ( $force || get_option('use_balanceTags') == 1 ) {
1443 return force_balance_tags( $text );
1450 * Balances tags of string using a modified stack.
1454 * @author Leonard Lin <leonard@acm.org>
1456 * @copyright November 4, 2001
1458 * @todo Make better - change loop condition to $text in 1.2
1459 * @internal Modified by Scott Reilly (coffee2code) 02 Aug 2004
1460 * 1.1 Fixed handling of append/stack pop order of end text
1461 * Added Cleaning Hooks
1464 * @param string $text Text to be balanced.
1465 * @return string Balanced text.
1467 function force_balance_tags( $text ) {
1468 $tagstack = array();
1472 // Known single-entity/self-closing tags
1473 $single_tags = array( 'area', 'base', 'basefont', 'br', 'col', 'command', 'embed', 'frame', 'hr', 'img', 'input', 'isindex', 'link', 'meta', 'param', 'source' );
1474 // Tags that can be immediately nested within themselves
1475 $nestable_tags = array( 'blockquote', 'div', 'object', 'q', 'span' );
1477 // WP bug fix for comments - in case you REALLY meant to type '< !--'
1478 $text = str_replace('< !--', '< !--', $text);
1479 // WP bug fix for LOVE <3 (and other situations with '<' before a number)
1480 $text = preg_replace('#<([0-9]{1})#', '<$1', $text);
1482 while ( preg_match("/<(\/?[\w:]*)\s*([^>]*)>/", $text, $regex) ) {
1483 $newtext .= $tagqueue;
1485 $i = strpos($text, $regex[0]);
1486 $l = strlen($regex[0]);
1488 // clear the shifter
1491 if ( isset($regex[1][0]) && '/' == $regex[1][0] ) { // End Tag
1492 $tag = strtolower(substr($regex[1],1));
1493 // if too many closing tags
1494 if( $stacksize <= 0 ) {
1496 // or close to be safe $tag = '/' . $tag;
1498 // if stacktop value = tag close value then pop
1499 else if ( $tagstack[$stacksize - 1] == $tag ) { // found closing tag
1500 $tag = '</' . $tag . '>'; // Close Tag
1502 array_pop( $tagstack );
1504 } else { // closing tag not at top, search for it
1505 for ( $j = $stacksize-1; $j >= 0; $j-- ) {
1506 if ( $tagstack[$j] == $tag ) {
1507 // add tag to tagqueue
1508 for ( $k = $stacksize-1; $k >= $j; $k--) {
1509 $tagqueue .= '</' . array_pop( $tagstack ) . '>';
1517 } else { // Begin Tag
1518 $tag = strtolower($regex[1]);
1522 // If it's an empty tag "< >", do nothing
1526 // ElseIf it presents itself as a self-closing tag...
1527 elseif ( substr( $regex[2], -1 ) == '/' ) {
1528 // ...but it isn't a known single-entity self-closing tag, then don't let it be treated as such and
1529 // immediately close it with a closing tag (the tag will encapsulate no text as a result)
1530 if ( ! in_array( $tag, $single_tags ) )
1531 $regex[2] = trim( substr( $regex[2], 0, -1 ) ) . "></$tag";
1533 // ElseIf it's a known single-entity tag but it doesn't close itself, do so
1534 elseif ( in_array($tag, $single_tags) ) {
1537 // Else it's not a single-entity tag
1539 // If the top of the stack is the same as the tag we want to push, close previous tag
1540 if ( $stacksize > 0 && !in_array($tag, $nestable_tags) && $tagstack[$stacksize - 1] == $tag ) {
1541 $tagqueue = '</' . array_pop( $tagstack ) . '>';
1544 $stacksize = array_push( $tagstack, $tag );
1548 $attributes = $regex[2];
1549 if( ! empty( $attributes ) && $attributes[0] != '>' )
1550 $attributes = ' ' . $attributes;
1552 $tag = '<' . $tag . $attributes . '>';
1553 //If already queuing a close tag, then put this tag on, too
1554 if ( !empty($tagqueue) ) {
1559 $newtext .= substr($text, 0, $i) . $tag;
1560 $text = substr($text, $i + $l);
1564 $newtext .= $tagqueue;
1566 // Add Remaining text
1570 while( $x = array_pop($tagstack) )
1571 $newtext .= '</' . $x . '>'; // Add remaining tags to close
1573 // WP fix for the bug with HTML comments
1574 $newtext = str_replace("< !--","<!--",$newtext);
1575 $newtext = str_replace("< !--","< !--",$newtext);
1581 * Acts on text which is about to be edited.
1583 * The $content is run through esc_textarea(), which uses htmlspecialchars()
1584 * to convert special characters to HTML entities. If $richedit is set to true,
1585 * it is simply a holder for the 'format_to_edit' filter.
1589 * @param string $content The text about to be edited.
1590 * @param bool $richedit Whether the $content should not pass through htmlspecialchars(). Default false (meaning it will be passed).
1591 * @return string The text after the filter (and possibly htmlspecialchars()) has been run.
1593 function format_to_edit( $content, $richedit = false ) {
1595 * Filter the text to be formatted for editing.
1599 * @param string $content The text, prior to formatting for editing.
1601 $content = apply_filters( 'format_to_edit', $content );
1603 $content = esc_textarea( $content );
1608 * Add leading zeros when necessary.
1610 * If you set the threshold to '4' and the number is '10', then you will get
1611 * back '0010'. If you set the threshold to '4' and the number is '5000', then you
1612 * will get back '5000'.
1614 * Uses sprintf to append the amount of zeros based on the $threshold parameter
1615 * and the size of the number. If the number is large enough, then no zeros will
1620 * @param mixed $number Number to append zeros to if not greater than threshold.
1621 * @param int $threshold Digit places number needs to be to not have zeros added.
1622 * @return string Adds leading zeros to number if needed.
1624 function zeroise($number, $threshold) {
1625 return sprintf('%0'.$threshold.'s', $number);
1629 * Adds backslashes before letters and before a number at the start of a string.
1633 * @param string $string Value to which backslashes will be added.
1634 * @return string String with backslashes inserted.
1636 function backslashit($string) {
1637 if ( isset( $string[0] ) && $string[0] >= '0' && $string[0] <= '9' )
1638 $string = '\\\\' . $string;
1639 return addcslashes( $string, 'A..Za..z' );
1643 * Appends a trailing slash.
1645 * Will remove trailing forward and backslashes if it exists already before adding
1646 * a trailing forward slash. This prevents double slashing a string or path.
1648 * The primary use of this is for paths and thus should be used for paths. It is
1649 * not restricted to paths and offers no specific path support.
1653 * @param string $string What to add the trailing slash to.
1654 * @return string String with trailing slash added.
1656 function trailingslashit( $string ) {
1657 return untrailingslashit( $string ) . '/';
1661 * Removes trailing forward slashes and backslashes if they exist.
1663 * The primary use of this is for paths and thus should be used for paths. It is
1664 * not restricted to paths and offers no specific path support.
1668 * @param string $string What to remove the trailing slashes from.
1669 * @return string String without the trailing slashes.
1671 function untrailingslashit( $string ) {
1672 return rtrim( $string, '/\\' );
1676 * Adds slashes to escape strings.
1678 * Slashes will first be removed if magic_quotes_gpc is set, see {@link
1679 * http://www.php.net/magic_quotes} for more details.
1683 * @param string $gpc The string returned from HTTP request data.
1684 * @return string Returns a string escaped with slashes.
1686 function addslashes_gpc($gpc) {
1687 if ( get_magic_quotes_gpc() )
1688 $gpc = stripslashes($gpc);
1690 return wp_slash($gpc);
1694 * Navigates through an array and removes slashes from the values.
1696 * If an array is passed, the array_map() function causes a callback to pass the
1697 * value back to the function. The slashes from this value will removed.
1701 * @param mixed $value The value to be stripped.
1702 * @return mixed Stripped value.
1704 function stripslashes_deep($value) {
1705 if ( is_array($value) ) {
1706 $value = array_map('stripslashes_deep', $value);
1707 } elseif ( is_object($value) ) {
1708 $vars = get_object_vars( $value );
1709 foreach ($vars as $key=>$data) {
1710 $value->{$key} = stripslashes_deep( $data );
1712 } elseif ( is_string( $value ) ) {
1713 $value = stripslashes($value);
1720 * Navigates through an array and encodes the values to be used in a URL.
1725 * @param array|string $value The array or string to be encoded.
1726 * @return array|string $value The encoded array (or string from the callback).
1728 function urlencode_deep($value) {
1729 $value = is_array($value) ? array_map('urlencode_deep', $value) : urlencode($value);
1734 * Navigates through an array and raw encodes the values to be used in a URL.
1738 * @param array|string $value The array or string to be encoded.
1739 * @return array|string $value The encoded array (or string from the callback).
1741 function rawurlencode_deep( $value ) {
1742 return is_array( $value ) ? array_map( 'rawurlencode_deep', $value ) : rawurlencode( $value );
1746 * Converts email addresses characters to HTML entities to block spam bots.
1750 * @param string $email_address Email address.
1751 * @param int $hex_encoding Optional. Set to 1 to enable hex encoding.
1752 * @return string Converted email address.
1754 function antispambot( $email_address, $hex_encoding = 0 ) {
1755 $email_no_spam_address = '';
1756 for ( $i = 0; $i < strlen( $email_address ); $i++ ) {
1757 $j = rand( 0, 1 + $hex_encoding );
1759 $email_no_spam_address .= '&#' . ord( $email_address[$i] ) . ';';
1760 } elseif ( $j == 1 ) {
1761 $email_no_spam_address .= $email_address[$i];
1762 } elseif ( $j == 2 ) {
1763 $email_no_spam_address .= '%' . zeroise( dechex( ord( $email_address[$i] ) ), 2 );
1767 $email_no_spam_address = str_replace( '@', '@', $email_no_spam_address );
1769 return $email_no_spam_address;
1773 * Callback to convert URI match to HTML A element.
1775 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1776 * make_clickable()}.
1781 * @param array $matches Single Regex Match.
1782 * @return string HTML A element with URI address.
1784 function _make_url_clickable_cb($matches) {
1787 if ( ')' == $matches[3] && strpos( $url, '(' ) ) {
1788 // If the trailing character is a closing parethesis, and the URL has an opening parenthesis in it, add the closing parenthesis to the URL.
1789 // Then we can let the parenthesis balancer do its thing below.
1790 $url .= $matches[3];
1793 $suffix = $matches[3];
1796 // Include parentheses in the URL only if paired
1797 while ( substr_count( $url, '(' ) < substr_count( $url, ')' ) ) {
1798 $suffix = strrchr( $url, ')' ) . $suffix;
1799 $url = substr( $url, 0, strrpos( $url, ')' ) );
1802 $url = esc_url($url);
1806 return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $suffix;
1810 * Callback to convert URL match to HTML A element.
1812 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1813 * make_clickable()}.
1818 * @param array $matches Single Regex Match.
1819 * @return string HTML A element with URL address.
1821 function _make_web_ftp_clickable_cb($matches) {
1823 $dest = $matches[2];
1824 $dest = 'http://' . $dest;
1825 $dest = esc_url($dest);
1829 // removed trailing [.,;:)] from URL
1830 if ( in_array( substr($dest, -1), array('.', ',', ';', ':', ')') ) === true ) {
1831 $ret = substr($dest, -1);
1832 $dest = substr($dest, 0, strlen($dest)-1);
1834 return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>$ret";
1838 * Callback to convert email address match to HTML A element.
1840 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1841 * make_clickable()}.
1846 * @param array $matches Single Regex Match.
1847 * @return string HTML A element with email address.
1849 function _make_email_clickable_cb($matches) {
1850 $email = $matches[2] . '@' . $matches[3];
1851 return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
1855 * Convert plaintext URI to HTML links.
1857 * Converts URI, www and ftp, and email addresses. Finishes by fixing links
1862 * @param string $text Content to convert URIs.
1863 * @return string Content with converted URIs.
1865 function make_clickable( $text ) {
1867 $textarr = preg_split( '/(<[^<>]+>)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // split out HTML tags
1868 $nested_code_pre = 0; // Keep track of how many levels link is nested inside <pre> or <code>
1869 foreach ( $textarr as $piece ) {
1871 if ( preg_match( '|^<code[\s>]|i', $piece ) || preg_match( '|^<pre[\s>]|i', $piece ) )
1873 elseif ( ( '</code>' === strtolower( $piece ) || '</pre>' === strtolower( $piece ) ) && $nested_code_pre )
1876 if ( $nested_code_pre || empty( $piece ) || ( $piece[0] === '<' && ! preg_match( '|^<\s*[\w]{1,20}+://|', $piece ) ) ) {
1881 // Long strings might contain expensive edge cases ...
1882 if ( 10000 < strlen( $piece ) ) {
1884 foreach ( _split_str_by_whitespace( $piece, 2100 ) as $chunk ) { // 2100: Extra room for scheme and leading and trailing paretheses
1885 if ( 2101 < strlen( $chunk ) ) {
1886 $r .= $chunk; // Too big, no whitespace: bail.
1888 $r .= make_clickable( $chunk );
1892 $ret = " $piece "; // Pad with whitespace to simplify the regexes
1895 ([\\s(<.,;:!?]) # 1: Leading whitespace, or punctuation
1897 [\\w]{1,20}+:// # Scheme and hier-part prefix
1898 (?=\S{1,2000}\s) # Limit to URLs less than about 2000 characters long
1899 [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]*+ # Non-punctuation URL character
1900 (?: # Unroll the Loop: Only allow puctuation URL character if followed by a non-punctuation URL character
1901 [\'.,;:!?)] # Punctuation URL character
1902 [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]++ # Non-punctuation URL character
1905 (\)?) # 3: Trailing closing parenthesis (for parethesis balancing post processing)
1906 ~xS'; // The regex is a non-anchored pattern and does not have a single fixed starting character.
1907 // Tell PCRE to spend more time optimizing since, when used on a page load, it will probably be used several times.
1909 $ret = preg_replace_callback( $url_clickable, '_make_url_clickable_cb', $ret );
1911 $ret = preg_replace_callback( '#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]+)#is', '_make_web_ftp_clickable_cb', $ret );
1912 $ret = preg_replace_callback( '#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret );
1914 $ret = substr( $ret, 1, -1 ); // Remove our whitespace padding.
1919 // Cleanup of accidental links within links
1920 $r = preg_replace( '#(<a([ \r\n\t]+[^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i', "$1$3</a>", $r );
1925 * Breaks a string into chunks by splitting at whitespace characters.
1926 * The length of each returned chunk is as close to the specified length goal as possible,
1927 * with the caveat that each chunk includes its trailing delimiter.
1928 * Chunks longer than the goal are guaranteed to not have any inner whitespace.
1930 * Joining the returned chunks with empty delimiters reconstructs the input string losslessly.
1932 * Input string must have no null characters (or eventual transformations on output chunks must not care about null characters)
1935 * _split_str_by_whitespace( "1234 67890 1234 67890a cd 1234 890 123456789 1234567890a 45678 1 3 5 7 90 ", 10 ) ==
1937 * 0 => '1234 67890 ', // 11 characters: Perfect split
1938 * 1 => '1234 ', // 5 characters: '1234 67890a' was too long
1939 * 2 => '67890a cd ', // 10 characters: '67890a cd 1234' was too long
1940 * 3 => '1234 890 ', // 11 characters: Perfect split
1941 * 4 => '123456789 ', // 10 characters: '123456789 1234567890a' was too long
1942 * 5 => '1234567890a ', // 12 characters: Too long, but no inner whitespace on which to split
1943 * 6 => ' 45678 ', // 11 characters: Perfect split
1944 * 7 => '1 3 5 7 9', // 9 characters: End of $string
1951 * @param string $string The string to split.
1952 * @param int $goal The desired chunk length.
1953 * @return array Numeric array of chunks.
1955 function _split_str_by_whitespace( $string, $goal ) {
1958 $string_nullspace = strtr( $string, "\r\n\t\v\f ", "\000\000\000\000\000\000" );
1960 while ( $goal < strlen( $string_nullspace ) ) {
1961 $pos = strrpos( substr( $string_nullspace, 0, $goal + 1 ), "\000" );
1963 if ( false === $pos ) {
1964 $pos = strpos( $string_nullspace, "\000", $goal + 1 );
1965 if ( false === $pos ) {
1970 $chunks[] = substr( $string, 0, $pos + 1 );
1971 $string = substr( $string, $pos + 1 );
1972 $string_nullspace = substr( $string_nullspace, $pos + 1 );
1976 $chunks[] = $string;
1983 * Adds rel nofollow string to all HTML A elements in content.
1987 * @param string $text Content that may contain HTML A elements.
1988 * @return string Converted content.
1990 function wp_rel_nofollow( $text ) {
1991 // This is a pre save filter, so text is already escaped.
1992 $text = stripslashes($text);
1993 $text = preg_replace_callback('|<a (.+?)>|i', 'wp_rel_nofollow_callback', $text);
1994 $text = wp_slash($text);
1999 * Callback to add rel=nofollow string to HTML A element.
2001 * Will remove already existing rel="nofollow" and rel='nofollow' from the
2002 * string to prevent from invalidating (X)HTML.
2006 * @param array $matches Single Match
2007 * @return string HTML A Element with rel nofollow.
2009 function wp_rel_nofollow_callback( $matches ) {
2010 $text = $matches[1];
2011 $text = str_replace(array(' rel="nofollow"', " rel='nofollow'"), '', $text);
2012 return "<a $text rel=\"nofollow\">";
2016 * Convert one smiley code to the icon graphic file equivalent.
2018 * Callback handler for {@link convert_smilies()}.
2019 * Looks up one smiley code in the $wpsmiliestrans global array and returns an
2020 * <img> string for that smiley.
2022 * @global array $wpsmiliestrans
2025 * @param array $matches Single match. Smiley code to convert to image.
2026 * @return string Image string for smiley.
2028 function translate_smiley( $matches ) {
2029 global $wpsmiliestrans;
2031 if ( count( $matches ) == 0 )
2034 $smiley = trim( reset( $matches ) );
2035 $img = $wpsmiliestrans[ $smiley ];
2038 * Filter the Smiley image URL before it's used in the image element.
2042 * @param string $smiley_url URL for the smiley image.
2043 * @param string $img Filename for the smiley image.
2044 * @param string $site_url Site URL, as returned by site_url().
2046 $src_url = apply_filters( 'smilies_src', includes_url( "images/smilies/$img" ), $img, site_url() );
2048 return sprintf( '<img src="%s" alt="%s" class="wp-smiley" />', esc_url( $src_url ), esc_attr( $smiley ) );
2052 * Convert text equivalent of smilies to images.
2054 * Will only convert smilies if the option 'use_smilies' is true and the global
2055 * used in the function isn't empty.
2058 * @uses $wp_smiliessearch
2060 * @param string $text Content to convert smilies from text.
2061 * @return string Converted content with text smilies replaced with images.
2063 function convert_smilies( $text ) {
2064 global $wp_smiliessearch;
2066 if ( get_option( 'use_smilies' ) && ! empty( $wp_smiliessearch ) ) {
2067 // HTML loop taken from texturize function, could possible be consolidated
2068 $textarr = preg_split( '/(<.*>)/U', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // capture the tags as well as in between
2069 $stop = count( $textarr );// loop stuff
2071 // Ignore proessing of specific tags
2072 $tags_to_ignore = 'code|pre|style|script|textarea';
2073 $ignore_block_element = '';
2075 for ( $i = 0; $i < $stop; $i++ ) {
2076 $content = $textarr[$i];
2078 // If we're in an ignore block, wait until we find its closing tag
2079 if ( '' == $ignore_block_element && preg_match( '/^<(' . $tags_to_ignore . ')>/', $content, $matches ) ) {
2080 $ignore_block_element = $matches[1];
2083 // If it's not a tag and not in ignore block
2084 if ( '' == $ignore_block_element && strlen( $content ) > 0 && '<' != $content[0] ) {
2085 $content = preg_replace_callback( $wp_smiliessearch, 'translate_smiley', $content );
2088 // did we exit ignore block
2089 if ( '' != $ignore_block_element && '</' . $ignore_block_element . '>' == $content ) {
2090 $ignore_block_element = '';
2093 $output .= $content;
2096 // return default text.
2103 * Verifies that an email is valid.
2105 * Does not grok i18n domains. Not RFC compliant.
2109 * @param string $email Email address to verify.
2110 * @param boolean $deprecated Deprecated.
2111 * @return string|bool Either false or the valid email address.
2113 function is_email( $email, $deprecated = false ) {
2114 if ( ! empty( $deprecated ) )
2115 _deprecated_argument( __FUNCTION__, '3.0' );
2117 // Test for the minimum length the email can be
2118 if ( strlen( $email ) < 3 ) {
2120 * Filter whether an email address is valid.
2122 * This filter is evaluated under several different contexts, such as 'email_too_short',
2123 * 'email_no_at', 'local_invalid_chars', 'domain_period_sequence', 'domain_period_limits',
2124 * 'domain_no_periods', 'sub_hyphen_limits', 'sub_invalid_chars', or no specific context.
2128 * @param bool $is_email Whether the email address has passed the is_email() checks. Default false.
2129 * @param string $email The email address being checked.
2130 * @param string $message An explanatory message to the user.
2131 * @param string $context Context under which the email was tested.
2133 return apply_filters( 'is_email', false, $email, 'email_too_short' );
2136 // Test for an @ character after the first position
2137 if ( strpos( $email, '@', 1 ) === false ) {
2138 /** This filter is documented in wp-includes/formatting.php */
2139 return apply_filters( 'is_email', false, $email, 'email_no_at' );
2142 // Split out the local and domain parts
2143 list( $local, $domain ) = explode( '@', $email, 2 );
2146 // Test for invalid characters
2147 if ( !preg_match( '/^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]+$/', $local ) ) {
2148 /** This filter is documented in wp-includes/formatting.php */
2149 return apply_filters( 'is_email', false, $email, 'local_invalid_chars' );
2153 // Test for sequences of periods
2154 if ( preg_match( '/\.{2,}/', $domain ) ) {
2155 /** This filter is documented in wp-includes/formatting.php */
2156 return apply_filters( 'is_email', false, $email, 'domain_period_sequence' );
2159 // Test for leading and trailing periods and whitespace
2160 if ( trim( $domain, " \t\n\r\0\x0B." ) !== $domain ) {
2161 /** This filter is documented in wp-includes/formatting.php */
2162 return apply_filters( 'is_email', false, $email, 'domain_period_limits' );
2165 // Split the domain into subs
2166 $subs = explode( '.', $domain );
2168 // Assume the domain will have at least two subs
2169 if ( 2 > count( $subs ) ) {
2170 /** This filter is documented in wp-includes/formatting.php */
2171 return apply_filters( 'is_email', false, $email, 'domain_no_periods' );
2174 // Loop through each sub
2175 foreach ( $subs as $sub ) {
2176 // Test for leading and trailing hyphens and whitespace
2177 if ( trim( $sub, " \t\n\r\0\x0B-" ) !== $sub ) {
2178 /** This filter is documented in wp-includes/formatting.php */
2179 return apply_filters( 'is_email', false, $email, 'sub_hyphen_limits' );
2182 // Test for invalid characters
2183 if ( !preg_match('/^[a-z0-9-]+$/i', $sub ) ) {
2184 /** This filter is documented in wp-includes/formatting.php */
2185 return apply_filters( 'is_email', false, $email, 'sub_invalid_chars' );
2189 // Congratulations your email made it!
2190 /** This filter is documented in wp-includes/formatting.php */
2191 return apply_filters( 'is_email', $email, $email, null );
2195 * Convert to ASCII from email subjects.
2199 * @param string $string Subject line
2200 * @return string Converted string to ASCII
2202 function wp_iso_descrambler($string) {
2203 /* this may only work with iso-8859-1, I'm afraid */
2204 if (!preg_match('#\=\?(.+)\?Q\?(.+)\?\=#i', $string, $matches)) {
2207 $subject = str_replace('_', ' ', $matches[2]);
2208 $subject = preg_replace_callback('#\=([0-9a-f]{2})#i', '_wp_iso_convert', $subject);
2214 * Helper function to convert hex encoded chars to ASCII
2219 * @param array $match The preg_replace_callback matches array
2220 * @return array Converted chars
2222 function _wp_iso_convert( $match ) {
2223 return chr( hexdec( strtolower( $match[1] ) ) );
2227 * Returns a date in the GMT equivalent.
2229 * Requires and returns a date in the Y-m-d H:i:s format. If there is a
2230 * timezone_string available, the date is assumed to be in that timezone,
2231 * otherwise it simply subtracts the value of the 'gmt_offset' option. Return
2232 * format can be overridden using the $format parameter.
2236 * @uses get_option() to retrieve the value of 'gmt_offset'.
2237 * @param string $string The date to be converted.
2238 * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
2239 * @return string GMT version of the date provided.
2241 function get_gmt_from_date( $string, $format = 'Y-m-d H:i:s' ) {
2242 $tz = get_option( 'timezone_string' );
2244 $datetime = date_create( $string, new DateTimeZone( $tz ) );
2246 return gmdate( $format, 0 );
2247 $datetime->setTimezone( new DateTimeZone( 'UTC' ) );
2248 $string_gmt = $datetime->format( $format );
2250 if ( ! preg_match( '#([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})#', $string, $matches ) )
2251 return gmdate( $format, 0 );
2252 $string_time = gmmktime( $matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1] );
2253 $string_gmt = gmdate( $format, $string_time - get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
2259 * Converts a GMT date into the correct format for the blog.
2261 * Requires and returns a date in the Y-m-d H:i:s format. If there is a
2262 * timezone_string available, the returned date is in that timezone, otherwise
2263 * it simply adds the value of gmt_offset. Return format can be overridden
2264 * using the $format parameter
2268 * @param string $string The date to be converted.
2269 * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
2270 * @return string Formatted date relative to the timezone / GMT offset.
2272 function get_date_from_gmt( $string, $format = 'Y-m-d H:i:s' ) {
2273 $tz = get_option( 'timezone_string' );
2275 $datetime = date_create( $string, new DateTimeZone( 'UTC' ) );
2277 return date( $format, 0 );
2278 $datetime->setTimezone( new DateTimeZone( $tz ) );
2279 $string_localtime = $datetime->format( $format );
2281 if ( ! preg_match('#([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})#', $string, $matches) )
2282 return date( $format, 0 );
2283 $string_time = gmmktime( $matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1] );
2284 $string_localtime = gmdate( $format, $string_time + get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
2286 return $string_localtime;
2290 * Computes an offset in seconds from an iso8601 timezone.
2294 * @param string $timezone Either 'Z' for 0 offset or '±hhmm'.
2295 * @return int|float The offset in seconds.
2297 function iso8601_timezone_to_offset($timezone) {
2298 // $timezone is either 'Z' or '[+|-]hhmm'
2299 if ($timezone == 'Z') {
2302 $sign = (substr($timezone, 0, 1) == '+') ? 1 : -1;
2303 $hours = intval(substr($timezone, 1, 2));
2304 $minutes = intval(substr($timezone, 3, 4)) / 60;
2305 $offset = $sign * HOUR_IN_SECONDS * ($hours + $minutes);
2311 * Converts an iso8601 date to MySQL DateTime format used by post_date[_gmt].
2315 * @param string $date_string Date and time in ISO 8601 format {@link http://en.wikipedia.org/wiki/ISO_8601}.
2316 * @param string $timezone Optional. If set to GMT returns the time minus gmt_offset. Default is 'user'.
2317 * @return string The date and time in MySQL DateTime format - Y-m-d H:i:s.
2319 function iso8601_to_datetime($date_string, $timezone = 'user') {
2320 $timezone = strtolower($timezone);
2322 if ($timezone == 'gmt') {
2324 preg_match('#([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(Z|[\+|\-][0-9]{2,4}){0,1}#', $date_string, $date_bits);
2326 if (!empty($date_bits[7])) { // we have a timezone, so let's compute an offset
2327 $offset = iso8601_timezone_to_offset($date_bits[7]);
2328 } else { // we don't have a timezone, so we assume user local timezone (not server's!)
2329 $offset = HOUR_IN_SECONDS * get_option('gmt_offset');
2332 $timestamp = gmmktime($date_bits[4], $date_bits[5], $date_bits[6], $date_bits[2], $date_bits[3], $date_bits[1]);
2333 $timestamp -= $offset;
2335 return gmdate('Y-m-d H:i:s', $timestamp);
2337 } else if ($timezone == 'user') {
2338 return preg_replace('#([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(Z|[\+|\-][0-9]{2,4}){0,1}#', '$1-$2-$3 $4:$5:$6', $date_string);
2343 * Adds a element attributes to open links in new windows.
2345 * Comment text in popup windows should be filtered through this. Right now it's
2346 * a moderately dumb function, ideally it would detect whether a target or rel
2347 * attribute was already there and adjust its actions accordingly.
2351 * @param string $text Content to replace links to open in a new window.
2352 * @return string Content that has filtered links.
2354 function popuplinks($text) {
2355 $text = preg_replace('/<a (.+?)>/i', "<a $1 target='_blank' rel='external'>", $text);
2360 * Strips out all characters that are not allowable in an email.
2364 * @param string $email Email address to filter.
2365 * @return string Filtered email address.
2367 function sanitize_email( $email ) {
2368 // Test for the minimum length the email can be
2369 if ( strlen( $email ) < 3 ) {
2371 * Filter a sanitized email address.
2373 * This filter is evaluated under several contexts, including 'email_too_short',
2374 * 'email_no_at', 'local_invalid_chars', 'domain_period_sequence', 'domain_period_limits',
2375 * 'domain_no_periods', 'domain_no_valid_subs', or no context.
2379 * @param string $email The sanitized email address.
2380 * @param string $email The email address, as provided to sanitize_email().
2381 * @param string $message A message to pass to the user.
2383 return apply_filters( 'sanitize_email', '', $email, 'email_too_short' );
2386 // Test for an @ character after the first position
2387 if ( strpos( $email, '@', 1 ) === false ) {
2388 /** This filter is documented in wp-includes/formatting.php */
2389 return apply_filters( 'sanitize_email', '', $email, 'email_no_at' );
2392 // Split out the local and domain parts
2393 list( $local, $domain ) = explode( '@', $email, 2 );
2396 // Test for invalid characters
2397 $local = preg_replace( '/[^a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]/', '', $local );
2398 if ( '' === $local ) {
2399 /** This filter is documented in wp-includes/formatting.php */
2400 return apply_filters( 'sanitize_email', '', $email, 'local_invalid_chars' );
2404 // Test for sequences of periods
2405 $domain = preg_replace( '/\.{2,}/', '', $domain );
2406 if ( '' === $domain ) {
2407 /** This filter is documented in wp-includes/formatting.php */
2408 return apply_filters( 'sanitize_email', '', $email, 'domain_period_sequence' );
2411 // Test for leading and trailing periods and whitespace
2412 $domain = trim( $domain, " \t\n\r\0\x0B." );
2413 if ( '' === $domain ) {
2414 /** This filter is documented in wp-includes/formatting.php */
2415 return apply_filters( 'sanitize_email', '', $email, 'domain_period_limits' );
2418 // Split the domain into subs
2419 $subs = explode( '.', $domain );
2421 // Assume the domain will have at least two subs
2422 if ( 2 > count( $subs ) ) {
2423 /** This filter is documented in wp-includes/formatting.php */
2424 return apply_filters( 'sanitize_email', '', $email, 'domain_no_periods' );
2427 // Create an array that will contain valid subs
2428 $new_subs = array();
2430 // Loop through each sub
2431 foreach ( $subs as $sub ) {
2432 // Test for leading and trailing hyphens
2433 $sub = trim( $sub, " \t\n\r\0\x0B-" );
2435 // Test for invalid characters
2436 $sub = preg_replace( '/[^a-z0-9-]+/i', '', $sub );
2438 // If there's anything left, add it to the valid subs
2439 if ( '' !== $sub ) {
2444 // If there aren't 2 or more valid subs
2445 if ( 2 > count( $new_subs ) ) {
2446 /** This filter is documented in wp-includes/formatting.php */
2447 return apply_filters( 'sanitize_email', '', $email, 'domain_no_valid_subs' );
2450 // Join valid subs into the new domain
2451 $domain = join( '.', $new_subs );
2453 // Put the email back together
2454 $email = $local . '@' . $domain;
2456 // Congratulations your email made it!
2457 /** This filter is documented in wp-includes/formatting.php */
2458 return apply_filters( 'sanitize_email', $email, $email, null );
2462 * Determines the difference between two timestamps.
2464 * The difference is returned in a human readable format such as "1 hour",
2465 * "5 mins", "2 days".
2469 * @param int $from Unix timestamp from which the difference begins.
2470 * @param int $to Optional. Unix timestamp to end the time difference. Default becomes time() if not set.
2471 * @return string Human readable time difference.
2473 function human_time_diff( $from, $to = '' ) {
2474 if ( empty( $to ) ) {
2478 $diff = (int) abs( $to - $from );
2480 if ( $diff < HOUR_IN_SECONDS ) {
2481 $mins = round( $diff / MINUTE_IN_SECONDS );
2484 /* translators: min=minute */
2485 $since = sprintf( _n( '%s min', '%s mins', $mins ), $mins );
2486 } elseif ( $diff < DAY_IN_SECONDS && $diff >= HOUR_IN_SECONDS ) {
2487 $hours = round( $diff / HOUR_IN_SECONDS );
2490 $since = sprintf( _n( '%s hour', '%s hours', $hours ), $hours );
2491 } elseif ( $diff < WEEK_IN_SECONDS && $diff >= DAY_IN_SECONDS ) {
2492 $days = round( $diff / DAY_IN_SECONDS );
2495 $since = sprintf( _n( '%s day', '%s days', $days ), $days );
2496 } elseif ( $diff < 30 * DAY_IN_SECONDS && $diff >= WEEK_IN_SECONDS ) {
2497 $weeks = round( $diff / WEEK_IN_SECONDS );
2500 $since = sprintf( _n( '%s week', '%s weeks', $weeks ), $weeks );
2501 } elseif ( $diff < YEAR_IN_SECONDS && $diff >= 30 * DAY_IN_SECONDS ) {
2502 $months = round( $diff / ( 30 * DAY_IN_SECONDS ) );
2505 $since = sprintf( _n( '%s month', '%s months', $months ), $months );
2506 } elseif ( $diff >= YEAR_IN_SECONDS ) {
2507 $years = round( $diff / YEAR_IN_SECONDS );
2510 $since = sprintf( _n( '%s year', '%s years', $years ), $years );
2514 * Filter the human readable difference between two timestamps.
2518 * @param string $since The difference in human readable text.
2519 * @param int $diff The difference in seconds.
2520 * @param int $from Unix timestamp from which the difference begins.
2521 * @param int $to Unix timestamp to end the time difference.
2523 return apply_filters( 'human_time_diff', $since, $diff, $from, $to );
2527 * Generates an excerpt from the content, if needed.
2529 * The excerpt word amount will be 55 words and if the amount is greater than
2530 * that, then the string ' […]' will be appended to the excerpt. If the string
2531 * is less than 55 words, then the content will be returned as is.
2533 * The 55 word limit can be modified by plugins/themes using the excerpt_length filter
2534 * The ' […]' string can be modified by plugins/themes using the excerpt_more filter
2538 * @param string $text Optional. The excerpt. If set to empty, an excerpt is generated.
2539 * @return string The excerpt.
2541 function wp_trim_excerpt($text = '') {
2542 $raw_excerpt = $text;
2543 if ( '' == $text ) {
2544 $text = get_the_content('');
2546 $text = strip_shortcodes( $text );
2548 /** This filter is documented in wp-includes/post-template.php */
2549 $text = apply_filters( 'the_content', $text );
2550 $text = str_replace(']]>', ']]>', $text);
2553 * Filter the number of words in an excerpt.
2557 * @param int $number The number of words. Default 55.
2559 $excerpt_length = apply_filters( 'excerpt_length', 55 );
2561 * Filter the string in the "more" link displayed after a trimmed excerpt.
2565 * @param string $more_string The string shown within the more link.
2567 $excerpt_more = apply_filters( 'excerpt_more', ' ' . '[…]' );
2568 $text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
2571 * Filter the trimmed excerpt string.
2575 * @param string $text The trimmed text.
2576 * @param string $raw_excerpt The text prior to trimming.
2578 return apply_filters( 'wp_trim_excerpt', $text, $raw_excerpt );
2582 * Trims text to a certain number of words.
2584 * This function is localized. For languages that count 'words' by the individual
2585 * character (such as East Asian languages), the $num_words argument will apply
2586 * to the number of individual characters.
2590 * @param string $text Text to trim.
2591 * @param int $num_words Number of words. Default 55.
2592 * @param string $more Optional. What to append if $text needs to be trimmed. Default '…'.
2593 * @return string Trimmed text.
2595 function wp_trim_words( $text, $num_words = 55, $more = null ) {
2596 if ( null === $more )
2597 $more = __( '…' );
2598 $original_text = $text;
2599 $text = wp_strip_all_tags( $text );
2600 /* translators: If your word count is based on single characters (East Asian characters),
2601 enter 'characters'. Otherwise, enter 'words'. Do not translate into your own language. */
2602 if ( 'characters' == _x( 'words', 'word count: words or characters?' ) && preg_match( '/^utf\-?8$/i', get_option( 'blog_charset' ) ) ) {
2603 $text = trim( preg_replace( "/[\n\r\t ]+/", ' ', $text ), ' ' );
2604 preg_match_all( '/./u', $text, $words_array );
2605 $words_array = array_slice( $words_array[0], 0, $num_words + 1 );
2608 $words_array = preg_split( "/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY );
2611 if ( count( $words_array ) > $num_words ) {
2612 array_pop( $words_array );
2613 $text = implode( $sep, $words_array );
2614 $text = $text . $more;
2616 $text = implode( $sep, $words_array );
2619 * Filter the text content after words have been trimmed.
2623 * @param string $text The trimmed text.
2624 * @param int $num_words The number of words to trim the text to. Default 5.
2625 * @param string $more An optional string to append to the end of the trimmed text, e.g. ….
2626 * @param string $original_text The text before it was trimmed.
2628 return apply_filters( 'wp_trim_words', $text, $num_words, $more, $original_text );
2632 * Converts named entities into numbered entities.
2636 * @param string $text The text within which entities will be converted.
2637 * @return string Text with converted entities.
2639 function ent2ncr($text) {
2642 * Filter text before named entities are converted into numbered entities.
2644 * A non-null string must be returned for the filter to be evaluated.
2648 * @param null $converted_text The text to be converted. Default null.
2649 * @param string $text The text prior to entity conversion.
2651 $filtered = apply_filters( 'pre_ent2ncr', null, $text );
2652 if( null !== $filtered )
2656 '"' => '"',
2661 ' ' => ' ',
2662 '¡' => '¡',
2663 '¢' => '¢',
2664 '£' => '£',
2665 '¤' => '¤',
2666 '¥' => '¥',
2667 '¦' => '¦',
2668 '&brkbar;' => '¦',
2669 '§' => '§',
2670 '¨' => '¨',
2671 '¨' => '¨',
2672 '©' => '©',
2673 'ª' => 'ª',
2674 '«' => '«',
2675 '¬' => '¬',
2676 '­' => '­',
2677 '®' => '®',
2678 '¯' => '¯',
2679 '&hibar;' => '¯',
2680 '°' => '°',
2681 '±' => '±',
2682 '²' => '²',
2683 '³' => '³',
2684 '´' => '´',
2685 'µ' => 'µ',
2686 '¶' => '¶',
2687 '·' => '·',
2688 '¸' => '¸',
2689 '¹' => '¹',
2690 'º' => 'º',
2691 '»' => '»',
2692 '¼' => '¼',
2693 '½' => '½',
2694 '¾' => '¾',
2695 '¿' => '¿',
2696 'À' => 'À',
2697 'Á' => 'Á',
2698 'Â' => 'Â',
2699 'Ã' => 'Ã',
2700 'Ä' => 'Ä',
2701 'Å' => 'Å',
2702 'Æ' => 'Æ',
2703 'Ç' => 'Ç',
2704 'È' => 'È',
2705 'É' => 'É',
2706 'Ê' => 'Ê',
2707 'Ë' => 'Ë',
2708 'Ì' => 'Ì',
2709 'Í' => 'Í',
2710 'Î' => 'Î',
2711 'Ï' => 'Ï',
2712 'Ð' => 'Ð',
2713 'Ñ' => 'Ñ',
2714 'Ò' => 'Ò',
2715 'Ó' => 'Ó',
2716 'Ô' => 'Ô',
2717 'Õ' => 'Õ',
2718 'Ö' => 'Ö',
2719 '×' => '×',
2720 'Ø' => 'Ø',
2721 'Ù' => 'Ù',
2722 'Ú' => 'Ú',
2723 'Û' => 'Û',
2724 'Ü' => 'Ü',
2725 'Ý' => 'Ý',
2726 'Þ' => 'Þ',
2727 'ß' => 'ß',
2728 'à' => 'à',
2729 'á' => 'á',
2730 'â' => 'â',
2731 'ã' => 'ã',
2732 'ä' => 'ä',
2733 'å' => 'å',
2734 'æ' => 'æ',
2735 'ç' => 'ç',
2736 'è' => 'è',
2737 'é' => 'é',
2738 'ê' => 'ê',
2739 'ë' => 'ë',
2740 'ì' => 'ì',
2741 'í' => 'í',
2742 'î' => 'î',
2743 'ï' => 'ï',
2744 'ð' => 'ð',
2745 'ñ' => 'ñ',
2746 'ò' => 'ò',
2747 'ó' => 'ó',
2748 'ô' => 'ô',
2749 'õ' => 'õ',
2750 'ö' => 'ö',
2751 '÷' => '÷',
2752 'ø' => 'ø',
2753 'ù' => 'ù',
2754 'ú' => 'ú',
2755 'û' => 'û',
2756 'ü' => 'ü',
2757 'ý' => 'ý',
2758 'þ' => 'þ',
2759 'ÿ' => 'ÿ',
2760 'Œ' => 'Œ',
2761 'œ' => 'œ',
2762 'Š' => 'Š',
2763 'š' => 'š',
2764 'Ÿ' => 'Ÿ',
2765 'ƒ' => 'ƒ',
2766 'ˆ' => 'ˆ',
2767 '˜' => '˜',
2768 'Α' => 'Α',
2769 'Β' => 'Β',
2770 'Γ' => 'Γ',
2771 'Δ' => 'Δ',
2772 'Ε' => 'Ε',
2773 'Ζ' => 'Ζ',
2774 'Η' => 'Η',
2775 'Θ' => 'Θ',
2776 'Ι' => 'Ι',
2777 'Κ' => 'Κ',
2778 'Λ' => 'Λ',
2782 'Ο' => 'Ο',
2784 'Ρ' => 'Ρ',
2785 'Σ' => 'Σ',
2786 'Τ' => 'Τ',
2787 'Υ' => 'Υ',
2788 'Φ' => 'Φ',
2789 'Χ' => 'Χ',
2790 'Ψ' => 'Ψ',
2791 'Ω' => 'Ω',
2792 'α' => 'α',
2793 'β' => 'β',
2794 'γ' => 'γ',
2795 'δ' => 'δ',
2796 'ε' => 'ε',
2797 'ζ' => 'ζ',
2798 'η' => 'η',
2799 'θ' => 'θ',
2800 'ι' => 'ι',
2801 'κ' => 'κ',
2802 'λ' => 'λ',
2806 'ο' => 'ο',
2808 'ρ' => 'ρ',
2809 'ς' => 'ς',
2810 'σ' => 'σ',
2811 'τ' => 'τ',
2812 'υ' => 'υ',
2813 'φ' => 'φ',
2814 'χ' => 'χ',
2815 'ψ' => 'ψ',
2816 'ω' => 'ω',
2817 'ϑ' => 'ϑ',
2818 'ϒ' => 'ϒ',
2819 'ϖ' => 'ϖ',
2820 ' ' => ' ',
2821 ' ' => ' ',
2822 ' ' => ' ',
2823 '‌' => '‌',
2824 '‍' => '‍',
2825 '‎' => '‎',
2826 '‏' => '‏',
2827 '–' => '–',
2828 '—' => '—',
2829 '‘' => '‘',
2830 '’' => '’',
2831 '‚' => '‚',
2832 '“' => '“',
2833 '”' => '”',
2834 '„' => '„',
2835 '†' => '†',
2836 '‡' => '‡',
2837 '•' => '•',
2838 '…' => '…',
2839 '‰' => '‰',
2840 '′' => '′',
2841 '″' => '″',
2842 '‹' => '‹',
2843 '›' => '›',
2844 '‾' => '‾',
2845 '⁄' => '⁄',
2846 '€' => '€',
2847 'ℑ' => 'ℑ',
2848 '℘' => '℘',
2849 'ℜ' => 'ℜ',
2850 '™' => '™',
2851 'ℵ' => 'ℵ',
2852 '↵' => '↵',
2853 '⇐' => '⇐',
2854 '⇑' => '⇑',
2855 '⇒' => '⇒',
2856 '⇓' => '⇓',
2857 '⇔' => '⇔',
2858 '∀' => '∀',
2859 '∂' => '∂',
2860 '∃' => '∃',
2861 '∅' => '∅',
2862 '∇' => '∇',
2863 '∈' => '∈',
2864 '∉' => '∉',
2865 '∋' => '∋',
2866 '∏' => '∏',
2867 '∑' => '∑',
2868 '−' => '−',
2869 '∗' => '∗',
2870 '√' => '√',
2871 '∝' => '∝',
2872 '∞' => '∞',
2873 '∠' => '∠',
2874 '∧' => '∧',
2875 '∨' => '∨',
2876 '∩' => '∩',
2877 '∪' => '∪',
2878 '∫' => '∫',
2879 '∴' => '∴',
2880 '∼' => '∼',
2881 '≅' => '≅',
2882 '≈' => '≈',
2883 '≠' => '≠',
2884 '≡' => '≡',
2885 '≤' => '≤',
2886 '≥' => '≥',
2887 '⊂' => '⊂',
2888 '⊃' => '⊃',
2889 '⊄' => '⊄',
2890 '⊆' => '⊆',
2891 '⊇' => '⊇',
2892 '⊕' => '⊕',
2893 '⊗' => '⊗',
2894 '⊥' => '⊥',
2895 '⋅' => '⋅',
2896 '⌈' => '⌈',
2897 '⌉' => '⌉',
2898 '⌊' => '⌊',
2899 '⌋' => '⌋',
2900 '⟨' => '〈',
2901 '⟩' => '〉',
2902 '←' => '←',
2903 '↑' => '↑',
2904 '→' => '→',
2905 '↓' => '↓',
2906 '↔' => '↔',
2907 '◊' => '◊',
2908 '♠' => '♠',
2909 '♣' => '♣',
2910 '♥' => '♥',
2911 '♦' => '♦'
2914 return str_replace( array_keys($to_ncr), array_values($to_ncr), $text );
2918 * Formats text for the rich text editor.
2920 * The filter 'richedit_pre' is applied here. If $text is empty the filter will
2921 * be applied to an empty string.
2925 * @param string $text The text to be formatted.
2926 * @return string The formatted text after filter is applied.
2928 function wp_richedit_pre($text) {
2929 if ( empty( $text ) ) {
2931 * Filter text returned for the rich text editor.
2933 * This filter is first evaluated, and the value returned, if an empty string
2934 * is passed to wp_richedit_pre(). If an empty string is passed, it results
2935 * in a break tag and line feed.
2937 * If a non-empty string is passed, the filter is evaluated on the wp_richedit_pre()
2938 * return after being formatted.
2942 * @param string $output Text for the rich text editor.
2944 return apply_filters( 'richedit_pre', '' );
2947 $output = convert_chars($text);
2948 $output = wpautop($output);
2949 $output = htmlspecialchars($output, ENT_NOQUOTES, get_option( 'blog_charset' ) );
2951 /** This filter is documented in wp-includes/formatting.php */
2952 return apply_filters( 'richedit_pre', $output );
2956 * Formats text for the HTML editor.
2958 * Unless $output is empty it will pass through htmlspecialchars before the
2959 * 'htmledit_pre' filter is applied.
2963 * @param string $output The text to be formatted.
2964 * @return string Formatted text after filter applied.
2966 function wp_htmledit_pre($output) {
2967 if ( !empty($output) )
2968 $output = htmlspecialchars($output, ENT_NOQUOTES, get_option( 'blog_charset' ) ); // convert only < > &
2971 * Filter the text before it is formatted for the HTML editor.
2975 * @param string $output The HTML-formatted text.
2977 return apply_filters( 'htmledit_pre', $output );
2981 * Perform a deep string replace operation to ensure the values in $search are no longer present
2983 * Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values
2984 * e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that
2985 * str_replace would return
2990 * @param string|array $search The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.
2991 * @param string $subject The string being searched and replaced on, otherwise known as the haystack.
2992 * @return string The string with the replaced svalues.
2994 function _deep_replace( $search, $subject ) {
2995 $subject = (string) $subject;
2999 $subject = str_replace( $search, '', $subject, $count );
3006 * Escapes data for use in a MySQL query.
3008 * Usually you should prepare queries using wpdb::prepare().
3009 * Sometimes, spot-escaping is required or useful. One example
3010 * is preparing an array for use in an IN clause.
3013 * @param string|array $data Unescaped data
3014 * @return string|array Escaped data
3016 function esc_sql( $data ) {
3018 return $wpdb->_escape( $data );
3022 * Checks and cleans a URL.
3024 * A number of characters are removed from the URL. If the URL is for displaying
3025 * (the default behaviour) ampersands are also replaced. The 'clean_url' filter
3026 * is applied to the returned cleaned URL.
3029 * @uses wp_kses_bad_protocol() To only permit protocols in the URL set
3030 * via $protocols or the common ones set in the function.
3032 * @param string $url The URL to be cleaned.
3033 * @param array $protocols Optional. An array of acceptable protocols.
3034 * Defaults to 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn' if not set.
3035 * @param string $_context Private. Use esc_url_raw() for database usage.
3036 * @return string The cleaned $url after the 'clean_url' filter is applied.
3038 function esc_url( $url, $protocols = null, $_context = 'display' ) {
3039 $original_url = $url;
3043 $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);
3044 $strip = array('%0d', '%0a', '%0D', '%0A');
3045 $url = _deep_replace($strip, $url);
3046 $url = str_replace(';//', '://', $url);
3047 /* If the URL doesn't appear to contain a scheme, we
3048 * presume it needs http:// appended (unless a relative
3049 * link starting with /, # or ? or a php file).
3051 if ( strpos($url, ':') === false && ! in_array( $url[0], array( '/', '#', '?' ) ) &&
3052 ! preg_match('/^[a-z0-9-]+?\.php/i', $url) )
3053 $url = 'http://' . $url;
3055 // Replace ampersands and single quotes only when displaying.
3056 if ( 'display' == $_context ) {
3057 $url = wp_kses_normalize_entities( $url );
3058 $url = str_replace( '&', '&', $url );
3059 $url = str_replace( "'", ''', $url );
3062 if ( '/' === $url[0] ) {
3063 $good_protocol_url = $url;
3065 if ( ! is_array( $protocols ) )
3066 $protocols = wp_allowed_protocols();
3067 $good_protocol_url = wp_kses_bad_protocol( $url, $protocols );
3068 if ( strtolower( $good_protocol_url ) != strtolower( $url ) )
3073 * Filter a string cleaned and escaped for output as a URL.
3077 * @param string $good_protocol_url The cleaned URL to be returned.
3078 * @param string $original_url The URL prior to cleaning.
3079 * @param string $_context If 'display', replace ampersands and single quotes only.
3081 return apply_filters( 'clean_url', $good_protocol_url, $original_url, $_context );
3085 * Performs esc_url() for database usage.
3090 * @param string $url The URL to be cleaned.
3091 * @param array $protocols An array of acceptable protocols.
3092 * @return string The cleaned URL.
3094 function esc_url_raw( $url, $protocols = null ) {
3095 return esc_url( $url, $protocols, 'db' );
3099 * Convert entities, while preserving already-encoded entities.
3101 * @link http://www.php.net/htmlentities Borrowed from the PHP Manual user notes.
3105 * @param string $myHTML The text to be converted.
3106 * @return string Converted text.
3108 function htmlentities2($myHTML) {
3109 $translation_table = get_html_translation_table( HTML_ENTITIES, ENT_QUOTES );
3110 $translation_table[chr(38)] = '&';
3111 return preg_replace( "/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/", "&", strtr($myHTML, $translation_table) );
3115 * Escape single quotes, htmlspecialchar " < > &, and fix line endings.
3117 * Escapes text strings for echoing in JS. It is intended to be used for inline JS
3118 * (in a tag attribute, for example onclick="..."). Note that the strings have to
3119 * be in single quotes. The filter 'js_escape' is also applied here.
3123 * @param string $text The text to be escaped.
3124 * @return string Escaped text.
3126 function esc_js( $text ) {
3127 $safe_text = wp_check_invalid_utf8( $text );
3128 $safe_text = _wp_specialchars( $safe_text, ENT_COMPAT );
3129 $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) );
3130 $safe_text = str_replace( "\r", '', $safe_text );
3131 $safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) );
3133 * Filter a string cleaned and escaped for output in JavaScript.
3135 * Text passed to esc_js() is stripped of invalid or special characters,
3136 * and properly slashed for output.
3140 * @param string $safe_text The text after it has been escaped.
3141 * @param string $text The text prior to being escaped.
3143 return apply_filters( 'js_escape', $safe_text, $text );
3147 * Escaping for HTML blocks.
3151 * @param string $text
3154 function esc_html( $text ) {
3155 $safe_text = wp_check_invalid_utf8( $text );
3156 $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
3158 * Filter a string cleaned and escaped for output in HTML.
3160 * Text passed to esc_html() is stripped of invalid or special characters
3165 * @param string $safe_text The text after it has been escaped.
3166 * @param string $text The text prior to being escaped.
3168 return apply_filters( 'esc_html', $safe_text, $text );
3172 * Escaping for HTML attributes.
3176 * @param string $text
3179 function esc_attr( $text ) {
3180 $safe_text = wp_check_invalid_utf8( $text );
3181 $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
3183 * Filter a string cleaned and escaped for output in an HTML attribute.
3185 * Text passed to esc_attr() is stripped of invalid or special characters
3190 * @param string $safe_text The text after it has been escaped.
3191 * @param string $text The text prior to being escaped.
3193 return apply_filters( 'attribute_escape', $safe_text, $text );
3197 * Escaping for textarea values.
3201 * @param string $text
3204 function esc_textarea( $text ) {
3205 $safe_text = htmlspecialchars( $text, ENT_QUOTES, get_option( 'blog_charset' ) );
3207 * Filter a string cleaned and escaped for output in a textarea element.
3211 * @param string $safe_text The text after it has been escaped.
3212 * @param string $text The text prior to being escaped.
3214 return apply_filters( 'esc_textarea', $safe_text, $text );
3218 * Escape an HTML tag name.
3222 * @param string $tag_name
3225 function tag_escape($tag_name) {
3226 $safe_tag = strtolower( preg_replace('/[^a-zA-Z0-9_:]/', '', $tag_name) );
3228 * Filter a string cleaned and escaped for output as an HTML tag.
3232 * @param string $safe_tag The tag name after it has been escaped.
3233 * @param string $tag_name The text before it was escaped.
3235 return apply_filters( 'tag_escape', $safe_tag, $tag_name );
3239 * Convert full URL paths to absolute paths.
3241 * Removes the http or https protocols and the domain. Keeps the path '/' at the
3242 * beginning, so it isn't a true relative link, but from the web root base.
3246 * @param string $link Full URL path.
3247 * @return string Absolute path.
3249 function wp_make_link_relative( $link ) {
3250 return preg_replace( '|https?://[^/]+(/.*)|i', '$1', $link );
3254 * Sanitises various option values based on the nature of the option.
3256 * This is basically a switch statement which will pass $value through a number
3257 * of functions depending on the $option.
3261 * @param string $option The name of the option.
3262 * @param string $value The unsanitised value.
3263 * @return string Sanitized value.
3265 function sanitize_option($option, $value) {
3267 switch ( $option ) {
3268 case 'admin_email' :
3269 case 'new_admin_email' :
3270 $value = sanitize_email( $value );
3271 if ( ! is_email( $value ) ) {
3272 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
3273 if ( function_exists( 'add_settings_error' ) )
3274 add_settings_error( $option, 'invalid_admin_email', __( 'The email address entered did not appear to be a valid email address. Please enter a valid email address.' ) );
3278 case 'thumbnail_size_w':
3279 case 'thumbnail_size_h':
3280 case 'medium_size_w':
3281 case 'medium_size_h':
3282 case 'large_size_w':
3283 case 'large_size_h':
3284 case 'mailserver_port':
3285 case 'comment_max_links':
3286 case 'page_on_front':
3287 case 'page_for_posts':
3288 case 'rss_excerpt_length':
3289 case 'default_category':
3290 case 'default_email_category':
3291 case 'default_link_category':
3292 case 'close_comments_days_old':
3293 case 'comments_per_page':
3294 case 'thread_comments_depth':
3295 case 'users_can_register':
3296 case 'start_of_week':
3297 $value = absint( $value );
3300 case 'posts_per_page':
3301 case 'posts_per_rss':
3302 $value = (int) $value;
3303 if ( empty($value) )
3306 $value = abs($value);
3309 case 'default_ping_status':
3310 case 'default_comment_status':
3311 // Options that if not there have 0 value but need to be something like "closed"
3312 if ( $value == '0' || $value == '')
3316 case 'blogdescription':
3318 $value = wp_kses_post( $value );
3319 $value = esc_html( $value );
3322 case 'blog_charset':
3323 $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value); // strips slashes
3327 // This is the value if the settings checkbox is not checked on POST. Don't rely on this.
3328 if ( null === $value )
3331 $value = intval( $value );
3336 case 'mailserver_url':
3337 case 'mailserver_login':
3338 case 'mailserver_pass':
3340 $value = strip_tags( $value );
3341 $value = wp_kses_data( $value );
3345 $value = explode( "\n", $value );
3346 $value = array_filter( array_map( 'trim', $value ) );
3347 $value = array_filter( array_map( 'esc_url_raw', $value ) );
3348 $value = implode( "\n", $value );
3352 $value = preg_replace('/[^0-9:.-]/', '', $value); // strips slashes
3356 if ( (bool)preg_match( '#http(s?)://(.+)#i', $value) ) {
3357 $value = esc_url_raw($value);
3359 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
3360 if ( function_exists('add_settings_error') )
3361 add_settings_error('siteurl', 'invalid_siteurl', __('The WordPress address you entered did not appear to be a valid URL. Please enter a valid URL.'));
3366 if ( (bool)preg_match( '#http(s?)://(.+)#i', $value) ) {
3367 $value = esc_url_raw($value);
3369 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
3370 if ( function_exists('add_settings_error') )
3371 add_settings_error('home', 'invalid_home', __('The Site address you entered did not appear to be a valid URL. Please enter a valid URL.'));
3376 $allowed = get_available_languages();
3377 if ( ! is_multisite() && defined( 'WPLANG' ) && '' !== WPLANG && 'en_US' !== WPLANG ) {
3378 $allowed[] = WPLANG;
3380 if ( ! in_array( $value, $allowed ) && ! empty( $value ) ) {
3381 $value = get_option( $option );
3385 case 'illegal_names':
3386 if ( ! is_array( $value ) )
3387 $value = explode( ' ', $value );
3389 $value = array_values( array_filter( array_map( 'trim', $value ) ) );
3395 case 'limited_email_domains':
3396 case 'banned_email_domains':
3397 if ( ! is_array( $value ) )
3398 $value = explode( "\n", $value );
3400 $domains = array_values( array_filter( array_map( 'trim', $value ) ) );
3403 foreach ( $domains as $domain ) {
3404 if ( ! preg_match( '/(--|\.\.)/', $domain ) && preg_match( '|^([a-zA-Z0-9-\.])+$|', $domain ) )
3411 case 'timezone_string':
3412 $allowed_zones = timezone_identifiers_list();
3413 if ( ! in_array( $value, $allowed_zones ) && ! empty( $value ) ) {
3414 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
3415 if ( function_exists('add_settings_error') )
3416 add_settings_error('timezone_string', 'invalid_timezone_string', __('The timezone you have entered is not valid. Please select a valid timezone.') );
3420 case 'permalink_structure':
3421 case 'category_base':
3423 $value = esc_url_raw( $value );
3424 $value = str_replace( 'http://', '', $value );
3427 case 'default_role' :
3428 if ( ! get_role( $value ) && get_role( 'subscriber' ) )
3429 $value = 'subscriber';
3432 case 'moderation_keys':
3433 case 'blacklist_keys':
3434 $value = explode( "\n", $value );
3435 $value = array_filter( array_map( 'trim', $value ) );
3436 $value = array_unique( $value );
3437 $value = implode( "\n", $value );
3442 * Filter an option value following sanitization.
3446 * @param string $value The sanitized option value.
3447 * @param string $option The option name.
3449 $value = apply_filters( "sanitize_option_{$option}", $value, $option );
3455 * Parses a string into variables to be stored in an array.
3457 * Uses {@link http://www.php.net/parse_str parse_str()} and stripslashes if
3458 * {@link http://www.php.net/magic_quotes magic_quotes_gpc} is on.
3462 * @param string $string The string to be parsed.
3463 * @param array $array Variables will be stored in this array.
3465 function wp_parse_str( $string, &$array ) {
3466 parse_str( $string, $array );
3467 if ( get_magic_quotes_gpc() )
3468 $array = stripslashes_deep( $array );
3470 * Filter the array of variables derived from a parsed string.
3474 * @param array $array The array populated with variables.
3476 $array = apply_filters( 'wp_parse_str', $array );
3480 * Convert lone less than signs.
3482 * KSES already converts lone greater than signs.
3484 * @uses wp_pre_kses_less_than_callback in the callback function.
3487 * @param string $text Text to be converted.
3488 * @return string Converted text.
3490 function wp_pre_kses_less_than( $text ) {
3491 return preg_replace_callback('%<[^>]*?((?=<)|>|$)%', 'wp_pre_kses_less_than_callback', $text);
3495 * Callback function used by preg_replace.
3497 * @uses esc_html to format the $matches text.
3500 * @param array $matches Populated by matches to preg_replace.
3501 * @return string The text returned after esc_html if needed.
3503 function wp_pre_kses_less_than_callback( $matches ) {
3504 if ( false === strpos($matches[0], '>') )
3505 return esc_html($matches[0]);
3510 * WordPress implementation of PHP sprintf() with filters.
3513 * @link http://www.php.net/sprintf
3515 * @param string $pattern The string which formatted args are inserted.
3516 * @param mixed $args,... Arguments to be formatted into the $pattern string.
3517 * @return string The formatted string.
3519 function wp_sprintf( $pattern ) {
3520 $args = func_get_args();
3521 $len = strlen($pattern);
3525 while ( $len > $start ) {
3526 // Last character: append and break
3527 if ( strlen($pattern) - 1 == $start ) {
3528 $result .= substr($pattern, -1);
3532 // Literal %: append and continue
3533 if ( substr($pattern, $start, 2) == '%%' ) {
3539 // Get fragment before next %
3540 $end = strpos($pattern, '%', $start + 1);
3541 if ( false === $end )
3543 $fragment = substr($pattern, $start, $end - $start);
3545 // Fragment has a specifier
3546 if ( $pattern[$start] == '%' ) {
3547 // Find numbered arguments or take the next one in order
3548 if ( preg_match('/^%(\d+)\$/', $fragment, $matches) ) {
3549 $arg = isset($args[$matches[1]]) ? $args[$matches[1]] : '';
3550 $fragment = str_replace("%{$matches[1]}$", '%', $fragment);
3553 $arg = isset($args[$arg_index]) ? $args[$arg_index] : '';
3557 * Filter a fragment from the pattern passed to wp_sprintf().
3559 * If the fragment is unchanged, then sprintf() will be run on the fragment.
3563 * @param string $fragment A fragment from the pattern.
3564 * @param string $arg The argument.
3566 $_fragment = apply_filters( 'wp_sprintf', $fragment, $arg );
3567 if ( $_fragment != $fragment )
3568 $fragment = $_fragment;
3570 $fragment = sprintf($fragment, strval($arg) );
3573 // Append to result and move to next fragment
3574 $result .= $fragment;
3581 * Localize list items before the rest of the content.
3583 * The '%l' must be at the first characters can then contain the rest of the
3584 * content. The list items will have ', ', ', and', and ' and ' added depending
3585 * on the amount of list items in the $args parameter.
3589 * @param string $pattern Content containing '%l' at the beginning.
3590 * @param array $args List items to prepend to the content and replace '%l'.
3591 * @return string Localized list items and rest of the content.
3593 function wp_sprintf_l($pattern, $args) {
3595 if ( substr($pattern, 0, 2) != '%l' )
3598 // Nothing to work with
3603 * Filter the translated delimiters used by wp_sprintf_l().
3604 * Placeholders (%s) are included to assist translators and then
3605 * removed before the array of strings reaches the filter.
3607 * Please note: Ampersands and entities should be avoided here.
3611 * @param array $delimiters An array of translated delimiters.
3613 $l = apply_filters( 'wp_sprintf_l', array(
3614 /* translators: used to join items in a list with more than 2 items */
3615 'between' => sprintf( __('%s, %s'), '', '' ),
3616 /* translators: used to join last two items in a list with more than 2 times */
3617 'between_last_two' => sprintf( __('%s, and %s'), '', '' ),
3618 /* translators: used to join items in a list with only 2 items */
3619 'between_only_two' => sprintf( __('%s and %s'), '', '' ),
3622 $args = (array) $args;
3623 $result = array_shift($args);
3624 if ( count($args) == 1 )
3625 $result .= $l['between_only_two'] . array_shift($args);
3626 // Loop when more than two args
3629 $arg = array_shift($args);
3632 $result .= $l['between_last_two'] . $arg;
3634 $result .= $l['between'] . $arg;
3636 return $result . substr($pattern, 2);
3640 * Safely extracts not more than the first $count characters from html string.
3642 * UTF-8, tags and entities safe prefix extraction. Entities inside will *NOT*
3643 * be counted as one character. For example & will be counted as 4, < as
3648 * @param string $str String to get the excerpt from.
3649 * @param integer $count Maximum number of characters to take.
3650 * @param string $more Optional. What to append if $str needs to be trimmed. Defaults to empty string.
3651 * @return string The excerpt.
3653 function wp_html_excerpt( $str, $count, $more = null ) {
3654 if ( null === $more )
3656 $str = wp_strip_all_tags( $str, true );
3657 $excerpt = mb_substr( $str, 0, $count );
3658 // remove part of an entity at the end
3659 $excerpt = preg_replace( '/&[^;\s]{0,6}$/', '', $excerpt );
3660 if ( $str != $excerpt )
3661 $excerpt = trim( $excerpt ) . $more;
3666 * Add a Base url to relative links in passed content.
3668 * By default it supports the 'src' and 'href' attributes. However this can be
3669 * changed via the 3rd param.
3673 * @param string $content String to search for links in.
3674 * @param string $base The base URL to prefix to links.
3675 * @param array $attrs The attributes which should be processed.
3676 * @return string The processed content.
3678 function links_add_base_url( $content, $base, $attrs = array('src', 'href') ) {
3679 global $_links_add_base;
3680 $_links_add_base = $base;
3681 $attrs = implode('|', (array)$attrs);
3682 return preg_replace_callback( "!($attrs)=(['\"])(.+?)\\2!i", '_links_add_base', $content );
3686 * Callback to add a base url to relative links in passed content.
3691 * @param string $m The matched link.
3692 * @return string The processed link.
3694 function _links_add_base($m) {
3695 global $_links_add_base;
3696 //1 = attribute name 2 = quotation mark 3 = URL
3697 return $m[1] . '=' . $m[2] .
3698 ( preg_match( '#^(\w{1,20}):#', $m[3], $protocol ) && in_array( $protocol[1], wp_allowed_protocols() ) ?
3700 path_join( $_links_add_base, $m[3] ) )
3705 * Adds a Target attribute to all links in passed content.
3707 * This function by default only applies to <a> tags, however this can be
3708 * modified by the 3rd param.
3710 * <b>NOTE:</b> Any current target attributed will be stripped and replaced.
3714 * @param string $content String to search for links in.
3715 * @param string $target The Target to add to the links.
3716 * @param array $tags An array of tags to apply to.
3717 * @return string The processed content.
3719 function links_add_target( $content, $target = '_blank', $tags = array('a') ) {
3720 global $_links_add_target;
3721 $_links_add_target = $target;
3722 $tags = implode('|', (array)$tags);
3723 return preg_replace_callback( "!<($tags)([^>]*)>!i", '_links_add_target', $content );
3727 * Callback to add a target attribute to all links in passed content.
3732 * @param string $m The matched link.
3733 * @return string The processed link.
3735 function _links_add_target( $m ) {
3736 global $_links_add_target;
3738 $link = preg_replace('|( target=([\'"])(.*?)\2)|i', '', $m[2]);
3739 return '<' . $tag . $link . ' target="' . esc_attr( $_links_add_target ) . '">';
3743 * Normalize EOL characters and strip duplicate whitespace.
3747 * @param string $str The string to normalize.
3748 * @return string The normalized string.
3750 function normalize_whitespace( $str ) {
3751 $str = trim( $str );
3752 $str = str_replace( "\r", "\n", $str );
3753 $str = preg_replace( array( '/\n+/', '/[ \t]+/' ), array( "\n", ' ' ), $str );
3758 * Properly strip all HTML tags including script and style
3760 * This differs from strip_tags() because it removes the contents of
3761 * the <script> and <style> tags. E.g. strip_tags( '<script>something</script>' )
3762 * will return 'something'. wp_strip_all_tags will return ''
3766 * @param string $string String containing HTML tags
3767 * @param bool $remove_breaks optional Whether to remove left over line breaks and white space chars
3768 * @return string The processed string.
3770 function wp_strip_all_tags($string, $remove_breaks = false) {
3771 $string = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $string );
3772 $string = strip_tags($string);
3774 if ( $remove_breaks )
3775 $string = preg_replace('/[\r\n\t ]+/', ' ', $string);
3777 return trim( $string );
3781 * Sanitize a string from user input or from the db
3783 * check for invalid UTF-8,
3784 * Convert single < characters to entity,
3786 * remove line breaks, tabs and extra white space,
3791 * @param string $str
3794 function sanitize_text_field($str) {
3795 $filtered = wp_check_invalid_utf8( $str );
3797 if ( strpos($filtered, '<') !== false ) {
3798 $filtered = wp_pre_kses_less_than( $filtered );
3799 // This will strip extra whitespace for us.
3800 $filtered = wp_strip_all_tags( $filtered, true );
3802 $filtered = trim( preg_replace('/[\r\n\t ]+/', ' ', $filtered) );
3806 while ( preg_match('/%[a-f0-9]{2}/i', $filtered, $match) ) {
3807 $filtered = str_replace($match[0], '', $filtered);
3812 // Strip out the whitespace that may now exist after removing the octets.
3813 $filtered = trim( preg_replace('/ +/', ' ', $filtered) );
3817 * Filter a sanitized text field string.
3821 * @param string $filtered The sanitized string.
3822 * @param string $str The string prior to being sanitized.
3824 return apply_filters( 'sanitize_text_field', $filtered, $str );
3828 * i18n friendly version of basename()
3832 * @param string $path A path.
3833 * @param string $suffix If the filename ends in suffix this will also be cut off.
3836 function wp_basename( $path, $suffix = '' ) {
3837 return urldecode( basename( str_replace( array( '%2F', '%5C' ), '/', urlencode( $path ) ), $suffix ) );
3841 * Forever eliminate "Wordpress" from the planet (or at least the little bit we can influence).
3843 * Violating our coding standards for a good function name.
3847 function capital_P_dangit( $text ) {
3848 // Simple replacement for titles
3849 $current_filter = current_filter();
3850 if ( 'the_title' === $current_filter || 'wp_title' === $current_filter )
3851 return str_replace( 'Wordpress', 'WordPress', $text );
3852 // Still here? Use the more judicious replacement
3853 static $dblq = false;
3854 if ( false === $dblq )
3855 $dblq = _x( '“', 'opening curly double quote' );
3857 array( ' Wordpress', '‘Wordpress', $dblq . 'Wordpress', '>Wordpress', '(Wordpress' ),
3858 array( ' WordPress', '‘WordPress', $dblq . 'WordPress', '>WordPress', '(WordPress' ),
3864 * Sanitize a mime type
3868 * @param string $mime_type Mime type
3869 * @return string Sanitized mime type
3871 function sanitize_mime_type( $mime_type ) {
3872 $sani_mime_type = preg_replace( '/[^-+*.a-zA-Z0-9\/]/', '', $mime_type );
3874 * Filter a mime type following sanitization.
3878 * @param string $sani_mime_type The sanitized mime type.
3879 * @param string $mime_type The mime type prior to sanitization.
3881 return apply_filters( 'sanitize_mime_type', $sani_mime_type, $mime_type );
3885 * Sanitize space or carriage return separated URLs that are used to send trackbacks.
3889 * @param string $to_ping Space or carriage return separated URLs
3890 * @return string URLs starting with the http or https protocol, separated by a carriage return.
3892 function sanitize_trackback_urls( $to_ping ) {
3893 $urls_to_ping = preg_split( '/[\r\n\t ]/', trim( $to_ping ), -1, PREG_SPLIT_NO_EMPTY );
3894 foreach ( $urls_to_ping as $k => $url ) {
3895 if ( !preg_match( '#^https?://.#i', $url ) )
3896 unset( $urls_to_ping[$k] );
3898 $urls_to_ping = array_map( 'esc_url_raw', $urls_to_ping );
3899 $urls_to_ping = implode( "\n", $urls_to_ping );
3901 * Filter a list of trackback URLs following sanitization.
3903 * The string returned here consists of a space or carriage return-delimited list
3904 * of trackback URLs.
3908 * @param string $urls_to_ping Sanitized space or carriage return separated URLs.
3909 * @param string $to_ping Space or carriage return separated URLs before sanitization.
3911 return apply_filters( 'sanitize_trackback_urls', $urls_to_ping, $to_ping );
3915 * Add slashes to a string or array of strings.
3917 * This should be used when preparing data for core API that expects slashed data.
3918 * This should not be used to escape data going directly into an SQL query.
3922 * @param string|array $value String or array of strings to slash.
3923 * @return string|array Slashed $value
3925 function wp_slash( $value ) {
3926 if ( is_array( $value ) ) {
3927 foreach ( $value as $k => $v ) {
3928 if ( is_array( $v ) ) {
3929 $value[$k] = wp_slash( $v );
3931 $value[$k] = addslashes( $v );
3935 $value = addslashes( $value );
3942 * Remove slashes from a string or array of strings.
3944 * This should be used to remove slashes from data passed to core API that
3945 * expects data to be unslashed.
3949 * @param string|array $value String or array of strings to unslash.
3950 * @return string|array Unslashed $value
3952 function wp_unslash( $value ) {
3953 return stripslashes_deep( $value );
3957 * Extract and return the first URL from passed content.
3961 * @param string $content A string which might contain a URL.
3962 * @return string The found URL.
3964 function get_url_in_content( $content ) {
3965 if ( empty( $content ) ) {
3969 if ( preg_match( '/<a\s[^>]*?href=([\'"])(.+?)\1/is', $content, $matches ) ) {
3970 return esc_url_raw( $matches[2] );
3977 * Returns the regexp for common whitespace characters.
3979 * By default, spaces include new lines, tabs, nbsp entities, and the UTF-8 nbsp.
3980 * This is designed to replace the PCRE \s sequence. In ticket #22692, that
3981 * sequence was found to be unreliable due to random inclusion of the A0 byte.
3985 * @return string The spaces regexp.
3987 function wp_spaces_regexp() {
3990 if ( empty( $spaces ) ) {
3992 * Filter the regexp for common whitespace characters.
3994 * This string is substituted for the \s sequence as needed in regular
3995 * expressions. For websites not written in English, different characters
3996 * may represent whitespace. For websites not encoded in UTF-8, the 0xC2 0xA0
3997 * sequence may not be in use.
4001 * @param string $spaces Regexp pattern for matching common whitespace characters.
4003 $spaces = apply_filters( 'wp_spaces_regexp', '[\r\n\t ]|\xC2\xA0| ' );