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", "'em" );
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", $apos . "em" );
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. If not found, match all input.
221 '\[' // Find start of shortcode.
222 . '[\/\[]?' // Shortcodes may begin with [/ or [[
223 . $tagregexp // Only match registered shortcodes, because performance.
225 . '[^\[\]<>]+' // Shortcodes do not contain other shortcodes. Quantifier critical.
227 . '<[^\[\]>]*>' // HTML elements permitted. Prevents matching ] before >.
228 . ')*+' // Possessive critical.
229 . '\]' // Find end of shortcode.
230 . '\]?'; // Shortcodes may end with ]]
233 '/(' // Capture the entire match.
234 . '<' // Find start of element.
235 . '(?(?=!--)' // Is this a comment?
236 . $comment_regex // Find end of comment.
238 . '[^>]*>' // Find end of element.
241 . $shortcode_regex // Find shortcodes.
244 $textarr = preg_split( $regex, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY );
246 foreach ( $textarr as &$curl ) {
247 // Only call _wptexturize_pushpop_element if $curl is a delimiter.
249 if ( '<' === $first && '<!--' === substr( $curl, 0, 4 ) ) {
250 // This is an HTML comment delimeter.
254 } elseif ( '<' === $first && '>' === substr( $curl, -1 ) ) {
255 // This is an HTML element delimiter.
257 _wptexturize_pushpop_element( $curl, $no_texturize_tags_stack, $no_texturize_tags );
259 } elseif ( '' === trim( $curl ) ) {
260 // This is a newline between delimiters. Performance improves when we check this.
264 } elseif ( '[' === $first && 1 === preg_match( '/^' . $shortcode_regex . '$/', $curl ) ) {
265 // This is a shortcode delimiter.
267 if ( '[[' !== substr( $curl, 0, 2 ) && ']]' !== substr( $curl, -2 ) ) {
268 // Looks like a normal shortcode.
269 _wptexturize_pushpop_element( $curl, $no_texturize_shortcodes_stack, $no_texturize_shortcodes );
271 // Looks like an escaped shortcode.
275 } elseif ( empty( $no_texturize_shortcodes_stack ) && empty( $no_texturize_tags_stack ) ) {
276 // This is neither a delimiter, nor is this content inside of no_texturize pairs. Do texturize.
278 $curl = str_replace( $static_characters, $static_replacements, $curl );
280 if ( false !== strpos( $curl, "'" ) ) {
281 $curl = preg_replace( $dynamic_characters['apos'], $dynamic_replacements['apos'], $curl );
283 if ( false !== strpos( $curl, '"' ) ) {
284 $curl = preg_replace( $dynamic_characters['quote'], $dynamic_replacements['quote'], $curl );
286 if ( false !== strpos( $curl, '-' ) ) {
287 $curl = preg_replace( $dynamic_characters['dash'], $dynamic_replacements['dash'], $curl );
290 // 9x9 (times), but never 0x9999
291 if ( 1 === preg_match( '/(?<=\d)x\d/', $curl ) ) {
292 // Searching for a digit is 10 times more expensive than for the x, so we avoid doing this one!
293 $curl = preg_replace( '/\b(\d(?(?<=0)[\d\.,]+|[\d\.,]*))x(\d[\d\.,]*)\b/', '$1×$2', $curl );
297 $text = implode( '', $textarr );
299 // Replace each & with & unless it already looks like an entity.
300 $text = preg_replace('/&(?!#(?:\d+|x[a-f0-9]+);|[a-z1-4]{1,8};)/i', '&', $text);
306 * Search for disabled element tags. Push element to stack on tag open and pop
309 * Assumes first char of $text is tag opening and last char is tag closing.
310 * Assumes second char of $text is optionally '/' to indicate closing as in </html>.
315 * @param string $text Text to check. Must be a tag like `<html>` or `[shortcode]`.
316 * @param array $stack List of open tag elements.
317 * @param array $disabled_elements The tag names to match against. Spaces are not allowed in tag names.
319 function _wptexturize_pushpop_element($text, &$stack, $disabled_elements) {
320 // Is it an opening tag or closing tag?
321 if ( '/' !== $text[1] ) {
324 } elseif ( 0 == count( $stack ) ) {
325 // Stack is empty. Just stop.
328 $opening_tag = false;
332 // Parse out the tag name.
333 $space = strpos( $text, ' ' );
334 if ( false === $space ) {
337 $space -= $name_offset;
339 $tag = substr( $text, $name_offset, $space );
341 // Handle disabled tags.
342 if ( in_array( $tag, $disabled_elements ) ) {
343 if ( $opening_tag ) {
345 * This disables texturize until we find a closing tag of our type
346 * (e.g. <pre>) even if there was invalid nesting before that
348 * Example: in the case <pre>sadsadasd</code>"baba"</pre>
349 * "baba" won't be texturize
352 array_push( $stack, $tag );
353 } elseif ( end( $stack ) == $tag ) {
360 * Replaces double line-breaks with paragraph elements.
362 * A group of regex replaces used to identify text formatted with newlines and
363 * replace double line-breaks with HTML paragraph tags. The remaining line-breaks
364 * after conversion become <<br />> tags, unless $br is set to '0' or 'false'.
368 * @param string $pee The text which has to be formatted.
369 * @param bool $br Optional. If set, this will convert all remaining line-breaks
370 * after paragraphing. Default true.
371 * @return string Text which has been converted into correct paragraph tags.
373 function wpautop($pee, $br = true) {
376 if ( trim($pee) === '' )
379 // Just to make things a little easier, pad the end.
383 * Pre tags shouldn't be touched by autop.
384 * Replace pre tags with placeholders and bring them back after autop.
386 if ( strpos($pee, '<pre') !== false ) {
387 $pee_parts = explode( '</pre>', $pee );
388 $last_pee = array_pop($pee_parts);
392 foreach ( $pee_parts as $pee_part ) {
393 $start = strpos($pee_part, '<pre');
396 if ( $start === false ) {
401 $name = "<pre wp-pre-tag-$i></pre>";
402 $pre_tags[$name] = substr( $pee_part, $start ) . '</pre>';
404 $pee .= substr( $pee_part, 0, $start ) . $name;
410 // Change multiple <br>s into two line breaks, which will turn into paragraphs.
411 $pee = preg_replace('|<br />\s*<br />|', "\n\n", $pee);
413 $allblocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|form|map|area|blockquote|address|math|style|p|h[1-6]|hr|fieldset|legend|section|article|aside|hgroup|header|footer|nav|figure|figcaption|details|menu|summary)';
415 // Add a single line break above block-level opening tags.
416 $pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee);
418 // Add a double line break below block-level closing tags.
419 $pee = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $pee);
421 // Standardize newline characters to "\n".
422 $pee = str_replace(array("\r\n", "\r"), "\n", $pee);
424 // Strip newlines from all elements.
425 $pee = wp_replace_in_html_tags( $pee, array( "\n" => " " ) );
427 // Collapse line breaks before and after <option> elements so they don't get autop'd.
428 if ( strpos( $pee, '<option' ) !== false ) {
429 $pee = preg_replace( '|\s*<option|', '<option', $pee );
430 $pee = preg_replace( '|</option>\s*|', '</option>', $pee );
434 * Collapse line breaks inside <object> elements, before <param> and <embed> elements
435 * so they don't get autop'd.
437 if ( strpos( $pee, '</object>' ) !== false ) {
438 $pee = preg_replace( '|(<object[^>]*>)\s*|', '$1', $pee );
439 $pee = preg_replace( '|\s*</object>|', '</object>', $pee );
440 $pee = preg_replace( '%\s*(</?(?:param|embed)[^>]*>)\s*%', '$1', $pee );
444 * Collapse line breaks inside <audio> and <video> elements,
445 * before and after <source> and <track> elements.
447 if ( strpos( $pee, '<source' ) !== false || strpos( $pee, '<track' ) !== false ) {
448 $pee = preg_replace( '%([<\[](?:audio|video)[^>\]]*[>\]])\s*%', '$1', $pee );
449 $pee = preg_replace( '%\s*([<\[]/(?:audio|video)[>\]])%', '$1', $pee );
450 $pee = preg_replace( '%\s*(<(?:source|track)[^>]*>)\s*%', '$1', $pee );
453 // Remove more than two contiguous line breaks.
454 $pee = preg_replace("/\n\n+/", "\n\n", $pee);
456 // Split up the contents into an array of strings, separated by double line breaks.
457 $pees = preg_split('/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY);
459 // Reset $pee prior to rebuilding.
462 // Rebuild the content as a string, wrapping every bit with a <p>.
463 foreach ( $pees as $tinkle ) {
464 $pee .= '<p>' . trim($tinkle, "\n") . "</p>\n";
467 // Under certain strange conditions it could create a P of entirely whitespace.
468 $pee = preg_replace('|<p>\s*</p>|', '', $pee);
470 // Add a closing <p> inside <div>, <address>, or <form> tag if missing.
471 $pee = preg_replace('!<p>([^<]+)</(div|address|form)>!', "<p>$1</p></$2>", $pee);
473 // If an opening or closing block element tag is wrapped in a <p>, unwrap it.
474 $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
476 // In some cases <li> may get wrapped in <p>, fix them.
477 $pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee);
479 // If a <blockquote> is wrapped with a <p>, move it inside the <blockquote>.
480 $pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee);
481 $pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee);
483 // If an opening or closing block element tag is preceded by an opening <p> tag, remove it.
484 $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)!', "$1", $pee);
486 // If an opening or closing block element tag is followed by a closing <p> tag, remove it.
487 $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
489 // Optionally insert line breaks.
491 // Replace newlines that shouldn't be touched with a placeholder.
492 $pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', '_autop_newline_preservation_helper', $pee);
494 // Replace any new line characters that aren't preceded by a <br /> with a <br />.
495 $pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee);
497 // Replace newline placeholders with newlines.
498 $pee = str_replace('<WPPreserveNewline />', "\n", $pee);
501 // If a <br /> tag is after an opening or closing block tag, remove it.
502 $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', "$1", $pee);
504 // If a <br /> tag is before a subset of opening or closing block tags, remove it.
505 $pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee);
506 $pee = preg_replace( "|\n</p>$|", '</p>', $pee );
508 // Replace placeholder <pre> tags with their original content.
509 if ( !empty($pre_tags) )
510 $pee = str_replace(array_keys($pre_tags), array_values($pre_tags), $pee);
516 * Replace characters or phrases within HTML elements only.
520 * @param string $haystack The text which has to be formatted.
521 * @param array $replace_pairs In the form array('from' => 'to', ...).
522 * @return string The formatted text.
524 function wp_replace_in_html_tags( $haystack, $replace_pairs ) {
525 // Find all elements.
527 '!' // Start of comment, after the <.
528 . '(?:' // Unroll the loop: Consume everything until --> is found.
529 . '-(?!->)' // Dash not followed by end of comment.
530 . '[^\-]*+' // Consume non-dashes.
531 . ')*+' // Loop possessively.
532 . '(?:-->)?'; // End of comment. If not found, match all input.
535 '/(' // Capture the entire match.
536 . '<' // Find start of element.
537 . '(?(?=!--)' // Is this a comment?
538 . $comments // Find end of comment.
540 . '[^>]*>?' // Find end of element. If not found, match all input.
544 $textarr = preg_split( $regex, $haystack, -1, PREG_SPLIT_DELIM_CAPTURE );
547 // Optimize when searching for one item.
548 if ( 1 === count( $replace_pairs ) ) {
549 // Extract $needle and $replace.
550 foreach ( $replace_pairs as $needle => $replace );
552 // Loop through delimeters (elements) only.
553 for ( $i = 1, $c = count( $textarr ); $i < $c; $i += 2 ) {
554 if ( false !== strpos( $textarr[$i], $needle ) ) {
555 $textarr[$i] = str_replace( $needle, $replace, $textarr[$i] );
560 // Extract all $needles.
561 $needles = array_keys( $replace_pairs );
563 // Loop through delimeters (elements) only.
564 for ( $i = 1, $c = count( $textarr ); $i < $c; $i += 2 ) {
565 foreach ( $needles as $needle ) {
566 if ( false !== strpos( $textarr[$i], $needle ) ) {
567 $textarr[$i] = strtr( $textarr[$i], $replace_pairs );
569 // After one strtr() break out of the foreach loop and look at next element.
577 $haystack = implode( $textarr );
584 * Newline preservation help function for wpautop
589 * @param array $matches preg_replace_callback matches array
592 function _autop_newline_preservation_helper( $matches ) {
593 return str_replace("\n", "<WPPreserveNewline />", $matches[0]);
597 * Don't auto-p wrap shortcodes that stand alone
599 * Ensures that shortcodes are not wrapped in `<p>...</p>`.
603 * @param string $pee The content.
604 * @return string The filtered content.
606 function shortcode_unautop( $pee ) {
607 global $shortcode_tags;
609 if ( empty( $shortcode_tags ) || !is_array( $shortcode_tags ) ) {
613 $tagregexp = join( '|', array_map( 'preg_quote', array_keys( $shortcode_tags ) ) );
614 $spaces = wp_spaces_regexp();
618 . '<p>' // Opening paragraph
619 . '(?:' . $spaces . ')*+' // Optional leading whitespace
620 . '(' // 1: The shortcode
621 . '\\[' // Opening bracket
622 . "($tagregexp)" // 2: Shortcode name
623 . '(?![\\w-])' // Not followed by word character or hyphen
624 // Unroll the loop: Inside the opening shortcode tag
625 . '[^\\]\\/]*' // Not a closing bracket or forward slash
627 . '\\/(?!\\])' // A forward slash not followed by a closing bracket
628 . '[^\\]\\/]*' // Not a closing bracket or forward slash
631 . '\\/\\]' // Self closing tag and closing bracket
633 . '\\]' // Closing bracket
634 . '(?:' // Unroll the loop: Optionally, anything between the opening and closing shortcode tags
635 . '[^\\[]*+' // Not an opening bracket
637 . '\\[(?!\\/\\2\\])' // An opening bracket not followed by the closing shortcode tag
638 . '[^\\[]*+' // Not an opening bracket
640 . '\\[\\/\\2\\]' // Closing shortcode tag
644 . '(?:' . $spaces . ')*+' // optional trailing whitespace
645 . '<\\/p>' // closing paragraph
648 return preg_replace( $pattern, '$1', $pee );
652 * Checks to see if a string is utf8 encoded.
654 * NOTE: This function checks for 5-Byte sequences, UTF8
655 * has Bytes Sequences with a maximum length of 4.
657 * @author bmorel at ssi dot fr (modified)
660 * @param string $str The string to be checked
661 * @return bool True if $str fits a UTF-8 model, false otherwise.
663 function seems_utf8($str) {
664 mbstring_binary_safe_encoding();
665 $length = strlen($str);
666 reset_mbstring_encoding();
667 for ($i=0; $i < $length; $i++) {
669 if ($c < 0x80) $n = 0; // 0bbbbbbb
670 elseif (($c & 0xE0) == 0xC0) $n=1; // 110bbbbb
671 elseif (($c & 0xF0) == 0xE0) $n=2; // 1110bbbb
672 elseif (($c & 0xF8) == 0xF0) $n=3; // 11110bbb
673 elseif (($c & 0xFC) == 0xF8) $n=4; // 111110bb
674 elseif (($c & 0xFE) == 0xFC) $n=5; // 1111110b
675 else return false; // Does not match any model
676 for ($j=0; $j<$n; $j++) { // n bytes matching 10bbbbbb follow ?
677 if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))
685 * Converts a number of special characters into their HTML entities.
687 * Specifically deals with: &, <, >, ", and '.
689 * $quote_style can be set to ENT_COMPAT to encode " to
690 * ", or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded.
695 * @param string $string The text which is to be encoded.
696 * @param int $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.
697 * @param string $charset Optional. The character encoding of the string. Default is false.
698 * @param boolean $double_encode Optional. Whether to encode existing html entities. Default is false.
699 * @return string The encoded text with HTML entities.
701 function _wp_specialchars( $string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false ) {
702 $string = (string) $string;
704 if ( 0 === strlen( $string ) )
707 // Don't bother if there are no specialchars - saves some processing
708 if ( ! preg_match( '/[&<>"\']/', $string ) )
711 // Account for the previous behaviour of the function when the $quote_style is not an accepted value
712 if ( empty( $quote_style ) )
713 $quote_style = ENT_NOQUOTES;
714 elseif ( ! in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) )
715 $quote_style = ENT_QUOTES;
717 // Store the site charset as a static to avoid multiple calls to wp_load_alloptions()
720 if ( ! isset( $_charset ) ) {
721 $alloptions = wp_load_alloptions();
722 $_charset = isset( $alloptions['blog_charset'] ) ? $alloptions['blog_charset'] : '';
724 $charset = $_charset;
727 if ( in_array( $charset, array( 'utf8', 'utf-8', 'UTF8' ) ) )
730 $_quote_style = $quote_style;
732 if ( $quote_style === 'double' ) {
733 $quote_style = ENT_COMPAT;
734 $_quote_style = ENT_COMPAT;
735 } elseif ( $quote_style === 'single' ) {
736 $quote_style = ENT_NOQUOTES;
739 // Handle double encoding ourselves
740 if ( $double_encode ) {
741 $string = @htmlspecialchars( $string, $quote_style, $charset );
743 // Decode & into &
744 $string = wp_specialchars_decode( $string, $_quote_style );
746 // Guarantee every &entity; is valid or re-encode the &
747 $string = wp_kses_normalize_entities( $string );
749 // Now re-encode everything except &entity;
750 $string = preg_split( '/(&#?x?[0-9a-z]+;)/i', $string, -1, PREG_SPLIT_DELIM_CAPTURE );
752 for ( $i = 0, $c = count( $string ); $i < $c; $i += 2 ) {
753 $string[$i] = @htmlspecialchars( $string[$i], $quote_style, $charset );
755 $string = implode( '', $string );
758 // Backwards compatibility
759 if ( 'single' === $_quote_style )
760 $string = str_replace( "'", ''', $string );
766 * Converts a number of HTML entities into their special characters.
768 * Specifically deals with: &, <, >, ", and '.
770 * $quote_style can be set to ENT_COMPAT to decode " entities,
771 * or ENT_QUOTES to do both " and '. Default is ENT_NOQUOTES where no quotes are decoded.
775 * @param string $string The text which is to be decoded.
776 * @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.
777 * @return string The decoded text without HTML entities.
779 function wp_specialchars_decode( $string, $quote_style = ENT_NOQUOTES ) {
780 $string = (string) $string;
782 if ( 0 === strlen( $string ) ) {
786 // Don't bother if there are no entities - saves a lot of processing
787 if ( strpos( $string, '&' ) === false ) {
791 // Match the previous behaviour of _wp_specialchars() when the $quote_style is not an accepted value
792 if ( empty( $quote_style ) ) {
793 $quote_style = ENT_NOQUOTES;
794 } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
795 $quote_style = ENT_QUOTES;
798 // More complete than get_html_translation_table( HTML_SPECIALCHARS )
799 $single = array( ''' => '\'', ''' => '\'' );
800 $single_preg = array( '/�*39;/' => ''', '/�*27;/i' => ''' );
801 $double = array( '"' => '"', '"' => '"', '"' => '"' );
802 $double_preg = array( '/�*34;/' => '"', '/�*22;/i' => '"' );
803 $others = array( '<' => '<', '<' => '<', '>' => '>', '>' => '>', '&' => '&', '&' => '&', '&' => '&' );
804 $others_preg = array( '/�*60;/' => '<', '/�*62;/' => '>', '/�*38;/' => '&', '/�*26;/i' => '&' );
806 if ( $quote_style === ENT_QUOTES ) {
807 $translation = array_merge( $single, $double, $others );
808 $translation_preg = array_merge( $single_preg, $double_preg, $others_preg );
809 } elseif ( $quote_style === ENT_COMPAT || $quote_style === 'double' ) {
810 $translation = array_merge( $double, $others );
811 $translation_preg = array_merge( $double_preg, $others_preg );
812 } elseif ( $quote_style === 'single' ) {
813 $translation = array_merge( $single, $others );
814 $translation_preg = array_merge( $single_preg, $others_preg );
815 } elseif ( $quote_style === ENT_NOQUOTES ) {
816 $translation = $others;
817 $translation_preg = $others_preg;
820 // Remove zero padding on numeric entities
821 $string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string );
823 // Replace characters according to translation table
824 return strtr( $string, $translation );
828 * Checks for invalid UTF8 in a string.
832 * @param string $string The text which is to be checked.
833 * @param boolean $strip Optional. Whether to attempt to strip out invalid UTF8. Default is false.
834 * @return string The checked text.
836 function wp_check_invalid_utf8( $string, $strip = false ) {
837 $string = (string) $string;
839 if ( 0 === strlen( $string ) ) {
843 // Store the site charset as a static to avoid multiple calls to get_option()
845 if ( !isset( $is_utf8 ) ) {
846 $is_utf8 = in_array( get_option( 'blog_charset' ), array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ) );
852 // Check for support for utf8 in the installed PCRE library once and store the result in a static
854 if ( !isset( $utf8_pcre ) ) {
855 $utf8_pcre = @preg_match( '/^./u', 'a' );
857 // We can't demand utf8 in the PCRE installation, so just return the string in those cases
862 // preg_match fails when it encounters invalid UTF8 in $string
863 if ( 1 === @preg_match( '/^./us', $string ) ) {
867 // Attempt to strip the bad chars if requested (not recommended)
868 if ( $strip && function_exists( 'iconv' ) ) {
869 return iconv( 'utf-8', 'utf-8', $string );
876 * Encode the Unicode values to be used in the URI.
880 * @param string $utf8_string
881 * @param int $length Max length of the string
882 * @return string String with Unicode encoded for URI.
884 function utf8_uri_encode( $utf8_string, $length = 0 ) {
890 mbstring_binary_safe_encoding();
891 $string_length = strlen( $utf8_string );
892 reset_mbstring_encoding();
894 for ($i = 0; $i < $string_length; $i++ ) {
896 $value = ord( $utf8_string[ $i ] );
898 if ( $value < 128 ) {
899 if ( $length && ( $unicode_length >= $length ) )
901 $unicode .= chr($value);
904 if ( count( $values ) == 0 ) {
905 if ( $value < 224 ) {
907 } elseif ( $value < 240 ) {
916 if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length )
918 if ( count( $values ) == $num_octets ) {
919 for ( $j = 0; $j < $num_octets; $j++ ) {
920 $unicode .= '%' . dechex( $values[ $j ] );
923 $unicode_length += $num_octets * 3;
935 * Converts all accent characters to ASCII characters.
937 * If there are no accent characters, then the string given is just returned.
941 * @param string $string Text that might have accent characters
942 * @return string Filtered string with replaced "nice" characters.
944 function remove_accents($string) {
945 if ( !preg_match('/[\x80-\xff]/', $string) )
948 if (seems_utf8($string)) {
950 // Decompositions for Latin-1 Supplement
951 chr(194).chr(170) => 'a', chr(194).chr(186) => 'o',
952 chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
953 chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
954 chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
955 chr(195).chr(134) => 'AE',chr(195).chr(135) => 'C',
956 chr(195).chr(136) => 'E', chr(195).chr(137) => 'E',
957 chr(195).chr(138) => 'E', chr(195).chr(139) => 'E',
958 chr(195).chr(140) => 'I', chr(195).chr(141) => 'I',
959 chr(195).chr(142) => 'I', chr(195).chr(143) => 'I',
960 chr(195).chr(144) => 'D', chr(195).chr(145) => 'N',
961 chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
962 chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
963 chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
964 chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
965 chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
966 chr(195).chr(158) => 'TH',chr(195).chr(159) => 's',
967 chr(195).chr(160) => 'a', chr(195).chr(161) => 'a',
968 chr(195).chr(162) => 'a', chr(195).chr(163) => 'a',
969 chr(195).chr(164) => 'a', chr(195).chr(165) => 'a',
970 chr(195).chr(166) => 'ae',chr(195).chr(167) => 'c',
971 chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
972 chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
973 chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
974 chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
975 chr(195).chr(176) => 'd', chr(195).chr(177) => 'n',
976 chr(195).chr(178) => 'o', chr(195).chr(179) => 'o',
977 chr(195).chr(180) => 'o', chr(195).chr(181) => 'o',
978 chr(195).chr(182) => 'o', chr(195).chr(184) => 'o',
979 chr(195).chr(185) => 'u', chr(195).chr(186) => 'u',
980 chr(195).chr(187) => 'u', chr(195).chr(188) => 'u',
981 chr(195).chr(189) => 'y', chr(195).chr(190) => 'th',
982 chr(195).chr(191) => 'y', chr(195).chr(152) => 'O',
983 // Decompositions for Latin Extended-A
984 chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
985 chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
986 chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
987 chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
988 chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
989 chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
990 chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
991 chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
992 chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
993 chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
994 chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
995 chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
996 chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
997 chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
998 chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
999 chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
1000 chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
1001 chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
1002 chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
1003 chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
1004 chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
1005 chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
1006 chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
1007 chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
1008 chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
1009 chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
1010 chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
1011 chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
1012 chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
1013 chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
1014 chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
1015 chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
1016 chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
1017 chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
1018 chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
1019 chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
1020 chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
1021 chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
1022 chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
1023 chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
1024 chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
1025 chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
1026 chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
1027 chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
1028 chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
1029 chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
1030 chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
1031 chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
1032 chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
1033 chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
1034 chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
1035 chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
1036 chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
1037 chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
1038 chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
1039 chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
1040 chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
1041 chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
1042 chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
1043 chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
1044 chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
1045 chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
1046 chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
1047 chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
1048 // Decompositions for Latin Extended-B
1049 chr(200).chr(152) => 'S', chr(200).chr(153) => 's',
1050 chr(200).chr(154) => 'T', chr(200).chr(155) => 't',
1052 chr(226).chr(130).chr(172) => 'E',
1054 chr(194).chr(163) => '',
1055 // Vowels with diacritic (Vietnamese)
1057 chr(198).chr(160) => 'O', chr(198).chr(161) => 'o',
1058 chr(198).chr(175) => 'U', chr(198).chr(176) => 'u',
1060 chr(225).chr(186).chr(166) => 'A', chr(225).chr(186).chr(167) => 'a',
1061 chr(225).chr(186).chr(176) => 'A', chr(225).chr(186).chr(177) => 'a',
1062 chr(225).chr(187).chr(128) => 'E', chr(225).chr(187).chr(129) => 'e',
1063 chr(225).chr(187).chr(146) => 'O', chr(225).chr(187).chr(147) => 'o',
1064 chr(225).chr(187).chr(156) => 'O', chr(225).chr(187).chr(157) => 'o',
1065 chr(225).chr(187).chr(170) => 'U', chr(225).chr(187).chr(171) => 'u',
1066 chr(225).chr(187).chr(178) => 'Y', chr(225).chr(187).chr(179) => 'y',
1068 chr(225).chr(186).chr(162) => 'A', chr(225).chr(186).chr(163) => 'a',
1069 chr(225).chr(186).chr(168) => 'A', chr(225).chr(186).chr(169) => 'a',
1070 chr(225).chr(186).chr(178) => 'A', chr(225).chr(186).chr(179) => 'a',
1071 chr(225).chr(186).chr(186) => 'E', chr(225).chr(186).chr(187) => 'e',
1072 chr(225).chr(187).chr(130) => 'E', chr(225).chr(187).chr(131) => 'e',
1073 chr(225).chr(187).chr(136) => 'I', chr(225).chr(187).chr(137) => 'i',
1074 chr(225).chr(187).chr(142) => 'O', chr(225).chr(187).chr(143) => 'o',
1075 chr(225).chr(187).chr(148) => 'O', chr(225).chr(187).chr(149) => 'o',
1076 chr(225).chr(187).chr(158) => 'O', chr(225).chr(187).chr(159) => 'o',
1077 chr(225).chr(187).chr(166) => 'U', chr(225).chr(187).chr(167) => 'u',
1078 chr(225).chr(187).chr(172) => 'U', chr(225).chr(187).chr(173) => 'u',
1079 chr(225).chr(187).chr(182) => 'Y', chr(225).chr(187).chr(183) => 'y',
1081 chr(225).chr(186).chr(170) => 'A', chr(225).chr(186).chr(171) => 'a',
1082 chr(225).chr(186).chr(180) => 'A', chr(225).chr(186).chr(181) => 'a',
1083 chr(225).chr(186).chr(188) => 'E', chr(225).chr(186).chr(189) => 'e',
1084 chr(225).chr(187).chr(132) => 'E', chr(225).chr(187).chr(133) => 'e',
1085 chr(225).chr(187).chr(150) => 'O', chr(225).chr(187).chr(151) => 'o',
1086 chr(225).chr(187).chr(160) => 'O', chr(225).chr(187).chr(161) => 'o',
1087 chr(225).chr(187).chr(174) => 'U', chr(225).chr(187).chr(175) => 'u',
1088 chr(225).chr(187).chr(184) => 'Y', chr(225).chr(187).chr(185) => 'y',
1090 chr(225).chr(186).chr(164) => 'A', chr(225).chr(186).chr(165) => 'a',
1091 chr(225).chr(186).chr(174) => 'A', chr(225).chr(186).chr(175) => 'a',
1092 chr(225).chr(186).chr(190) => 'E', chr(225).chr(186).chr(191) => 'e',
1093 chr(225).chr(187).chr(144) => 'O', chr(225).chr(187).chr(145) => 'o',
1094 chr(225).chr(187).chr(154) => 'O', chr(225).chr(187).chr(155) => 'o',
1095 chr(225).chr(187).chr(168) => 'U', chr(225).chr(187).chr(169) => 'u',
1097 chr(225).chr(186).chr(160) => 'A', chr(225).chr(186).chr(161) => 'a',
1098 chr(225).chr(186).chr(172) => 'A', chr(225).chr(186).chr(173) => 'a',
1099 chr(225).chr(186).chr(182) => 'A', chr(225).chr(186).chr(183) => 'a',
1100 chr(225).chr(186).chr(184) => 'E', chr(225).chr(186).chr(185) => 'e',
1101 chr(225).chr(187).chr(134) => 'E', chr(225).chr(187).chr(135) => 'e',
1102 chr(225).chr(187).chr(138) => 'I', chr(225).chr(187).chr(139) => 'i',
1103 chr(225).chr(187).chr(140) => 'O', chr(225).chr(187).chr(141) => 'o',
1104 chr(225).chr(187).chr(152) => 'O', chr(225).chr(187).chr(153) => 'o',
1105 chr(225).chr(187).chr(162) => 'O', chr(225).chr(187).chr(163) => 'o',
1106 chr(225).chr(187).chr(164) => 'U', chr(225).chr(187).chr(165) => 'u',
1107 chr(225).chr(187).chr(176) => 'U', chr(225).chr(187).chr(177) => 'u',
1108 chr(225).chr(187).chr(180) => 'Y', chr(225).chr(187).chr(181) => 'y',
1109 // Vowels with diacritic (Chinese, Hanyu Pinyin)
1110 chr(201).chr(145) => 'a',
1112 chr(199).chr(149) => 'U', chr(199).chr(150) => 'u',
1114 chr(199).chr(151) => 'U', chr(199).chr(152) => 'u',
1116 chr(199).chr(141) => 'A', chr(199).chr(142) => 'a',
1117 chr(199).chr(143) => 'I', chr(199).chr(144) => 'i',
1118 chr(199).chr(145) => 'O', chr(199).chr(146) => 'o',
1119 chr(199).chr(147) => 'U', chr(199).chr(148) => 'u',
1120 chr(199).chr(153) => 'U', chr(199).chr(154) => 'u',
1122 chr(199).chr(155) => 'U', chr(199).chr(156) => 'u',
1125 // Used for locale-specific rules
1126 $locale = get_locale();
1128 if ( 'de_DE' == $locale ) {
1129 $chars[ chr(195).chr(132) ] = 'Ae';
1130 $chars[ chr(195).chr(164) ] = 'ae';
1131 $chars[ chr(195).chr(150) ] = 'Oe';
1132 $chars[ chr(195).chr(182) ] = 'oe';
1133 $chars[ chr(195).chr(156) ] = 'Ue';
1134 $chars[ chr(195).chr(188) ] = 'ue';
1135 $chars[ chr(195).chr(159) ] = 'ss';
1136 } elseif ( 'da_DK' === $locale ) {
1137 $chars[ chr(195).chr(134) ] = 'Ae';
1138 $chars[ chr(195).chr(166) ] = 'ae';
1139 $chars[ chr(195).chr(152) ] = 'Oe';
1140 $chars[ chr(195).chr(184) ] = 'oe';
1141 $chars[ chr(195).chr(133) ] = 'Aa';
1142 $chars[ chr(195).chr(165) ] = 'aa';
1145 $string = strtr($string, $chars);
1148 // Assume ISO-8859-1 if not UTF-8
1149 $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
1150 .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
1151 .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
1152 .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
1153 .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
1154 .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
1155 .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
1156 .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
1157 .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
1158 .chr(252).chr(253).chr(255);
1160 $chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";
1162 $string = strtr($string, $chars['in'], $chars['out']);
1163 $double_chars = array();
1164 $double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
1165 $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
1166 $string = str_replace($double_chars['in'], $double_chars['out'], $string);
1173 * Sanitizes a filename, replacing whitespace with dashes.
1175 * Removes special characters that are illegal in filenames on certain
1176 * operating systems and special characters requiring special escaping
1177 * to manipulate at the command line. Replaces spaces and consecutive
1178 * dashes with a single dash. Trims period, dash and underscore from beginning
1179 * and end of filename.
1183 * @param string $filename The filename to be sanitized
1184 * @return string The sanitized filename
1186 function sanitize_file_name( $filename ) {
1187 $filename_raw = $filename;
1188 $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", chr(0));
1190 * Filter the list of characters to remove from a filename.
1194 * @param array $special_chars Characters to remove.
1195 * @param string $filename_raw Filename as it was passed into sanitize_file_name().
1197 $special_chars = apply_filters( 'sanitize_file_name_chars', $special_chars, $filename_raw );
1198 $filename = preg_replace( "#\x{00a0}#siu", ' ', $filename );
1199 $filename = str_replace( $special_chars, '', $filename );
1200 $filename = str_replace( array( '%20', '+' ), '-', $filename );
1201 $filename = preg_replace( '/[\r\n\t -]+/', '-', $filename );
1202 $filename = trim( $filename, '.-_' );
1204 // Split the filename into a base and extension[s]
1205 $parts = explode('.', $filename);
1207 // Return if only one extension
1208 if ( count( $parts ) <= 2 ) {
1210 * Filter a sanitized filename string.
1214 * @param string $filename Sanitized filename.
1215 * @param string $filename_raw The filename prior to sanitization.
1217 return apply_filters( 'sanitize_file_name', $filename, $filename_raw );
1220 // Process multiple extensions
1221 $filename = array_shift($parts);
1222 $extension = array_pop($parts);
1223 $mimes = get_allowed_mime_types();
1226 * Loop over any intermediate extensions. Postfix them with a trailing underscore
1227 * if they are a 2 - 5 character long alpha string not in the extension whitelist.
1229 foreach ( (array) $parts as $part) {
1230 $filename .= '.' . $part;
1232 if ( preg_match("/^[a-zA-Z]{2,5}\d?$/", $part) ) {
1234 foreach ( $mimes as $ext_preg => $mime_match ) {
1235 $ext_preg = '!^(' . $ext_preg . ')$!i';
1236 if ( preg_match( $ext_preg, $part ) ) {
1245 $filename .= '.' . $extension;
1246 /** This filter is documented in wp-includes/formatting.php */
1247 return apply_filters('sanitize_file_name', $filename, $filename_raw);
1251 * Sanitizes a username, stripping out unsafe characters.
1253 * Removes tags, octets, entities, and if strict is enabled, will only keep
1254 * alphanumeric, _, space, ., -, @. After sanitizing, it passes the username,
1255 * raw username (the username in the parameter), and the value of $strict as
1256 * parameters for the 'sanitize_user' filter.
1260 * @param string $username The username to be sanitized.
1261 * @param bool $strict If set limits $username to specific characters. Default false.
1262 * @return string The sanitized username, after passing through filters.
1264 function sanitize_user( $username, $strict = false ) {
1265 $raw_username = $username;
1266 $username = wp_strip_all_tags( $username );
1267 $username = remove_accents( $username );
1269 $username = preg_replace( '|%([a-fA-F0-9][a-fA-F0-9])|', '', $username );
1270 $username = preg_replace( '/&.+?;/', '', $username ); // Kill entities
1272 // If strict, reduce to ASCII for max portability.
1274 $username = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $username );
1276 $username = trim( $username );
1277 // Consolidate contiguous whitespace
1278 $username = preg_replace( '|\s+|', ' ', $username );
1281 * Filter a sanitized username string.
1285 * @param string $username Sanitized username.
1286 * @param string $raw_username The username prior to sanitization.
1287 * @param bool $strict Whether to limit the sanitization to specific characters. Default false.
1289 return apply_filters( 'sanitize_user', $username, $raw_username, $strict );
1293 * Sanitizes a string key.
1295 * Keys are used as internal identifiers. Lowercase alphanumeric characters, dashes and underscores are allowed.
1299 * @param string $key String key
1300 * @return string Sanitized key
1302 function sanitize_key( $key ) {
1304 $key = strtolower( $key );
1305 $key = preg_replace( '/[^a-z0-9_\-]/', '', $key );
1308 * Filter a sanitized key string.
1312 * @param string $key Sanitized key.
1313 * @param string $raw_key The key prior to sanitization.
1315 return apply_filters( 'sanitize_key', $key, $raw_key );
1319 * Sanitizes a title, or returns a fallback title.
1321 * Specifically, HTML and PHP tags are stripped. Further actions can be added
1322 * via the plugin API. If $title is empty and $fallback_title is set, the latter
1327 * @param string $title The string to be sanitized.
1328 * @param string $fallback_title Optional. A title to use if $title is empty.
1329 * @param string $context Optional. The operation for which the string is sanitized
1330 * @return string The sanitized string.
1332 function sanitize_title( $title, $fallback_title = '', $context = 'save' ) {
1333 $raw_title = $title;
1335 if ( 'save' == $context )
1336 $title = remove_accents($title);
1339 * Filter a sanitized title string.
1343 * @param string $title Sanitized title.
1344 * @param string $raw_title The title prior to sanitization.
1345 * @param string $context The context for which the title is being sanitized.
1347 $title = apply_filters( 'sanitize_title', $title, $raw_title, $context );
1349 if ( '' === $title || false === $title )
1350 $title = $fallback_title;
1356 * Sanitizes a title with the 'query' context.
1358 * Used for querying the database for a value from URL.
1362 * @param string $title The string to be sanitized.
1363 * @return string The sanitized string.
1365 function sanitize_title_for_query( $title ) {
1366 return sanitize_title( $title, '', 'query' );
1370 * Sanitizes a title, replacing whitespace and a few other characters with dashes.
1372 * Limits the output to alphanumeric characters, underscore (_) and dash (-).
1373 * Whitespace becomes a dash.
1377 * @param string $title The title to be sanitized.
1378 * @param string $raw_title Optional. Not used.
1379 * @param string $context Optional. The operation for which the string is sanitized.
1380 * @return string The sanitized title.
1382 function sanitize_title_with_dashes( $title, $raw_title = '', $context = 'display' ) {
1383 $title = strip_tags($title);
1384 // Preserve escaped octets.
1385 $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
1386 // Remove percent signs that are not part of an octet.
1387 $title = str_replace('%', '', $title);
1389 $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
1391 if (seems_utf8($title)) {
1392 if (function_exists('mb_strtolower')) {
1393 $title = mb_strtolower($title, 'UTF-8');
1395 $title = utf8_uri_encode($title, 200);
1398 $title = strtolower($title);
1399 $title = preg_replace('/&.+?;/', '', $title); // kill entities
1400 $title = str_replace('.', '-', $title);
1402 if ( 'save' == $context ) {
1403 // Convert nbsp, ndash and mdash to hyphens
1404 $title = str_replace( array( '%c2%a0', '%e2%80%93', '%e2%80%94' ), '-', $title );
1406 // Strip these characters entirely
1407 $title = str_replace( array(
1411 '%c2%ab', '%c2%bb', '%e2%80%b9', '%e2%80%ba',
1413 '%e2%80%98', '%e2%80%99', '%e2%80%9c', '%e2%80%9d',
1414 '%e2%80%9a', '%e2%80%9b', '%e2%80%9e', '%e2%80%9f',
1415 // copy, reg, deg, hellip and trade
1416 '%c2%a9', '%c2%ae', '%c2%b0', '%e2%80%a6', '%e2%84%a2',
1418 '%c2%b4', '%cb%8a', '%cc%81', '%cd%81',
1419 // grave accent, macron, caron
1420 '%cc%80', '%cc%84', '%cc%8c',
1423 // Convert times to x
1424 $title = str_replace( '%c3%97', 'x', $title );
1427 $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
1428 $title = preg_replace('/\s+/', '-', $title);
1429 $title = preg_replace('|-+|', '-', $title);
1430 $title = trim($title, '-');
1436 * Ensures a string is a valid SQL 'order by' clause.
1438 * Accepts one or more columns, with or without a sort order (ASC / DESC).
1439 * e.g. 'column_1', 'column_1, column_2', 'column_1 ASC, column_2 DESC' etc.
1441 * Also accepts 'RAND()'.
1445 * @param string $orderby Order by clause to be validated.
1446 * @return string|bool Returns $orderby if valid, false otherwise.
1448 function sanitize_sql_orderby( $orderby ) {
1449 if ( preg_match( '/^\s*(([a-z0-9_]+|`[a-z0-9_]+`)(\s+(ASC|DESC))?\s*(,\s*(?=[a-z0-9_`])|$))+$/i', $orderby ) || preg_match( '/^\s*RAND\(\s*\)\s*$/i', $orderby ) ) {
1456 * Sanitizes an HTML classname to ensure it only contains valid characters.
1458 * Strips the string down to A-Z,a-z,0-9,_,-. If this results in an empty
1459 * string then it will return the alternative value supplied.
1461 * @todo Expand to support the full range of CDATA that a class attribute can contain.
1465 * @param string $class The classname to be sanitized
1466 * @param string $fallback Optional. The value to return if the sanitization ends up as an empty string.
1467 * Defaults to an empty string.
1468 * @return string The sanitized value
1470 function sanitize_html_class( $class, $fallback = '' ) {
1471 //Strip out any % encoded octets
1472 $sanitized = preg_replace( '|%[a-fA-F0-9][a-fA-F0-9]|', '', $class );
1474 //Limit to A-Z,a-z,0-9,_,-
1475 $sanitized = preg_replace( '/[^A-Za-z0-9_-]/', '', $sanitized );
1477 if ( '' == $sanitized )
1478 $sanitized = $fallback;
1481 * Filter a sanitized HTML class string.
1485 * @param string $sanitized The sanitized HTML class.
1486 * @param string $class HTML class before sanitization.
1487 * @param string $fallback The fallback string.
1489 return apply_filters( 'sanitize_html_class', $sanitized, $class, $fallback );
1493 * Converts a number of characters from a string.
1495 * Metadata tags `<title>` and `<category>` are removed, `<br>` and `<hr>` are
1496 * converted into correct XHTML and Unicode characters are converted to the
1501 * @param string $content String of characters to be converted.
1502 * @param string $deprecated Not used.
1503 * @return string Converted string.
1505 function convert_chars($content, $deprecated = '') {
1506 if ( !empty( $deprecated ) )
1507 _deprecated_argument( __FUNCTION__, '0.71' );
1509 // Translation of invalid Unicode references range to valid range
1510 $wp_htmltranswinuni = array(
1511 '€' => '€', // the Euro sign
1513 '‚' => '‚', // these are Windows CP1252 specific characters
1514 'ƒ' => 'ƒ', // they would look weird on non-Windows browsers
1515 '„' => '„',
1516 '…' => '…',
1517 '†' => '†',
1518 '‡' => '‡',
1519 'ˆ' => 'ˆ',
1520 '‰' => '‰',
1521 'Š' => 'Š',
1522 '‹' => '‹',
1523 'Œ' => 'Œ',
1525 'Ž' => 'Ž',
1528 '‘' => '‘',
1529 '’' => '’',
1530 '“' => '“',
1531 '”' => '”',
1532 '•' => '•',
1533 '–' => '–',
1534 '—' => '—',
1535 '˜' => '˜',
1536 '™' => '™',
1537 'š' => 'š',
1538 '›' => '›',
1539 'œ' => 'œ',
1541 'ž' => 'ž',
1542 'Ÿ' => 'Ÿ'
1545 // Remove metadata tags
1546 $content = preg_replace('/<title>(.+?)<\/title>/','',$content);
1547 $content = preg_replace('/<category>(.+?)<\/category>/','',$content);
1549 // Converts lone & characters into & (a.k.a. &)
1550 $content = preg_replace('/&([^#])(?![a-z1-4]{1,8};)/i', '&$1', $content);
1553 $content = strtr($content, $wp_htmltranswinuni);
1555 // Just a little XHTML help
1556 $content = str_replace('<br>', '<br />', $content);
1557 $content = str_replace('<hr>', '<hr />', $content);
1563 * Balances tags if forced to, or if the 'use_balanceTags' option is set to true.
1567 * @param string $text Text to be balanced
1568 * @param bool $force If true, forces balancing, ignoring the value of the option. Default false.
1569 * @return string Balanced text
1571 function balanceTags( $text, $force = false ) {
1572 if ( $force || get_option('use_balanceTags') == 1 ) {
1573 return force_balance_tags( $text );
1580 * Balances tags of string using a modified stack.
1584 * @author Leonard Lin <leonard@acm.org>
1586 * @copyright November 4, 2001
1588 * @todo Make better - change loop condition to $text in 1.2
1589 * @internal Modified by Scott Reilly (coffee2code) 02 Aug 2004
1590 * 1.1 Fixed handling of append/stack pop order of end text
1591 * Added Cleaning Hooks
1594 * @param string $text Text to be balanced.
1595 * @return string Balanced text.
1597 function force_balance_tags( $text ) {
1598 $tagstack = array();
1602 // Known single-entity/self-closing tags
1603 $single_tags = array( 'area', 'base', 'basefont', 'br', 'col', 'command', 'embed', 'frame', 'hr', 'img', 'input', 'isindex', 'link', 'meta', 'param', 'source' );
1604 // Tags that can be immediately nested within themselves
1605 $nestable_tags = array( 'blockquote', 'div', 'object', 'q', 'span' );
1607 // WP bug fix for comments - in case you REALLY meant to type '< !--'
1608 $text = str_replace('< !--', '< !--', $text);
1609 // WP bug fix for LOVE <3 (and other situations with '<' before a number)
1610 $text = preg_replace('#<([0-9]{1})#', '<$1', $text);
1612 while ( preg_match("/<(\/?[\w:]*)\s*([^>]*)>/", $text, $regex) ) {
1613 $newtext .= $tagqueue;
1615 $i = strpos($text, $regex[0]);
1616 $l = strlen($regex[0]);
1618 // clear the shifter
1621 if ( isset($regex[1][0]) && '/' == $regex[1][0] ) { // End Tag
1622 $tag = strtolower(substr($regex[1],1));
1623 // if too many closing tags
1624 if( $stacksize <= 0 ) {
1626 // or close to be safe $tag = '/' . $tag;
1628 // if stacktop value = tag close value then pop
1629 elseif ( $tagstack[$stacksize - 1] == $tag ) { // found closing tag
1630 $tag = '</' . $tag . '>'; // Close Tag
1632 array_pop( $tagstack );
1634 } else { // closing tag not at top, search for it
1635 for ( $j = $stacksize-1; $j >= 0; $j-- ) {
1636 if ( $tagstack[$j] == $tag ) {
1637 // add tag to tagqueue
1638 for ( $k = $stacksize-1; $k >= $j; $k--) {
1639 $tagqueue .= '</' . array_pop( $tagstack ) . '>';
1647 } else { // Begin Tag
1648 $tag = strtolower($regex[1]);
1652 // If it's an empty tag "< >", do nothing
1656 // ElseIf it presents itself as a self-closing tag...
1657 elseif ( substr( $regex[2], -1 ) == '/' ) {
1658 // ...but it isn't a known single-entity self-closing tag, then don't let it be treated as such and
1659 // immediately close it with a closing tag (the tag will encapsulate no text as a result)
1660 if ( ! in_array( $tag, $single_tags ) )
1661 $regex[2] = trim( substr( $regex[2], 0, -1 ) ) . "></$tag";
1663 // ElseIf it's a known single-entity tag but it doesn't close itself, do so
1664 elseif ( in_array($tag, $single_tags) ) {
1667 // Else it's not a single-entity tag
1669 // If the top of the stack is the same as the tag we want to push, close previous tag
1670 if ( $stacksize > 0 && !in_array($tag, $nestable_tags) && $tagstack[$stacksize - 1] == $tag ) {
1671 $tagqueue = '</' . array_pop( $tagstack ) . '>';
1674 $stacksize = array_push( $tagstack, $tag );
1678 $attributes = $regex[2];
1679 if( ! empty( $attributes ) && $attributes[0] != '>' )
1680 $attributes = ' ' . $attributes;
1682 $tag = '<' . $tag . $attributes . '>';
1683 //If already queuing a close tag, then put this tag on, too
1684 if ( !empty($tagqueue) ) {
1689 $newtext .= substr($text, 0, $i) . $tag;
1690 $text = substr($text, $i + $l);
1694 $newtext .= $tagqueue;
1696 // Add Remaining text
1700 while( $x = array_pop($tagstack) )
1701 $newtext .= '</' . $x . '>'; // Add remaining tags to close
1703 // WP fix for the bug with HTML comments
1704 $newtext = str_replace("< !--","<!--",$newtext);
1705 $newtext = str_replace("< !--","< !--",$newtext);
1711 * Acts on text which is about to be edited.
1713 * The $content is run through esc_textarea(), which uses htmlspecialchars()
1714 * to convert special characters to HTML entities. If $richedit is set to true,
1715 * it is simply a holder for the 'format_to_edit' filter.
1719 * @param string $content The text about to be edited.
1720 * @param bool $richedit Whether the $content should not pass through htmlspecialchars(). Default false (meaning it will be passed).
1721 * @return string The text after the filter (and possibly htmlspecialchars()) has been run.
1723 function format_to_edit( $content, $richedit = false ) {
1725 * Filter the text to be formatted for editing.
1729 * @param string $content The text, prior to formatting for editing.
1731 $content = apply_filters( 'format_to_edit', $content );
1733 $content = esc_textarea( $content );
1738 * Add leading zeros when necessary.
1740 * If you set the threshold to '4' and the number is '10', then you will get
1741 * back '0010'. If you set the threshold to '4' and the number is '5000', then you
1742 * will get back '5000'.
1744 * Uses sprintf to append the amount of zeros based on the $threshold parameter
1745 * and the size of the number. If the number is large enough, then no zeros will
1750 * @param mixed $number Number to append zeros to if not greater than threshold.
1751 * @param int $threshold Digit places number needs to be to not have zeros added.
1752 * @return string Adds leading zeros to number if needed.
1754 function zeroise($number, $threshold) {
1755 return sprintf('%0'.$threshold.'s', $number);
1759 * Adds backslashes before letters and before a number at the start of a string.
1763 * @param string $string Value to which backslashes will be added.
1764 * @return string String with backslashes inserted.
1766 function backslashit($string) {
1767 if ( isset( $string[0] ) && $string[0] >= '0' && $string[0] <= '9' )
1768 $string = '\\\\' . $string;
1769 return addcslashes( $string, 'A..Za..z' );
1773 * Appends a trailing slash.
1775 * Will remove trailing forward and backslashes if it exists already before adding
1776 * a trailing forward slash. This prevents double slashing a string or path.
1778 * The primary use of this is for paths and thus should be used for paths. It is
1779 * not restricted to paths and offers no specific path support.
1783 * @param string $string What to add the trailing slash to.
1784 * @return string String with trailing slash added.
1786 function trailingslashit( $string ) {
1787 return untrailingslashit( $string ) . '/';
1791 * Removes trailing forward slashes and backslashes if they exist.
1793 * The primary use of this is for paths and thus should be used for paths. It is
1794 * not restricted to paths and offers no specific path support.
1798 * @param string $string What to remove the trailing slashes from.
1799 * @return string String without the trailing slashes.
1801 function untrailingslashit( $string ) {
1802 return rtrim( $string, '/\\' );
1806 * Adds slashes to escape strings.
1808 * Slashes will first be removed if magic_quotes_gpc is set, see {@link
1809 * http://www.php.net/magic_quotes} for more details.
1813 * @param string $gpc The string returned from HTTP request data.
1814 * @return string Returns a string escaped with slashes.
1816 function addslashes_gpc($gpc) {
1817 if ( get_magic_quotes_gpc() )
1818 $gpc = stripslashes($gpc);
1820 return wp_slash($gpc);
1824 * Navigates through an array and removes slashes from the values.
1826 * If an array is passed, the array_map() function causes a callback to pass the
1827 * value back to the function. The slashes from this value will removed.
1831 * @param mixed $value The value to be stripped.
1832 * @return mixed Stripped value.
1834 function stripslashes_deep($value) {
1835 if ( is_array($value) ) {
1836 $value = array_map('stripslashes_deep', $value);
1837 } elseif ( is_object($value) ) {
1838 $vars = get_object_vars( $value );
1839 foreach ($vars as $key=>$data) {
1840 $value->{$key} = stripslashes_deep( $data );
1842 } elseif ( is_string( $value ) ) {
1843 $value = stripslashes($value);
1850 * Navigates through an array and encodes the values to be used in a URL.
1855 * @param array|string $value The array or string to be encoded.
1856 * @return array|string $value The encoded array (or string from the callback).
1858 function urlencode_deep($value) {
1859 $value = is_array($value) ? array_map('urlencode_deep', $value) : urlencode($value);
1864 * Navigates through an array and raw encodes the values to be used in a URL.
1868 * @param array|string $value The array or string to be encoded.
1869 * @return array|string $value The encoded array (or string from the callback).
1871 function rawurlencode_deep( $value ) {
1872 return is_array( $value ) ? array_map( 'rawurlencode_deep', $value ) : rawurlencode( $value );
1876 * Converts email addresses characters to HTML entities to block spam bots.
1880 * @param string $email_address Email address.
1881 * @param int $hex_encoding Optional. Set to 1 to enable hex encoding.
1882 * @return string Converted email address.
1884 function antispambot( $email_address, $hex_encoding = 0 ) {
1885 $email_no_spam_address = '';
1886 for ( $i = 0, $len = strlen( $email_address ); $i < $len; $i++ ) {
1887 $j = rand( 0, 1 + $hex_encoding );
1889 $email_no_spam_address .= '&#' . ord( $email_address[$i] ) . ';';
1890 } elseif ( $j == 1 ) {
1891 $email_no_spam_address .= $email_address[$i];
1892 } elseif ( $j == 2 ) {
1893 $email_no_spam_address .= '%' . zeroise( dechex( ord( $email_address[$i] ) ), 2 );
1897 $email_no_spam_address = str_replace( '@', '@', $email_no_spam_address );
1899 return $email_no_spam_address;
1903 * Callback to convert URI match to HTML A element.
1905 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1906 * make_clickable()}.
1911 * @param array $matches Single Regex Match.
1912 * @return string HTML A element with URI address.
1914 function _make_url_clickable_cb($matches) {
1917 if ( ')' == $matches[3] && strpos( $url, '(' ) ) {
1918 // If the trailing character is a closing parethesis, and the URL has an opening parenthesis in it, add the closing parenthesis to the URL.
1919 // Then we can let the parenthesis balancer do its thing below.
1920 $url .= $matches[3];
1923 $suffix = $matches[3];
1926 // Include parentheses in the URL only if paired
1927 while ( substr_count( $url, '(' ) < substr_count( $url, ')' ) ) {
1928 $suffix = strrchr( $url, ')' ) . $suffix;
1929 $url = substr( $url, 0, strrpos( $url, ')' ) );
1932 $url = esc_url($url);
1936 return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $suffix;
1940 * Callback to convert URL match to HTML A element.
1942 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1943 * make_clickable()}.
1948 * @param array $matches Single Regex Match.
1949 * @return string HTML A element with URL address.
1951 function _make_web_ftp_clickable_cb($matches) {
1953 $dest = $matches[2];
1954 $dest = 'http://' . $dest;
1955 $dest = esc_url($dest);
1959 // removed trailing [.,;:)] from URL
1960 if ( in_array( substr($dest, -1), array('.', ',', ';', ':', ')') ) === true ) {
1961 $ret = substr($dest, -1);
1962 $dest = substr($dest, 0, strlen($dest)-1);
1964 return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>$ret";
1968 * Callback to convert email address match to HTML A element.
1970 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1971 * make_clickable()}.
1976 * @param array $matches Single Regex Match.
1977 * @return string HTML A element with email address.
1979 function _make_email_clickable_cb($matches) {
1980 $email = $matches[2] . '@' . $matches[3];
1981 return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
1985 * Convert plaintext URI to HTML links.
1987 * Converts URI, www and ftp, and email addresses. Finishes by fixing links
1992 * @param string $text Content to convert URIs.
1993 * @return string Content with converted URIs.
1995 function make_clickable( $text ) {
1997 $textarr = preg_split( '/(<[^<>]+>)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // split out HTML tags
1998 $nested_code_pre = 0; // Keep track of how many levels link is nested inside <pre> or <code>
1999 foreach ( $textarr as $piece ) {
2001 if ( preg_match( '|^<code[\s>]|i', $piece ) || preg_match( '|^<pre[\s>]|i', $piece ) )
2003 elseif ( ( '</code>' === strtolower( $piece ) || '</pre>' === strtolower( $piece ) ) && $nested_code_pre )
2006 if ( $nested_code_pre || empty( $piece ) || ( $piece[0] === '<' && ! preg_match( '|^<\s*[\w]{1,20}+://|', $piece ) ) ) {
2011 // Long strings might contain expensive edge cases ...
2012 if ( 10000 < strlen( $piece ) ) {
2014 foreach ( _split_str_by_whitespace( $piece, 2100 ) as $chunk ) { // 2100: Extra room for scheme and leading and trailing paretheses
2015 if ( 2101 < strlen( $chunk ) ) {
2016 $r .= $chunk; // Too big, no whitespace: bail.
2018 $r .= make_clickable( $chunk );
2022 $ret = " $piece "; // Pad with whitespace to simplify the regexes
2025 ([\\s(<.,;:!?]) # 1: Leading whitespace, or punctuation
2027 [\\w]{1,20}+:// # Scheme and hier-part prefix
2028 (?=\S{1,2000}\s) # Limit to URLs less than about 2000 characters long
2029 [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]*+ # Non-punctuation URL character
2030 (?: # Unroll the Loop: Only allow puctuation URL character if followed by a non-punctuation URL character
2031 [\'.,;:!?)] # Punctuation URL character
2032 [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]++ # Non-punctuation URL character
2035 (\)?) # 3: Trailing closing parenthesis (for parethesis balancing post processing)
2036 ~xS'; // The regex is a non-anchored pattern and does not have a single fixed starting character.
2037 // Tell PCRE to spend more time optimizing since, when used on a page load, it will probably be used several times.
2039 $ret = preg_replace_callback( $url_clickable, '_make_url_clickable_cb', $ret );
2041 $ret = preg_replace_callback( '#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]+)#is', '_make_web_ftp_clickable_cb', $ret );
2042 $ret = preg_replace_callback( '#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret );
2044 $ret = substr( $ret, 1, -1 ); // Remove our whitespace padding.
2049 // Cleanup of accidental links within links
2050 $r = preg_replace( '#(<a([ \r\n\t]+[^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i', "$1$3</a>", $r );
2055 * Breaks a string into chunks by splitting at whitespace characters.
2056 * The length of each returned chunk is as close to the specified length goal as possible,
2057 * with the caveat that each chunk includes its trailing delimiter.
2058 * Chunks longer than the goal are guaranteed to not have any inner whitespace.
2060 * Joining the returned chunks with empty delimiters reconstructs the input string losslessly.
2062 * Input string must have no null characters (or eventual transformations on output chunks must not care about null characters)
2064 * _split_str_by_whitespace( "1234 67890 1234 67890a cd 1234 890 123456789 1234567890a 45678 1 3 5 7 90 ", 10 ) ==
2066 * 0 => '1234 67890 ', // 11 characters: Perfect split
2067 * 1 => '1234 ', // 5 characters: '1234 67890a' was too long
2068 * 2 => '67890a cd ', // 10 characters: '67890a cd 1234' was too long
2069 * 3 => '1234 890 ', // 11 characters: Perfect split
2070 * 4 => '123456789 ', // 10 characters: '123456789 1234567890a' was too long
2071 * 5 => '1234567890a ', // 12 characters: Too long, but no inner whitespace on which to split
2072 * 6 => ' 45678 ', // 11 characters: Perfect split
2073 * 7 => '1 3 5 7 90 ', // 11 characters: End of $string
2079 * @param string $string The string to split.
2080 * @param int $goal The desired chunk length.
2081 * @return array Numeric array of chunks.
2083 function _split_str_by_whitespace( $string, $goal ) {
2086 $string_nullspace = strtr( $string, "\r\n\t\v\f ", "\000\000\000\000\000\000" );
2088 while ( $goal < strlen( $string_nullspace ) ) {
2089 $pos = strrpos( substr( $string_nullspace, 0, $goal + 1 ), "\000" );
2091 if ( false === $pos ) {
2092 $pos = strpos( $string_nullspace, "\000", $goal + 1 );
2093 if ( false === $pos ) {
2098 $chunks[] = substr( $string, 0, $pos + 1 );
2099 $string = substr( $string, $pos + 1 );
2100 $string_nullspace = substr( $string_nullspace, $pos + 1 );
2104 $chunks[] = $string;
2111 * Adds rel nofollow string to all HTML A elements in content.
2115 * @param string $text Content that may contain HTML A elements.
2116 * @return string Converted content.
2118 function wp_rel_nofollow( $text ) {
2119 // This is a pre save filter, so text is already escaped.
2120 $text = stripslashes($text);
2121 $text = preg_replace_callback('|<a (.+?)>|i', 'wp_rel_nofollow_callback', $text);
2122 $text = wp_slash($text);
2127 * Callback to add rel=nofollow string to HTML A element.
2129 * Will remove already existing rel="nofollow" and rel='nofollow' from the
2130 * string to prevent from invalidating (X)HTML.
2134 * @param array $matches Single Match
2135 * @return string HTML A Element with rel nofollow.
2137 function wp_rel_nofollow_callback( $matches ) {
2138 $text = $matches[1];
2139 $text = str_replace(array(' rel="nofollow"', " rel='nofollow'"), '', $text);
2140 return "<a $text rel=\"nofollow\">";
2144 * Convert one smiley code to the icon graphic file equivalent.
2146 * Callback handler for {@link convert_smilies()}.
2147 * Looks up one smiley code in the $wpsmiliestrans global array and returns an
2148 * `<img>` string for that smiley.
2150 * @global array $wpsmiliestrans
2153 * @param array $matches Single match. Smiley code to convert to image.
2154 * @return string Image string for smiley.
2156 function translate_smiley( $matches ) {
2157 global $wpsmiliestrans;
2159 if ( count( $matches ) == 0 )
2162 $smiley = trim( reset( $matches ) );
2163 $img = $wpsmiliestrans[ $smiley ];
2166 $ext = preg_match( '/\.([^.]+)$/', $img, $matches ) ? strtolower( $matches[1] ) : false;
2167 $image_exts = array( 'jpg', 'jpeg', 'jpe', 'gif', 'png' );
2169 // Don't convert smilies that aren't images - they're probably emoji.
2170 if ( ! in_array( $ext, $image_exts ) ) {
2175 * Filter the Smiley image URL before it's used in the image element.
2179 * @param string $smiley_url URL for the smiley image.
2180 * @param string $img Filename for the smiley image.
2181 * @param string $site_url Site URL, as returned by site_url().
2183 $src_url = apply_filters( 'smilies_src', includes_url( "images/smilies/$img" ), $img, site_url() );
2185 return sprintf( '<img src="%s" alt="%s" class="wp-smiley" style="height: 1em; max-height: 1em;" />', esc_url( $src_url ), esc_attr( $smiley ) );
2189 * Convert text equivalent of smilies to images.
2191 * Will only convert smilies if the option 'use_smilies' is true and the global
2192 * used in the function isn't empty.
2195 * @uses $wp_smiliessearch
2197 * @param string $text Content to convert smilies from text.
2198 * @return string Converted content with text smilies replaced with images.
2200 function convert_smilies( $text ) {
2201 global $wp_smiliessearch;
2203 if ( get_option( 'use_smilies' ) && ! empty( $wp_smiliessearch ) ) {
2204 // HTML loop taken from texturize function, could possible be consolidated
2205 $textarr = preg_split( '/(<.*>)/U', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // capture the tags as well as in between
2206 $stop = count( $textarr );// loop stuff
2208 // Ignore proessing of specific tags
2209 $tags_to_ignore = 'code|pre|style|script|textarea';
2210 $ignore_block_element = '';
2212 for ( $i = 0; $i < $stop; $i++ ) {
2213 $content = $textarr[$i];
2215 // If we're in an ignore block, wait until we find its closing tag
2216 if ( '' == $ignore_block_element && preg_match( '/^<(' . $tags_to_ignore . ')>/', $content, $matches ) ) {
2217 $ignore_block_element = $matches[1];
2220 // If it's not a tag and not in ignore block
2221 if ( '' == $ignore_block_element && strlen( $content ) > 0 && '<' != $content[0] ) {
2222 $content = preg_replace_callback( $wp_smiliessearch, 'translate_smiley', $content );
2225 // did we exit ignore block
2226 if ( '' != $ignore_block_element && '</' . $ignore_block_element . '>' == $content ) {
2227 $ignore_block_element = '';
2230 $output .= $content;
2233 // return default text.
2240 * Verifies that an email is valid.
2242 * Does not grok i18n domains. Not RFC compliant.
2246 * @param string $email Email address to verify.
2247 * @param boolean $deprecated Deprecated.
2248 * @return string|bool Either false or the valid email address.
2250 function is_email( $email, $deprecated = false ) {
2251 if ( ! empty( $deprecated ) )
2252 _deprecated_argument( __FUNCTION__, '3.0' );
2254 // Test for the minimum length the email can be
2255 if ( strlen( $email ) < 3 ) {
2257 * Filter whether an email address is valid.
2259 * This filter is evaluated under several different contexts, such as 'email_too_short',
2260 * 'email_no_at', 'local_invalid_chars', 'domain_period_sequence', 'domain_period_limits',
2261 * 'domain_no_periods', 'sub_hyphen_limits', 'sub_invalid_chars', or no specific context.
2265 * @param bool $is_email Whether the email address has passed the is_email() checks. Default false.
2266 * @param string $email The email address being checked.
2267 * @param string $message An explanatory message to the user.
2268 * @param string $context Context under which the email was tested.
2270 return apply_filters( 'is_email', false, $email, 'email_too_short' );
2273 // Test for an @ character after the first position
2274 if ( strpos( $email, '@', 1 ) === false ) {
2275 /** This filter is documented in wp-includes/formatting.php */
2276 return apply_filters( 'is_email', false, $email, 'email_no_at' );
2279 // Split out the local and domain parts
2280 list( $local, $domain ) = explode( '@', $email, 2 );
2283 // Test for invalid characters
2284 if ( !preg_match( '/^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]+$/', $local ) ) {
2285 /** This filter is documented in wp-includes/formatting.php */
2286 return apply_filters( 'is_email', false, $email, 'local_invalid_chars' );
2290 // Test for sequences of periods
2291 if ( preg_match( '/\.{2,}/', $domain ) ) {
2292 /** This filter is documented in wp-includes/formatting.php */
2293 return apply_filters( 'is_email', false, $email, 'domain_period_sequence' );
2296 // Test for leading and trailing periods and whitespace
2297 if ( trim( $domain, " \t\n\r\0\x0B." ) !== $domain ) {
2298 /** This filter is documented in wp-includes/formatting.php */
2299 return apply_filters( 'is_email', false, $email, 'domain_period_limits' );
2302 // Split the domain into subs
2303 $subs = explode( '.', $domain );
2305 // Assume the domain will have at least two subs
2306 if ( 2 > count( $subs ) ) {
2307 /** This filter is documented in wp-includes/formatting.php */
2308 return apply_filters( 'is_email', false, $email, 'domain_no_periods' );
2311 // Loop through each sub
2312 foreach ( $subs as $sub ) {
2313 // Test for leading and trailing hyphens and whitespace
2314 if ( trim( $sub, " \t\n\r\0\x0B-" ) !== $sub ) {
2315 /** This filter is documented in wp-includes/formatting.php */
2316 return apply_filters( 'is_email', false, $email, 'sub_hyphen_limits' );
2319 // Test for invalid characters
2320 if ( !preg_match('/^[a-z0-9-]+$/i', $sub ) ) {
2321 /** This filter is documented in wp-includes/formatting.php */
2322 return apply_filters( 'is_email', false, $email, 'sub_invalid_chars' );
2326 // Congratulations your email made it!
2327 /** This filter is documented in wp-includes/formatting.php */
2328 return apply_filters( 'is_email', $email, $email, null );
2332 * Convert to ASCII from email subjects.
2336 * @param string $string Subject line
2337 * @return string Converted string to ASCII
2339 function wp_iso_descrambler($string) {
2340 /* this may only work with iso-8859-1, I'm afraid */
2341 if (!preg_match('#\=\?(.+)\?Q\?(.+)\?\=#i', $string, $matches)) {
2344 $subject = str_replace('_', ' ', $matches[2]);
2345 $subject = preg_replace_callback('#\=([0-9a-f]{2})#i', '_wp_iso_convert', $subject);
2351 * Helper function to convert hex encoded chars to ASCII
2356 * @param array $match The preg_replace_callback matches array
2357 * @return string Converted chars
2359 function _wp_iso_convert( $match ) {
2360 return chr( hexdec( strtolower( $match[1] ) ) );
2364 * Returns a date in the GMT equivalent.
2366 * Requires and returns a date in the Y-m-d H:i:s format. If there is a
2367 * timezone_string available, the date is assumed to be in that timezone,
2368 * otherwise it simply subtracts the value of the 'gmt_offset' option. Return
2369 * format can be overridden using the $format parameter.
2373 * @param string $string The date to be converted.
2374 * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
2375 * @return string GMT version of the date provided.
2377 function get_gmt_from_date( $string, $format = 'Y-m-d H:i:s' ) {
2378 $tz = get_option( 'timezone_string' );
2380 $datetime = date_create( $string, new DateTimeZone( $tz ) );
2382 return gmdate( $format, 0 );
2383 $datetime->setTimezone( new DateTimeZone( 'UTC' ) );
2384 $string_gmt = $datetime->format( $format );
2386 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 ) )
2387 return gmdate( $format, 0 );
2388 $string_time = gmmktime( $matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1] );
2389 $string_gmt = gmdate( $format, $string_time - get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
2395 * Converts a GMT date into the correct format for the blog.
2397 * Requires and returns a date in the Y-m-d H:i:s format. If there is a
2398 * timezone_string available, the returned date is in that timezone, otherwise
2399 * it simply adds the value of gmt_offset. Return format can be overridden
2400 * using the $format parameter
2404 * @param string $string The date to be converted.
2405 * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
2406 * @return string Formatted date relative to the timezone / GMT offset.
2408 function get_date_from_gmt( $string, $format = 'Y-m-d H:i:s' ) {
2409 $tz = get_option( 'timezone_string' );
2411 $datetime = date_create( $string, new DateTimeZone( 'UTC' ) );
2413 return date( $format, 0 );
2414 $datetime->setTimezone( new DateTimeZone( $tz ) );
2415 $string_localtime = $datetime->format( $format );
2417 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) )
2418 return date( $format, 0 );
2419 $string_time = gmmktime( $matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1] );
2420 $string_localtime = gmdate( $format, $string_time + get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
2422 return $string_localtime;
2426 * Computes an offset in seconds from an iso8601 timezone.
2430 * @param string $timezone Either 'Z' for 0 offset or '±hhmm'.
2431 * @return int|float The offset in seconds.
2433 function iso8601_timezone_to_offset($timezone) {
2434 // $timezone is either 'Z' or '[+|-]hhmm'
2435 if ($timezone == 'Z') {
2438 $sign = (substr($timezone, 0, 1) == '+') ? 1 : -1;
2439 $hours = intval(substr($timezone, 1, 2));
2440 $minutes = intval(substr($timezone, 3, 4)) / 60;
2441 $offset = $sign * HOUR_IN_SECONDS * ($hours + $minutes);
2447 * Converts an iso8601 date to MySQL DateTime format used by post_date[_gmt].
2451 * @param string $date_string Date and time in ISO 8601 format {@link http://en.wikipedia.org/wiki/ISO_8601}.
2452 * @param string $timezone Optional. If set to GMT returns the time minus gmt_offset. Default is 'user'.
2453 * @return string The date and time in MySQL DateTime format - Y-m-d H:i:s.
2455 function iso8601_to_datetime($date_string, $timezone = 'user') {
2456 $timezone = strtolower($timezone);
2458 if ($timezone == 'gmt') {
2460 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);
2462 if (!empty($date_bits[7])) { // we have a timezone, so let's compute an offset
2463 $offset = iso8601_timezone_to_offset($date_bits[7]);
2464 } else { // we don't have a timezone, so we assume user local timezone (not server's!)
2465 $offset = HOUR_IN_SECONDS * get_option('gmt_offset');
2468 $timestamp = gmmktime($date_bits[4], $date_bits[5], $date_bits[6], $date_bits[2], $date_bits[3], $date_bits[1]);
2469 $timestamp -= $offset;
2471 return gmdate('Y-m-d H:i:s', $timestamp);
2473 } elseif ($timezone == 'user') {
2474 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);
2479 * Adds a element attributes to open links in new windows.
2481 * Comment text in popup windows should be filtered through this. Right now it's
2482 * a moderately dumb function, ideally it would detect whether a target or rel
2483 * attribute was already there and adjust its actions accordingly.
2487 * @param string $text Content to replace links to open in a new window.
2488 * @return string Content that has filtered links.
2490 function popuplinks($text) {
2491 $text = preg_replace('/<a (.+?)>/i', "<a $1 target='_blank' rel='external'>", $text);
2496 * Strips out all characters that are not allowable in an email.
2500 * @param string $email Email address to filter.
2501 * @return string Filtered email address.
2503 function sanitize_email( $email ) {
2504 // Test for the minimum length the email can be
2505 if ( strlen( $email ) < 3 ) {
2507 * Filter a sanitized email address.
2509 * This filter is evaluated under several contexts, including 'email_too_short',
2510 * 'email_no_at', 'local_invalid_chars', 'domain_period_sequence', 'domain_period_limits',
2511 * 'domain_no_periods', 'domain_no_valid_subs', or no context.
2515 * @param string $email The sanitized email address.
2516 * @param string $email The email address, as provided to sanitize_email().
2517 * @param string $message A message to pass to the user.
2519 return apply_filters( 'sanitize_email', '', $email, 'email_too_short' );
2522 // Test for an @ character after the first position
2523 if ( strpos( $email, '@', 1 ) === false ) {
2524 /** This filter is documented in wp-includes/formatting.php */
2525 return apply_filters( 'sanitize_email', '', $email, 'email_no_at' );
2528 // Split out the local and domain parts
2529 list( $local, $domain ) = explode( '@', $email, 2 );
2532 // Test for invalid characters
2533 $local = preg_replace( '/[^a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]/', '', $local );
2534 if ( '' === $local ) {
2535 /** This filter is documented in wp-includes/formatting.php */
2536 return apply_filters( 'sanitize_email', '', $email, 'local_invalid_chars' );
2540 // Test for sequences of periods
2541 $domain = preg_replace( '/\.{2,}/', '', $domain );
2542 if ( '' === $domain ) {
2543 /** This filter is documented in wp-includes/formatting.php */
2544 return apply_filters( 'sanitize_email', '', $email, 'domain_period_sequence' );
2547 // Test for leading and trailing periods and whitespace
2548 $domain = trim( $domain, " \t\n\r\0\x0B." );
2549 if ( '' === $domain ) {
2550 /** This filter is documented in wp-includes/formatting.php */
2551 return apply_filters( 'sanitize_email', '', $email, 'domain_period_limits' );
2554 // Split the domain into subs
2555 $subs = explode( '.', $domain );
2557 // Assume the domain will have at least two subs
2558 if ( 2 > count( $subs ) ) {
2559 /** This filter is documented in wp-includes/formatting.php */
2560 return apply_filters( 'sanitize_email', '', $email, 'domain_no_periods' );
2563 // Create an array that will contain valid subs
2564 $new_subs = array();
2566 // Loop through each sub
2567 foreach ( $subs as $sub ) {
2568 // Test for leading and trailing hyphens
2569 $sub = trim( $sub, " \t\n\r\0\x0B-" );
2571 // Test for invalid characters
2572 $sub = preg_replace( '/[^a-z0-9-]+/i', '', $sub );
2574 // If there's anything left, add it to the valid subs
2575 if ( '' !== $sub ) {
2580 // If there aren't 2 or more valid subs
2581 if ( 2 > count( $new_subs ) ) {
2582 /** This filter is documented in wp-includes/formatting.php */
2583 return apply_filters( 'sanitize_email', '', $email, 'domain_no_valid_subs' );
2586 // Join valid subs into the new domain
2587 $domain = join( '.', $new_subs );
2589 // Put the email back together
2590 $email = $local . '@' . $domain;
2592 // Congratulations your email made it!
2593 /** This filter is documented in wp-includes/formatting.php */
2594 return apply_filters( 'sanitize_email', $email, $email, null );
2598 * Determines the difference between two timestamps.
2600 * The difference is returned in a human readable format such as "1 hour",
2601 * "5 mins", "2 days".
2605 * @param int $from Unix timestamp from which the difference begins.
2606 * @param int $to Optional. Unix timestamp to end the time difference. Default becomes time() if not set.
2607 * @return string Human readable time difference.
2609 function human_time_diff( $from, $to = '' ) {
2610 if ( empty( $to ) ) {
2614 $diff = (int) abs( $to - $from );
2616 if ( $diff < HOUR_IN_SECONDS ) {
2617 $mins = round( $diff / MINUTE_IN_SECONDS );
2620 /* translators: min=minute */
2621 $since = sprintf( _n( '%s min', '%s mins', $mins ), $mins );
2622 } elseif ( $diff < DAY_IN_SECONDS && $diff >= HOUR_IN_SECONDS ) {
2623 $hours = round( $diff / HOUR_IN_SECONDS );
2626 $since = sprintf( _n( '%s hour', '%s hours', $hours ), $hours );
2627 } elseif ( $diff < WEEK_IN_SECONDS && $diff >= DAY_IN_SECONDS ) {
2628 $days = round( $diff / DAY_IN_SECONDS );
2631 $since = sprintf( _n( '%s day', '%s days', $days ), $days );
2632 } elseif ( $diff < 30 * DAY_IN_SECONDS && $diff >= WEEK_IN_SECONDS ) {
2633 $weeks = round( $diff / WEEK_IN_SECONDS );
2636 $since = sprintf( _n( '%s week', '%s weeks', $weeks ), $weeks );
2637 } elseif ( $diff < YEAR_IN_SECONDS && $diff >= 30 * DAY_IN_SECONDS ) {
2638 $months = round( $diff / ( 30 * DAY_IN_SECONDS ) );
2641 $since = sprintf( _n( '%s month', '%s months', $months ), $months );
2642 } elseif ( $diff >= YEAR_IN_SECONDS ) {
2643 $years = round( $diff / YEAR_IN_SECONDS );
2646 $since = sprintf( _n( '%s year', '%s years', $years ), $years );
2650 * Filter the human readable difference between two timestamps.
2654 * @param string $since The difference in human readable text.
2655 * @param int $diff The difference in seconds.
2656 * @param int $from Unix timestamp from which the difference begins.
2657 * @param int $to Unix timestamp to end the time difference.
2659 return apply_filters( 'human_time_diff', $since, $diff, $from, $to );
2663 * Generates an excerpt from the content, if needed.
2665 * The excerpt word amount will be 55 words and if the amount is greater than
2666 * that, then the string ' […]' will be appended to the excerpt. If the string
2667 * is less than 55 words, then the content will be returned as is.
2669 * The 55 word limit can be modified by plugins/themes using the excerpt_length filter
2670 * The ' […]' string can be modified by plugins/themes using the excerpt_more filter
2674 * @param string $text Optional. The excerpt. If set to empty, an excerpt is generated.
2675 * @return string The excerpt.
2677 function wp_trim_excerpt($text = '') {
2678 $raw_excerpt = $text;
2679 if ( '' == $text ) {
2680 $text = get_the_content('');
2682 $text = strip_shortcodes( $text );
2684 /** This filter is documented in wp-includes/post-template.php */
2685 $text = apply_filters( 'the_content', $text );
2686 $text = str_replace(']]>', ']]>', $text);
2689 * Filter the number of words in an excerpt.
2693 * @param int $number The number of words. Default 55.
2695 $excerpt_length = apply_filters( 'excerpt_length', 55 );
2697 * Filter the string in the "more" link displayed after a trimmed excerpt.
2701 * @param string $more_string The string shown within the more link.
2703 $excerpt_more = apply_filters( 'excerpt_more', ' ' . '[…]' );
2704 $text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
2707 * Filter the trimmed excerpt string.
2711 * @param string $text The trimmed text.
2712 * @param string $raw_excerpt The text prior to trimming.
2714 return apply_filters( 'wp_trim_excerpt', $text, $raw_excerpt );
2718 * Trims text to a certain number of words.
2720 * This function is localized. For languages that count 'words' by the individual
2721 * character (such as East Asian languages), the $num_words argument will apply
2722 * to the number of individual characters.
2726 * @param string $text Text to trim.
2727 * @param int $num_words Number of words. Default 55.
2728 * @param string $more Optional. What to append if $text needs to be trimmed. Default '…'.
2729 * @return string Trimmed text.
2731 function wp_trim_words( $text, $num_words = 55, $more = null ) {
2732 if ( null === $more )
2733 $more = __( '…' );
2734 $original_text = $text;
2735 $text = wp_strip_all_tags( $text );
2736 /* translators: If your word count is based on single characters (East Asian characters),
2737 enter 'characters'. Otherwise, enter 'words'. Do not translate into your own language. */
2738 if ( 'characters' == _x( 'words', 'word count: words or characters?' ) && preg_match( '/^utf\-?8$/i', get_option( 'blog_charset' ) ) ) {
2739 $text = trim( preg_replace( "/[\n\r\t ]+/", ' ', $text ), ' ' );
2740 preg_match_all( '/./u', $text, $words_array );
2741 $words_array = array_slice( $words_array[0], 0, $num_words + 1 );
2744 $words_array = preg_split( "/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY );
2747 if ( count( $words_array ) > $num_words ) {
2748 array_pop( $words_array );
2749 $text = implode( $sep, $words_array );
2750 $text = $text . $more;
2752 $text = implode( $sep, $words_array );
2755 * Filter the text content after words have been trimmed.
2759 * @param string $text The trimmed text.
2760 * @param int $num_words The number of words to trim the text to. Default 5.
2761 * @param string $more An optional string to append to the end of the trimmed text, e.g. ….
2762 * @param string $original_text The text before it was trimmed.
2764 return apply_filters( 'wp_trim_words', $text, $num_words, $more, $original_text );
2768 * Converts named entities into numbered entities.
2772 * @param string $text The text within which entities will be converted.
2773 * @return string Text with converted entities.
2775 function ent2ncr($text) {
2778 * Filter text before named entities are converted into numbered entities.
2780 * A non-null string must be returned for the filter to be evaluated.
2784 * @param null $converted_text The text to be converted. Default null.
2785 * @param string $text The text prior to entity conversion.
2787 $filtered = apply_filters( 'pre_ent2ncr', null, $text );
2788 if( null !== $filtered )
2792 '"' => '"',
2797 ' ' => ' ',
2798 '¡' => '¡',
2799 '¢' => '¢',
2800 '£' => '£',
2801 '¤' => '¤',
2802 '¥' => '¥',
2803 '¦' => '¦',
2804 '&brkbar;' => '¦',
2805 '§' => '§',
2806 '¨' => '¨',
2807 '¨' => '¨',
2808 '©' => '©',
2809 'ª' => 'ª',
2810 '«' => '«',
2811 '¬' => '¬',
2812 '­' => '­',
2813 '®' => '®',
2814 '¯' => '¯',
2815 '&hibar;' => '¯',
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 'Θ' => 'Θ',
2912 'Ι' => 'Ι',
2913 'Κ' => 'Κ',
2914 'Λ' => 'Λ',
2918 'Ο' => 'Ο',
2920 'Ρ' => 'Ρ',
2921 'Σ' => 'Σ',
2922 'Τ' => 'Τ',
2923 'Υ' => 'Υ',
2924 'Φ' => 'Φ',
2925 'Χ' => 'Χ',
2926 'Ψ' => 'Ψ',
2927 'Ω' => 'Ω',
2928 'α' => 'α',
2929 'β' => 'β',
2930 'γ' => 'γ',
2931 'δ' => 'δ',
2932 'ε' => 'ε',
2933 'ζ' => 'ζ',
2934 'η' => 'η',
2935 'θ' => 'θ',
2936 'ι' => 'ι',
2937 'κ' => 'κ',
2938 'λ' => 'λ',
2942 'ο' => 'ο',
2944 'ρ' => 'ρ',
2945 'ς' => 'ς',
2946 'σ' => 'σ',
2947 'τ' => 'τ',
2948 'υ' => 'υ',
2949 'φ' => 'φ',
2950 'χ' => 'χ',
2951 'ψ' => 'ψ',
2952 'ω' => 'ω',
2953 'ϑ' => 'ϑ',
2954 'ϒ' => 'ϒ',
2955 'ϖ' => 'ϖ',
2956 ' ' => ' ',
2957 ' ' => ' ',
2958 ' ' => ' ',
2959 '‌' => '‌',
2960 '‍' => '‍',
2961 '‎' => '‎',
2962 '‏' => '‏',
2963 '–' => '–',
2964 '—' => '—',
2965 '‘' => '‘',
2966 '’' => '’',
2967 '‚' => '‚',
2968 '“' => '“',
2969 '”' => '”',
2970 '„' => '„',
2971 '†' => '†',
2972 '‡' => '‡',
2973 '•' => '•',
2974 '…' => '…',
2975 '‰' => '‰',
2976 '′' => '′',
2977 '″' => '″',
2978 '‹' => '‹',
2979 '›' => '›',
2980 '‾' => '‾',
2981 '⁄' => '⁄',
2982 '€' => '€',
2983 'ℑ' => 'ℑ',
2984 '℘' => '℘',
2985 'ℜ' => 'ℜ',
2986 '™' => '™',
2987 'ℵ' => 'ℵ',
2988 '↵' => '↵',
2989 '⇐' => '⇐',
2990 '⇑' => '⇑',
2991 '⇒' => '⇒',
2992 '⇓' => '⇓',
2993 '⇔' => '⇔',
2994 '∀' => '∀',
2995 '∂' => '∂',
2996 '∃' => '∃',
2997 '∅' => '∅',
2998 '∇' => '∇',
2999 '∈' => '∈',
3000 '∉' => '∉',
3001 '∋' => '∋',
3002 '∏' => '∏',
3003 '∑' => '∑',
3004 '−' => '−',
3005 '∗' => '∗',
3006 '√' => '√',
3007 '∝' => '∝',
3008 '∞' => '∞',
3009 '∠' => '∠',
3010 '∧' => '∧',
3011 '∨' => '∨',
3012 '∩' => '∩',
3013 '∪' => '∪',
3014 '∫' => '∫',
3015 '∴' => '∴',
3016 '∼' => '∼',
3017 '≅' => '≅',
3018 '≈' => '≈',
3019 '≠' => '≠',
3020 '≡' => '≡',
3021 '≤' => '≤',
3022 '≥' => '≥',
3023 '⊂' => '⊂',
3024 '⊃' => '⊃',
3025 '⊄' => '⊄',
3026 '⊆' => '⊆',
3027 '⊇' => '⊇',
3028 '⊕' => '⊕',
3029 '⊗' => '⊗',
3030 '⊥' => '⊥',
3031 '⋅' => '⋅',
3032 '⌈' => '⌈',
3033 '⌉' => '⌉',
3034 '⌊' => '⌊',
3035 '⌋' => '⌋',
3036 '⟨' => '〈',
3037 '⟩' => '〉',
3038 '←' => '←',
3039 '↑' => '↑',
3040 '→' => '→',
3041 '↓' => '↓',
3042 '↔' => '↔',
3043 '◊' => '◊',
3044 '♠' => '♠',
3045 '♣' => '♣',
3046 '♥' => '♥',
3047 '♦' => '♦'
3050 return str_replace( array_keys($to_ncr), array_values($to_ncr), $text );
3054 * Formats text for the rich text editor.
3056 * The filter 'richedit_pre' is applied here. If $text is empty the filter will
3057 * be applied to an empty string.
3061 * @param string $text The text to be formatted.
3062 * @return string The formatted text after filter is applied.
3064 function wp_richedit_pre($text) {
3065 if ( empty( $text ) ) {
3067 * Filter text returned for the rich text editor.
3069 * This filter is first evaluated, and the value returned, if an empty string
3070 * is passed to wp_richedit_pre(). If an empty string is passed, it results
3071 * in a break tag and line feed.
3073 * If a non-empty string is passed, the filter is evaluated on the wp_richedit_pre()
3074 * return after being formatted.
3078 * @param string $output Text for the rich text editor.
3080 return apply_filters( 'richedit_pre', '' );
3083 $output = convert_chars($text);
3084 $output = wpautop($output);
3085 $output = htmlspecialchars($output, ENT_NOQUOTES, get_option( 'blog_charset' ) );
3087 /** This filter is documented in wp-includes/formatting.php */
3088 return apply_filters( 'richedit_pre', $output );
3092 * Formats text for the HTML editor.
3094 * Unless $output is empty it will pass through htmlspecialchars before the
3095 * 'htmledit_pre' filter is applied.
3099 * @param string $output The text to be formatted.
3100 * @return string Formatted text after filter applied.
3102 function wp_htmledit_pre($output) {
3103 if ( !empty($output) )
3104 $output = htmlspecialchars($output, ENT_NOQUOTES, get_option( 'blog_charset' ) ); // convert only < > &
3107 * Filter the text before it is formatted for the HTML editor.
3111 * @param string $output The HTML-formatted text.
3113 return apply_filters( 'htmledit_pre', $output );
3117 * Perform a deep string replace operation to ensure the values in $search are no longer present
3119 * Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values
3120 * e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that
3121 * str_replace would return
3126 * @param string|array $search The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.
3127 * @param string $subject The string being searched and replaced on, otherwise known as the haystack.
3128 * @return string The string with the replaced svalues.
3130 function _deep_replace( $search, $subject ) {
3131 $subject = (string) $subject;
3135 $subject = str_replace( $search, '', $subject, $count );
3142 * Escapes data for use in a MySQL query.
3144 * Usually you should prepare queries using wpdb::prepare().
3145 * Sometimes, spot-escaping is required or useful. One example
3146 * is preparing an array for use in an IN clause.
3149 * @param string|array $data Unescaped data
3150 * @return string|array Escaped data
3152 function esc_sql( $data ) {
3154 return $wpdb->_escape( $data );
3158 * Checks and cleans a URL.
3160 * A number of characters are removed from the URL. If the URL is for displaying
3161 * (the default behaviour) ampersands are also replaced. The 'clean_url' filter
3162 * is applied to the returned cleaned URL.
3166 * @param string $url The URL to be cleaned.
3167 * @param array $protocols Optional. An array of acceptable protocols.
3168 * Defaults to 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn' if not set.
3169 * @param string $_context Private. Use esc_url_raw() for database usage.
3170 * @return string The cleaned $url after the 'clean_url' filter is applied.
3172 function esc_url( $url, $protocols = null, $_context = 'display' ) {
3173 $original_url = $url;
3177 $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);
3178 $strip = array('%0d', '%0a', '%0D', '%0A');
3179 $url = _deep_replace($strip, $url);
3180 $url = str_replace(';//', '://', $url);
3181 /* If the URL doesn't appear to contain a scheme, we
3182 * presume it needs http:// appended (unless a relative
3183 * link starting with /, # or ? or a php file).
3185 if ( strpos($url, ':') === false && ! in_array( $url[0], array( '/', '#', '?' ) ) &&
3186 ! preg_match('/^[a-z0-9-]+?\.php/i', $url) )
3187 $url = 'http://' . $url;
3189 // Replace ampersands and single quotes only when displaying.
3190 if ( 'display' == $_context ) {
3191 $url = wp_kses_normalize_entities( $url );
3192 $url = str_replace( '&', '&', $url );
3193 $url = str_replace( "'", ''', $url );
3196 if ( '/' === $url[0] ) {
3197 $good_protocol_url = $url;
3199 if ( ! is_array( $protocols ) )
3200 $protocols = wp_allowed_protocols();
3201 $good_protocol_url = wp_kses_bad_protocol( $url, $protocols );
3202 if ( strtolower( $good_protocol_url ) != strtolower( $url ) )
3207 * Filter a string cleaned and escaped for output as a URL.
3211 * @param string $good_protocol_url The cleaned URL to be returned.
3212 * @param string $original_url The URL prior to cleaning.
3213 * @param string $_context If 'display', replace ampersands and single quotes only.
3215 return apply_filters( 'clean_url', $good_protocol_url, $original_url, $_context );
3219 * Performs esc_url() for database usage.
3223 * @param string $url The URL to be cleaned.
3224 * @param array $protocols An array of acceptable protocols.
3225 * @return string The cleaned URL.
3227 function esc_url_raw( $url, $protocols = null ) {
3228 return esc_url( $url, $protocols, 'db' );
3232 * Convert entities, while preserving already-encoded entities.
3234 * @link http://www.php.net/htmlentities Borrowed from the PHP Manual user notes.
3238 * @param string $myHTML The text to be converted.
3239 * @return string Converted text.
3241 function htmlentities2($myHTML) {
3242 $translation_table = get_html_translation_table( HTML_ENTITIES, ENT_QUOTES );
3243 $translation_table[chr(38)] = '&';
3244 return preg_replace( "/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/", "&", strtr($myHTML, $translation_table) );
3248 * Escape single quotes, htmlspecialchar " < > &, and fix line endings.
3250 * Escapes text strings for echoing in JS. It is intended to be used for inline JS
3251 * (in a tag attribute, for example onclick="..."). Note that the strings have to
3252 * be in single quotes. The filter 'js_escape' is also applied here.
3256 * @param string $text The text to be escaped.
3257 * @return string Escaped text.
3259 function esc_js( $text ) {
3260 $safe_text = wp_check_invalid_utf8( $text );
3261 $safe_text = _wp_specialchars( $safe_text, ENT_COMPAT );
3262 $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) );
3263 $safe_text = str_replace( "\r", '', $safe_text );
3264 $safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) );
3266 * Filter a string cleaned and escaped for output in JavaScript.
3268 * Text passed to esc_js() is stripped of invalid or special characters,
3269 * and properly slashed for output.
3273 * @param string $safe_text The text after it has been escaped.
3274 * @param string $text The text prior to being escaped.
3276 return apply_filters( 'js_escape', $safe_text, $text );
3280 * Escaping for HTML blocks.
3284 * @param string $text
3287 function esc_html( $text ) {
3288 $safe_text = wp_check_invalid_utf8( $text );
3289 $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
3291 * Filter a string cleaned and escaped for output in HTML.
3293 * Text passed to esc_html() is stripped of invalid or special characters
3298 * @param string $safe_text The text after it has been escaped.
3299 * @param string $text The text prior to being escaped.
3301 return apply_filters( 'esc_html', $safe_text, $text );
3305 * Escaping for HTML attributes.
3309 * @param string $text
3312 function esc_attr( $text ) {
3313 $safe_text = wp_check_invalid_utf8( $text );
3314 $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
3316 * Filter a string cleaned and escaped for output in an HTML attribute.
3318 * Text passed to esc_attr() is stripped of invalid or special characters
3323 * @param string $safe_text The text after it has been escaped.
3324 * @param string $text The text prior to being escaped.
3326 return apply_filters( 'attribute_escape', $safe_text, $text );
3330 * Escaping for textarea values.
3334 * @param string $text
3337 function esc_textarea( $text ) {
3338 $safe_text = htmlspecialchars( $text, ENT_QUOTES, get_option( 'blog_charset' ) );
3340 * Filter a string cleaned and escaped for output in a textarea element.
3344 * @param string $safe_text The text after it has been escaped.
3345 * @param string $text The text prior to being escaped.
3347 return apply_filters( 'esc_textarea', $safe_text, $text );
3351 * Escape an HTML tag name.
3355 * @param string $tag_name
3358 function tag_escape($tag_name) {
3359 $safe_tag = strtolower( preg_replace('/[^a-zA-Z0-9_:]/', '', $tag_name) );
3361 * Filter a string cleaned and escaped for output as an HTML tag.
3365 * @param string $safe_tag The tag name after it has been escaped.
3366 * @param string $tag_name The text before it was escaped.
3368 return apply_filters( 'tag_escape', $safe_tag, $tag_name );
3372 * Convert full URL paths to absolute paths.
3374 * Removes the http or https protocols and the domain. Keeps the path '/' at the
3375 * beginning, so it isn't a true relative link, but from the web root base.
3378 * @since 4.1.0 Support was added for relative URLs.
3380 * @param string $link Full URL path.
3381 * @return string Absolute path.
3383 function wp_make_link_relative( $link ) {
3384 return preg_replace( '|^(https?:)?//[^/]+(/.*)|i', '$2', $link );
3388 * Sanitises various option values based on the nature of the option.
3390 * This is basically a switch statement which will pass $value through a number
3391 * of functions depending on the $option.
3395 * @param string $option The name of the option.
3396 * @param string $value The unsanitised value.
3397 * @return string Sanitized value.
3399 function sanitize_option($option, $value) {
3403 switch ( $option ) {
3404 case 'admin_email' :
3405 case 'new_admin_email' :
3406 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3407 if ( is_wp_error( $value ) ) {
3408 $error = $value->get_error_message();
3410 $value = sanitize_email( $value );
3411 if ( ! is_email( $value ) ) {
3412 $error = __( 'The email address entered did not appear to be a valid email address. Please enter a valid email address.' );
3417 case 'thumbnail_size_w':
3418 case 'thumbnail_size_h':
3419 case 'medium_size_w':
3420 case 'medium_size_h':
3421 case 'large_size_w':
3422 case 'large_size_h':
3423 case 'mailserver_port':
3424 case 'comment_max_links':
3425 case 'page_on_front':
3426 case 'page_for_posts':
3427 case 'rss_excerpt_length':
3428 case 'default_category':
3429 case 'default_email_category':
3430 case 'default_link_category':
3431 case 'close_comments_days_old':
3432 case 'comments_per_page':
3433 case 'thread_comments_depth':
3434 case 'users_can_register':
3435 case 'start_of_week':
3436 $value = absint( $value );
3439 case 'posts_per_page':
3440 case 'posts_per_rss':
3441 $value = (int) $value;
3442 if ( empty($value) )
3445 $value = abs($value);
3448 case 'default_ping_status':
3449 case 'default_comment_status':
3450 // Options that if not there have 0 value but need to be something like "closed"
3451 if ( $value == '0' || $value == '')
3455 case 'blogdescription':
3457 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3458 if ( is_wp_error( $value ) ) {
3459 $error = $value->get_error_message();
3461 $value = wp_kses_post( $value );
3462 $value = esc_html( $value );
3466 case 'blog_charset':
3467 $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value); // strips slashes
3471 // This is the value if the settings checkbox is not checked on POST. Don't rely on this.
3472 if ( null === $value )
3475 $value = intval( $value );
3480 case 'mailserver_url':
3481 case 'mailserver_login':
3482 case 'mailserver_pass':
3484 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3485 if ( is_wp_error( $value ) ) {
3486 $error = $value->get_error_message();
3488 $value = strip_tags( $value );
3489 $value = wp_kses_data( $value );
3494 $value = explode( "\n", $value );
3495 $value = array_filter( array_map( 'trim', $value ) );
3496 $value = array_filter( array_map( 'esc_url_raw', $value ) );
3497 $value = implode( "\n", $value );
3501 $value = preg_replace('/[^0-9:.-]/', '', $value); // strips slashes
3505 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3506 if ( is_wp_error( $value ) ) {
3507 $error = $value->get_error_message();
3509 if ( preg_match( '#http(s?)://(.+)#i', $value ) ) {
3510 $value = esc_url_raw( $value );
3512 $error = __( 'The WordPress address you entered did not appear to be a valid URL. Please enter a valid URL.' );
3518 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3519 if ( is_wp_error( $value ) ) {
3520 $error = $value->get_error_message();
3522 if ( preg_match( '#http(s?)://(.+)#i', $value ) ) {
3523 $value = esc_url_raw( $value );
3525 $error = __( 'The Site address you entered did not appear to be a valid URL. Please enter a valid URL.' );
3531 $allowed = get_available_languages();
3532 if ( ! is_multisite() && defined( 'WPLANG' ) && '' !== WPLANG && 'en_US' !== WPLANG ) {
3533 $allowed[] = WPLANG;
3535 if ( ! in_array( $value, $allowed ) && ! empty( $value ) ) {
3536 $value = get_option( $option );
3540 case 'illegal_names':
3541 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3542 if ( is_wp_error( $value ) ) {
3543 $error = $value->get_error_message();
3545 if ( ! is_array( $value ) )
3546 $value = explode( ' ', $value );
3548 $value = array_values( array_filter( array_map( 'trim', $value ) ) );
3555 case 'limited_email_domains':
3556 case 'banned_email_domains':
3557 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3558 if ( is_wp_error( $value ) ) {
3559 $error = $value->get_error_message();
3561 if ( ! is_array( $value ) )
3562 $value = explode( "\n", $value );
3564 $domains = array_values( array_filter( array_map( 'trim', $value ) ) );
3567 foreach ( $domains as $domain ) {
3568 if ( ! preg_match( '/(--|\.\.)/', $domain ) && preg_match( '|^([a-zA-Z0-9-\.])+$|', $domain ) ) {
3577 case 'timezone_string':
3578 $allowed_zones = timezone_identifiers_list();
3579 if ( ! in_array( $value, $allowed_zones ) && ! empty( $value ) ) {
3580 $error = __( 'The timezone you have entered is not valid. Please select a valid timezone.' );
3584 case 'permalink_structure':
3585 case 'category_base':
3587 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3588 if ( is_wp_error( $value ) ) {
3589 $error = $value->get_error_message();
3591 $value = esc_url_raw( $value );
3592 $value = str_replace( 'http://', '', $value );
3596 case 'default_role' :
3597 if ( ! get_role( $value ) && get_role( 'subscriber' ) )
3598 $value = 'subscriber';
3601 case 'moderation_keys':
3602 case 'blacklist_keys':
3603 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3604 if ( is_wp_error( $value ) ) {
3605 $error = $value->get_error_message();
3607 $value = explode( "\n", $value );
3608 $value = array_filter( array_map( 'trim', $value ) );
3609 $value = array_unique( $value );
3610 $value = implode( "\n", $value );
3615 if ( ! empty( $error ) ) {
3616 $value = get_option( $option );
3617 if ( function_exists( 'add_settings_error' ) ) {
3618 add_settings_error( $option, "invalid_{$option}", $error );
3623 * Filter an option value following sanitization.
3627 * @param string $value The sanitized option value.
3628 * @param string $option The option name.
3630 $value = apply_filters( "sanitize_option_{$option}", $value, $option );
3636 * Parses a string into variables to be stored in an array.
3638 * Uses {@link http://www.php.net/parse_str parse_str()} and stripslashes if
3639 * {@link http://www.php.net/magic_quotes magic_quotes_gpc} is on.
3643 * @param string $string The string to be parsed.
3644 * @param array $array Variables will be stored in this array.
3646 function wp_parse_str( $string, &$array ) {
3647 parse_str( $string, $array );
3648 if ( get_magic_quotes_gpc() )
3649 $array = stripslashes_deep( $array );
3651 * Filter the array of variables derived from a parsed string.
3655 * @param array $array The array populated with variables.
3657 $array = apply_filters( 'wp_parse_str', $array );
3661 * Convert lone less than signs.
3663 * KSES already converts lone greater than signs.
3667 * @param string $text Text to be converted.
3668 * @return string Converted text.
3670 function wp_pre_kses_less_than( $text ) {
3671 return preg_replace_callback('%<[^>]*?((?=<)|>|$)%', 'wp_pre_kses_less_than_callback', $text);
3675 * Callback function used by preg_replace.
3679 * @param array $matches Populated by matches to preg_replace.
3680 * @return string The text returned after esc_html if needed.
3682 function wp_pre_kses_less_than_callback( $matches ) {
3683 if ( false === strpos($matches[0], '>') )
3684 return esc_html($matches[0]);
3689 * WordPress implementation of PHP sprintf() with filters.
3692 * @link http://www.php.net/sprintf
3694 * @param string $pattern The string which formatted args are inserted.
3695 * @param mixed $args ,... Arguments to be formatted into the $pattern string.
3696 * @return string The formatted string.
3698 function wp_sprintf( $pattern ) {
3699 $args = func_get_args();
3700 $len = strlen($pattern);
3704 while ( $len > $start ) {
3705 // Last character: append and break
3706 if ( strlen($pattern) - 1 == $start ) {
3707 $result .= substr($pattern, -1);
3711 // Literal %: append and continue
3712 if ( substr($pattern, $start, 2) == '%%' ) {
3718 // Get fragment before next %
3719 $end = strpos($pattern, '%', $start + 1);
3720 if ( false === $end )
3722 $fragment = substr($pattern, $start, $end - $start);
3724 // Fragment has a specifier
3725 if ( $pattern[$start] == '%' ) {
3726 // Find numbered arguments or take the next one in order
3727 if ( preg_match('/^%(\d+)\$/', $fragment, $matches) ) {
3728 $arg = isset($args[$matches[1]]) ? $args[$matches[1]] : '';
3729 $fragment = str_replace("%{$matches[1]}$", '%', $fragment);
3732 $arg = isset($args[$arg_index]) ? $args[$arg_index] : '';
3736 * Filter a fragment from the pattern passed to wp_sprintf().
3738 * If the fragment is unchanged, then sprintf() will be run on the fragment.
3742 * @param string $fragment A fragment from the pattern.
3743 * @param string $arg The argument.
3745 $_fragment = apply_filters( 'wp_sprintf', $fragment, $arg );
3746 if ( $_fragment != $fragment )
3747 $fragment = $_fragment;
3749 $fragment = sprintf($fragment, strval($arg) );
3752 // Append to result and move to next fragment
3753 $result .= $fragment;
3760 * Localize list items before the rest of the content.
3762 * The '%l' must be at the first characters can then contain the rest of the
3763 * content. The list items will have ', ', ', and', and ' and ' added depending
3764 * on the amount of list items in the $args parameter.
3768 * @param string $pattern Content containing '%l' at the beginning.
3769 * @param array $args List items to prepend to the content and replace '%l'.
3770 * @return string Localized list items and rest of the content.
3772 function wp_sprintf_l($pattern, $args) {
3774 if ( substr($pattern, 0, 2) != '%l' )
3777 // Nothing to work with
3782 * Filter the translated delimiters used by wp_sprintf_l().
3783 * Placeholders (%s) are included to assist translators and then
3784 * removed before the array of strings reaches the filter.
3786 * Please note: Ampersands and entities should be avoided here.
3790 * @param array $delimiters An array of translated delimiters.
3792 $l = apply_filters( 'wp_sprintf_l', array(
3793 /* translators: used to join items in a list with more than 2 items */
3794 'between' => sprintf( __('%s, %s'), '', '' ),
3795 /* translators: used to join last two items in a list with more than 2 times */
3796 'between_last_two' => sprintf( __('%s, and %s'), '', '' ),
3797 /* translators: used to join items in a list with only 2 items */
3798 'between_only_two' => sprintf( __('%s and %s'), '', '' ),
3801 $args = (array) $args;
3802 $result = array_shift($args);
3803 if ( count($args) == 1 )
3804 $result .= $l['between_only_two'] . array_shift($args);
3805 // Loop when more than two args
3808 $arg = array_shift($args);
3811 $result .= $l['between_last_two'] . $arg;
3813 $result .= $l['between'] . $arg;
3815 return $result . substr($pattern, 2);
3819 * Safely extracts not more than the first $count characters from html string.
3821 * UTF-8, tags and entities safe prefix extraction. Entities inside will *NOT*
3822 * be counted as one character. For example & will be counted as 4, < as
3827 * @param string $str String to get the excerpt from.
3828 * @param integer $count Maximum number of characters to take.
3829 * @param string $more Optional. What to append if $str needs to be trimmed. Defaults to empty string.
3830 * @return string The excerpt.
3832 function wp_html_excerpt( $str, $count, $more = null ) {
3833 if ( null === $more )
3835 $str = wp_strip_all_tags( $str, true );
3836 $excerpt = mb_substr( $str, 0, $count );
3837 // remove part of an entity at the end
3838 $excerpt = preg_replace( '/&[^;\s]{0,6}$/', '', $excerpt );
3839 if ( $str != $excerpt )
3840 $excerpt = trim( $excerpt ) . $more;
3845 * Add a Base url to relative links in passed content.
3847 * By default it supports the 'src' and 'href' attributes. However this can be
3848 * changed via the 3rd param.
3852 * @param string $content String to search for links in.
3853 * @param string $base The base URL to prefix to links.
3854 * @param array $attrs The attributes which should be processed.
3855 * @return string The processed content.
3857 function links_add_base_url( $content, $base, $attrs = array('src', 'href') ) {
3858 global $_links_add_base;
3859 $_links_add_base = $base;
3860 $attrs = implode('|', (array)$attrs);
3861 return preg_replace_callback( "!($attrs)=(['\"])(.+?)\\2!i", '_links_add_base', $content );
3865 * Callback to add a base url to relative links in passed content.
3870 * @param string $m The matched link.
3871 * @return string The processed link.
3873 function _links_add_base($m) {
3874 global $_links_add_base;
3875 //1 = attribute name 2 = quotation mark 3 = URL
3876 return $m[1] . '=' . $m[2] .
3877 ( preg_match( '#^(\w{1,20}):#', $m[3], $protocol ) && in_array( $protocol[1], wp_allowed_protocols() ) ?
3879 WP_HTTP::make_absolute_url( $m[3], $_links_add_base )
3885 * Adds a Target attribute to all links in passed content.
3887 * This function by default only applies to `<a>` tags, however this can be
3888 * modified by the 3rd param.
3890 * *NOTE:* Any current target attributed will be stripped and replaced.
3894 * @param string $content String to search for links in.
3895 * @param string $target The Target to add to the links.
3896 * @param array $tags An array of tags to apply to.
3897 * @return string The processed content.
3899 function links_add_target( $content, $target = '_blank', $tags = array('a') ) {
3900 global $_links_add_target;
3901 $_links_add_target = $target;
3902 $tags = implode('|', (array)$tags);
3903 return preg_replace_callback( "!<($tags)([^>]*)>!i", '_links_add_target', $content );
3907 * Callback to add a target attribute to all links in passed content.
3912 * @param string $m The matched link.
3913 * @return string The processed link.
3915 function _links_add_target( $m ) {
3916 global $_links_add_target;
3918 $link = preg_replace('|( target=([\'"])(.*?)\2)|i', '', $m[2]);
3919 return '<' . $tag . $link . ' target="' . esc_attr( $_links_add_target ) . '">';
3923 * Normalize EOL characters and strip duplicate whitespace.
3927 * @param string $str The string to normalize.
3928 * @return string The normalized string.
3930 function normalize_whitespace( $str ) {
3931 $str = trim( $str );
3932 $str = str_replace( "\r", "\n", $str );
3933 $str = preg_replace( array( '/\n+/', '/[ \t]+/' ), array( "\n", ' ' ), $str );
3938 * Properly strip all HTML tags including script and style
3940 * This differs from strip_tags() because it removes the contents of
3941 * the `<script>` and `<style>` tags. E.g. `strip_tags( '<script>something</script>' )`
3942 * will return 'something'. wp_strip_all_tags will return ''
3946 * @param string $string String containing HTML tags
3947 * @param bool $remove_breaks optional Whether to remove left over line breaks and white space chars
3948 * @return string The processed string.
3950 function wp_strip_all_tags($string, $remove_breaks = false) {
3951 $string = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $string );
3952 $string = strip_tags($string);
3954 if ( $remove_breaks )
3955 $string = preg_replace('/[\r\n\t ]+/', ' ', $string);
3957 return trim( $string );
3961 * Sanitize a string from user input or from the db
3963 * check for invalid UTF-8,
3964 * Convert single < characters to entity,
3966 * remove line breaks, tabs and extra white space,
3971 * @param string $str
3974 function sanitize_text_field($str) {
3975 $filtered = wp_check_invalid_utf8( $str );
3977 if ( strpos($filtered, '<') !== false ) {
3978 $filtered = wp_pre_kses_less_than( $filtered );
3979 // This will strip extra whitespace for us.
3980 $filtered = wp_strip_all_tags( $filtered, true );
3982 $filtered = trim( preg_replace('/[\r\n\t ]+/', ' ', $filtered) );
3986 while ( preg_match('/%[a-f0-9]{2}/i', $filtered, $match) ) {
3987 $filtered = str_replace($match[0], '', $filtered);
3992 // Strip out the whitespace that may now exist after removing the octets.
3993 $filtered = trim( preg_replace('/ +/', ' ', $filtered) );
3997 * Filter a sanitized text field string.
4001 * @param string $filtered The sanitized string.
4002 * @param string $str The string prior to being sanitized.
4004 return apply_filters( 'sanitize_text_field', $filtered, $str );
4008 * i18n friendly version of basename()
4012 * @param string $path A path.
4013 * @param string $suffix If the filename ends in suffix this will also be cut off.
4016 function wp_basename( $path, $suffix = '' ) {
4017 return urldecode( basename( str_replace( array( '%2F', '%5C' ), '/', urlencode( $path ) ), $suffix ) );
4021 * Forever eliminate "Wordpress" from the planet (or at least the little bit we can influence).
4023 * Violating our coding standards for a good function name.
4027 function capital_P_dangit( $text ) {
4028 // Simple replacement for titles
4029 $current_filter = current_filter();
4030 if ( 'the_title' === $current_filter || 'wp_title' === $current_filter )
4031 return str_replace( 'Wordpress', 'WordPress', $text );
4032 // Still here? Use the more judicious replacement
4033 static $dblq = false;
4034 if ( false === $dblq )
4035 $dblq = _x( '“', 'opening curly double quote' );
4037 array( ' Wordpress', '‘Wordpress', $dblq . 'Wordpress', '>Wordpress', '(Wordpress' ),
4038 array( ' WordPress', '‘WordPress', $dblq . 'WordPress', '>WordPress', '(WordPress' ),
4044 * Sanitize a mime type
4048 * @param string $mime_type Mime type
4049 * @return string Sanitized mime type
4051 function sanitize_mime_type( $mime_type ) {
4052 $sani_mime_type = preg_replace( '/[^-+*.a-zA-Z0-9\/]/', '', $mime_type );
4054 * Filter a mime type following sanitization.
4058 * @param string $sani_mime_type The sanitized mime type.
4059 * @param string $mime_type The mime type prior to sanitization.
4061 return apply_filters( 'sanitize_mime_type', $sani_mime_type, $mime_type );
4065 * Sanitize space or carriage return separated URLs that are used to send trackbacks.
4069 * @param string $to_ping Space or carriage return separated URLs
4070 * @return string URLs starting with the http or https protocol, separated by a carriage return.
4072 function sanitize_trackback_urls( $to_ping ) {
4073 $urls_to_ping = preg_split( '/[\r\n\t ]/', trim( $to_ping ), -1, PREG_SPLIT_NO_EMPTY );
4074 foreach ( $urls_to_ping as $k => $url ) {
4075 if ( !preg_match( '#^https?://.#i', $url ) )
4076 unset( $urls_to_ping[$k] );
4078 $urls_to_ping = array_map( 'esc_url_raw', $urls_to_ping );
4079 $urls_to_ping = implode( "\n", $urls_to_ping );
4081 * Filter a list of trackback URLs following sanitization.
4083 * The string returned here consists of a space or carriage return-delimited list
4084 * of trackback URLs.
4088 * @param string $urls_to_ping Sanitized space or carriage return separated URLs.
4089 * @param string $to_ping Space or carriage return separated URLs before sanitization.
4091 return apply_filters( 'sanitize_trackback_urls', $urls_to_ping, $to_ping );
4095 * Add slashes to a string or array of strings.
4097 * This should be used when preparing data for core API that expects slashed data.
4098 * This should not be used to escape data going directly into an SQL query.
4102 * @param string|array $value String or array of strings to slash.
4103 * @return string|array Slashed $value
4105 function wp_slash( $value ) {
4106 if ( is_array( $value ) ) {
4107 foreach ( $value as $k => $v ) {
4108 if ( is_array( $v ) ) {
4109 $value[$k] = wp_slash( $v );
4111 $value[$k] = addslashes( $v );
4115 $value = addslashes( $value );
4122 * Remove slashes from a string or array of strings.
4124 * This should be used to remove slashes from data passed to core API that
4125 * expects data to be unslashed.
4129 * @param string|array $value String or array of strings to unslash.
4130 * @return string|array Unslashed $value
4132 function wp_unslash( $value ) {
4133 return stripslashes_deep( $value );
4137 * Extract and return the first URL from passed content.
4141 * @param string $content A string which might contain a URL.
4142 * @return string The found URL.
4144 function get_url_in_content( $content ) {
4145 if ( empty( $content ) ) {
4149 if ( preg_match( '/<a\s[^>]*?href=([\'"])(.+?)\1/is', $content, $matches ) ) {
4150 return esc_url_raw( $matches[2] );
4157 * Returns the regexp for common whitespace characters.
4159 * By default, spaces include new lines, tabs, nbsp entities, and the UTF-8 nbsp.
4160 * This is designed to replace the PCRE \s sequence. In ticket #22692, that
4161 * sequence was found to be unreliable due to random inclusion of the A0 byte.
4165 * @return string The spaces regexp.
4167 function wp_spaces_regexp() {
4170 if ( empty( $spaces ) ) {
4172 * Filter the regexp for common whitespace characters.
4174 * This string is substituted for the \s sequence as needed in regular
4175 * expressions. For websites not written in English, different characters
4176 * may represent whitespace. For websites not encoded in UTF-8, the 0xC2 0xA0
4177 * sequence may not be in use.
4181 * @param string $spaces Regexp pattern for matching common whitespace characters.
4183 $spaces = apply_filters( 'wp_spaces_regexp', '[\r\n\t ]|\xC2\xA0| ' );
4190 * Print the important emoji-related styles.
4194 function print_emoji_styles() {
4195 static $printed = false;
4203 <style type="text/css">
4206 display: inline !important;
4207 border: none !important;
4208 box-shadow: none !important;
4209 height: 1em !important;
4210 width: 1em !important;
4211 margin: 0 .07em !important;
4212 vertical-align: -0.1em !important;
4213 background: none !important;
4214 padding: 0 !important;
4220 function print_emoji_detection_script() {
4222 static $printed = false;
4232 * Filter the URL where emoji images are hosted.
4236 * @param string The emoji base URL.
4238 'baseUrl' => apply_filters( 'emoji_url', set_url_scheme( '//s.w.org/images/core/emoji/72x72/' ) ),
4241 * Filter the extension of the emoji files.
4245 * @param string The emoji extension. Default .png.
4247 'ext' => apply_filters( 'emoji_ext', '.png' ),
4250 $version = 'ver=' . $wp_version;
4251 $develop_src = false !== strpos( $wp_version, '-src' );
4253 if ( $develop_src || ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ) {
4254 $settings['source'] = array(
4255 /** This filter is documented in wp-includes/class.wp-scripts.php */
4256 'wpemoji' => apply_filters( 'script_loader_src', includes_url( "js/wp-emoji.js?$version" ), 'wpemoji' ),
4257 /** This filter is documented in wp-includes/class.wp-scripts.php */
4258 'twemoji' => apply_filters( 'script_loader_src', includes_url( "js/twemoji.js?$version" ), 'twemoji' ),
4262 <script type="text/javascript">
4263 window._wpemojiSettings = <?php echo wp_json_encode( $settings ); ?>;
4264 <?php readfile( ABSPATH . WPINC . "/js/wp-emoji-loader.js" ); ?>
4268 $settings['source'] = array(
4269 /** This filter is documented in wp-includes/class.wp-scripts.php */
4270 'concatemoji' => apply_filters( 'script_loader_src', includes_url( "js/wp-emoji-release.min.js?$version" ), 'concatemoji' ),
4274 * If you're looking at a src version of this file, you'll see an "include"
4275 * statement below. This is used by the `grunt build` process to directly
4276 * include a minified version of wp-emoji-loader.js, instead of using the
4277 * readfile() method from above.
4279 * If you're looking at a build version of this file, you'll see a string of
4280 * minified JavaScript. If you need to debug it, please turn on SCRIPT_DEBUG
4281 * and edit wp-emoji-loader.js directly.
4284 <script type="text/javascript">
4285 window._wpemojiSettings = <?php echo wp_json_encode( $settings ); ?>;
4286 !function(a,b,c){function d(a){var c=b.createElement("canvas"),d=c.getContext&&c.getContext("2d");return d&&d.fillText?(d.textBaseline="top",d.font="600 32px Arial","flag"===a?(d.fillText(String.fromCharCode(55356,56812,55356,56807),0,0),c.toDataURL().length>3e3):(d.fillText(String.fromCharCode(55357,56835),0,0),0!==d.getImageData(16,16,1,1).data[0])):!1}function e(a){var c=b.createElement("script");c.src=a,c.type="text/javascript",b.getElementsByTagName("head")[0].appendChild(c)}var f,g;c.supports={simple:d("simple"),flag:d("flag")},c.DOMReady=!1,c.readyCallback=function(){c.DOMReady=!0},c.supports.simple&&c.supports.flag||(g=function(){c.readyCallback()},b.addEventListener?(b.addEventListener("DOMContentLoaded",g,!1),a.addEventListener("load",g,!1)):(a.attachEvent("onload",g),b.attachEvent("onreadystatechange",function(){"complete"===b.readyState&&c.readyCallback()})),f=c.source||{},f.concatemoji?e(f.concatemoji):f.wpemoji&&f.twemoji&&(e(f.twemoji),e(f.wpemoji)))}(window,document,window._wpemojiSettings);
4293 * Convert any 4 byte emoji in a string to their equivalent HTML entity.
4295 * Currently, only Unicode 7 emoji are supported. Skin tone modifiers are allowed,
4296 * all other Unicode 8 emoji will be added when the spec is finalised.
4298 * This allows us to store emoji in a DB using the utf8 character set.
4302 * @param string $content The content to encode.
4303 * @return string The encoded content.
4305 function wp_encode_emoji( $content ) {
4306 if ( function_exists( 'mb_convert_encoding' ) ) {
4308 \x23\xE2\x83\xA3 # Digits
4309 [\x30-\x39]\xE2\x83\xA3
4310 | \xF0\x9F[\x85-\x88][\xA6-\xBF] # Enclosed characters
4311 | \xF0\x9F[\x8C-\x97][\x80-\xBF] # Misc
4312 | \xF0\x9F\x98[\x80-\xBF] # Smilies
4313 | \xF0\x9F\x99[\x80-\x8F]
4314 | \xF0\x9F\x9A[\x80-\xBF] # Transport and map symbols
4318 if ( preg_match_all( $regex, $content, $matches ) ) {
4319 if ( ! empty( $matches[1] ) ) {
4320 foreach( $matches[1] as $emoji ) {
4322 * UTF-32's hex encoding is the same as HTML's hex encoding.
4323 * So, by converting the emoji from UTF-8 to UTF-32, we magically
4324 * get the correct hex encoding.
4326 $unpacked = unpack( 'H*', mb_convert_encoding( $emoji, 'UTF-32', 'UTF-8' ) );
4327 if ( isset( $unpacked[1] ) ) {
4328 $entity = '&#x' . ltrim( $unpacked[1], '0' ) . ';';
4329 $content = str_replace( $emoji, $entity, $content );
4340 * Convert emoji to a static img element.
4344 * @param string $text The content to encode.
4345 * @return string The encoded content.
4347 function wp_staticize_emoji( $text ) {
4348 $text = wp_encode_emoji( $text );
4350 /** This filter is documented in wp-includes/formatting.php */
4351 $cdn_url = apply_filters( 'emoji_url', set_url_scheme( '//s.w.org/images/core/emoji/72x72/' ) );
4353 /** This filter is documented in wp-includes/formatting.php */
4354 $ext = apply_filters( 'emoji_ext', '.png' );
4358 * HTML loop taken from smiley function, which was taken from texturize function.
4359 * It'll never be consolidated.
4361 * First, capture the tags as well as in between.
4363 $textarr = preg_split( '/(<.*>)/U', $text, -1, PREG_SPLIT_DELIM_CAPTURE );
4364 $stop = count( $textarr );
4366 // Ignore processing of specific tags.
4367 $tags_to_ignore = 'code|pre|style|script|textarea';
4368 $ignore_block_element = '';
4370 for ( $i = 0; $i < $stop; $i++ ) {
4371 $content = $textarr[$i];
4373 // If we're in an ignore block, wait until we find its closing tag.
4374 if ( '' == $ignore_block_element && preg_match( '/^<(' . $tags_to_ignore . ')>/', $content, $matches ) ) {
4375 $ignore_block_element = $matches[1];
4378 // If it's not a tag and not in ignore block.
4379 if ( '' == $ignore_block_element && strlen( $content ) > 0 && '<' != $content[0] ) {
4381 if ( preg_match_all( '/(DZ(e[6-9a-f]|f[0-9a-f]);){2}/', $content, $matches ) ) {
4382 if ( ! empty( $matches[0] ) ) {
4383 foreach ( $matches[0] as $flag ) {
4384 $chars = str_replace( array( '&#x', ';'), '', $flag );
4386 list( $char1, $char2 ) = str_split( $chars, 5 );
4387 $entity = sprintf( '<img src="%s" alt="%s" class="wp-smiley" style="height: 1em; max-height: 1em;" />', $cdn_url . $char1 . '-' . $char2 . $ext, html_entity_decode( $flag ) );
4389 $content = str_replace( $flag, $entity, $content );
4394 // Loosely match the Emoji Unicode range.
4395 $regex = '/(&#x[2-3][0-9a-f]{3};|[1-6][0-9a-f]{2};)/';
4398 if ( preg_match_all( $regex, $content, $matches ) ) {
4399 if ( ! empty( $matches[1] ) ) {
4400 foreach ( $matches[1] as $emoji ) {
4401 $char = str_replace( array( '&#x', ';'), '', $emoji );
4402 $entity = sprintf( '<img src="%s" alt="%s" class="wp-smiley" style="height: 1em; max-height: 1em;" />', $cdn_url . $char . $ext, html_entity_decode( $emoji ) );
4404 $content = str_replace( $emoji, $entity, $content );
4410 // Did we exit ignore block.
4411 if ( '' != $ignore_block_element && '</' . $ignore_block_element . '>' == $content ) {
4412 $ignore_block_element = '';
4415 $output .= $content;
4422 * Convert emoji in emails into static images.
4426 * @param array $mail The email data array.
4427 * @return array The email data array, with emoji in the message staticized.
4429 function wp_staticize_emoji_for_email( $mail ) {
4430 if ( ! isset( $mail['message'] ) ) {
4435 * We can only transform the emoji into images if it's a text/html email.
4436 * To do that, here's a cut down version of the same process that happens
4437 * in wp_mail() - get the Content-Type from the headers, if there is one,
4438 * then pass it through the wp_mail_content_type filter, in case a plugin
4439 * is handling changing the Content-Type.
4442 if ( isset( $mail['headers'] ) ) {
4443 if ( is_array( $mail['headers'] ) ) {
4444 $headers = $mail['headers'];
4446 $headers = explode( "\n", str_replace( "\r\n", "\n", $mail['headers'] ) );
4450 foreach ( $headers as $header ) {
4451 if ( strpos($header, ':') === false ) {
4455 // Explode them out.
4456 list( $name, $content ) = explode( ':', trim( $header ), 2 );
4459 $name = trim( $name );
4460 $content = trim( $content );
4462 if ( 'content-type' === strtolower( $name ) ) {
4463 if ( strpos( $content, ';' ) !== false ) {
4464 list( $type, $charset ) = explode( ';', $content );
4465 $content_type = trim( $type );
4467 $content_type = trim( $content );
4473 // Set Content-Type if we don't have a content-type from the input headers.
4474 if ( ! isset( $content_type ) ) {
4475 $content_type = 'text/plain';
4478 /** This filter is documented in wp-includes/pluggable.php */
4479 $content_type = apply_filters( 'wp_mail_content_type', $content_type );
4481 if ( 'text/html' === $content_type ) {
4482 $mail['message'] = wp_staticize_emoji( $mail['message'] );