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 // Find newlines in all elements and add placeholders.
425 $pee = wp_replace_in_html_tags( $pee, array( "\n" => " <!-- wpnl --> " ) );
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);
512 // Restore newlines in all elements.
513 $pee = str_replace( " <!-- wpnl --> ", "\n", $pee );
519 * Separate HTML elements and comments from the text.
523 * @param string $input The text which has to be formatted.
524 * @return array The formatted text.
526 function wp_html_split( $input ) {
529 if ( ! isset( $regex ) ) {
531 '!' // Start of comment, after the <.
532 . '(?:' // Unroll the loop: Consume everything until --> is found.
533 . '-(?!->)' // Dash not followed by end of comment.
534 . '[^\-]*+' // Consume non-dashes.
535 . ')*+' // Loop possessively.
536 . '(?:-->)?'; // End of comment. If not found, match all input.
539 '!\[CDATA\[' // Start of comment, after the <.
540 . '[^\]]*+' // Consume non-].
541 . '(?:' // Unroll the loop: Consume everything until ]]> is found.
542 . '](?!]>)' // One ] not followed by end of comment.
543 . '[^\]]*+' // Consume non-].
544 . ')*+' // Loop possessively.
545 . '(?:]]>)?'; // End of comment. If not found, match all input.
548 '/(' // Capture the entire match.
549 . '<' // Find start of element.
550 . '(?(?=!--)' // Is this a comment?
551 . $comments // Find end of comment.
553 . '(?(?=!\[CDATA\[)' // Is this a comment?
554 . $cdata // Find end of comment.
556 . '[^>]*>?' // Find end of element. If not found, match all input.
562 return preg_split( $regex, $input, -1, PREG_SPLIT_DELIM_CAPTURE );
566 * Replace characters or phrases within HTML elements only.
570 * @param string $haystack The text which has to be formatted.
571 * @param array $replace_pairs In the form array('from' => 'to', ...).
572 * @return string The formatted text.
574 function wp_replace_in_html_tags( $haystack, $replace_pairs ) {
575 // Find all elements.
576 $textarr = wp_html_split( $haystack );
579 // Optimize when searching for one item.
580 if ( 1 === count( $replace_pairs ) ) {
581 // Extract $needle and $replace.
582 foreach ( $replace_pairs as $needle => $replace );
584 // Loop through delimeters (elements) only.
585 for ( $i = 1, $c = count( $textarr ); $i < $c; $i += 2 ) {
586 if ( false !== strpos( $textarr[$i], $needle ) ) {
587 $textarr[$i] = str_replace( $needle, $replace, $textarr[$i] );
592 // Extract all $needles.
593 $needles = array_keys( $replace_pairs );
595 // Loop through delimeters (elements) only.
596 for ( $i = 1, $c = count( $textarr ); $i < $c; $i += 2 ) {
597 foreach ( $needles as $needle ) {
598 if ( false !== strpos( $textarr[$i], $needle ) ) {
599 $textarr[$i] = strtr( $textarr[$i], $replace_pairs );
601 // After one strtr() break out of the foreach loop and look at next element.
609 $haystack = implode( $textarr );
616 * Newline preservation help function for wpautop
621 * @param array $matches preg_replace_callback matches array
624 function _autop_newline_preservation_helper( $matches ) {
625 return str_replace("\n", "<WPPreserveNewline />", $matches[0]);
629 * Don't auto-p wrap shortcodes that stand alone
631 * Ensures that shortcodes are not wrapped in `<p>...</p>`.
635 * @param string $pee The content.
636 * @return string The filtered content.
638 function shortcode_unautop( $pee ) {
639 global $shortcode_tags;
641 if ( empty( $shortcode_tags ) || !is_array( $shortcode_tags ) ) {
645 $tagregexp = join( '|', array_map( 'preg_quote', array_keys( $shortcode_tags ) ) );
646 $spaces = wp_spaces_regexp();
650 . '<p>' // Opening paragraph
651 . '(?:' . $spaces . ')*+' // Optional leading whitespace
652 . '(' // 1: The shortcode
653 . '\\[' // Opening bracket
654 . "($tagregexp)" // 2: Shortcode name
655 . '(?![\\w-])' // Not followed by word character or hyphen
656 // Unroll the loop: Inside the opening shortcode tag
657 . '[^\\]\\/]*' // Not a closing bracket or forward slash
659 . '\\/(?!\\])' // A forward slash not followed by a closing bracket
660 . '[^\\]\\/]*' // Not a closing bracket or forward slash
663 . '\\/\\]' // Self closing tag and closing bracket
665 . '\\]' // Closing bracket
666 . '(?:' // Unroll the loop: Optionally, anything between the opening and closing shortcode tags
667 . '[^\\[]*+' // Not an opening bracket
669 . '\\[(?!\\/\\2\\])' // An opening bracket not followed by the closing shortcode tag
670 . '[^\\[]*+' // Not an opening bracket
672 . '\\[\\/\\2\\]' // Closing shortcode tag
676 . '(?:' . $spaces . ')*+' // optional trailing whitespace
677 . '<\\/p>' // closing paragraph
680 return preg_replace( $pattern, '$1', $pee );
684 * Checks to see if a string is utf8 encoded.
686 * NOTE: This function checks for 5-Byte sequences, UTF8
687 * has Bytes Sequences with a maximum length of 4.
689 * @author bmorel at ssi dot fr (modified)
692 * @param string $str The string to be checked
693 * @return bool True if $str fits a UTF-8 model, false otherwise.
695 function seems_utf8($str) {
696 mbstring_binary_safe_encoding();
697 $length = strlen($str);
698 reset_mbstring_encoding();
699 for ($i=0; $i < $length; $i++) {
701 if ($c < 0x80) $n = 0; // 0bbbbbbb
702 elseif (($c & 0xE0) == 0xC0) $n=1; // 110bbbbb
703 elseif (($c & 0xF0) == 0xE0) $n=2; // 1110bbbb
704 elseif (($c & 0xF8) == 0xF0) $n=3; // 11110bbb
705 elseif (($c & 0xFC) == 0xF8) $n=4; // 111110bb
706 elseif (($c & 0xFE) == 0xFC) $n=5; // 1111110b
707 else return false; // Does not match any model
708 for ($j=0; $j<$n; $j++) { // n bytes matching 10bbbbbb follow ?
709 if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))
717 * Converts a number of special characters into their HTML entities.
719 * Specifically deals with: &, <, >, ", and '.
721 * $quote_style can be set to ENT_COMPAT to encode " to
722 * ", or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded.
727 * @param string $string The text which is to be encoded.
728 * @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.
729 * @param string $charset Optional. The character encoding of the string. Default is false.
730 * @param boolean $double_encode Optional. Whether to encode existing html entities. Default is false.
731 * @return string The encoded text with HTML entities.
733 function _wp_specialchars( $string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false ) {
734 $string = (string) $string;
736 if ( 0 === strlen( $string ) )
739 // Don't bother if there are no specialchars - saves some processing
740 if ( ! preg_match( '/[&<>"\']/', $string ) )
743 // Account for the previous behaviour of the function when the $quote_style is not an accepted value
744 if ( empty( $quote_style ) )
745 $quote_style = ENT_NOQUOTES;
746 elseif ( ! in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) )
747 $quote_style = ENT_QUOTES;
749 // Store the site charset as a static to avoid multiple calls to wp_load_alloptions()
752 if ( ! isset( $_charset ) ) {
753 $alloptions = wp_load_alloptions();
754 $_charset = isset( $alloptions['blog_charset'] ) ? $alloptions['blog_charset'] : '';
756 $charset = $_charset;
759 if ( in_array( $charset, array( 'utf8', 'utf-8', 'UTF8' ) ) )
762 $_quote_style = $quote_style;
764 if ( $quote_style === 'double' ) {
765 $quote_style = ENT_COMPAT;
766 $_quote_style = ENT_COMPAT;
767 } elseif ( $quote_style === 'single' ) {
768 $quote_style = ENT_NOQUOTES;
771 // Handle double encoding ourselves
772 if ( $double_encode ) {
773 $string = @htmlspecialchars( $string, $quote_style, $charset );
775 // Decode & into &
776 $string = wp_specialchars_decode( $string, $_quote_style );
778 // Guarantee every &entity; is valid or re-encode the &
779 $string = wp_kses_normalize_entities( $string );
781 // Now re-encode everything except &entity;
782 $string = preg_split( '/(&#?x?[0-9a-z]+;)/i', $string, -1, PREG_SPLIT_DELIM_CAPTURE );
784 for ( $i = 0, $c = count( $string ); $i < $c; $i += 2 ) {
785 $string[$i] = @htmlspecialchars( $string[$i], $quote_style, $charset );
787 $string = implode( '', $string );
790 // Backwards compatibility
791 if ( 'single' === $_quote_style )
792 $string = str_replace( "'", ''', $string );
798 * Converts a number of HTML entities into their special characters.
800 * Specifically deals with: &, <, >, ", and '.
802 * $quote_style can be set to ENT_COMPAT to decode " entities,
803 * or ENT_QUOTES to do both " and '. Default is ENT_NOQUOTES where no quotes are decoded.
807 * @param string $string The text which is to be decoded.
808 * @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.
809 * @return string The decoded text without HTML entities.
811 function wp_specialchars_decode( $string, $quote_style = ENT_NOQUOTES ) {
812 $string = (string) $string;
814 if ( 0 === strlen( $string ) ) {
818 // Don't bother if there are no entities - saves a lot of processing
819 if ( strpos( $string, '&' ) === false ) {
823 // Match the previous behaviour of _wp_specialchars() when the $quote_style is not an accepted value
824 if ( empty( $quote_style ) ) {
825 $quote_style = ENT_NOQUOTES;
826 } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
827 $quote_style = ENT_QUOTES;
830 // More complete than get_html_translation_table( HTML_SPECIALCHARS )
831 $single = array( ''' => '\'', ''' => '\'' );
832 $single_preg = array( '/�*39;/' => ''', '/�*27;/i' => ''' );
833 $double = array( '"' => '"', '"' => '"', '"' => '"' );
834 $double_preg = array( '/�*34;/' => '"', '/�*22;/i' => '"' );
835 $others = array( '<' => '<', '<' => '<', '>' => '>', '>' => '>', '&' => '&', '&' => '&', '&' => '&' );
836 $others_preg = array( '/�*60;/' => '<', '/�*62;/' => '>', '/�*38;/' => '&', '/�*26;/i' => '&' );
838 if ( $quote_style === ENT_QUOTES ) {
839 $translation = array_merge( $single, $double, $others );
840 $translation_preg = array_merge( $single_preg, $double_preg, $others_preg );
841 } elseif ( $quote_style === ENT_COMPAT || $quote_style === 'double' ) {
842 $translation = array_merge( $double, $others );
843 $translation_preg = array_merge( $double_preg, $others_preg );
844 } elseif ( $quote_style === 'single' ) {
845 $translation = array_merge( $single, $others );
846 $translation_preg = array_merge( $single_preg, $others_preg );
847 } elseif ( $quote_style === ENT_NOQUOTES ) {
848 $translation = $others;
849 $translation_preg = $others_preg;
852 // Remove zero padding on numeric entities
853 $string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string );
855 // Replace characters according to translation table
856 return strtr( $string, $translation );
860 * Checks for invalid UTF8 in a string.
864 * @param string $string The text which is to be checked.
865 * @param boolean $strip Optional. Whether to attempt to strip out invalid UTF8. Default is false.
866 * @return string The checked text.
868 function wp_check_invalid_utf8( $string, $strip = false ) {
869 $string = (string) $string;
871 if ( 0 === strlen( $string ) ) {
875 // Store the site charset as a static to avoid multiple calls to get_option()
877 if ( !isset( $is_utf8 ) ) {
878 $is_utf8 = in_array( get_option( 'blog_charset' ), array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ) );
884 // Check for support for utf8 in the installed PCRE library once and store the result in a static
886 if ( !isset( $utf8_pcre ) ) {
887 $utf8_pcre = @preg_match( '/^./u', 'a' );
889 // We can't demand utf8 in the PCRE installation, so just return the string in those cases
894 // preg_match fails when it encounters invalid UTF8 in $string
895 if ( 1 === @preg_match( '/^./us', $string ) ) {
899 // Attempt to strip the bad chars if requested (not recommended)
900 if ( $strip && function_exists( 'iconv' ) ) {
901 return iconv( 'utf-8', 'utf-8', $string );
908 * Encode the Unicode values to be used in the URI.
912 * @param string $utf8_string
913 * @param int $length Max length of the string
914 * @return string String with Unicode encoded for URI.
916 function utf8_uri_encode( $utf8_string, $length = 0 ) {
922 mbstring_binary_safe_encoding();
923 $string_length = strlen( $utf8_string );
924 reset_mbstring_encoding();
926 for ($i = 0; $i < $string_length; $i++ ) {
928 $value = ord( $utf8_string[ $i ] );
930 if ( $value < 128 ) {
931 if ( $length && ( $unicode_length >= $length ) )
933 $unicode .= chr($value);
936 if ( count( $values ) == 0 ) {
937 if ( $value < 224 ) {
939 } elseif ( $value < 240 ) {
948 if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length )
950 if ( count( $values ) == $num_octets ) {
951 for ( $j = 0; $j < $num_octets; $j++ ) {
952 $unicode .= '%' . dechex( $values[ $j ] );
955 $unicode_length += $num_octets * 3;
967 * Converts all accent characters to ASCII characters.
969 * If there are no accent characters, then the string given is just returned.
973 * @param string $string Text that might have accent characters
974 * @return string Filtered string with replaced "nice" characters.
976 function remove_accents($string) {
977 if ( !preg_match('/[\x80-\xff]/', $string) )
980 if (seems_utf8($string)) {
982 // Decompositions for Latin-1 Supplement
983 chr(194).chr(170) => 'a', chr(194).chr(186) => 'o',
984 chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
985 chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
986 chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
987 chr(195).chr(134) => 'AE',chr(195).chr(135) => 'C',
988 chr(195).chr(136) => 'E', chr(195).chr(137) => 'E',
989 chr(195).chr(138) => 'E', chr(195).chr(139) => 'E',
990 chr(195).chr(140) => 'I', chr(195).chr(141) => 'I',
991 chr(195).chr(142) => 'I', chr(195).chr(143) => 'I',
992 chr(195).chr(144) => 'D', chr(195).chr(145) => 'N',
993 chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
994 chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
995 chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
996 chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
997 chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
998 chr(195).chr(158) => 'TH',chr(195).chr(159) => 's',
999 chr(195).chr(160) => 'a', chr(195).chr(161) => 'a',
1000 chr(195).chr(162) => 'a', chr(195).chr(163) => 'a',
1001 chr(195).chr(164) => 'a', chr(195).chr(165) => 'a',
1002 chr(195).chr(166) => 'ae',chr(195).chr(167) => 'c',
1003 chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
1004 chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
1005 chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
1006 chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
1007 chr(195).chr(176) => 'd', chr(195).chr(177) => 'n',
1008 chr(195).chr(178) => 'o', chr(195).chr(179) => 'o',
1009 chr(195).chr(180) => 'o', chr(195).chr(181) => 'o',
1010 chr(195).chr(182) => 'o', chr(195).chr(184) => 'o',
1011 chr(195).chr(185) => 'u', chr(195).chr(186) => 'u',
1012 chr(195).chr(187) => 'u', chr(195).chr(188) => 'u',
1013 chr(195).chr(189) => 'y', chr(195).chr(190) => 'th',
1014 chr(195).chr(191) => 'y', chr(195).chr(152) => 'O',
1015 // Decompositions for Latin Extended-A
1016 chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
1017 chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
1018 chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
1019 chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
1020 chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
1021 chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
1022 chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
1023 chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
1024 chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
1025 chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
1026 chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
1027 chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
1028 chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
1029 chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
1030 chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
1031 chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
1032 chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
1033 chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
1034 chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
1035 chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
1036 chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
1037 chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
1038 chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
1039 chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
1040 chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
1041 chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
1042 chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
1043 chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
1044 chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
1045 chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
1046 chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
1047 chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
1048 chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
1049 chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
1050 chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
1051 chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
1052 chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
1053 chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
1054 chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
1055 chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
1056 chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
1057 chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
1058 chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
1059 chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
1060 chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
1061 chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
1062 chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
1063 chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
1064 chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
1065 chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
1066 chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
1067 chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
1068 chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
1069 chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
1070 chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
1071 chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
1072 chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
1073 chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
1074 chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
1075 chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
1076 chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
1077 chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
1078 chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
1079 chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
1080 // Decompositions for Latin Extended-B
1081 chr(200).chr(152) => 'S', chr(200).chr(153) => 's',
1082 chr(200).chr(154) => 'T', chr(200).chr(155) => 't',
1084 chr(226).chr(130).chr(172) => 'E',
1086 chr(194).chr(163) => '',
1087 // Vowels with diacritic (Vietnamese)
1089 chr(198).chr(160) => 'O', chr(198).chr(161) => 'o',
1090 chr(198).chr(175) => 'U', chr(198).chr(176) => 'u',
1092 chr(225).chr(186).chr(166) => 'A', chr(225).chr(186).chr(167) => 'a',
1093 chr(225).chr(186).chr(176) => 'A', chr(225).chr(186).chr(177) => 'a',
1094 chr(225).chr(187).chr(128) => 'E', chr(225).chr(187).chr(129) => 'e',
1095 chr(225).chr(187).chr(146) => 'O', chr(225).chr(187).chr(147) => 'o',
1096 chr(225).chr(187).chr(156) => 'O', chr(225).chr(187).chr(157) => 'o',
1097 chr(225).chr(187).chr(170) => 'U', chr(225).chr(187).chr(171) => 'u',
1098 chr(225).chr(187).chr(178) => 'Y', chr(225).chr(187).chr(179) => 'y',
1100 chr(225).chr(186).chr(162) => 'A', chr(225).chr(186).chr(163) => 'a',
1101 chr(225).chr(186).chr(168) => 'A', chr(225).chr(186).chr(169) => 'a',
1102 chr(225).chr(186).chr(178) => 'A', chr(225).chr(186).chr(179) => 'a',
1103 chr(225).chr(186).chr(186) => 'E', chr(225).chr(186).chr(187) => 'e',
1104 chr(225).chr(187).chr(130) => 'E', chr(225).chr(187).chr(131) => 'e',
1105 chr(225).chr(187).chr(136) => 'I', chr(225).chr(187).chr(137) => 'i',
1106 chr(225).chr(187).chr(142) => 'O', chr(225).chr(187).chr(143) => 'o',
1107 chr(225).chr(187).chr(148) => 'O', chr(225).chr(187).chr(149) => 'o',
1108 chr(225).chr(187).chr(158) => 'O', chr(225).chr(187).chr(159) => 'o',
1109 chr(225).chr(187).chr(166) => 'U', chr(225).chr(187).chr(167) => 'u',
1110 chr(225).chr(187).chr(172) => 'U', chr(225).chr(187).chr(173) => 'u',
1111 chr(225).chr(187).chr(182) => 'Y', chr(225).chr(187).chr(183) => 'y',
1113 chr(225).chr(186).chr(170) => 'A', chr(225).chr(186).chr(171) => 'a',
1114 chr(225).chr(186).chr(180) => 'A', chr(225).chr(186).chr(181) => 'a',
1115 chr(225).chr(186).chr(188) => 'E', chr(225).chr(186).chr(189) => 'e',
1116 chr(225).chr(187).chr(132) => 'E', chr(225).chr(187).chr(133) => 'e',
1117 chr(225).chr(187).chr(150) => 'O', chr(225).chr(187).chr(151) => 'o',
1118 chr(225).chr(187).chr(160) => 'O', chr(225).chr(187).chr(161) => 'o',
1119 chr(225).chr(187).chr(174) => 'U', chr(225).chr(187).chr(175) => 'u',
1120 chr(225).chr(187).chr(184) => 'Y', chr(225).chr(187).chr(185) => 'y',
1122 chr(225).chr(186).chr(164) => 'A', chr(225).chr(186).chr(165) => 'a',
1123 chr(225).chr(186).chr(174) => 'A', chr(225).chr(186).chr(175) => 'a',
1124 chr(225).chr(186).chr(190) => 'E', chr(225).chr(186).chr(191) => 'e',
1125 chr(225).chr(187).chr(144) => 'O', chr(225).chr(187).chr(145) => 'o',
1126 chr(225).chr(187).chr(154) => 'O', chr(225).chr(187).chr(155) => 'o',
1127 chr(225).chr(187).chr(168) => 'U', chr(225).chr(187).chr(169) => 'u',
1129 chr(225).chr(186).chr(160) => 'A', chr(225).chr(186).chr(161) => 'a',
1130 chr(225).chr(186).chr(172) => 'A', chr(225).chr(186).chr(173) => 'a',
1131 chr(225).chr(186).chr(182) => 'A', chr(225).chr(186).chr(183) => 'a',
1132 chr(225).chr(186).chr(184) => 'E', chr(225).chr(186).chr(185) => 'e',
1133 chr(225).chr(187).chr(134) => 'E', chr(225).chr(187).chr(135) => 'e',
1134 chr(225).chr(187).chr(138) => 'I', chr(225).chr(187).chr(139) => 'i',
1135 chr(225).chr(187).chr(140) => 'O', chr(225).chr(187).chr(141) => 'o',
1136 chr(225).chr(187).chr(152) => 'O', chr(225).chr(187).chr(153) => 'o',
1137 chr(225).chr(187).chr(162) => 'O', chr(225).chr(187).chr(163) => 'o',
1138 chr(225).chr(187).chr(164) => 'U', chr(225).chr(187).chr(165) => 'u',
1139 chr(225).chr(187).chr(176) => 'U', chr(225).chr(187).chr(177) => 'u',
1140 chr(225).chr(187).chr(180) => 'Y', chr(225).chr(187).chr(181) => 'y',
1141 // Vowels with diacritic (Chinese, Hanyu Pinyin)
1142 chr(201).chr(145) => 'a',
1144 chr(199).chr(149) => 'U', chr(199).chr(150) => 'u',
1146 chr(199).chr(151) => 'U', chr(199).chr(152) => 'u',
1148 chr(199).chr(141) => 'A', chr(199).chr(142) => 'a',
1149 chr(199).chr(143) => 'I', chr(199).chr(144) => 'i',
1150 chr(199).chr(145) => 'O', chr(199).chr(146) => 'o',
1151 chr(199).chr(147) => 'U', chr(199).chr(148) => 'u',
1152 chr(199).chr(153) => 'U', chr(199).chr(154) => 'u',
1154 chr(199).chr(155) => 'U', chr(199).chr(156) => 'u',
1157 // Used for locale-specific rules
1158 $locale = get_locale();
1160 if ( 'de_DE' == $locale ) {
1161 $chars[ chr(195).chr(132) ] = 'Ae';
1162 $chars[ chr(195).chr(164) ] = 'ae';
1163 $chars[ chr(195).chr(150) ] = 'Oe';
1164 $chars[ chr(195).chr(182) ] = 'oe';
1165 $chars[ chr(195).chr(156) ] = 'Ue';
1166 $chars[ chr(195).chr(188) ] = 'ue';
1167 $chars[ chr(195).chr(159) ] = 'ss';
1168 } elseif ( 'da_DK' === $locale ) {
1169 $chars[ chr(195).chr(134) ] = 'Ae';
1170 $chars[ chr(195).chr(166) ] = 'ae';
1171 $chars[ chr(195).chr(152) ] = 'Oe';
1172 $chars[ chr(195).chr(184) ] = 'oe';
1173 $chars[ chr(195).chr(133) ] = 'Aa';
1174 $chars[ chr(195).chr(165) ] = 'aa';
1177 $string = strtr($string, $chars);
1180 // Assume ISO-8859-1 if not UTF-8
1181 $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
1182 .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
1183 .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
1184 .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
1185 .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
1186 .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
1187 .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
1188 .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
1189 .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
1190 .chr(252).chr(253).chr(255);
1192 $chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";
1194 $string = strtr($string, $chars['in'], $chars['out']);
1195 $double_chars = array();
1196 $double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
1197 $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
1198 $string = str_replace($double_chars['in'], $double_chars['out'], $string);
1205 * Sanitizes a filename, replacing whitespace with dashes.
1207 * Removes special characters that are illegal in filenames on certain
1208 * operating systems and special characters requiring special escaping
1209 * to manipulate at the command line. Replaces spaces and consecutive
1210 * dashes with a single dash. Trims period, dash and underscore from beginning
1211 * and end of filename.
1215 * @param string $filename The filename to be sanitized
1216 * @return string The sanitized filename
1218 function sanitize_file_name( $filename ) {
1219 $filename_raw = $filename;
1220 $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", chr(0));
1222 * Filter the list of characters to remove from a filename.
1226 * @param array $special_chars Characters to remove.
1227 * @param string $filename_raw Filename as it was passed into sanitize_file_name().
1229 $special_chars = apply_filters( 'sanitize_file_name_chars', $special_chars, $filename_raw );
1230 $filename = preg_replace( "#\x{00a0}#siu", ' ', $filename );
1231 $filename = str_replace( $special_chars, '', $filename );
1232 $filename = str_replace( array( '%20', '+' ), '-', $filename );
1233 $filename = preg_replace( '/[\r\n\t -]+/', '-', $filename );
1234 $filename = trim( $filename, '.-_' );
1236 // Split the filename into a base and extension[s]
1237 $parts = explode('.', $filename);
1239 // Return if only one extension
1240 if ( count( $parts ) <= 2 ) {
1242 * Filter a sanitized filename string.
1246 * @param string $filename Sanitized filename.
1247 * @param string $filename_raw The filename prior to sanitization.
1249 return apply_filters( 'sanitize_file_name', $filename, $filename_raw );
1252 // Process multiple extensions
1253 $filename = array_shift($parts);
1254 $extension = array_pop($parts);
1255 $mimes = get_allowed_mime_types();
1258 * Loop over any intermediate extensions. Postfix them with a trailing underscore
1259 * if they are a 2 - 5 character long alpha string not in the extension whitelist.
1261 foreach ( (array) $parts as $part) {
1262 $filename .= '.' . $part;
1264 if ( preg_match("/^[a-zA-Z]{2,5}\d?$/", $part) ) {
1266 foreach ( $mimes as $ext_preg => $mime_match ) {
1267 $ext_preg = '!^(' . $ext_preg . ')$!i';
1268 if ( preg_match( $ext_preg, $part ) ) {
1277 $filename .= '.' . $extension;
1278 /** This filter is documented in wp-includes/formatting.php */
1279 return apply_filters('sanitize_file_name', $filename, $filename_raw);
1283 * Sanitizes a username, stripping out unsafe characters.
1285 * Removes tags, octets, entities, and if strict is enabled, will only keep
1286 * alphanumeric, _, space, ., -, @. After sanitizing, it passes the username,
1287 * raw username (the username in the parameter), and the value of $strict as
1288 * parameters for the 'sanitize_user' filter.
1292 * @param string $username The username to be sanitized.
1293 * @param bool $strict If set limits $username to specific characters. Default false.
1294 * @return string The sanitized username, after passing through filters.
1296 function sanitize_user( $username, $strict = false ) {
1297 $raw_username = $username;
1298 $username = wp_strip_all_tags( $username );
1299 $username = remove_accents( $username );
1301 $username = preg_replace( '|%([a-fA-F0-9][a-fA-F0-9])|', '', $username );
1302 $username = preg_replace( '/&.+?;/', '', $username ); // Kill entities
1304 // If strict, reduce to ASCII for max portability.
1306 $username = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $username );
1308 $username = trim( $username );
1309 // Consolidate contiguous whitespace
1310 $username = preg_replace( '|\s+|', ' ', $username );
1313 * Filter a sanitized username string.
1317 * @param string $username Sanitized username.
1318 * @param string $raw_username The username prior to sanitization.
1319 * @param bool $strict Whether to limit the sanitization to specific characters. Default false.
1321 return apply_filters( 'sanitize_user', $username, $raw_username, $strict );
1325 * Sanitizes a string key.
1327 * Keys are used as internal identifiers. Lowercase alphanumeric characters, dashes and underscores are allowed.
1331 * @param string $key String key
1332 * @return string Sanitized key
1334 function sanitize_key( $key ) {
1336 $key = strtolower( $key );
1337 $key = preg_replace( '/[^a-z0-9_\-]/', '', $key );
1340 * Filter a sanitized key string.
1344 * @param string $key Sanitized key.
1345 * @param string $raw_key The key prior to sanitization.
1347 return apply_filters( 'sanitize_key', $key, $raw_key );
1351 * Sanitizes a title, or returns a fallback title.
1353 * Specifically, HTML and PHP tags are stripped. Further actions can be added
1354 * via the plugin API. If $title is empty and $fallback_title is set, the latter
1359 * @param string $title The string to be sanitized.
1360 * @param string $fallback_title Optional. A title to use if $title is empty.
1361 * @param string $context Optional. The operation for which the string is sanitized
1362 * @return string The sanitized string.
1364 function sanitize_title( $title, $fallback_title = '', $context = 'save' ) {
1365 $raw_title = $title;
1367 if ( 'save' == $context )
1368 $title = remove_accents($title);
1371 * Filter a sanitized title string.
1375 * @param string $title Sanitized title.
1376 * @param string $raw_title The title prior to sanitization.
1377 * @param string $context The context for which the title is being sanitized.
1379 $title = apply_filters( 'sanitize_title', $title, $raw_title, $context );
1381 if ( '' === $title || false === $title )
1382 $title = $fallback_title;
1388 * Sanitizes a title with the 'query' context.
1390 * Used for querying the database for a value from URL.
1394 * @param string $title The string to be sanitized.
1395 * @return string The sanitized string.
1397 function sanitize_title_for_query( $title ) {
1398 return sanitize_title( $title, '', 'query' );
1402 * Sanitizes a title, replacing whitespace and a few other characters with dashes.
1404 * Limits the output to alphanumeric characters, underscore (_) and dash (-).
1405 * Whitespace becomes a dash.
1409 * @param string $title The title to be sanitized.
1410 * @param string $raw_title Optional. Not used.
1411 * @param string $context Optional. The operation for which the string is sanitized.
1412 * @return string The sanitized title.
1414 function sanitize_title_with_dashes( $title, $raw_title = '', $context = 'display' ) {
1415 $title = strip_tags($title);
1416 // Preserve escaped octets.
1417 $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
1418 // Remove percent signs that are not part of an octet.
1419 $title = str_replace('%', '', $title);
1421 $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
1423 if (seems_utf8($title)) {
1424 if (function_exists('mb_strtolower')) {
1425 $title = mb_strtolower($title, 'UTF-8');
1427 $title = utf8_uri_encode($title, 200);
1430 $title = strtolower($title);
1431 $title = preg_replace('/&.+?;/', '', $title); // kill entities
1432 $title = str_replace('.', '-', $title);
1434 if ( 'save' == $context ) {
1435 // Convert nbsp, ndash and mdash to hyphens
1436 $title = str_replace( array( '%c2%a0', '%e2%80%93', '%e2%80%94' ), '-', $title );
1438 // Strip these characters entirely
1439 $title = str_replace( array(
1443 '%c2%ab', '%c2%bb', '%e2%80%b9', '%e2%80%ba',
1445 '%e2%80%98', '%e2%80%99', '%e2%80%9c', '%e2%80%9d',
1446 '%e2%80%9a', '%e2%80%9b', '%e2%80%9e', '%e2%80%9f',
1447 // copy, reg, deg, hellip and trade
1448 '%c2%a9', '%c2%ae', '%c2%b0', '%e2%80%a6', '%e2%84%a2',
1450 '%c2%b4', '%cb%8a', '%cc%81', '%cd%81',
1451 // grave accent, macron, caron
1452 '%cc%80', '%cc%84', '%cc%8c',
1455 // Convert times to x
1456 $title = str_replace( '%c3%97', 'x', $title );
1459 $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
1460 $title = preg_replace('/\s+/', '-', $title);
1461 $title = preg_replace('|-+|', '-', $title);
1462 $title = trim($title, '-');
1468 * Ensures a string is a valid SQL 'order by' clause.
1470 * Accepts one or more columns, with or without a sort order (ASC / DESC).
1471 * e.g. 'column_1', 'column_1, column_2', 'column_1 ASC, column_2 DESC' etc.
1473 * Also accepts 'RAND()'.
1477 * @param string $orderby Order by clause to be validated.
1478 * @return string|bool Returns $orderby if valid, false otherwise.
1480 function sanitize_sql_orderby( $orderby ) {
1481 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 ) ) {
1488 * Sanitizes an HTML classname to ensure it only contains valid characters.
1490 * Strips the string down to A-Z,a-z,0-9,_,-. If this results in an empty
1491 * string then it will return the alternative value supplied.
1493 * @todo Expand to support the full range of CDATA that a class attribute can contain.
1497 * @param string $class The classname to be sanitized
1498 * @param string $fallback Optional. The value to return if the sanitization ends up as an empty string.
1499 * Defaults to an empty string.
1500 * @return string The sanitized value
1502 function sanitize_html_class( $class, $fallback = '' ) {
1503 //Strip out any % encoded octets
1504 $sanitized = preg_replace( '|%[a-fA-F0-9][a-fA-F0-9]|', '', $class );
1506 //Limit to A-Z,a-z,0-9,_,-
1507 $sanitized = preg_replace( '/[^A-Za-z0-9_-]/', '', $sanitized );
1509 if ( '' == $sanitized )
1510 $sanitized = $fallback;
1513 * Filter a sanitized HTML class string.
1517 * @param string $sanitized The sanitized HTML class.
1518 * @param string $class HTML class before sanitization.
1519 * @param string $fallback The fallback string.
1521 return apply_filters( 'sanitize_html_class', $sanitized, $class, $fallback );
1525 * Converts a number of characters from a string.
1527 * Metadata tags `<title>` and `<category>` are removed, `<br>` and `<hr>` are
1528 * converted into correct XHTML and Unicode characters are converted to the
1533 * @param string $content String of characters to be converted.
1534 * @param string $deprecated Not used.
1535 * @return string Converted string.
1537 function convert_chars($content, $deprecated = '') {
1538 if ( !empty( $deprecated ) )
1539 _deprecated_argument( __FUNCTION__, '0.71' );
1541 // Translation of invalid Unicode references range to valid range
1542 $wp_htmltranswinuni = array(
1543 '€' => '€', // the Euro sign
1545 '‚' => '‚', // these are Windows CP1252 specific characters
1546 'ƒ' => 'ƒ', // they would look weird on non-Windows browsers
1547 '„' => '„',
1548 '…' => '…',
1549 '†' => '†',
1550 '‡' => '‡',
1551 'ˆ' => 'ˆ',
1552 '‰' => '‰',
1553 'Š' => 'Š',
1554 '‹' => '‹',
1555 'Œ' => 'Œ',
1557 'Ž' => 'Ž',
1560 '‘' => '‘',
1561 '’' => '’',
1562 '“' => '“',
1563 '”' => '”',
1564 '•' => '•',
1565 '–' => '–',
1566 '—' => '—',
1567 '˜' => '˜',
1568 '™' => '™',
1569 'š' => 'š',
1570 '›' => '›',
1571 'œ' => 'œ',
1573 'ž' => 'ž',
1574 'Ÿ' => 'Ÿ'
1577 // Remove metadata tags
1578 $content = preg_replace('/<title>(.+?)<\/title>/','',$content);
1579 $content = preg_replace('/<category>(.+?)<\/category>/','',$content);
1581 // Converts lone & characters into & (a.k.a. &)
1582 $content = preg_replace('/&([^#])(?![a-z1-4]{1,8};)/i', '&$1', $content);
1585 $content = strtr($content, $wp_htmltranswinuni);
1587 // Just a little XHTML help
1588 $content = str_replace('<br>', '<br />', $content);
1589 $content = str_replace('<hr>', '<hr />', $content);
1595 * Balances tags if forced to, or if the 'use_balanceTags' option is set to true.
1599 * @param string $text Text to be balanced
1600 * @param bool $force If true, forces balancing, ignoring the value of the option. Default false.
1601 * @return string Balanced text
1603 function balanceTags( $text, $force = false ) {
1604 if ( $force || get_option('use_balanceTags') == 1 ) {
1605 return force_balance_tags( $text );
1612 * Balances tags of string using a modified stack.
1616 * @author Leonard Lin <leonard@acm.org>
1618 * @copyright November 4, 2001
1620 * @todo Make better - change loop condition to $text in 1.2
1621 * @internal Modified by Scott Reilly (coffee2code) 02 Aug 2004
1622 * 1.1 Fixed handling of append/stack pop order of end text
1623 * Added Cleaning Hooks
1626 * @param string $text Text to be balanced.
1627 * @return string Balanced text.
1629 function force_balance_tags( $text ) {
1630 $tagstack = array();
1634 // Known single-entity/self-closing tags
1635 $single_tags = array( 'area', 'base', 'basefont', 'br', 'col', 'command', 'embed', 'frame', 'hr', 'img', 'input', 'isindex', 'link', 'meta', 'param', 'source' );
1636 // Tags that can be immediately nested within themselves
1637 $nestable_tags = array( 'blockquote', 'div', 'object', 'q', 'span' );
1639 // WP bug fix for comments - in case you REALLY meant to type '< !--'
1640 $text = str_replace('< !--', '< !--', $text);
1641 // WP bug fix for LOVE <3 (and other situations with '<' before a number)
1642 $text = preg_replace('#<([0-9]{1})#', '<$1', $text);
1644 while ( preg_match("/<(\/?[\w:]*)\s*([^>]*)>/", $text, $regex) ) {
1645 $newtext .= $tagqueue;
1647 $i = strpos($text, $regex[0]);
1648 $l = strlen($regex[0]);
1650 // clear the shifter
1653 if ( isset($regex[1][0]) && '/' == $regex[1][0] ) { // End Tag
1654 $tag = strtolower(substr($regex[1],1));
1655 // if too many closing tags
1656 if( $stacksize <= 0 ) {
1658 // or close to be safe $tag = '/' . $tag;
1660 // if stacktop value = tag close value then pop
1661 elseif ( $tagstack[$stacksize - 1] == $tag ) { // found closing tag
1662 $tag = '</' . $tag . '>'; // Close Tag
1664 array_pop( $tagstack );
1666 } else { // closing tag not at top, search for it
1667 for ( $j = $stacksize-1; $j >= 0; $j-- ) {
1668 if ( $tagstack[$j] == $tag ) {
1669 // add tag to tagqueue
1670 for ( $k = $stacksize-1; $k >= $j; $k--) {
1671 $tagqueue .= '</' . array_pop( $tagstack ) . '>';
1679 } else { // Begin Tag
1680 $tag = strtolower($regex[1]);
1684 // If it's an empty tag "< >", do nothing
1688 // ElseIf it presents itself as a self-closing tag...
1689 elseif ( substr( $regex[2], -1 ) == '/' ) {
1690 // ...but it isn't a known single-entity self-closing tag, then don't let it be treated as such and
1691 // immediately close it with a closing tag (the tag will encapsulate no text as a result)
1692 if ( ! in_array( $tag, $single_tags ) )
1693 $regex[2] = trim( substr( $regex[2], 0, -1 ) ) . "></$tag";
1695 // ElseIf it's a known single-entity tag but it doesn't close itself, do so
1696 elseif ( in_array($tag, $single_tags) ) {
1699 // Else it's not a single-entity tag
1701 // If the top of the stack is the same as the tag we want to push, close previous tag
1702 if ( $stacksize > 0 && !in_array($tag, $nestable_tags) && $tagstack[$stacksize - 1] == $tag ) {
1703 $tagqueue = '</' . array_pop( $tagstack ) . '>';
1706 $stacksize = array_push( $tagstack, $tag );
1710 $attributes = $regex[2];
1711 if( ! empty( $attributes ) && $attributes[0] != '>' )
1712 $attributes = ' ' . $attributes;
1714 $tag = '<' . $tag . $attributes . '>';
1715 //If already queuing a close tag, then put this tag on, too
1716 if ( !empty($tagqueue) ) {
1721 $newtext .= substr($text, 0, $i) . $tag;
1722 $text = substr($text, $i + $l);
1726 $newtext .= $tagqueue;
1728 // Add Remaining text
1732 while( $x = array_pop($tagstack) )
1733 $newtext .= '</' . $x . '>'; // Add remaining tags to close
1735 // WP fix for the bug with HTML comments
1736 $newtext = str_replace("< !--","<!--",$newtext);
1737 $newtext = str_replace("< !--","< !--",$newtext);
1743 * Acts on text which is about to be edited.
1745 * The $content is run through esc_textarea(), which uses htmlspecialchars()
1746 * to convert special characters to HTML entities. If $richedit is set to true,
1747 * it is simply a holder for the 'format_to_edit' filter.
1751 * @param string $content The text about to be edited.
1752 * @param bool $richedit Whether the $content should not pass through htmlspecialchars(). Default false (meaning it will be passed).
1753 * @return string The text after the filter (and possibly htmlspecialchars()) has been run.
1755 function format_to_edit( $content, $richedit = false ) {
1757 * Filter the text to be formatted for editing.
1761 * @param string $content The text, prior to formatting for editing.
1763 $content = apply_filters( 'format_to_edit', $content );
1765 $content = esc_textarea( $content );
1770 * Add leading zeros when necessary.
1772 * If you set the threshold to '4' and the number is '10', then you will get
1773 * back '0010'. If you set the threshold to '4' and the number is '5000', then you
1774 * will get back '5000'.
1776 * Uses sprintf to append the amount of zeros based on the $threshold parameter
1777 * and the size of the number. If the number is large enough, then no zeros will
1782 * @param mixed $number Number to append zeros to if not greater than threshold.
1783 * @param int $threshold Digit places number needs to be to not have zeros added.
1784 * @return string Adds leading zeros to number if needed.
1786 function zeroise($number, $threshold) {
1787 return sprintf('%0'.$threshold.'s', $number);
1791 * Adds backslashes before letters and before a number at the start of a string.
1795 * @param string $string Value to which backslashes will be added.
1796 * @return string String with backslashes inserted.
1798 function backslashit($string) {
1799 if ( isset( $string[0] ) && $string[0] >= '0' && $string[0] <= '9' )
1800 $string = '\\\\' . $string;
1801 return addcslashes( $string, 'A..Za..z' );
1805 * Appends a trailing slash.
1807 * Will remove trailing forward and backslashes if it exists already before adding
1808 * a trailing forward slash. This prevents double slashing a string or path.
1810 * The primary use of this is for paths and thus should be used for paths. It is
1811 * not restricted to paths and offers no specific path support.
1815 * @param string $string What to add the trailing slash to.
1816 * @return string String with trailing slash added.
1818 function trailingslashit( $string ) {
1819 return untrailingslashit( $string ) . '/';
1823 * Removes trailing forward slashes and backslashes if they exist.
1825 * The primary use of this is for paths and thus should be used for paths. It is
1826 * not restricted to paths and offers no specific path support.
1830 * @param string $string What to remove the trailing slashes from.
1831 * @return string String without the trailing slashes.
1833 function untrailingslashit( $string ) {
1834 return rtrim( $string, '/\\' );
1838 * Adds slashes to escape strings.
1840 * Slashes will first be removed if magic_quotes_gpc is set, see {@link
1841 * http://www.php.net/magic_quotes} for more details.
1845 * @param string $gpc The string returned from HTTP request data.
1846 * @return string Returns a string escaped with slashes.
1848 function addslashes_gpc($gpc) {
1849 if ( get_magic_quotes_gpc() )
1850 $gpc = stripslashes($gpc);
1852 return wp_slash($gpc);
1856 * Navigates through an array and removes slashes from the values.
1858 * If an array is passed, the array_map() function causes a callback to pass the
1859 * value back to the function. The slashes from this value will removed.
1863 * @param mixed $value The value to be stripped.
1864 * @return mixed Stripped value.
1866 function stripslashes_deep($value) {
1867 if ( is_array($value) ) {
1868 $value = array_map('stripslashes_deep', $value);
1869 } elseif ( is_object($value) ) {
1870 $vars = get_object_vars( $value );
1871 foreach ($vars as $key=>$data) {
1872 $value->{$key} = stripslashes_deep( $data );
1874 } elseif ( is_string( $value ) ) {
1875 $value = stripslashes($value);
1882 * Navigates through an array and encodes the values to be used in a URL.
1887 * @param array|string $value The array or string to be encoded.
1888 * @return array|string $value The encoded array (or string from the callback).
1890 function urlencode_deep($value) {
1891 $value = is_array($value) ? array_map('urlencode_deep', $value) : urlencode($value);
1896 * Navigates through an array and raw encodes the values to be used in a URL.
1900 * @param array|string $value The array or string to be encoded.
1901 * @return array|string $value The encoded array (or string from the callback).
1903 function rawurlencode_deep( $value ) {
1904 return is_array( $value ) ? array_map( 'rawurlencode_deep', $value ) : rawurlencode( $value );
1908 * Converts email addresses characters to HTML entities to block spam bots.
1912 * @param string $email_address Email address.
1913 * @param int $hex_encoding Optional. Set to 1 to enable hex encoding.
1914 * @return string Converted email address.
1916 function antispambot( $email_address, $hex_encoding = 0 ) {
1917 $email_no_spam_address = '';
1918 for ( $i = 0, $len = strlen( $email_address ); $i < $len; $i++ ) {
1919 $j = rand( 0, 1 + $hex_encoding );
1921 $email_no_spam_address .= '&#' . ord( $email_address[$i] ) . ';';
1922 } elseif ( $j == 1 ) {
1923 $email_no_spam_address .= $email_address[$i];
1924 } elseif ( $j == 2 ) {
1925 $email_no_spam_address .= '%' . zeroise( dechex( ord( $email_address[$i] ) ), 2 );
1929 $email_no_spam_address = str_replace( '@', '@', $email_no_spam_address );
1931 return $email_no_spam_address;
1935 * Callback to convert URI match to HTML A element.
1937 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1938 * make_clickable()}.
1943 * @param array $matches Single Regex Match.
1944 * @return string HTML A element with URI address.
1946 function _make_url_clickable_cb($matches) {
1949 if ( ')' == $matches[3] && strpos( $url, '(' ) ) {
1950 // If the trailing character is a closing parethesis, and the URL has an opening parenthesis in it, add the closing parenthesis to the URL.
1951 // Then we can let the parenthesis balancer do its thing below.
1952 $url .= $matches[3];
1955 $suffix = $matches[3];
1958 // Include parentheses in the URL only if paired
1959 while ( substr_count( $url, '(' ) < substr_count( $url, ')' ) ) {
1960 $suffix = strrchr( $url, ')' ) . $suffix;
1961 $url = substr( $url, 0, strrpos( $url, ')' ) );
1964 $url = esc_url($url);
1968 return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $suffix;
1972 * Callback to convert URL match to HTML A element.
1974 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1975 * make_clickable()}.
1980 * @param array $matches Single Regex Match.
1981 * @return string HTML A element with URL address.
1983 function _make_web_ftp_clickable_cb($matches) {
1985 $dest = $matches[2];
1986 $dest = 'http://' . $dest;
1987 $dest = esc_url($dest);
1991 // removed trailing [.,;:)] from URL
1992 if ( in_array( substr($dest, -1), array('.', ',', ';', ':', ')') ) === true ) {
1993 $ret = substr($dest, -1);
1994 $dest = substr($dest, 0, strlen($dest)-1);
1996 return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>$ret";
2000 * Callback to convert email address match to HTML A element.
2002 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
2003 * make_clickable()}.
2008 * @param array $matches Single Regex Match.
2009 * @return string HTML A element with email address.
2011 function _make_email_clickable_cb($matches) {
2012 $email = $matches[2] . '@' . $matches[3];
2013 return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
2017 * Convert plaintext URI to HTML links.
2019 * Converts URI, www and ftp, and email addresses. Finishes by fixing links
2024 * @param string $text Content to convert URIs.
2025 * @return string Content with converted URIs.
2027 function make_clickable( $text ) {
2029 $textarr = preg_split( '/(<[^<>]+>)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // split out HTML tags
2030 $nested_code_pre = 0; // Keep track of how many levels link is nested inside <pre> or <code>
2031 foreach ( $textarr as $piece ) {
2033 if ( preg_match( '|^<code[\s>]|i', $piece ) || preg_match( '|^<pre[\s>]|i', $piece ) )
2035 elseif ( ( '</code>' === strtolower( $piece ) || '</pre>' === strtolower( $piece ) ) && $nested_code_pre )
2038 if ( $nested_code_pre || empty( $piece ) || ( $piece[0] === '<' && ! preg_match( '|^<\s*[\w]{1,20}+://|', $piece ) ) ) {
2043 // Long strings might contain expensive edge cases ...
2044 if ( 10000 < strlen( $piece ) ) {
2046 foreach ( _split_str_by_whitespace( $piece, 2100 ) as $chunk ) { // 2100: Extra room for scheme and leading and trailing paretheses
2047 if ( 2101 < strlen( $chunk ) ) {
2048 $r .= $chunk; // Too big, no whitespace: bail.
2050 $r .= make_clickable( $chunk );
2054 $ret = " $piece "; // Pad with whitespace to simplify the regexes
2057 ([\\s(<.,;:!?]) # 1: Leading whitespace, or punctuation
2059 [\\w]{1,20}+:// # Scheme and hier-part prefix
2060 (?=\S{1,2000}\s) # Limit to URLs less than about 2000 characters long
2061 [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]*+ # Non-punctuation URL character
2062 (?: # Unroll the Loop: Only allow puctuation URL character if followed by a non-punctuation URL character
2063 [\'.,;:!?)] # Punctuation URL character
2064 [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]++ # Non-punctuation URL character
2067 (\)?) # 3: Trailing closing parenthesis (for parethesis balancing post processing)
2068 ~xS'; // The regex is a non-anchored pattern and does not have a single fixed starting character.
2069 // Tell PCRE to spend more time optimizing since, when used on a page load, it will probably be used several times.
2071 $ret = preg_replace_callback( $url_clickable, '_make_url_clickable_cb', $ret );
2073 $ret = preg_replace_callback( '#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]+)#is', '_make_web_ftp_clickable_cb', $ret );
2074 $ret = preg_replace_callback( '#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret );
2076 $ret = substr( $ret, 1, -1 ); // Remove our whitespace padding.
2081 // Cleanup of accidental links within links
2082 $r = preg_replace( '#(<a([ \r\n\t]+[^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i', "$1$3</a>", $r );
2087 * Breaks a string into chunks by splitting at whitespace characters.
2088 * The length of each returned chunk is as close to the specified length goal as possible,
2089 * with the caveat that each chunk includes its trailing delimiter.
2090 * Chunks longer than the goal are guaranteed to not have any inner whitespace.
2092 * Joining the returned chunks with empty delimiters reconstructs the input string losslessly.
2094 * Input string must have no null characters (or eventual transformations on output chunks must not care about null characters)
2096 * _split_str_by_whitespace( "1234 67890 1234 67890a cd 1234 890 123456789 1234567890a 45678 1 3 5 7 90 ", 10 ) ==
2098 * 0 => '1234 67890 ', // 11 characters: Perfect split
2099 * 1 => '1234 ', // 5 characters: '1234 67890a' was too long
2100 * 2 => '67890a cd ', // 10 characters: '67890a cd 1234' was too long
2101 * 3 => '1234 890 ', // 11 characters: Perfect split
2102 * 4 => '123456789 ', // 10 characters: '123456789 1234567890a' was too long
2103 * 5 => '1234567890a ', // 12 characters: Too long, but no inner whitespace on which to split
2104 * 6 => ' 45678 ', // 11 characters: Perfect split
2105 * 7 => '1 3 5 7 90 ', // 11 characters: End of $string
2111 * @param string $string The string to split.
2112 * @param int $goal The desired chunk length.
2113 * @return array Numeric array of chunks.
2115 function _split_str_by_whitespace( $string, $goal ) {
2118 $string_nullspace = strtr( $string, "\r\n\t\v\f ", "\000\000\000\000\000\000" );
2120 while ( $goal < strlen( $string_nullspace ) ) {
2121 $pos = strrpos( substr( $string_nullspace, 0, $goal + 1 ), "\000" );
2123 if ( false === $pos ) {
2124 $pos = strpos( $string_nullspace, "\000", $goal + 1 );
2125 if ( false === $pos ) {
2130 $chunks[] = substr( $string, 0, $pos + 1 );
2131 $string = substr( $string, $pos + 1 );
2132 $string_nullspace = substr( $string_nullspace, $pos + 1 );
2136 $chunks[] = $string;
2143 * Adds rel nofollow string to all HTML A elements in content.
2147 * @param string $text Content that may contain HTML A elements.
2148 * @return string Converted content.
2150 function wp_rel_nofollow( $text ) {
2151 // This is a pre save filter, so text is already escaped.
2152 $text = stripslashes($text);
2153 $text = preg_replace_callback('|<a (.+?)>|i', 'wp_rel_nofollow_callback', $text);
2154 $text = wp_slash($text);
2159 * Callback to add rel=nofollow string to HTML A element.
2161 * Will remove already existing rel="nofollow" and rel='nofollow' from the
2162 * string to prevent from invalidating (X)HTML.
2166 * @param array $matches Single Match
2167 * @return string HTML A Element with rel nofollow.
2169 function wp_rel_nofollow_callback( $matches ) {
2170 $text = $matches[1];
2171 $text = str_replace(array(' rel="nofollow"', " rel='nofollow'"), '', $text);
2172 return "<a $text rel=\"nofollow\">";
2176 * Convert one smiley code to the icon graphic file equivalent.
2178 * Callback handler for {@link convert_smilies()}.
2179 * Looks up one smiley code in the $wpsmiliestrans global array and returns an
2180 * `<img>` string for that smiley.
2182 * @global array $wpsmiliestrans
2185 * @param array $matches Single match. Smiley code to convert to image.
2186 * @return string Image string for smiley.
2188 function translate_smiley( $matches ) {
2189 global $wpsmiliestrans;
2191 if ( count( $matches ) == 0 )
2194 $smiley = trim( reset( $matches ) );
2195 $img = $wpsmiliestrans[ $smiley ];
2198 $ext = preg_match( '/\.([^.]+)$/', $img, $matches ) ? strtolower( $matches[1] ) : false;
2199 $image_exts = array( 'jpg', 'jpeg', 'jpe', 'gif', 'png' );
2201 // Don't convert smilies that aren't images - they're probably emoji.
2202 if ( ! in_array( $ext, $image_exts ) ) {
2207 * Filter the Smiley image URL before it's used in the image element.
2211 * @param string $smiley_url URL for the smiley image.
2212 * @param string $img Filename for the smiley image.
2213 * @param string $site_url Site URL, as returned by site_url().
2215 $src_url = apply_filters( 'smilies_src', includes_url( "images/smilies/$img" ), $img, site_url() );
2217 return sprintf( '<img src="%s" alt="%s" class="wp-smiley" style="height: 1em; max-height: 1em;" />', esc_url( $src_url ), esc_attr( $smiley ) );
2221 * Convert text equivalent of smilies to images.
2223 * Will only convert smilies if the option 'use_smilies' is true and the global
2224 * used in the function isn't empty.
2227 * @uses $wp_smiliessearch
2229 * @param string $text Content to convert smilies from text.
2230 * @return string Converted content with text smilies replaced with images.
2232 function convert_smilies( $text ) {
2233 global $wp_smiliessearch;
2235 if ( get_option( 'use_smilies' ) && ! empty( $wp_smiliessearch ) ) {
2236 // HTML loop taken from texturize function, could possible be consolidated
2237 $textarr = preg_split( '/(<.*>)/U', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // capture the tags as well as in between
2238 $stop = count( $textarr );// loop stuff
2240 // Ignore proessing of specific tags
2241 $tags_to_ignore = 'code|pre|style|script|textarea';
2242 $ignore_block_element = '';
2244 for ( $i = 0; $i < $stop; $i++ ) {
2245 $content = $textarr[$i];
2247 // If we're in an ignore block, wait until we find its closing tag
2248 if ( '' == $ignore_block_element && preg_match( '/^<(' . $tags_to_ignore . ')>/', $content, $matches ) ) {
2249 $ignore_block_element = $matches[1];
2252 // If it's not a tag and not in ignore block
2253 if ( '' == $ignore_block_element && strlen( $content ) > 0 && '<' != $content[0] ) {
2254 $content = preg_replace_callback( $wp_smiliessearch, 'translate_smiley', $content );
2257 // did we exit ignore block
2258 if ( '' != $ignore_block_element && '</' . $ignore_block_element . '>' == $content ) {
2259 $ignore_block_element = '';
2262 $output .= $content;
2265 // return default text.
2272 * Verifies that an email is valid.
2274 * Does not grok i18n domains. Not RFC compliant.
2278 * @param string $email Email address to verify.
2279 * @param boolean $deprecated Deprecated.
2280 * @return string|bool Either false or the valid email address.
2282 function is_email( $email, $deprecated = false ) {
2283 if ( ! empty( $deprecated ) )
2284 _deprecated_argument( __FUNCTION__, '3.0' );
2286 // Test for the minimum length the email can be
2287 if ( strlen( $email ) < 3 ) {
2289 * Filter whether an email address is valid.
2291 * This filter is evaluated under several different contexts, such as 'email_too_short',
2292 * 'email_no_at', 'local_invalid_chars', 'domain_period_sequence', 'domain_period_limits',
2293 * 'domain_no_periods', 'sub_hyphen_limits', 'sub_invalid_chars', or no specific context.
2297 * @param bool $is_email Whether the email address has passed the is_email() checks. Default false.
2298 * @param string $email The email address being checked.
2299 * @param string $message An explanatory message to the user.
2300 * @param string $context Context under which the email was tested.
2302 return apply_filters( 'is_email', false, $email, 'email_too_short' );
2305 // Test for an @ character after the first position
2306 if ( strpos( $email, '@', 1 ) === false ) {
2307 /** This filter is documented in wp-includes/formatting.php */
2308 return apply_filters( 'is_email', false, $email, 'email_no_at' );
2311 // Split out the local and domain parts
2312 list( $local, $domain ) = explode( '@', $email, 2 );
2315 // Test for invalid characters
2316 if ( !preg_match( '/^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]+$/', $local ) ) {
2317 /** This filter is documented in wp-includes/formatting.php */
2318 return apply_filters( 'is_email', false, $email, 'local_invalid_chars' );
2322 // Test for sequences of periods
2323 if ( preg_match( '/\.{2,}/', $domain ) ) {
2324 /** This filter is documented in wp-includes/formatting.php */
2325 return apply_filters( 'is_email', false, $email, 'domain_period_sequence' );
2328 // Test for leading and trailing periods and whitespace
2329 if ( trim( $domain, " \t\n\r\0\x0B." ) !== $domain ) {
2330 /** This filter is documented in wp-includes/formatting.php */
2331 return apply_filters( 'is_email', false, $email, 'domain_period_limits' );
2334 // Split the domain into subs
2335 $subs = explode( '.', $domain );
2337 // Assume the domain will have at least two subs
2338 if ( 2 > count( $subs ) ) {
2339 /** This filter is documented in wp-includes/formatting.php */
2340 return apply_filters( 'is_email', false, $email, 'domain_no_periods' );
2343 // Loop through each sub
2344 foreach ( $subs as $sub ) {
2345 // Test for leading and trailing hyphens and whitespace
2346 if ( trim( $sub, " \t\n\r\0\x0B-" ) !== $sub ) {
2347 /** This filter is documented in wp-includes/formatting.php */
2348 return apply_filters( 'is_email', false, $email, 'sub_hyphen_limits' );
2351 // Test for invalid characters
2352 if ( !preg_match('/^[a-z0-9-]+$/i', $sub ) ) {
2353 /** This filter is documented in wp-includes/formatting.php */
2354 return apply_filters( 'is_email', false, $email, 'sub_invalid_chars' );
2358 // Congratulations your email made it!
2359 /** This filter is documented in wp-includes/formatting.php */
2360 return apply_filters( 'is_email', $email, $email, null );
2364 * Convert to ASCII from email subjects.
2368 * @param string $string Subject line
2369 * @return string Converted string to ASCII
2371 function wp_iso_descrambler($string) {
2372 /* this may only work with iso-8859-1, I'm afraid */
2373 if (!preg_match('#\=\?(.+)\?Q\?(.+)\?\=#i', $string, $matches)) {
2376 $subject = str_replace('_', ' ', $matches[2]);
2377 $subject = preg_replace_callback('#\=([0-9a-f]{2})#i', '_wp_iso_convert', $subject);
2383 * Helper function to convert hex encoded chars to ASCII
2388 * @param array $match The preg_replace_callback matches array
2389 * @return string Converted chars
2391 function _wp_iso_convert( $match ) {
2392 return chr( hexdec( strtolower( $match[1] ) ) );
2396 * Returns a date in the GMT equivalent.
2398 * Requires and returns a date in the Y-m-d H:i:s format. If there is a
2399 * timezone_string available, the date is assumed to be in that timezone,
2400 * otherwise it simply subtracts the value of the 'gmt_offset' option. Return
2401 * format can be overridden using the $format parameter.
2405 * @param string $string The date to be converted.
2406 * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
2407 * @return string GMT version of the date provided.
2409 function get_gmt_from_date( $string, $format = 'Y-m-d H:i:s' ) {
2410 $tz = get_option( 'timezone_string' );
2412 $datetime = date_create( $string, new DateTimeZone( $tz ) );
2414 return gmdate( $format, 0 );
2415 $datetime->setTimezone( new DateTimeZone( 'UTC' ) );
2416 $string_gmt = $datetime->format( $format );
2418 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 ) )
2419 return gmdate( $format, 0 );
2420 $string_time = gmmktime( $matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1] );
2421 $string_gmt = gmdate( $format, $string_time - get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
2427 * Converts a GMT date into the correct format for the blog.
2429 * Requires and returns a date in the Y-m-d H:i:s format. If there is a
2430 * timezone_string available, the returned date is in that timezone, otherwise
2431 * it simply adds the value of gmt_offset. Return format can be overridden
2432 * using the $format parameter
2436 * @param string $string The date to be converted.
2437 * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
2438 * @return string Formatted date relative to the timezone / GMT offset.
2440 function get_date_from_gmt( $string, $format = 'Y-m-d H:i:s' ) {
2441 $tz = get_option( 'timezone_string' );
2443 $datetime = date_create( $string, new DateTimeZone( 'UTC' ) );
2445 return date( $format, 0 );
2446 $datetime->setTimezone( new DateTimeZone( $tz ) );
2447 $string_localtime = $datetime->format( $format );
2449 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) )
2450 return date( $format, 0 );
2451 $string_time = gmmktime( $matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1] );
2452 $string_localtime = gmdate( $format, $string_time + get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
2454 return $string_localtime;
2458 * Computes an offset in seconds from an iso8601 timezone.
2462 * @param string $timezone Either 'Z' for 0 offset or '±hhmm'.
2463 * @return int|float The offset in seconds.
2465 function iso8601_timezone_to_offset($timezone) {
2466 // $timezone is either 'Z' or '[+|-]hhmm'
2467 if ($timezone == 'Z') {
2470 $sign = (substr($timezone, 0, 1) == '+') ? 1 : -1;
2471 $hours = intval(substr($timezone, 1, 2));
2472 $minutes = intval(substr($timezone, 3, 4)) / 60;
2473 $offset = $sign * HOUR_IN_SECONDS * ($hours + $minutes);
2479 * Converts an iso8601 date to MySQL DateTime format used by post_date[_gmt].
2483 * @param string $date_string Date and time in ISO 8601 format {@link http://en.wikipedia.org/wiki/ISO_8601}.
2484 * @param string $timezone Optional. If set to GMT returns the time minus gmt_offset. Default is 'user'.
2485 * @return string The date and time in MySQL DateTime format - Y-m-d H:i:s.
2487 function iso8601_to_datetime($date_string, $timezone = 'user') {
2488 $timezone = strtolower($timezone);
2490 if ($timezone == 'gmt') {
2492 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);
2494 if (!empty($date_bits[7])) { // we have a timezone, so let's compute an offset
2495 $offset = iso8601_timezone_to_offset($date_bits[7]);
2496 } else { // we don't have a timezone, so we assume user local timezone (not server's!)
2497 $offset = HOUR_IN_SECONDS * get_option('gmt_offset');
2500 $timestamp = gmmktime($date_bits[4], $date_bits[5], $date_bits[6], $date_bits[2], $date_bits[3], $date_bits[1]);
2501 $timestamp -= $offset;
2503 return gmdate('Y-m-d H:i:s', $timestamp);
2505 } elseif ($timezone == 'user') {
2506 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);
2511 * Adds a element attributes to open links in new windows.
2513 * Comment text in popup windows should be filtered through this. Right now it's
2514 * a moderately dumb function, ideally it would detect whether a target or rel
2515 * attribute was already there and adjust its actions accordingly.
2519 * @param string $text Content to replace links to open in a new window.
2520 * @return string Content that has filtered links.
2522 function popuplinks($text) {
2523 $text = preg_replace('/<a (.+?)>/i', "<a $1 target='_blank' rel='external'>", $text);
2528 * Strips out all characters that are not allowable in an email.
2532 * @param string $email Email address to filter.
2533 * @return string Filtered email address.
2535 function sanitize_email( $email ) {
2536 // Test for the minimum length the email can be
2537 if ( strlen( $email ) < 3 ) {
2539 * Filter a sanitized email address.
2541 * This filter is evaluated under several contexts, including 'email_too_short',
2542 * 'email_no_at', 'local_invalid_chars', 'domain_period_sequence', 'domain_period_limits',
2543 * 'domain_no_periods', 'domain_no_valid_subs', or no context.
2547 * @param string $email The sanitized email address.
2548 * @param string $email The email address, as provided to sanitize_email().
2549 * @param string $message A message to pass to the user.
2551 return apply_filters( 'sanitize_email', '', $email, 'email_too_short' );
2554 // Test for an @ character after the first position
2555 if ( strpos( $email, '@', 1 ) === false ) {
2556 /** This filter is documented in wp-includes/formatting.php */
2557 return apply_filters( 'sanitize_email', '', $email, 'email_no_at' );
2560 // Split out the local and domain parts
2561 list( $local, $domain ) = explode( '@', $email, 2 );
2564 // Test for invalid characters
2565 $local = preg_replace( '/[^a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]/', '', $local );
2566 if ( '' === $local ) {
2567 /** This filter is documented in wp-includes/formatting.php */
2568 return apply_filters( 'sanitize_email', '', $email, 'local_invalid_chars' );
2572 // Test for sequences of periods
2573 $domain = preg_replace( '/\.{2,}/', '', $domain );
2574 if ( '' === $domain ) {
2575 /** This filter is documented in wp-includes/formatting.php */
2576 return apply_filters( 'sanitize_email', '', $email, 'domain_period_sequence' );
2579 // Test for leading and trailing periods and whitespace
2580 $domain = trim( $domain, " \t\n\r\0\x0B." );
2581 if ( '' === $domain ) {
2582 /** This filter is documented in wp-includes/formatting.php */
2583 return apply_filters( 'sanitize_email', '', $email, 'domain_period_limits' );
2586 // Split the domain into subs
2587 $subs = explode( '.', $domain );
2589 // Assume the domain will have at least two subs
2590 if ( 2 > count( $subs ) ) {
2591 /** This filter is documented in wp-includes/formatting.php */
2592 return apply_filters( 'sanitize_email', '', $email, 'domain_no_periods' );
2595 // Create an array that will contain valid subs
2596 $new_subs = array();
2598 // Loop through each sub
2599 foreach ( $subs as $sub ) {
2600 // Test for leading and trailing hyphens
2601 $sub = trim( $sub, " \t\n\r\0\x0B-" );
2603 // Test for invalid characters
2604 $sub = preg_replace( '/[^a-z0-9-]+/i', '', $sub );
2606 // If there's anything left, add it to the valid subs
2607 if ( '' !== $sub ) {
2612 // If there aren't 2 or more valid subs
2613 if ( 2 > count( $new_subs ) ) {
2614 /** This filter is documented in wp-includes/formatting.php */
2615 return apply_filters( 'sanitize_email', '', $email, 'domain_no_valid_subs' );
2618 // Join valid subs into the new domain
2619 $domain = join( '.', $new_subs );
2621 // Put the email back together
2622 $email = $local . '@' . $domain;
2624 // Congratulations your email made it!
2625 /** This filter is documented in wp-includes/formatting.php */
2626 return apply_filters( 'sanitize_email', $email, $email, null );
2630 * Determines the difference between two timestamps.
2632 * The difference is returned in a human readable format such as "1 hour",
2633 * "5 mins", "2 days".
2637 * @param int $from Unix timestamp from which the difference begins.
2638 * @param int $to Optional. Unix timestamp to end the time difference. Default becomes time() if not set.
2639 * @return string Human readable time difference.
2641 function human_time_diff( $from, $to = '' ) {
2642 if ( empty( $to ) ) {
2646 $diff = (int) abs( $to - $from );
2648 if ( $diff < HOUR_IN_SECONDS ) {
2649 $mins = round( $diff / MINUTE_IN_SECONDS );
2652 /* translators: min=minute */
2653 $since = sprintf( _n( '%s min', '%s mins', $mins ), $mins );
2654 } elseif ( $diff < DAY_IN_SECONDS && $diff >= HOUR_IN_SECONDS ) {
2655 $hours = round( $diff / HOUR_IN_SECONDS );
2658 $since = sprintf( _n( '%s hour', '%s hours', $hours ), $hours );
2659 } elseif ( $diff < WEEK_IN_SECONDS && $diff >= DAY_IN_SECONDS ) {
2660 $days = round( $diff / DAY_IN_SECONDS );
2663 $since = sprintf( _n( '%s day', '%s days', $days ), $days );
2664 } elseif ( $diff < 30 * DAY_IN_SECONDS && $diff >= WEEK_IN_SECONDS ) {
2665 $weeks = round( $diff / WEEK_IN_SECONDS );
2668 $since = sprintf( _n( '%s week', '%s weeks', $weeks ), $weeks );
2669 } elseif ( $diff < YEAR_IN_SECONDS && $diff >= 30 * DAY_IN_SECONDS ) {
2670 $months = round( $diff / ( 30 * DAY_IN_SECONDS ) );
2673 $since = sprintf( _n( '%s month', '%s months', $months ), $months );
2674 } elseif ( $diff >= YEAR_IN_SECONDS ) {
2675 $years = round( $diff / YEAR_IN_SECONDS );
2678 $since = sprintf( _n( '%s year', '%s years', $years ), $years );
2682 * Filter the human readable difference between two timestamps.
2686 * @param string $since The difference in human readable text.
2687 * @param int $diff The difference in seconds.
2688 * @param int $from Unix timestamp from which the difference begins.
2689 * @param int $to Unix timestamp to end the time difference.
2691 return apply_filters( 'human_time_diff', $since, $diff, $from, $to );
2695 * Generates an excerpt from the content, if needed.
2697 * The excerpt word amount will be 55 words and if the amount is greater than
2698 * that, then the string ' […]' will be appended to the excerpt. If the string
2699 * is less than 55 words, then the content will be returned as is.
2701 * The 55 word limit can be modified by plugins/themes using the excerpt_length filter
2702 * The ' […]' string can be modified by plugins/themes using the excerpt_more filter
2706 * @param string $text Optional. The excerpt. If set to empty, an excerpt is generated.
2707 * @return string The excerpt.
2709 function wp_trim_excerpt($text = '') {
2710 $raw_excerpt = $text;
2711 if ( '' == $text ) {
2712 $text = get_the_content('');
2714 $text = strip_shortcodes( $text );
2716 /** This filter is documented in wp-includes/post-template.php */
2717 $text = apply_filters( 'the_content', $text );
2718 $text = str_replace(']]>', ']]>', $text);
2721 * Filter the number of words in an excerpt.
2725 * @param int $number The number of words. Default 55.
2727 $excerpt_length = apply_filters( 'excerpt_length', 55 );
2729 * Filter the string in the "more" link displayed after a trimmed excerpt.
2733 * @param string $more_string The string shown within the more link.
2735 $excerpt_more = apply_filters( 'excerpt_more', ' ' . '[…]' );
2736 $text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
2739 * Filter the trimmed excerpt string.
2743 * @param string $text The trimmed text.
2744 * @param string $raw_excerpt The text prior to trimming.
2746 return apply_filters( 'wp_trim_excerpt', $text, $raw_excerpt );
2750 * Trims text to a certain number of words.
2752 * This function is localized. For languages that count 'words' by the individual
2753 * character (such as East Asian languages), the $num_words argument will apply
2754 * to the number of individual characters.
2758 * @param string $text Text to trim.
2759 * @param int $num_words Number of words. Default 55.
2760 * @param string $more Optional. What to append if $text needs to be trimmed. Default '…'.
2761 * @return string Trimmed text.
2763 function wp_trim_words( $text, $num_words = 55, $more = null ) {
2764 if ( null === $more )
2765 $more = __( '…' );
2766 $original_text = $text;
2767 $text = wp_strip_all_tags( $text );
2768 /* translators: If your word count is based on single characters (East Asian characters),
2769 enter 'characters'. Otherwise, enter 'words'. Do not translate into your own language. */
2770 if ( 'characters' == _x( 'words', 'word count: words or characters?' ) && preg_match( '/^utf\-?8$/i', get_option( 'blog_charset' ) ) ) {
2771 $text = trim( preg_replace( "/[\n\r\t ]+/", ' ', $text ), ' ' );
2772 preg_match_all( '/./u', $text, $words_array );
2773 $words_array = array_slice( $words_array[0], 0, $num_words + 1 );
2776 $words_array = preg_split( "/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY );
2779 if ( count( $words_array ) > $num_words ) {
2780 array_pop( $words_array );
2781 $text = implode( $sep, $words_array );
2782 $text = $text . $more;
2784 $text = implode( $sep, $words_array );
2787 * Filter the text content after words have been trimmed.
2791 * @param string $text The trimmed text.
2792 * @param int $num_words The number of words to trim the text to. Default 5.
2793 * @param string $more An optional string to append to the end of the trimmed text, e.g. ….
2794 * @param string $original_text The text before it was trimmed.
2796 return apply_filters( 'wp_trim_words', $text, $num_words, $more, $original_text );
2800 * Converts named entities into numbered entities.
2804 * @param string $text The text within which entities will be converted.
2805 * @return string Text with converted entities.
2807 function ent2ncr($text) {
2810 * Filter text before named entities are converted into numbered entities.
2812 * A non-null string must be returned for the filter to be evaluated.
2816 * @param null $converted_text The text to be converted. Default null.
2817 * @param string $text The text prior to entity conversion.
2819 $filtered = apply_filters( 'pre_ent2ncr', null, $text );
2820 if( null !== $filtered )
2824 '"' => '"',
2829 ' ' => ' ',
2830 '¡' => '¡',
2831 '¢' => '¢',
2832 '£' => '£',
2833 '¤' => '¤',
2834 '¥' => '¥',
2835 '¦' => '¦',
2836 '&brkbar;' => '¦',
2837 '§' => '§',
2838 '¨' => '¨',
2839 '¨' => '¨',
2840 '©' => '©',
2841 'ª' => 'ª',
2842 '«' => '«',
2843 '¬' => '¬',
2844 '­' => '­',
2845 '®' => '®',
2846 '¯' => '¯',
2847 '&hibar;' => '¯',
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 'ò' => 'ò',
2915 'ó' => 'ó',
2916 'ô' => 'ô',
2917 'õ' => 'õ',
2918 'ö' => 'ö',
2919 '÷' => '÷',
2920 'ø' => 'ø',
2921 'ù' => 'ù',
2922 'ú' => 'ú',
2923 'û' => 'û',
2924 'ü' => 'ü',
2925 'ý' => 'ý',
2926 'þ' => 'þ',
2927 'ÿ' => 'ÿ',
2928 'Œ' => 'Œ',
2929 'œ' => 'œ',
2930 'Š' => 'Š',
2931 'š' => 'š',
2932 'Ÿ' => 'Ÿ',
2933 'ƒ' => 'ƒ',
2934 'ˆ' => 'ˆ',
2935 '˜' => '˜',
2936 'Α' => 'Α',
2937 'Β' => 'Β',
2938 'Γ' => 'Γ',
2939 'Δ' => 'Δ',
2940 'Ε' => 'Ε',
2941 'Ζ' => 'Ζ',
2942 'Η' => 'Η',
2943 'Θ' => 'Θ',
2944 'Ι' => 'Ι',
2945 'Κ' => 'Κ',
2946 'Λ' => 'Λ',
2950 'Ο' => 'Ο',
2952 'Ρ' => 'Ρ',
2953 'Σ' => 'Σ',
2954 'Τ' => 'Τ',
2955 'Υ' => 'Υ',
2956 'Φ' => 'Φ',
2957 'Χ' => 'Χ',
2958 'Ψ' => 'Ψ',
2959 'Ω' => 'Ω',
2960 'α' => 'α',
2961 'β' => 'β',
2962 'γ' => 'γ',
2963 'δ' => 'δ',
2964 'ε' => 'ε',
2965 'ζ' => 'ζ',
2966 'η' => 'η',
2967 'θ' => 'θ',
2968 'ι' => 'ι',
2969 'κ' => 'κ',
2970 'λ' => 'λ',
2974 'ο' => 'ο',
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 '∴' => '∴',
3048 '∼' => '∼',
3049 '≅' => '≅',
3050 '≈' => '≈',
3051 '≠' => '≠',
3052 '≡' => '≡',
3053 '≤' => '≤',
3054 '≥' => '≥',
3055 '⊂' => '⊂',
3056 '⊃' => '⊃',
3057 '⊄' => '⊄',
3058 '⊆' => '⊆',
3059 '⊇' => '⊇',
3060 '⊕' => '⊕',
3061 '⊗' => '⊗',
3062 '⊥' => '⊥',
3063 '⋅' => '⋅',
3064 '⌈' => '⌈',
3065 '⌉' => '⌉',
3066 '⌊' => '⌊',
3067 '⌋' => '⌋',
3068 '⟨' => '〈',
3069 '⟩' => '〉',
3070 '←' => '←',
3071 '↑' => '↑',
3072 '→' => '→',
3073 '↓' => '↓',
3074 '↔' => '↔',
3075 '◊' => '◊',
3076 '♠' => '♠',
3077 '♣' => '♣',
3078 '♥' => '♥',
3079 '♦' => '♦'
3082 return str_replace( array_keys($to_ncr), array_values($to_ncr), $text );
3086 * Formats text for the rich text editor.
3088 * The filter 'richedit_pre' is applied here. If $text is empty the filter will
3089 * be applied to an empty string.
3093 * @param string $text The text to be formatted.
3094 * @return string The formatted text after filter is applied.
3096 function wp_richedit_pre($text) {
3097 if ( empty( $text ) ) {
3099 * Filter text returned for the rich text editor.
3101 * This filter is first evaluated, and the value returned, if an empty string
3102 * is passed to wp_richedit_pre(). If an empty string is passed, it results
3103 * in a break tag and line feed.
3105 * If a non-empty string is passed, the filter is evaluated on the wp_richedit_pre()
3106 * return after being formatted.
3110 * @param string $output Text for the rich text editor.
3112 return apply_filters( 'richedit_pre', '' );
3115 $output = convert_chars($text);
3116 $output = wpautop($output);
3117 $output = htmlspecialchars($output, ENT_NOQUOTES, get_option( 'blog_charset' ) );
3119 /** This filter is documented in wp-includes/formatting.php */
3120 return apply_filters( 'richedit_pre', $output );
3124 * Formats text for the HTML editor.
3126 * Unless $output is empty it will pass through htmlspecialchars before the
3127 * 'htmledit_pre' filter is applied.
3131 * @param string $output The text to be formatted.
3132 * @return string Formatted text after filter applied.
3134 function wp_htmledit_pre($output) {
3135 if ( !empty($output) )
3136 $output = htmlspecialchars($output, ENT_NOQUOTES, get_option( 'blog_charset' ) ); // convert only < > &
3139 * Filter the text before it is formatted for the HTML editor.
3143 * @param string $output The HTML-formatted text.
3145 return apply_filters( 'htmledit_pre', $output );
3149 * Perform a deep string replace operation to ensure the values in $search are no longer present
3151 * Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values
3152 * e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that
3153 * str_replace would return
3158 * @param string|array $search The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.
3159 * @param string $subject The string being searched and replaced on, otherwise known as the haystack.
3160 * @return string The string with the replaced svalues.
3162 function _deep_replace( $search, $subject ) {
3163 $subject = (string) $subject;
3167 $subject = str_replace( $search, '', $subject, $count );
3174 * Escapes data for use in a MySQL query.
3176 * Usually you should prepare queries using wpdb::prepare().
3177 * Sometimes, spot-escaping is required or useful. One example
3178 * is preparing an array for use in an IN clause.
3181 * @param string|array $data Unescaped data
3182 * @return string|array Escaped data
3184 function esc_sql( $data ) {
3186 return $wpdb->_escape( $data );
3190 * Checks and cleans a URL.
3192 * A number of characters are removed from the URL. If the URL is for displaying
3193 * (the default behaviour) ampersands are also replaced. The 'clean_url' filter
3194 * is applied to the returned cleaned URL.
3198 * @param string $url The URL to be cleaned.
3199 * @param array $protocols Optional. An array of acceptable protocols.
3200 * Defaults to 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn' if not set.
3201 * @param string $_context Private. Use esc_url_raw() for database usage.
3202 * @return string The cleaned $url after the 'clean_url' filter is applied.
3204 function esc_url( $url, $protocols = null, $_context = 'display' ) {
3205 $original_url = $url;
3209 $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);
3210 $strip = array('%0d', '%0a', '%0D', '%0A');
3211 $url = _deep_replace($strip, $url);
3212 $url = str_replace(';//', '://', $url);
3213 /* If the URL doesn't appear to contain a scheme, we
3214 * presume it needs http:// appended (unless a relative
3215 * link starting with /, # or ? or a php file).
3217 if ( strpos($url, ':') === false && ! in_array( $url[0], array( '/', '#', '?' ) ) &&
3218 ! preg_match('/^[a-z0-9-]+?\.php/i', $url) )
3219 $url = 'http://' . $url;
3221 // Replace ampersands and single quotes only when displaying.
3222 if ( 'display' == $_context ) {
3223 $url = wp_kses_normalize_entities( $url );
3224 $url = str_replace( '&', '&', $url );
3225 $url = str_replace( "'", ''', $url );
3228 if ( '/' === $url[0] ) {
3229 $good_protocol_url = $url;
3231 if ( ! is_array( $protocols ) )
3232 $protocols = wp_allowed_protocols();
3233 $good_protocol_url = wp_kses_bad_protocol( $url, $protocols );
3234 if ( strtolower( $good_protocol_url ) != strtolower( $url ) )
3239 * Filter a string cleaned and escaped for output as a URL.
3243 * @param string $good_protocol_url The cleaned URL to be returned.
3244 * @param string $original_url The URL prior to cleaning.
3245 * @param string $_context If 'display', replace ampersands and single quotes only.
3247 return apply_filters( 'clean_url', $good_protocol_url, $original_url, $_context );
3251 * Performs esc_url() for database usage.
3255 * @param string $url The URL to be cleaned.
3256 * @param array $protocols An array of acceptable protocols.
3257 * @return string The cleaned URL.
3259 function esc_url_raw( $url, $protocols = null ) {
3260 return esc_url( $url, $protocols, 'db' );
3264 * Convert entities, while preserving already-encoded entities.
3266 * @link http://www.php.net/htmlentities Borrowed from the PHP Manual user notes.
3270 * @param string $myHTML The text to be converted.
3271 * @return string Converted text.
3273 function htmlentities2($myHTML) {
3274 $translation_table = get_html_translation_table( HTML_ENTITIES, ENT_QUOTES );
3275 $translation_table[chr(38)] = '&';
3276 return preg_replace( "/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/", "&", strtr($myHTML, $translation_table) );
3280 * Escape single quotes, htmlspecialchar " < > &, and fix line endings.
3282 * Escapes text strings for echoing in JS. It is intended to be used for inline JS
3283 * (in a tag attribute, for example onclick="..."). Note that the strings have to
3284 * be in single quotes. The filter 'js_escape' is also applied here.
3288 * @param string $text The text to be escaped.
3289 * @return string Escaped text.
3291 function esc_js( $text ) {
3292 $safe_text = wp_check_invalid_utf8( $text );
3293 $safe_text = _wp_specialchars( $safe_text, ENT_COMPAT );
3294 $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) );
3295 $safe_text = str_replace( "\r", '', $safe_text );
3296 $safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) );
3298 * Filter a string cleaned and escaped for output in JavaScript.
3300 * Text passed to esc_js() is stripped of invalid or special characters,
3301 * and properly slashed for output.
3305 * @param string $safe_text The text after it has been escaped.
3306 * @param string $text The text prior to being escaped.
3308 return apply_filters( 'js_escape', $safe_text, $text );
3312 * Escaping for HTML blocks.
3316 * @param string $text
3319 function esc_html( $text ) {
3320 $safe_text = wp_check_invalid_utf8( $text );
3321 $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
3323 * Filter a string cleaned and escaped for output in HTML.
3325 * Text passed to esc_html() is stripped of invalid or special characters
3330 * @param string $safe_text The text after it has been escaped.
3331 * @param string $text The text prior to being escaped.
3333 return apply_filters( 'esc_html', $safe_text, $text );
3337 * Escaping for HTML attributes.
3341 * @param string $text
3344 function esc_attr( $text ) {
3345 $safe_text = wp_check_invalid_utf8( $text );
3346 $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
3348 * Filter a string cleaned and escaped for output in an HTML attribute.
3350 * Text passed to esc_attr() is stripped of invalid or special characters
3355 * @param string $safe_text The text after it has been escaped.
3356 * @param string $text The text prior to being escaped.
3358 return apply_filters( 'attribute_escape', $safe_text, $text );
3362 * Escaping for textarea values.
3366 * @param string $text
3369 function esc_textarea( $text ) {
3370 $safe_text = htmlspecialchars( $text, ENT_QUOTES, get_option( 'blog_charset' ) );
3372 * Filter a string cleaned and escaped for output in a textarea element.
3376 * @param string $safe_text The text after it has been escaped.
3377 * @param string $text The text prior to being escaped.
3379 return apply_filters( 'esc_textarea', $safe_text, $text );
3383 * Escape an HTML tag name.
3387 * @param string $tag_name
3390 function tag_escape($tag_name) {
3391 $safe_tag = strtolower( preg_replace('/[^a-zA-Z0-9_:]/', '', $tag_name) );
3393 * Filter a string cleaned and escaped for output as an HTML tag.
3397 * @param string $safe_tag The tag name after it has been escaped.
3398 * @param string $tag_name The text before it was escaped.
3400 return apply_filters( 'tag_escape', $safe_tag, $tag_name );
3404 * Convert full URL paths to absolute paths.
3406 * Removes the http or https protocols and the domain. Keeps the path '/' at the
3407 * beginning, so it isn't a true relative link, but from the web root base.
3410 * @since 4.1.0 Support was added for relative URLs.
3412 * @param string $link Full URL path.
3413 * @return string Absolute path.
3415 function wp_make_link_relative( $link ) {
3416 return preg_replace( '|^(https?:)?//[^/]+(/.*)|i', '$2', $link );
3420 * Sanitises various option values based on the nature of the option.
3422 * This is basically a switch statement which will pass $value through a number
3423 * of functions depending on the $option.
3427 * @param string $option The name of the option.
3428 * @param string $value The unsanitised value.
3429 * @return string Sanitized value.
3431 function sanitize_option($option, $value) {
3435 switch ( $option ) {
3436 case 'admin_email' :
3437 case 'new_admin_email' :
3438 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3439 if ( is_wp_error( $value ) ) {
3440 $error = $value->get_error_message();
3442 $value = sanitize_email( $value );
3443 if ( ! is_email( $value ) ) {
3444 $error = __( 'The email address entered did not appear to be a valid email address. Please enter a valid email address.' );
3449 case 'thumbnail_size_w':
3450 case 'thumbnail_size_h':
3451 case 'medium_size_w':
3452 case 'medium_size_h':
3453 case 'large_size_w':
3454 case 'large_size_h':
3455 case 'mailserver_port':
3456 case 'comment_max_links':
3457 case 'page_on_front':
3458 case 'page_for_posts':
3459 case 'rss_excerpt_length':
3460 case 'default_category':
3461 case 'default_email_category':
3462 case 'default_link_category':
3463 case 'close_comments_days_old':
3464 case 'comments_per_page':
3465 case 'thread_comments_depth':
3466 case 'users_can_register':
3467 case 'start_of_week':
3468 $value = absint( $value );
3471 case 'posts_per_page':
3472 case 'posts_per_rss':
3473 $value = (int) $value;
3474 if ( empty($value) )
3477 $value = abs($value);
3480 case 'default_ping_status':
3481 case 'default_comment_status':
3482 // Options that if not there have 0 value but need to be something like "closed"
3483 if ( $value == '0' || $value == '')
3487 case 'blogdescription':
3489 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3490 if ( is_wp_error( $value ) ) {
3491 $error = $value->get_error_message();
3493 $value = wp_kses_post( $value );
3494 $value = esc_html( $value );
3498 case 'blog_charset':
3499 $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value); // strips slashes
3503 // This is the value if the settings checkbox is not checked on POST. Don't rely on this.
3504 if ( null === $value )
3507 $value = intval( $value );
3512 case 'mailserver_url':
3513 case 'mailserver_login':
3514 case 'mailserver_pass':
3516 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3517 if ( is_wp_error( $value ) ) {
3518 $error = $value->get_error_message();
3520 $value = strip_tags( $value );
3521 $value = wp_kses_data( $value );
3526 $value = explode( "\n", $value );
3527 $value = array_filter( array_map( 'trim', $value ) );
3528 $value = array_filter( array_map( 'esc_url_raw', $value ) );
3529 $value = implode( "\n", $value );
3533 $value = preg_replace('/[^0-9:.-]/', '', $value); // strips slashes
3537 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3538 if ( is_wp_error( $value ) ) {
3539 $error = $value->get_error_message();
3541 if ( preg_match( '#http(s?)://(.+)#i', $value ) ) {
3542 $value = esc_url_raw( $value );
3544 $error = __( 'The WordPress address you entered did not appear to be a valid URL. Please enter a valid URL.' );
3550 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3551 if ( is_wp_error( $value ) ) {
3552 $error = $value->get_error_message();
3554 if ( preg_match( '#http(s?)://(.+)#i', $value ) ) {
3555 $value = esc_url_raw( $value );
3557 $error = __( 'The Site address you entered did not appear to be a valid URL. Please enter a valid URL.' );
3563 $allowed = get_available_languages();
3564 if ( ! is_multisite() && defined( 'WPLANG' ) && '' !== WPLANG && 'en_US' !== WPLANG ) {
3565 $allowed[] = WPLANG;
3567 if ( ! in_array( $value, $allowed ) && ! empty( $value ) ) {
3568 $value = get_option( $option );
3572 case 'illegal_names':
3573 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3574 if ( is_wp_error( $value ) ) {
3575 $error = $value->get_error_message();
3577 if ( ! is_array( $value ) )
3578 $value = explode( ' ', $value );
3580 $value = array_values( array_filter( array_map( 'trim', $value ) ) );
3587 case 'limited_email_domains':
3588 case 'banned_email_domains':
3589 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3590 if ( is_wp_error( $value ) ) {
3591 $error = $value->get_error_message();
3593 if ( ! is_array( $value ) )
3594 $value = explode( "\n", $value );
3596 $domains = array_values( array_filter( array_map( 'trim', $value ) ) );
3599 foreach ( $domains as $domain ) {
3600 if ( ! preg_match( '/(--|\.\.)/', $domain ) && preg_match( '|^([a-zA-Z0-9-\.])+$|', $domain ) ) {
3609 case 'timezone_string':
3610 $allowed_zones = timezone_identifiers_list();
3611 if ( ! in_array( $value, $allowed_zones ) && ! empty( $value ) ) {
3612 $error = __( 'The timezone you have entered is not valid. Please select a valid timezone.' );
3616 case 'permalink_structure':
3617 case 'category_base':
3619 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3620 if ( is_wp_error( $value ) ) {
3621 $error = $value->get_error_message();
3623 $value = esc_url_raw( $value );
3624 $value = str_replace( 'http://', '', $value );
3628 case 'default_role' :
3629 if ( ! get_role( $value ) && get_role( 'subscriber' ) )
3630 $value = 'subscriber';
3633 case 'moderation_keys':
3634 case 'blacklist_keys':
3635 $value = $wpdb->strip_invalid_text_for_column( $wpdb->options, 'option_value', $value );
3636 if ( is_wp_error( $value ) ) {
3637 $error = $value->get_error_message();
3639 $value = explode( "\n", $value );
3640 $value = array_filter( array_map( 'trim', $value ) );
3641 $value = array_unique( $value );
3642 $value = implode( "\n", $value );
3647 if ( ! empty( $error ) ) {
3648 $value = get_option( $option );
3649 if ( function_exists( 'add_settings_error' ) ) {
3650 add_settings_error( $option, "invalid_{$option}", $error );
3655 * Filter an option value following sanitization.
3659 * @param string $value The sanitized option value.
3660 * @param string $option The option name.
3662 $value = apply_filters( "sanitize_option_{$option}", $value, $option );
3668 * Parses a string into variables to be stored in an array.
3670 * Uses {@link http://www.php.net/parse_str parse_str()} and stripslashes if
3671 * {@link http://www.php.net/magic_quotes magic_quotes_gpc} is on.
3675 * @param string $string The string to be parsed.
3676 * @param array $array Variables will be stored in this array.
3678 function wp_parse_str( $string, &$array ) {
3679 parse_str( $string, $array );
3680 if ( get_magic_quotes_gpc() )
3681 $array = stripslashes_deep( $array );
3683 * Filter the array of variables derived from a parsed string.
3687 * @param array $array The array populated with variables.
3689 $array = apply_filters( 'wp_parse_str', $array );
3693 * Convert lone less than signs.
3695 * KSES already converts lone greater than signs.
3699 * @param string $text Text to be converted.
3700 * @return string Converted text.
3702 function wp_pre_kses_less_than( $text ) {
3703 return preg_replace_callback('%<[^>]*?((?=<)|>|$)%', 'wp_pre_kses_less_than_callback', $text);
3707 * Callback function used by preg_replace.
3711 * @param array $matches Populated by matches to preg_replace.
3712 * @return string The text returned after esc_html if needed.
3714 function wp_pre_kses_less_than_callback( $matches ) {
3715 if ( false === strpos($matches[0], '>') )
3716 return esc_html($matches[0]);
3721 * WordPress implementation of PHP sprintf() with filters.
3724 * @link http://www.php.net/sprintf
3726 * @param string $pattern The string which formatted args are inserted.
3727 * @param mixed $args ,... Arguments to be formatted into the $pattern string.
3728 * @return string The formatted string.
3730 function wp_sprintf( $pattern ) {
3731 $args = func_get_args();
3732 $len = strlen($pattern);
3736 while ( $len > $start ) {
3737 // Last character: append and break
3738 if ( strlen($pattern) - 1 == $start ) {
3739 $result .= substr($pattern, -1);
3743 // Literal %: append and continue
3744 if ( substr($pattern, $start, 2) == '%%' ) {
3750 // Get fragment before next %
3751 $end = strpos($pattern, '%', $start + 1);
3752 if ( false === $end )
3754 $fragment = substr($pattern, $start, $end - $start);
3756 // Fragment has a specifier
3757 if ( $pattern[$start] == '%' ) {
3758 // Find numbered arguments or take the next one in order
3759 if ( preg_match('/^%(\d+)\$/', $fragment, $matches) ) {
3760 $arg = isset($args[$matches[1]]) ? $args[$matches[1]] : '';
3761 $fragment = str_replace("%{$matches[1]}$", '%', $fragment);
3764 $arg = isset($args[$arg_index]) ? $args[$arg_index] : '';
3768 * Filter a fragment from the pattern passed to wp_sprintf().
3770 * If the fragment is unchanged, then sprintf() will be run on the fragment.
3774 * @param string $fragment A fragment from the pattern.
3775 * @param string $arg The argument.
3777 $_fragment = apply_filters( 'wp_sprintf', $fragment, $arg );
3778 if ( $_fragment != $fragment )
3779 $fragment = $_fragment;
3781 $fragment = sprintf($fragment, strval($arg) );
3784 // Append to result and move to next fragment
3785 $result .= $fragment;
3792 * Localize list items before the rest of the content.
3794 * The '%l' must be at the first characters can then contain the rest of the
3795 * content. The list items will have ', ', ', and', and ' and ' added depending
3796 * on the amount of list items in the $args parameter.
3800 * @param string $pattern Content containing '%l' at the beginning.
3801 * @param array $args List items to prepend to the content and replace '%l'.
3802 * @return string Localized list items and rest of the content.
3804 function wp_sprintf_l($pattern, $args) {
3806 if ( substr($pattern, 0, 2) != '%l' )
3809 // Nothing to work with
3814 * Filter the translated delimiters used by wp_sprintf_l().
3815 * Placeholders (%s) are included to assist translators and then
3816 * removed before the array of strings reaches the filter.
3818 * Please note: Ampersands and entities should be avoided here.
3822 * @param array $delimiters An array of translated delimiters.
3824 $l = apply_filters( 'wp_sprintf_l', array(
3825 /* translators: used to join items in a list with more than 2 items */
3826 'between' => sprintf( __('%s, %s'), '', '' ),
3827 /* translators: used to join last two items in a list with more than 2 times */
3828 'between_last_two' => sprintf( __('%s, and %s'), '', '' ),
3829 /* translators: used to join items in a list with only 2 items */
3830 'between_only_two' => sprintf( __('%s and %s'), '', '' ),
3833 $args = (array) $args;
3834 $result = array_shift($args);
3835 if ( count($args) == 1 )
3836 $result .= $l['between_only_two'] . array_shift($args);
3837 // Loop when more than two args
3840 $arg = array_shift($args);
3843 $result .= $l['between_last_two'] . $arg;
3845 $result .= $l['between'] . $arg;
3847 return $result . substr($pattern, 2);
3851 * Safely extracts not more than the first $count characters from html string.
3853 * UTF-8, tags and entities safe prefix extraction. Entities inside will *NOT*
3854 * be counted as one character. For example & will be counted as 4, < as
3859 * @param string $str String to get the excerpt from.
3860 * @param integer $count Maximum number of characters to take.
3861 * @param string $more Optional. What to append if $str needs to be trimmed. Defaults to empty string.
3862 * @return string The excerpt.
3864 function wp_html_excerpt( $str, $count, $more = null ) {
3865 if ( null === $more )
3867 $str = wp_strip_all_tags( $str, true );
3868 $excerpt = mb_substr( $str, 0, $count );
3869 // remove part of an entity at the end
3870 $excerpt = preg_replace( '/&[^;\s]{0,6}$/', '', $excerpt );
3871 if ( $str != $excerpt )
3872 $excerpt = trim( $excerpt ) . $more;
3877 * Add a Base url to relative links in passed content.
3879 * By default it supports the 'src' and 'href' attributes. However this can be
3880 * changed via the 3rd param.
3884 * @param string $content String to search for links in.
3885 * @param string $base The base URL to prefix to links.
3886 * @param array $attrs The attributes which should be processed.
3887 * @return string The processed content.
3889 function links_add_base_url( $content, $base, $attrs = array('src', 'href') ) {
3890 global $_links_add_base;
3891 $_links_add_base = $base;
3892 $attrs = implode('|', (array)$attrs);
3893 return preg_replace_callback( "!($attrs)=(['\"])(.+?)\\2!i", '_links_add_base', $content );
3897 * Callback to add a base url to relative links in passed content.
3902 * @param string $m The matched link.
3903 * @return string The processed link.
3905 function _links_add_base($m) {
3906 global $_links_add_base;
3907 //1 = attribute name 2 = quotation mark 3 = URL
3908 return $m[1] . '=' . $m[2] .
3909 ( preg_match( '#^(\w{1,20}):#', $m[3], $protocol ) && in_array( $protocol[1], wp_allowed_protocols() ) ?
3911 WP_HTTP::make_absolute_url( $m[3], $_links_add_base )
3917 * Adds a Target attribute to all links in passed content.
3919 * This function by default only applies to `<a>` tags, however this can be
3920 * modified by the 3rd param.
3922 * *NOTE:* Any current target attributed will be stripped and replaced.
3926 * @param string $content String to search for links in.
3927 * @param string $target The Target to add to the links.
3928 * @param array $tags An array of tags to apply to.
3929 * @return string The processed content.
3931 function links_add_target( $content, $target = '_blank', $tags = array('a') ) {
3932 global $_links_add_target;
3933 $_links_add_target = $target;
3934 $tags = implode('|', (array)$tags);
3935 return preg_replace_callback( "!<($tags)([^>]*)>!i", '_links_add_target', $content );
3939 * Callback to add a target attribute to all links in passed content.
3944 * @param string $m The matched link.
3945 * @return string The processed link.
3947 function _links_add_target( $m ) {
3948 global $_links_add_target;
3950 $link = preg_replace('|( target=([\'"])(.*?)\2)|i', '', $m[2]);
3951 return '<' . $tag . $link . ' target="' . esc_attr( $_links_add_target ) . '">';
3955 * Normalize EOL characters and strip duplicate whitespace.
3959 * @param string $str The string to normalize.
3960 * @return string The normalized string.
3962 function normalize_whitespace( $str ) {
3963 $str = trim( $str );
3964 $str = str_replace( "\r", "\n", $str );
3965 $str = preg_replace( array( '/\n+/', '/[ \t]+/' ), array( "\n", ' ' ), $str );
3970 * Properly strip all HTML tags including script and style
3972 * This differs from strip_tags() because it removes the contents of
3973 * the `<script>` and `<style>` tags. E.g. `strip_tags( '<script>something</script>' )`
3974 * will return 'something'. wp_strip_all_tags will return ''
3978 * @param string $string String containing HTML tags
3979 * @param bool $remove_breaks optional Whether to remove left over line breaks and white space chars
3980 * @return string The processed string.
3982 function wp_strip_all_tags($string, $remove_breaks = false) {
3983 $string = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $string );
3984 $string = strip_tags($string);
3986 if ( $remove_breaks )
3987 $string = preg_replace('/[\r\n\t ]+/', ' ', $string);
3989 return trim( $string );
3993 * Sanitize a string from user input or from the db
3995 * check for invalid UTF-8,
3996 * Convert single < characters to entity,
3998 * remove line breaks, tabs and extra white space,
4003 * @param string $str
4006 function sanitize_text_field($str) {
4007 $filtered = wp_check_invalid_utf8( $str );
4009 if ( strpos($filtered, '<') !== false ) {
4010 $filtered = wp_pre_kses_less_than( $filtered );
4011 // This will strip extra whitespace for us.
4012 $filtered = wp_strip_all_tags( $filtered, true );
4014 $filtered = trim( preg_replace('/[\r\n\t ]+/', ' ', $filtered) );
4018 while ( preg_match('/%[a-f0-9]{2}/i', $filtered, $match) ) {
4019 $filtered = str_replace($match[0], '', $filtered);
4024 // Strip out the whitespace that may now exist after removing the octets.
4025 $filtered = trim( preg_replace('/ +/', ' ', $filtered) );
4029 * Filter a sanitized text field string.
4033 * @param string $filtered The sanitized string.
4034 * @param string $str The string prior to being sanitized.
4036 return apply_filters( 'sanitize_text_field', $filtered, $str );
4040 * i18n friendly version of basename()
4044 * @param string $path A path.
4045 * @param string $suffix If the filename ends in suffix this will also be cut off.
4048 function wp_basename( $path, $suffix = '' ) {
4049 return urldecode( basename( str_replace( array( '%2F', '%5C' ), '/', urlencode( $path ) ), $suffix ) );
4053 * Forever eliminate "Wordpress" from the planet (or at least the little bit we can influence).
4055 * Violating our coding standards for a good function name.
4059 function capital_P_dangit( $text ) {
4060 // Simple replacement for titles
4061 $current_filter = current_filter();
4062 if ( 'the_title' === $current_filter || 'wp_title' === $current_filter )
4063 return str_replace( 'Wordpress', 'WordPress', $text );
4064 // Still here? Use the more judicious replacement
4065 static $dblq = false;
4066 if ( false === $dblq )
4067 $dblq = _x( '“', 'opening curly double quote' );
4069 array( ' Wordpress', '‘Wordpress', $dblq . 'Wordpress', '>Wordpress', '(Wordpress' ),
4070 array( ' WordPress', '‘WordPress', $dblq . 'WordPress', '>WordPress', '(WordPress' ),
4076 * Sanitize a mime type
4080 * @param string $mime_type Mime type
4081 * @return string Sanitized mime type
4083 function sanitize_mime_type( $mime_type ) {
4084 $sani_mime_type = preg_replace( '/[^-+*.a-zA-Z0-9\/]/', '', $mime_type );
4086 * Filter a mime type following sanitization.
4090 * @param string $sani_mime_type The sanitized mime type.
4091 * @param string $mime_type The mime type prior to sanitization.
4093 return apply_filters( 'sanitize_mime_type', $sani_mime_type, $mime_type );
4097 * Sanitize space or carriage return separated URLs that are used to send trackbacks.
4101 * @param string $to_ping Space or carriage return separated URLs
4102 * @return string URLs starting with the http or https protocol, separated by a carriage return.
4104 function sanitize_trackback_urls( $to_ping ) {
4105 $urls_to_ping = preg_split( '/[\r\n\t ]/', trim( $to_ping ), -1, PREG_SPLIT_NO_EMPTY );
4106 foreach ( $urls_to_ping as $k => $url ) {
4107 if ( !preg_match( '#^https?://.#i', $url ) )
4108 unset( $urls_to_ping[$k] );
4110 $urls_to_ping = array_map( 'esc_url_raw', $urls_to_ping );
4111 $urls_to_ping = implode( "\n", $urls_to_ping );
4113 * Filter a list of trackback URLs following sanitization.
4115 * The string returned here consists of a space or carriage return-delimited list
4116 * of trackback URLs.
4120 * @param string $urls_to_ping Sanitized space or carriage return separated URLs.
4121 * @param string $to_ping Space or carriage return separated URLs before sanitization.
4123 return apply_filters( 'sanitize_trackback_urls', $urls_to_ping, $to_ping );
4127 * Add slashes to a string or array of strings.
4129 * This should be used when preparing data for core API that expects slashed data.
4130 * This should not be used to escape data going directly into an SQL query.
4134 * @param string|array $value String or array of strings to slash.
4135 * @return string|array Slashed $value
4137 function wp_slash( $value ) {
4138 if ( is_array( $value ) ) {
4139 foreach ( $value as $k => $v ) {
4140 if ( is_array( $v ) ) {
4141 $value[$k] = wp_slash( $v );
4143 $value[$k] = addslashes( $v );
4147 $value = addslashes( $value );
4154 * Remove slashes from a string or array of strings.
4156 * This should be used to remove slashes from data passed to core API that
4157 * expects data to be unslashed.
4161 * @param string|array $value String or array of strings to unslash.
4162 * @return string|array Unslashed $value
4164 function wp_unslash( $value ) {
4165 return stripslashes_deep( $value );
4169 * Extract and return the first URL from passed content.
4173 * @param string $content A string which might contain a URL.
4174 * @return string The found URL.
4176 function get_url_in_content( $content ) {
4177 if ( empty( $content ) ) {
4181 if ( preg_match( '/<a\s[^>]*?href=([\'"])(.+?)\1/is', $content, $matches ) ) {
4182 return esc_url_raw( $matches[2] );
4189 * Returns the regexp for common whitespace characters.
4191 * By default, spaces include new lines, tabs, nbsp entities, and the UTF-8 nbsp.
4192 * This is designed to replace the PCRE \s sequence. In ticket #22692, that
4193 * sequence was found to be unreliable due to random inclusion of the A0 byte.
4197 * @return string The spaces regexp.
4199 function wp_spaces_regexp() {
4202 if ( empty( $spaces ) ) {
4204 * Filter the regexp for common whitespace characters.
4206 * This string is substituted for the \s sequence as needed in regular
4207 * expressions. For websites not written in English, different characters
4208 * may represent whitespace. For websites not encoded in UTF-8, the 0xC2 0xA0
4209 * sequence may not be in use.
4213 * @param string $spaces Regexp pattern for matching common whitespace characters.
4215 $spaces = apply_filters( 'wp_spaces_regexp', '[\r\n\t ]|\xC2\xA0| ' );
4222 * Print the important emoji-related styles.
4226 function print_emoji_styles() {
4227 static $printed = false;
4235 <style type="text/css">
4238 display: inline !important;
4239 border: none !important;
4240 box-shadow: none !important;
4241 height: 1em !important;
4242 width: 1em !important;
4243 margin: 0 .07em !important;
4244 vertical-align: -0.1em !important;
4245 background: none !important;
4246 padding: 0 !important;
4252 function print_emoji_detection_script() {
4254 static $printed = false;
4264 * Filter the URL where emoji images are hosted.
4268 * @param string The emoji base URL.
4270 'baseUrl' => apply_filters( 'emoji_url', set_url_scheme( '//s.w.org/images/core/emoji/72x72/' ) ),
4273 * Filter the extension of the emoji files.
4277 * @param string The emoji extension. Default .png.
4279 'ext' => apply_filters( 'emoji_ext', '.png' ),
4282 $version = 'ver=' . $wp_version;
4283 $develop_src = false !== strpos( $wp_version, '-src' );
4285 if ( $develop_src || ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ) {
4286 $settings['source'] = array(
4287 /** This filter is documented in wp-includes/class.wp-scripts.php */
4288 'wpemoji' => apply_filters( 'script_loader_src', includes_url( "js/wp-emoji.js?$version" ), 'wpemoji' ),
4289 /** This filter is documented in wp-includes/class.wp-scripts.php */
4290 'twemoji' => apply_filters( 'script_loader_src', includes_url( "js/twemoji.js?$version" ), 'twemoji' ),
4294 <script type="text/javascript">
4295 window._wpemojiSettings = <?php echo wp_json_encode( $settings ); ?>;
4296 <?php readfile( ABSPATH . WPINC . "/js/wp-emoji-loader.js" ); ?>
4300 $settings['source'] = array(
4301 /** This filter is documented in wp-includes/class.wp-scripts.php */
4302 'concatemoji' => apply_filters( 'script_loader_src', includes_url( "js/wp-emoji-release.min.js?$version" ), 'concatemoji' ),
4306 * If you're looking at a src version of this file, you'll see an "include"
4307 * statement below. This is used by the `grunt build` process to directly
4308 * include a minified version of wp-emoji-loader.js, instead of using the
4309 * readfile() method from above.
4311 * If you're looking at a build version of this file, you'll see a string of
4312 * minified JavaScript. If you need to debug it, please turn on SCRIPT_DEBUG
4313 * and edit wp-emoji-loader.js directly.
4316 <script type="text/javascript">
4317 window._wpemojiSettings = <?php echo wp_json_encode( $settings ); ?>;
4318 !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);
4325 * Convert any 4 byte emoji in a string to their equivalent HTML entity.
4327 * Currently, only Unicode 7 emoji are supported. Skin tone modifiers are allowed,
4328 * all other Unicode 8 emoji will be added when the spec is finalised.
4330 * This allows us to store emoji in a DB using the utf8 character set.
4334 * @param string $content The content to encode.
4335 * @return string The encoded content.
4337 function wp_encode_emoji( $content ) {
4338 if ( function_exists( 'mb_convert_encoding' ) ) {
4340 \x23\xE2\x83\xA3 # Digits
4341 [\x30-\x39]\xE2\x83\xA3
4342 | \xF0\x9F[\x85-\x88][\xA6-\xBF] # Enclosed characters
4343 | \xF0\x9F[\x8C-\x97][\x80-\xBF] # Misc
4344 | \xF0\x9F\x98[\x80-\xBF] # Smilies
4345 | \xF0\x9F\x99[\x80-\x8F]
4346 | \xF0\x9F\x9A[\x80-\xBF] # Transport and map symbols
4350 if ( preg_match_all( $regex, $content, $matches ) ) {
4351 if ( ! empty( $matches[1] ) ) {
4352 foreach( $matches[1] as $emoji ) {
4354 * UTF-32's hex encoding is the same as HTML's hex encoding.
4355 * So, by converting the emoji from UTF-8 to UTF-32, we magically
4356 * get the correct hex encoding.
4358 $unpacked = unpack( 'H*', mb_convert_encoding( $emoji, 'UTF-32', 'UTF-8' ) );
4359 if ( isset( $unpacked[1] ) ) {
4360 $entity = '&#x' . ltrim( $unpacked[1], '0' ) . ';';
4361 $content = str_replace( $emoji, $entity, $content );
4372 * Convert emoji to a static img element.
4376 * @param string $text The content to encode.
4377 * @return string The encoded content.
4379 function wp_staticize_emoji( $text ) {
4380 $text = wp_encode_emoji( $text );
4382 /** This filter is documented in wp-includes/formatting.php */
4383 $cdn_url = apply_filters( 'emoji_url', set_url_scheme( '//s.w.org/images/core/emoji/72x72/' ) );
4385 /** This filter is documented in wp-includes/formatting.php */
4386 $ext = apply_filters( 'emoji_ext', '.png' );
4390 * HTML loop taken from smiley function, which was taken from texturize function.
4391 * It'll never be consolidated.
4393 * First, capture the tags as well as in between.
4395 $textarr = preg_split( '/(<.*>)/U', $text, -1, PREG_SPLIT_DELIM_CAPTURE );
4396 $stop = count( $textarr );
4398 // Ignore processing of specific tags.
4399 $tags_to_ignore = 'code|pre|style|script|textarea';
4400 $ignore_block_element = '';
4402 for ( $i = 0; $i < $stop; $i++ ) {
4403 $content = $textarr[$i];
4405 // If we're in an ignore block, wait until we find its closing tag.
4406 if ( '' == $ignore_block_element && preg_match( '/^<(' . $tags_to_ignore . ')>/', $content, $matches ) ) {
4407 $ignore_block_element = $matches[1];
4410 // If it's not a tag and not in ignore block.
4411 if ( '' == $ignore_block_element && strlen( $content ) > 0 && '<' != $content[0] ) {
4413 if ( preg_match_all( '/(DZ(e[6-9a-f]|f[0-9a-f]);){2}/', $content, $matches ) ) {
4414 if ( ! empty( $matches[0] ) ) {
4415 foreach ( $matches[0] as $flag ) {
4416 $chars = str_replace( array( '&#x', ';'), '', $flag );
4418 list( $char1, $char2 ) = str_split( $chars, 5 );
4419 $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 ) );
4421 $content = str_replace( $flag, $entity, $content );
4426 // Loosely match the Emoji Unicode range.
4427 $regex = '/(&#x[2-3][0-9a-f]{3};|[1-6][0-9a-f]{2};)/';
4430 if ( preg_match_all( $regex, $content, $matches ) ) {
4431 if ( ! empty( $matches[1] ) ) {
4432 foreach ( $matches[1] as $emoji ) {
4433 $char = str_replace( array( '&#x', ';'), '', $emoji );
4434 $entity = sprintf( '<img src="%s" alt="%s" class="wp-smiley" style="height: 1em; max-height: 1em;" />', $cdn_url . $char . $ext, html_entity_decode( $emoji ) );
4436 $content = str_replace( $emoji, $entity, $content );
4442 // Did we exit ignore block.
4443 if ( '' != $ignore_block_element && '</' . $ignore_block_element . '>' == $content ) {
4444 $ignore_block_element = '';
4447 $output .= $content;
4454 * Convert emoji in emails into static images.
4458 * @param array $mail The email data array.
4459 * @return array The email data array, with emoji in the message staticized.
4461 function wp_staticize_emoji_for_email( $mail ) {
4462 if ( ! isset( $mail['message'] ) ) {
4467 * We can only transform the emoji into images if it's a text/html email.
4468 * To do that, here's a cut down version of the same process that happens
4469 * in wp_mail() - get the Content-Type from the headers, if there is one,
4470 * then pass it through the wp_mail_content_type filter, in case a plugin
4471 * is handling changing the Content-Type.
4474 if ( isset( $mail['headers'] ) ) {
4475 if ( is_array( $mail['headers'] ) ) {
4476 $headers = $mail['headers'];
4478 $headers = explode( "\n", str_replace( "\r\n", "\n", $mail['headers'] ) );
4482 foreach ( $headers as $header ) {
4483 if ( strpos($header, ':') === false ) {
4487 // Explode them out.
4488 list( $name, $content ) = explode( ':', trim( $header ), 2 );
4491 $name = trim( $name );
4492 $content = trim( $content );
4494 if ( 'content-type' === strtolower( $name ) ) {
4495 if ( strpos( $content, ';' ) !== false ) {
4496 list( $type, $charset ) = explode( ';', $content );
4497 $content_type = trim( $type );
4499 $content_type = trim( $content );
4505 // Set Content-Type if we don't have a content-type from the input headers.
4506 if ( ! isset( $content_type ) ) {
4507 $content_type = 'text/plain';
4510 /** This filter is documented in wp-includes/pluggable.php */
4511 $content_type = apply_filters( 'wp_mail_content_type', $content_type );
4513 if ( 'text/html' === $content_type ) {
4514 $mail['message'] = wp_staticize_emoji( $mail['message'] );