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 * @return string The string replaced with html entities
29 function wptexturize($text) {
30 global $wp_cockneyreplace;
31 static $static_setup = false, $opening_quote, $closing_quote, $default_no_texturize_tags, $default_no_texturize_shortcodes, $static_characters, $static_replacements, $dynamic_characters, $dynamic_replacements;
34 $textarr = preg_split('/(<.*>|\[.*\])/Us', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
35 $stop = count($textarr);
37 // No need to set up these variables more than once
39 /* translators: opening curly quote */
40 $opening_quote = _x('“', 'opening curly quote');
41 /* translators: closing curly quote */
42 $closing_quote = _x('”', 'closing curly quote');
44 $default_no_texturize_tags = array('pre', 'code', 'kbd', 'style', 'script', 'tt');
45 $default_no_texturize_shortcodes = array('code');
47 // if a plugin has provided an autocorrect array, use it
48 if ( isset($wp_cockneyreplace) ) {
49 $cockney = array_keys($wp_cockneyreplace);
50 $cockneyreplace = array_values($wp_cockneyreplace);
52 $cockney = array("'tain't","'twere","'twas","'tis","'twill","'til","'bout","'nuff","'round","'cause");
53 $cockneyreplace = array("’tain’t","’twere","’twas","’tis","’twill","’til","’bout","’nuff","’round","’cause");
56 $static_characters = array_merge(array('---', ' -- ', '--', ' - ', 'xn–', '...', '``', '\'\'', ' (tm)'), $cockney);
57 $static_replacements = array_merge(array('—', ' — ', '–', ' – ', 'xn--', '…', $opening_quote, $closing_quote, ' ™'), $cockneyreplace);
59 $dynamic_characters = array('/\'(\d\d(?:’|\')?s)/', '/\'(\d+)/', '/(\s|\A|[([{<]|")\'/', '/(\d+)"/', '/(\d+)\'/', '/(\S)\'([^\'\s])/', '/(\s|\A|[([{<])"(?!\s)/', '/"(\s|\S|\Z)/', '/\'([\s.]|\Z)/', '/\b(\d+)x(\d+)\b/');
60 $dynamic_replacements = array('’$1','’$1', '$1‘', '$1″', '$1′', '$1’$2', '$1' . $opening_quote . '$2', $closing_quote . '$1', '’$1', '$1×$2');
65 // Transform into regexp sub-expression used in _wptexturize_pushpop_element
66 // Must do this everytime in case plugins use these filters in a context sensitive manner
67 $no_texturize_tags = '(' . implode('|', apply_filters('no_texturize_tags', $default_no_texturize_tags) ) . ')';
68 $no_texturize_shortcodes = '(' . implode('|', apply_filters('no_texturize_shortcodes', $default_no_texturize_shortcodes) ) . ')';
70 $no_texturize_tags_stack = array();
71 $no_texturize_shortcodes_stack = array();
73 for ( $i = 0; $i < $stop; $i++ ) {
76 if ( !empty($curl) && '<' != $curl{0} && '[' != $curl{0}
77 && empty($no_texturize_shortcodes_stack) && empty($no_texturize_tags_stack)) {
78 // This is not a tag, nor is the texturization disabled
80 $curl = str_replace($static_characters, $static_replacements, $curl);
81 // regular expressions
82 $curl = preg_replace($dynamic_characters, $dynamic_replacements, $curl);
83 } elseif (!empty($curl)) {
85 * Only call _wptexturize_pushpop_element if first char is correct
89 _wptexturize_pushpop_element($curl, $no_texturize_tags_stack, $no_texturize_tags, '<', '>');
90 elseif ('[' == $curl{0})
91 _wptexturize_pushpop_element($curl, $no_texturize_shortcodes_stack, $no_texturize_shortcodes, '[', ']');
94 $curl = preg_replace('/&([^#])(?![a-zA-Z1-4]{1,8};)/', '&$1', $curl);
102 * Search for disabled element tags. Push element to stack on tag open and pop
103 * on tag close. Assumes first character of $text is tag opening.
108 * @param string $text Text to check. First character is assumed to be $opening
109 * @param array $stack Array used as stack of opened tag elements
110 * @param string $disabled_elements Tags to match against formatted as regexp sub-expression
111 * @param string $opening Tag opening character, assumed to be 1 character long
112 * @param string $opening Tag closing character
115 function _wptexturize_pushpop_element($text, &$stack, $disabled_elements, $opening = '<', $closing = '>') {
116 // Check if it is a closing tag -- otherwise assume opening tag
117 if (strncmp($opening . '/', $text, 2)) {
118 // Opening? Check $text+1 against disabled elements
119 if (preg_match('/^' . $disabled_elements . '\b/', substr($text, 1), $matches)) {
121 * This disables texturize until we find a closing tag of our type
122 * (e.g. <pre>) even if there was invalid nesting before that
124 * Example: in the case <pre>sadsadasd</code>"baba"</pre>
125 * "baba" won't be texturize
128 array_push($stack, $matches[1]);
131 // Closing? Check $text+2 against disabled elements
132 $c = preg_quote($closing, '/');
133 if (preg_match('/^' . $disabled_elements . $c . '/', substr($text, 2), $matches)) {
134 $last = array_pop($stack);
136 // Make sure it matches the opening tag
137 if ($last != $matches[1])
138 array_push($stack, $last);
144 * Accepts matches array from preg_replace_callback in wpautop() or a string.
146 * Ensures that the contents of a <<pre>>...<</pre>> HTML block are not
147 * converted into paragraphs or line-breaks.
151 * @param array|string $matches The array or string
152 * @return string The pre block without paragraph/line-break conversion.
154 function clean_pre($matches) {
155 if ( is_array($matches) )
156 $text = $matches[1] . $matches[2] . "</pre>";
160 $text = str_replace('<br />', '', $text);
161 $text = str_replace('<p>', "\n", $text);
162 $text = str_replace('</p>', '', $text);
168 * Replaces double line-breaks with paragraph elements.
170 * A group of regex replaces used to identify text formatted with newlines and
171 * replace double line-breaks with HTML paragraph tags. The remaining
172 * line-breaks after conversion become <<br />> tags, unless $br is set to '0'
177 * @param string $pee The text which has to be formatted.
178 * @param int|bool $br Optional. If set, this will convert all remaining line-breaks after paragraphing. Default true.
179 * @return string Text which has been converted into correct paragraph tags.
181 function wpautop($pee, $br = 1) {
183 if ( trim($pee) === '' )
185 $pee = $pee . "\n"; // just to make things a little easier, pad the end
186 $pee = preg_replace('|<br />\s*<br />|', "\n\n", $pee);
187 // Space things out a little
188 $allblocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|option|form|map|area|blockquote|address|math|style|input|p|h[1-6]|hr|fieldset|legend|section|article|aside|hgroup|header|footer|nav|figure|figcaption|details|menu|summary)';
189 $pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee);
190 $pee = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $pee);
191 $pee = str_replace(array("\r\n", "\r"), "\n", $pee); // cross-platform newlines
192 if ( strpos($pee, '<object') !== false ) {
193 $pee = preg_replace('|\s*<param([^>]*)>\s*|', "<param$1>", $pee); // no pee inside object/embed
194 $pee = preg_replace('|\s*</embed>\s*|', '</embed>', $pee);
196 $pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates
197 // make paragraphs, including one at the end
198 $pees = preg_split('/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY);
200 foreach ( $pees as $tinkle )
201 $pee .= '<p>' . trim($tinkle, "\n") . "</p>\n";
202 $pee = preg_replace('|<p>\s*</p>|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace
203 $pee = preg_replace('!<p>([^<]+)</(div|address|form)>!', "<p>$1</p></$2>", $pee);
204 $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee); // don't pee all over a tag
205 $pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee); // problem with nested lists
206 $pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee);
207 $pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee);
208 $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)!', "$1", $pee);
209 $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
211 $pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', create_function('$matches', 'return str_replace("\n", "<WPPreserveNewline />", $matches[0]);'), $pee);
212 $pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee); // optionally make line breaks
213 $pee = str_replace('<WPPreserveNewline />', "\n", $pee);
215 $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', "$1", $pee);
216 $pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee);
217 if (strpos($pee, '<pre') !== false)
218 $pee = preg_replace_callback('!(<pre[^>]*>)(.*?)</pre>!is', 'clean_pre', $pee );
219 $pee = preg_replace( "|\n</p>$|", '</p>', $pee );
225 * Don't auto-p wrap shortcodes that stand alone
227 * Ensures that shortcodes are not wrapped in <<p>>...<</p>>.
231 * @param string $pee The content.
232 * @return string The filtered content.
234 function shortcode_unautop($pee) {
235 global $shortcode_tags;
237 if ( !empty($shortcode_tags) && is_array($shortcode_tags) ) {
238 $tagnames = array_keys($shortcode_tags);
239 $tagregexp = join( '|', array_map('preg_quote', $tagnames) );
240 $pee = preg_replace('/<p>\\s*?(\\[(' . $tagregexp . ')\\b.*?\\/?\\](?:.+?\\[\\/\\2\\])?)\\s*<\\/p>/s', '$1', $pee);
247 * Checks to see if a string is utf8 encoded.
249 * NOTE: This function checks for 5-Byte sequences, UTF8
250 * has Bytes Sequences with a maximum length of 4.
252 * @author bmorel at ssi dot fr (modified)
255 * @param string $str The string to be checked
256 * @return bool True if $str fits a UTF-8 model, false otherwise.
258 function seems_utf8($str) {
259 $length = strlen($str);
260 for ($i=0; $i < $length; $i++) {
262 if ($c < 0x80) $n = 0; # 0bbbbbbb
263 elseif (($c & 0xE0) == 0xC0) $n=1; # 110bbbbb
264 elseif (($c & 0xF0) == 0xE0) $n=2; # 1110bbbb
265 elseif (($c & 0xF8) == 0xF0) $n=3; # 11110bbb
266 elseif (($c & 0xFC) == 0xF8) $n=4; # 111110bb
267 elseif (($c & 0xFE) == 0xFC) $n=5; # 1111110b
268 else return false; # Does not match any model
269 for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
270 if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))
278 * Converts a number of special characters into their HTML entities.
280 * Specifically deals with: &, <, >, ", and '.
282 * $quote_style can be set to ENT_COMPAT to encode " to
283 * ", or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded.
287 * @param string $string The text which is to be encoded.
288 * @param mixed $quote_style Optional. Converts double quotes if set to ENT_COMPAT, both single and double if set to ENT_QUOTES or none if set to ENT_NOQUOTES. Also compatible with old values; converting single quotes if set to 'single', double if set to 'double' or both if otherwise set. Default is ENT_NOQUOTES.
289 * @param string $charset Optional. The character encoding of the string. Default is false.
290 * @param boolean $double_encode Optional. Whether to encode existing html entities. Default is false.
291 * @return string The encoded text with HTML entities.
293 function _wp_specialchars( $string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false ) {
294 $string = (string) $string;
296 if ( 0 === strlen( $string ) ) {
300 // Don't bother if there are no specialchars - saves some processing
301 if ( !preg_match( '/[&<>"\']/', $string ) ) {
305 // Account for the previous behaviour of the function when the $quote_style is not an accepted value
306 if ( empty( $quote_style ) ) {
307 $quote_style = ENT_NOQUOTES;
308 } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
309 $quote_style = ENT_QUOTES;
312 // Store the site charset as a static to avoid multiple calls to wp_load_alloptions()
315 if ( !isset( $_charset ) ) {
316 $alloptions = wp_load_alloptions();
317 $_charset = isset( $alloptions['blog_charset'] ) ? $alloptions['blog_charset'] : '';
319 $charset = $_charset;
321 if ( in_array( $charset, array( 'utf8', 'utf-8', 'UTF8' ) ) ) {
325 $_quote_style = $quote_style;
327 if ( $quote_style === 'double' ) {
328 $quote_style = ENT_COMPAT;
329 $_quote_style = ENT_COMPAT;
330 } elseif ( $quote_style === 'single' ) {
331 $quote_style = ENT_NOQUOTES;
334 // Handle double encoding ourselves
335 if ( !$double_encode ) {
336 $string = wp_specialchars_decode( $string, $_quote_style );
339 // The previous line decodes &phrase; into &phrase; We must guarantee that &phrase; is valid before proceeding.
340 $string = wp_kses_normalize_entities($string);
342 // Now proceed with custom double-encoding silliness
343 $string = preg_replace( '/&(#?x?[0-9a-z]+);/i', '|wp_entity|$1|/wp_entity|', $string );
346 $string = @htmlspecialchars( $string, $quote_style, $charset );
348 // Handle double encoding ourselves
349 if ( !$double_encode ) {
350 $string = str_replace( array( '|wp_entity|', '|/wp_entity|' ), array( '&', ';' ), $string );
353 // Backwards compatibility
354 if ( 'single' === $_quote_style ) {
355 $string = str_replace( "'", ''', $string );
362 * Converts a number of HTML entities into their special characters.
364 * Specifically deals with: &, <, >, ", and '.
366 * $quote_style can be set to ENT_COMPAT to decode " entities,
367 * or ENT_QUOTES to do both " and '. Default is ENT_NOQUOTES where no quotes are decoded.
371 * @param string $string The text which is to be decoded.
372 * @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.
373 * @return string The decoded text without HTML entities.
375 function wp_specialchars_decode( $string, $quote_style = ENT_NOQUOTES ) {
376 $string = (string) $string;
378 if ( 0 === strlen( $string ) ) {
382 // Don't bother if there are no entities - saves a lot of processing
383 if ( strpos( $string, '&' ) === false ) {
387 // Match the previous behaviour of _wp_specialchars() when the $quote_style is not an accepted value
388 if ( empty( $quote_style ) ) {
389 $quote_style = ENT_NOQUOTES;
390 } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
391 $quote_style = ENT_QUOTES;
394 // More complete than get_html_translation_table( HTML_SPECIALCHARS )
395 $single = array( ''' => '\'', ''' => '\'' );
396 $single_preg = array( '/�*39;/' => ''', '/�*27;/i' => ''' );
397 $double = array( '"' => '"', '"' => '"', '"' => '"' );
398 $double_preg = array( '/�*34;/' => '"', '/�*22;/i' => '"' );
399 $others = array( '<' => '<', '<' => '<', '>' => '>', '>' => '>', '&' => '&', '&' => '&', '&' => '&' );
400 $others_preg = array( '/�*60;/' => '<', '/�*62;/' => '>', '/�*38;/' => '&', '/�*26;/i' => '&' );
402 if ( $quote_style === ENT_QUOTES ) {
403 $translation = array_merge( $single, $double, $others );
404 $translation_preg = array_merge( $single_preg, $double_preg, $others_preg );
405 } elseif ( $quote_style === ENT_COMPAT || $quote_style === 'double' ) {
406 $translation = array_merge( $double, $others );
407 $translation_preg = array_merge( $double_preg, $others_preg );
408 } elseif ( $quote_style === 'single' ) {
409 $translation = array_merge( $single, $others );
410 $translation_preg = array_merge( $single_preg, $others_preg );
411 } elseif ( $quote_style === ENT_NOQUOTES ) {
412 $translation = $others;
413 $translation_preg = $others_preg;
416 // Remove zero padding on numeric entities
417 $string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string );
419 // Replace characters according to translation table
420 return strtr( $string, $translation );
424 * Checks for invalid UTF8 in a string.
428 * @param string $string The text which is to be checked.
429 * @param boolean $strip Optional. Whether to attempt to strip out invalid UTF8. Default is false.
430 * @return string The checked text.
432 function wp_check_invalid_utf8( $string, $strip = false ) {
433 $string = (string) $string;
435 if ( 0 === strlen( $string ) ) {
439 // Store the site charset as a static to avoid multiple calls to get_option()
441 if ( !isset( $is_utf8 ) ) {
442 $is_utf8 = in_array( get_option( 'blog_charset' ), array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ) );
448 // Check for support for utf8 in the installed PCRE library once and store the result in a static
450 if ( !isset( $utf8_pcre ) ) {
451 $utf8_pcre = @preg_match( '/^./u', 'a' );
453 // We can't demand utf8 in the PCRE installation, so just return the string in those cases
458 // preg_match fails when it encounters invalid UTF8 in $string
459 if ( 1 === @preg_match( '/^./us', $string ) ) {
463 // Attempt to strip the bad chars if requested (not recommended)
464 if ( $strip && function_exists( 'iconv' ) ) {
465 return iconv( 'utf-8', 'utf-8', $string );
472 * Encode the Unicode values to be used in the URI.
476 * @param string $utf8_string
477 * @param int $length Max length of the string
478 * @return string String with Unicode encoded for URI.
480 function utf8_uri_encode( $utf8_string, $length = 0 ) {
486 $string_length = strlen( $utf8_string );
487 for ($i = 0; $i < $string_length; $i++ ) {
489 $value = ord( $utf8_string[ $i ] );
491 if ( $value < 128 ) {
492 if ( $length && ( $unicode_length >= $length ) )
494 $unicode .= chr($value);
497 if ( count( $values ) == 0 ) $num_octets = ( $value < 224 ) ? 2 : 3;
501 if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length )
503 if ( count( $values ) == $num_octets ) {
504 if ($num_octets == 3) {
505 $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]) . '%' . dechex($values[2]);
506 $unicode_length += 9;
508 $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]);
509 $unicode_length += 6;
522 * Converts all accent characters to ASCII characters.
524 * If there are no accent characters, then the string given is just returned.
528 * @param string $string Text that might have accent characters
529 * @return string Filtered string with replaced "nice" characters.
531 function remove_accents($string) {
532 if ( !preg_match('/[\x80-\xff]/', $string) )
535 if (seems_utf8($string)) {
537 // Decompositions for Latin-1 Supplement
538 chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
539 chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
540 chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
541 chr(195).chr(135) => 'C', chr(195).chr(136) => 'E',
542 chr(195).chr(137) => 'E', chr(195).chr(138) => 'E',
543 chr(195).chr(139) => 'E', chr(195).chr(140) => 'I',
544 chr(195).chr(141) => 'I', chr(195).chr(142) => 'I',
545 chr(195).chr(143) => 'I', chr(195).chr(145) => 'N',
546 chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
547 chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
548 chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
549 chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
550 chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
551 chr(195).chr(159) => 's', chr(195).chr(160) => 'a',
552 chr(195).chr(161) => 'a', chr(195).chr(162) => 'a',
553 chr(195).chr(163) => 'a', chr(195).chr(164) => 'a',
554 chr(195).chr(165) => 'a', chr(195).chr(167) => 'c',
555 chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
556 chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
557 chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
558 chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
559 chr(195).chr(177) => 'n', chr(195).chr(178) => 'o',
560 chr(195).chr(179) => 'o', chr(195).chr(180) => 'o',
561 chr(195).chr(181) => 'o', chr(195).chr(182) => 'o',
562 chr(195).chr(182) => 'o', chr(195).chr(185) => 'u',
563 chr(195).chr(186) => 'u', chr(195).chr(187) => 'u',
564 chr(195).chr(188) => 'u', chr(195).chr(189) => 'y',
565 chr(195).chr(191) => 'y',
566 // Decompositions for Latin Extended-A
567 chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
568 chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
569 chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
570 chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
571 chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
572 chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
573 chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
574 chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
575 chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
576 chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
577 chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
578 chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
579 chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
580 chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
581 chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
582 chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
583 chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
584 chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
585 chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
586 chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
587 chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
588 chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
589 chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
590 chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
591 chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
592 chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
593 chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
594 chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
595 chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
596 chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
597 chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
598 chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
599 chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
600 chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
601 chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
602 chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
603 chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
604 chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
605 chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
606 chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
607 chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
608 chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
609 chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
610 chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
611 chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
612 chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
613 chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
614 chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
615 chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
616 chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
617 chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
618 chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
619 chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
620 chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
621 chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
622 chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
623 chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
624 chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
625 chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
626 chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
627 chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
628 chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
629 chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
630 chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
632 chr(226).chr(130).chr(172) => 'E',
634 chr(194).chr(163) => '');
636 $string = strtr($string, $chars);
638 // Assume ISO-8859-1 if not UTF-8
639 $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
640 .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
641 .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
642 .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
643 .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
644 .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
645 .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
646 .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
647 .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
648 .chr(252).chr(253).chr(255);
650 $chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";
652 $string = strtr($string, $chars['in'], $chars['out']);
653 $double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
654 $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
655 $string = str_replace($double_chars['in'], $double_chars['out'], $string);
662 * Sanitizes a filename replacing whitespace with dashes
664 * Removes special characters that are illegal in filenames on certain
665 * operating systems and special characters requiring special escaping
666 * to manipulate at the command line. Replaces spaces and consecutive
667 * dashes with a single dash. Trim period, dash and underscore from beginning
668 * and end of filename.
672 * @param string $filename The filename to be sanitized
673 * @return string The sanitized filename
675 function sanitize_file_name( $filename ) {
676 $filename_raw = $filename;
677 $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", chr(0));
678 $special_chars = apply_filters('sanitize_file_name_chars', $special_chars, $filename_raw);
679 $filename = str_replace($special_chars, '', $filename);
680 $filename = preg_replace('/[\s-]+/', '-', $filename);
681 $filename = trim($filename, '.-_');
683 // Split the filename into a base and extension[s]
684 $parts = explode('.', $filename);
686 // Return if only one extension
687 if ( count($parts) <= 2 )
688 return apply_filters('sanitize_file_name', $filename, $filename_raw);
690 // Process multiple extensions
691 $filename = array_shift($parts);
692 $extension = array_pop($parts);
693 $mimes = get_allowed_mime_types();
695 // Loop over any intermediate extensions. Munge them with a trailing underscore if they are a 2 - 5 character
696 // long alpha string not in the extension whitelist.
697 foreach ( (array) $parts as $part) {
698 $filename .= '.' . $part;
700 if ( preg_match("/^[a-zA-Z]{2,5}\d?$/", $part) ) {
702 foreach ( $mimes as $ext_preg => $mime_match ) {
703 $ext_preg = '!(^' . $ext_preg . ')$!i';
704 if ( preg_match( $ext_preg, $part ) ) {
713 $filename .= '.' . $extension;
715 return apply_filters('sanitize_file_name', $filename, $filename_raw);
719 * Sanitize username stripping out unsafe characters.
721 * If $strict is true, only alphanumeric characters (as well as _, space, ., -,
723 * Removes tags, octets, entities, and if strict is enabled, will remove all
724 * non-ASCII characters. After sanitizing, it passes the username, raw username
725 * (the username in the parameter), and the strict parameter as parameters for
729 * @uses apply_filters() Calls 'sanitize_user' hook on username, raw username,
730 * and $strict parameter.
732 * @param string $username The username to be sanitized.
733 * @param bool $strict If set limits $username to specific characters. Default false.
734 * @return string The sanitized username, after passing through filters.
736 function sanitize_user( $username, $strict = false ) {
737 $raw_username = $username;
738 $username = wp_strip_all_tags( $username );
739 $username = remove_accents( $username );
741 $username = preg_replace( '|%([a-fA-F0-9][a-fA-F0-9])|', '', $username );
742 $username = preg_replace( '/&.+?;/', '', $username ); // Kill entities
744 // If strict, reduce to ASCII for max portability.
746 $username = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $username );
748 // Consolidate contiguous whitespace
749 $username = preg_replace( '|\s+|', ' ', $username );
751 return apply_filters( 'sanitize_user', $username, $raw_username, $strict );
755 * Sanitize a string key.
757 * Keys are used as internal identifiers. They should be lowercase ASCII. Dashes and underscores are allowed.
761 * @param string $key String key
762 * @return string Sanitized key
764 function sanitize_key( $key ) {
766 $key = wp_strip_all_tags($key);
768 $key = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '', $key);
769 $key = preg_replace('/&.+?;/', '', $key); // Kill entities
771 $key = preg_replace('|[^a-z0-9 _.\-@]|i', '', $key);
773 // Consolidate contiguous whitespace
774 $key = preg_replace('|\s+|', ' ', $key);
776 return apply_filters('sanitize_key', $key, $raw_key);
780 * Sanitizes title or use fallback title.
782 * Specifically, HTML and PHP tags are stripped. Further actions can be added
783 * via the plugin API. If $title is empty and $fallback_title is set, the latter
788 * @param string $title The string to be sanitized.
789 * @param string $fallback_title Optional. A title to use if $title is empty.
790 * @return string The sanitized string.
792 function sanitize_title($title, $fallback_title = '') {
794 $title = strip_tags($title);
795 $title = apply_filters('sanitize_title', $title, $raw_title);
797 if ( '' === $title || false === $title )
798 $title = $fallback_title;
804 * Sanitizes title, replacing whitespace with dashes.
806 * Limits the output to alphanumeric characters, underscore (_) and dash (-).
807 * Whitespace becomes a dash.
811 * @param string $title The title to be sanitized.
812 * @return string The sanitized title.
814 function sanitize_title_with_dashes($title) {
815 $title = strip_tags($title);
816 // Preserve escaped octets.
817 $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
818 // Remove percent signs that are not part of an octet.
819 $title = str_replace('%', '', $title);
821 $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
823 $title = remove_accents($title);
824 if (seems_utf8($title)) {
825 if (function_exists('mb_strtolower')) {
826 $title = mb_strtolower($title, 'UTF-8');
828 $title = utf8_uri_encode($title, 200);
831 $title = strtolower($title);
832 $title = preg_replace('/&.+?;/', '', $title); // kill entities
833 $title = str_replace('.', '-', $title);
834 $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
835 $title = preg_replace('/\s+/', '-', $title);
836 $title = preg_replace('|-+|', '-', $title);
837 $title = trim($title, '-');
843 * Ensures a string is a valid SQL order by clause.
845 * Accepts one or more columns, with or without ASC/DESC, and also accepts
850 * @param string $orderby Order by string to be checked.
851 * @return string|false Returns the order by clause if it is a match, false otherwise.
853 function sanitize_sql_orderby( $orderby ){
854 preg_match('/^\s*([a-z0-9_]+(\s+(ASC|DESC))?(\s*,\s*|\s*$))+|^\s*RAND\(\s*\)\s*$/i', $orderby, $obmatches);
861 * Santizes a html classname to ensure it only contains valid characters
863 * Strips the string down to A-Z,a-z,0-9,'-' if this results in an empty
864 * string then it will return the alternative value supplied.
866 * @todo Expand to support the full range of CDATA that a class attribute can contain.
870 * @param string $class The classname to be sanitized
871 * @param string $fallback Optional. The value to return if the sanitization end's up as an empty string.
872 * Defaults to an empty string.
873 * @return string The sanitized value
875 function sanitize_html_class( $class, $fallback = '' ) {
876 //Strip out any % encoded octets
877 $sanitized = preg_replace('|%[a-fA-F0-9][a-fA-F0-9]|', '', $class);
879 //Limit to A-Z,a-z,0-9,'-'
880 $sanitized = preg_replace('/[^A-Za-z0-9-]/', '', $sanitized);
882 if ( '' == $sanitized )
883 $sanitized = $fallback;
885 return apply_filters( 'sanitize_html_class', $sanitized, $class, $fallback );
889 * Converts a number of characters from a string.
891 * Metadata tags <<title>> and <<category>> are removed, <<br>> and <<hr>> are
892 * converted into correct XHTML and Unicode characters are converted to the
897 * @param string $content String of characters to be converted.
898 * @param string $deprecated Not used.
899 * @return string Converted string.
901 function convert_chars($content, $deprecated = '') {
902 if ( !empty( $deprecated ) )
903 _deprecated_argument( __FUNCTION__, '0.71' );
905 // Translation of invalid Unicode references range to valid range
906 $wp_htmltranswinuni = array(
907 '€' => '€', // the Euro sign
909 '‚' => '‚', // these are Windows CP1252 specific characters
910 'ƒ' => 'ƒ', // they would look weird on non-Windows browsers
911 '„' => '„',
912 '…' => '…',
913 '†' => '†',
914 '‡' => '‡',
915 'ˆ' => 'ˆ',
916 '‰' => '‰',
917 'Š' => 'Š',
918 '‹' => '‹',
919 'Œ' => 'Œ',
921 'Ž' => 'ž',
924 '‘' => '‘',
925 '’' => '’',
926 '“' => '“',
927 '”' => '”',
928 '•' => '•',
929 '–' => '–',
930 '—' => '—',
931 '˜' => '˜',
932 '™' => '™',
933 'š' => 'š',
934 '›' => '›',
935 'œ' => 'œ',
941 // Remove metadata tags
942 $content = preg_replace('/<title>(.+?)<\/title>/','',$content);
943 $content = preg_replace('/<category>(.+?)<\/category>/','',$content);
945 // Converts lone & characters into & (a.k.a. &)
946 $content = preg_replace('/&([^#])(?![a-z1-4]{1,8};)/i', '&$1', $content);
949 $content = strtr($content, $wp_htmltranswinuni);
951 // Just a little XHTML help
952 $content = str_replace('<br>', '<br />', $content);
953 $content = str_replace('<hr>', '<hr />', $content);
959 * Will only balance the tags if forced to and the option is set to balance tags.
961 * The option 'use_balanceTags' is used for whether the tags will be balanced.
962 * Both the $force parameter and 'use_balanceTags' option will have to be true
963 * before the tags will be balanced.
967 * @param string $text Text to be balanced
968 * @param bool $force Forces balancing, ignoring the value of the option. Default false.
969 * @return string Balanced text
971 function balanceTags( $text, $force = false ) {
972 if ( !$force && get_option('use_balanceTags') == 0 )
974 return force_balance_tags( $text );
978 * Balances tags of string using a modified stack.
982 * @author Leonard Lin <leonard@acm.org>
984 * @copyright November 4, 2001
986 * @todo Make better - change loop condition to $text in 1.2
987 * @internal Modified by Scott Reilly (coffee2code) 02 Aug 2004
988 * 1.1 Fixed handling of append/stack pop order of end text
989 * Added Cleaning Hooks
992 * @param string $text Text to be balanced.
993 * @return string Balanced text.
995 function force_balance_tags( $text ) {
1000 $single_tags = array('br', 'hr', 'img', 'input'); // Known single-entity/self-closing tags
1001 $nestable_tags = array('blockquote', 'div', 'span'); // Tags that can be immediately nested within themselves
1003 // WP bug fix for comments - in case you REALLY meant to type '< !--'
1004 $text = str_replace('< !--', '< !--', $text);
1005 // WP bug fix for LOVE <3 (and other situations with '<' before a number)
1006 $text = preg_replace('#<([0-9]{1})#', '<$1', $text);
1008 while ( preg_match("/<(\/?[\w:]*)\s*([^>]*)>/", $text, $regex) ) {
1009 $newtext .= $tagqueue;
1011 $i = strpos($text, $regex[0]);
1012 $l = strlen($regex[0]);
1014 // clear the shifter
1017 if ( isset($regex[1][0]) && '/' == $regex[1][0] ) { // End Tag
1018 $tag = strtolower(substr($regex[1],1));
1019 // if too many closing tags
1020 if( $stacksize <= 0 ) {
1022 // or close to be safe $tag = '/' . $tag;
1024 // if stacktop value = tag close value then pop
1025 else if ( $tagstack[$stacksize - 1] == $tag ) { // found closing tag
1026 $tag = '</' . $tag . '>'; // Close Tag
1028 array_pop( $tagstack );
1030 } else { // closing tag not at top, search for it
1031 for ( $j = $stacksize-1; $j >= 0; $j-- ) {
1032 if ( $tagstack[$j] == $tag ) {
1033 // add tag to tagqueue
1034 for ( $k = $stacksize-1; $k >= $j; $k--) {
1035 $tagqueue .= '</' . array_pop( $tagstack ) . '>';
1043 } else { // Begin Tag
1044 $tag = strtolower($regex[1]);
1048 // If self-closing or '', don't do anything.
1049 if ( substr($regex[2],-1) == '/' || $tag == '' ) {
1052 // ElseIf it's a known single-entity tag but it doesn't close itself, do so
1053 elseif ( in_array($tag, $single_tags) ) {
1055 } else { // Push the tag onto the stack
1056 // If the top of the stack is the same as the tag we want to push, close previous tag
1057 if ( $stacksize > 0 && !in_array($tag, $nestable_tags) && $tagstack[$stacksize - 1] == $tag ) {
1058 $tagqueue = '</' . array_pop ($tagstack) . '>';
1061 $stacksize = array_push ($tagstack, $tag);
1065 $attributes = $regex[2];
1066 if( !empty($attributes) )
1067 $attributes = ' '.$attributes;
1069 $tag = '<' . $tag . $attributes . '>';
1070 //If already queuing a close tag, then put this tag on, too
1071 if ( !empty($tagqueue) ) {
1076 $newtext .= substr($text, 0, $i) . $tag;
1077 $text = substr($text, $i + $l);
1081 $newtext .= $tagqueue;
1083 // Add Remaining text
1087 while( $x = array_pop($tagstack) )
1088 $newtext .= '</' . $x . '>'; // Add remaining tags to close
1090 // WP fix for the bug with HTML comments
1091 $newtext = str_replace("< !--","<!--",$newtext);
1092 $newtext = str_replace("< !--","< !--",$newtext);
1098 * Acts on text which is about to be edited.
1100 * Unless $richedit is set, it is simply a holder for the 'format_to_edit'
1101 * filter. If $richedit is set true htmlspecialchars() will be run on the
1102 * content, converting special characters to HTMl entities.
1106 * @param string $content The text about to be edited.
1107 * @param bool $richedit Whether the $content should pass through htmlspecialchars(). Default false.
1108 * @return string The text after the filter (and possibly htmlspecialchars()) has been run.
1110 function format_to_edit($content, $richedit = false) {
1111 $content = apply_filters('format_to_edit', $content);
1113 $content = htmlspecialchars($content);
1118 * Holder for the 'format_to_post' filter.
1122 * @param string $content The text to pass through the filter.
1123 * @return string Text returned from the 'format_to_post' filter.
1125 function format_to_post($content) {
1126 $content = apply_filters('format_to_post', $content);
1131 * Add leading zeros when necessary.
1133 * If you set the threshold to '4' and the number is '10', then you will get
1134 * back '0010'. If you set the number to '4' and the number is '5000', then you
1135 * will get back '5000'.
1137 * Uses sprintf to append the amount of zeros based on the $threshold parameter
1138 * and the size of the number. If the number is large enough, then no zeros will
1143 * @param mixed $number Number to append zeros to if not greater than threshold.
1144 * @param int $threshold Digit places number needs to be to not have zeros added.
1145 * @return string Adds leading zeros to number if needed.
1147 function zeroise($number, $threshold) {
1148 return sprintf('%0'.$threshold.'s', $number);
1152 * Adds backslashes before letters and before a number at the start of a string.
1156 * @param string $string Value to which backslashes will be added.
1157 * @return string String with backslashes inserted.
1159 function backslashit($string) {
1160 $string = preg_replace('/^([0-9])/', '\\\\\\\\\1', $string);
1161 $string = preg_replace('/([a-z])/i', '\\\\\1', $string);
1166 * Appends a trailing slash.
1168 * Will remove trailing slash if it exists already before adding a trailing
1169 * slash. This prevents double slashing a string or path.
1171 * The primary use of this is for paths and thus should be used for paths. It is
1172 * not restricted to paths and offers no specific path support.
1175 * @uses untrailingslashit() Unslashes string if it was slashed already.
1177 * @param string $string What to add the trailing slash to.
1178 * @return string String with trailing slash added.
1180 function trailingslashit($string) {
1181 return untrailingslashit($string) . '/';
1185 * Removes trailing slash if it exists.
1187 * The primary use of this is for paths and thus should be used for paths. It is
1188 * not restricted to paths and offers no specific path support.
1192 * @param string $string What to remove the trailing slash from.
1193 * @return string String without the trailing slash.
1195 function untrailingslashit($string) {
1196 return rtrim($string, '/');
1200 * Adds slashes to escape strings.
1202 * Slashes will first be removed if magic_quotes_gpc is set, see {@link
1203 * http://www.php.net/magic_quotes} for more details.
1207 * @param string $gpc The string returned from HTTP request data.
1208 * @return string Returns a string escaped with slashes.
1210 function addslashes_gpc($gpc) {
1211 if ( get_magic_quotes_gpc() )
1212 $gpc = stripslashes($gpc);
1214 return esc_sql($gpc);
1218 * Navigates through an array and removes slashes from the values.
1220 * If an array is passed, the array_map() function causes a callback to pass the
1221 * value back to the function. The slashes from this value will removed.
1225 * @param array|string $value The array or string to be striped.
1226 * @return array|string Stripped array (or string in the callback).
1228 function stripslashes_deep($value) {
1229 if ( is_array($value) ) {
1230 $value = array_map('stripslashes_deep', $value);
1231 } elseif ( is_object($value) ) {
1232 $vars = get_object_vars( $value );
1233 foreach ($vars as $key=>$data) {
1234 $value->{$key} = stripslashes_deep( $data );
1237 $value = stripslashes($value);
1244 * Navigates through an array and encodes the values to be used in a URL.
1246 * Uses a callback to pass the value of the array back to the function as a
1251 * @param array|string $value The array or string to be encoded.
1252 * @return array|string $value The encoded array (or string from the callback).
1254 function urlencode_deep($value) {
1255 $value = is_array($value) ? array_map('urlencode_deep', $value) : urlencode($value);
1260 * Converts email addresses characters to HTML entities to block spam bots.
1264 * @param string $emailaddy Email address.
1265 * @param int $mailto Optional. Range from 0 to 1. Used for encoding.
1266 * @return string Converted email address.
1268 function antispambot($emailaddy, $mailto=0) {
1269 $emailNOSPAMaddy = '';
1270 srand ((float) microtime() * 1000000);
1271 for ($i = 0; $i < strlen($emailaddy); $i = $i + 1) {
1272 $j = floor(rand(0, 1+$mailto));
1274 $emailNOSPAMaddy .= '&#'.ord(substr($emailaddy,$i,1)).';';
1276 $emailNOSPAMaddy .= substr($emailaddy,$i,1);
1278 $emailNOSPAMaddy .= '%'.zeroise(dechex(ord(substr($emailaddy, $i, 1))), 2);
1281 $emailNOSPAMaddy = str_replace('@','@',$emailNOSPAMaddy);
1282 return $emailNOSPAMaddy;
1286 * Callback to convert URI match to HTML A element.
1288 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1289 * make_clickable()}.
1294 * @param array $matches Single Regex Match.
1295 * @return string HTML A element with URI address.
1297 function _make_url_clickable_cb($matches) {
1300 $url = esc_url($url);
1304 return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>";
1308 * Callback to convert URL match to HTML A element.
1310 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1311 * make_clickable()}.
1316 * @param array $matches Single Regex Match.
1317 * @return string HTML A element with URL address.
1319 function _make_web_ftp_clickable_cb($matches) {
1321 $dest = $matches[2];
1322 $dest = 'http://' . $dest;
1323 $dest = esc_url($dest);
1327 // removed trailing [.,;:)] from URL
1328 if ( in_array( substr($dest, -1), array('.', ',', ';', ':', ')') ) === true ) {
1329 $ret = substr($dest, -1);
1330 $dest = substr($dest, 0, strlen($dest)-1);
1332 return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>$ret";
1336 * Callback to convert email address match to HTML A element.
1338 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1339 * make_clickable()}.
1344 * @param array $matches Single Regex Match.
1345 * @return string HTML A element with email address.
1347 function _make_email_clickable_cb($matches) {
1348 $email = $matches[2] . '@' . $matches[3];
1349 return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
1353 * Convert plaintext URI to HTML links.
1355 * Converts URI, www and ftp, and email addresses. Finishes by fixing links
1360 * @param string $ret Content to convert URIs.
1361 * @return string Content with converted URIs.
1363 function make_clickable($ret) {
1365 // in testing, using arrays here was found to be faster
1366 $ret = preg_replace_callback('#(?<=[\s>])(\()?([\w]+?://(?:[\w\\x80-\\xff\#$%&~/=?@\[\](+-]|[.,;:](?![\s<]|(\))?([\s]|$))|(?(1)\)(?![\s<.,;:]|$)|\)))+)#is', '_make_url_clickable_cb', $ret);
1367 $ret = preg_replace_callback('#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]+)#is', '_make_web_ftp_clickable_cb', $ret);
1368 $ret = preg_replace_callback('#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret);
1369 // this one is not in an array because we need it to run last, for cleanup of accidental links within links
1370 $ret = preg_replace("#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i", "$1$3</a>", $ret);
1376 * Adds rel nofollow string to all HTML A elements in content.
1380 * @param string $text Content that may contain HTML A elements.
1381 * @return string Converted content.
1383 function wp_rel_nofollow( $text ) {
1384 // This is a pre save filter, so text is already escaped.
1385 $text = stripslashes($text);
1386 $text = preg_replace_callback('|<a (.+?)>|i', 'wp_rel_nofollow_callback', $text);
1387 $text = esc_sql($text);
1392 * Callback to used to add rel=nofollow string to HTML A element.
1394 * Will remove already existing rel="nofollow" and rel='nofollow' from the
1395 * string to prevent from invalidating (X)HTML.
1399 * @param array $matches Single Match
1400 * @return string HTML A Element with rel nofollow.
1402 function wp_rel_nofollow_callback( $matches ) {
1403 $text = $matches[1];
1404 $text = str_replace(array(' rel="nofollow"', " rel='nofollow'"), '', $text);
1405 return "<a $text rel=\"nofollow\">";
1409 * Convert one smiley code to the icon graphic file equivalent.
1411 * Looks up one smiley code in the $wpsmiliestrans global array and returns an
1412 * <img> string for that smiley.
1414 * @global array $wpsmiliestrans
1417 * @param string $smiley Smiley code to convert to image.
1418 * @return string Image string for smiley.
1420 function translate_smiley($smiley) {
1421 global $wpsmiliestrans;
1423 if (count($smiley) == 0) {
1427 $siteurl = get_option( 'siteurl' );
1429 $smiley = trim(reset($smiley));
1430 $img = $wpsmiliestrans[$smiley];
1431 $smiley_masked = esc_attr($smiley);
1433 $srcurl = apply_filters('smilies_src', "$siteurl/wp-includes/images/smilies/$img", $img, $siteurl);
1435 return " <img src='$srcurl' alt='$smiley_masked' class='wp-smiley' /> ";
1439 * Convert text equivalent of smilies to images.
1441 * Will only convert smilies if the option 'use_smilies' is true and the global
1442 * used in the function isn't empty.
1445 * @uses $wp_smiliessearch
1447 * @param string $text Content to convert smilies from text.
1448 * @return string Converted content with text smilies replaced with images.
1450 function convert_smilies($text) {
1451 global $wp_smiliessearch;
1453 if ( get_option('use_smilies') && !empty($wp_smiliessearch) ) {
1454 // HTML loop taken from texturize function, could possible be consolidated
1455 $textarr = preg_split("/(<.*>)/U", $text, -1, PREG_SPLIT_DELIM_CAPTURE); // capture the tags as well as in between
1456 $stop = count($textarr);// loop stuff
1457 for ($i = 0; $i < $stop; $i++) {
1458 $content = $textarr[$i];
1459 if ((strlen($content) > 0) && ('<' != $content{0})) { // If it's not a tag
1460 $content = preg_replace_callback($wp_smiliessearch, 'translate_smiley', $content);
1462 $output .= $content;
1465 // return default text.
1472 * Verifies that an email is valid.
1474 * Does not grok i18n domains. Not RFC compliant.
1478 * @param string $email Email address to verify.
1479 * @param boolean $deprecated. Deprecated.
1480 * @return string|bool Either false or the valid email address.
1482 function is_email( $email, $deprecated = false ) {
1483 if ( ! empty( $deprecated ) )
1484 _deprecated_argument( __FUNCTION__, '3.0' );
1486 // Test for the minimum length the email can be
1487 if ( strlen( $email ) < 3 ) {
1488 return apply_filters( 'is_email', false, $email, 'email_too_short' );
1491 // Test for an @ character after the first position
1492 if ( strpos( $email, '@', 1 ) === false ) {
1493 return apply_filters( 'is_email', false, $email, 'email_no_at' );
1496 // Split out the local and domain parts
1497 list( $local, $domain ) = explode( '@', $email, 2 );
1500 // Test for invalid characters
1501 if ( !preg_match( '/^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]+$/', $local ) ) {
1502 return apply_filters( 'is_email', false, $email, 'local_invalid_chars' );
1506 // Test for sequences of periods
1507 if ( preg_match( '/\.{2,}/', $domain ) ) {
1508 return apply_filters( 'is_email', false, $email, 'domain_period_sequence' );
1511 // Test for leading and trailing periods and whitespace
1512 if ( trim( $domain, " \t\n\r\0\x0B." ) !== $domain ) {
1513 return apply_filters( 'is_email', false, $email, 'domain_period_limits' );
1516 // Split the domain into subs
1517 $subs = explode( '.', $domain );
1519 // Assume the domain will have at least two subs
1520 if ( 2 > count( $subs ) ) {
1521 return apply_filters( 'is_email', false, $email, 'domain_no_periods' );
1524 // Loop through each sub
1525 foreach ( $subs as $sub ) {
1526 // Test for leading and trailing hyphens and whitespace
1527 if ( trim( $sub, " \t\n\r\0\x0B-" ) !== $sub ) {
1528 return apply_filters( 'is_email', false, $email, 'sub_hyphen_limits' );
1531 // Test for invalid characters
1532 if ( !preg_match('/^[a-z0-9-]+$/i', $sub ) ) {
1533 return apply_filters( 'is_email', false, $email, 'sub_invalid_chars' );
1537 // Congratulations your email made it!
1538 return apply_filters( 'is_email', $email, $email, null );
1542 * Convert to ASCII from email subjects.
1545 * @usedby wp_mail() handles charsets in email subjects
1547 * @param string $string Subject line
1548 * @return string Converted string to ASCII
1550 function wp_iso_descrambler($string) {
1551 /* this may only work with iso-8859-1, I'm afraid */
1552 if (!preg_match('#\=\?(.+)\?Q\?(.+)\?\=#i', $string, $matches)) {
1555 $subject = str_replace('_', ' ', $matches[2]);
1556 $subject = preg_replace_callback('#\=([0-9a-f]{2})#i', create_function('$match', 'return chr(hexdec(strtolower($match[1])));'), $subject);
1562 * Returns a date in the GMT equivalent.
1564 * Requires and returns a date in the Y-m-d H:i:s format. Simply subtracts the
1565 * value of the 'gmt_offset' option. Return format can be overridden using the
1566 * $format parameter. If PHP5 is supported, the function uses the DateTime and
1567 * DateTimeZone objects to respect time zone differences in DST.
1571 * @uses get_option() to retrieve the the value of 'gmt_offset'.
1572 * @param string $string The date to be converted.
1573 * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
1574 * @return string GMT version of the date provided.
1576 function get_gmt_from_date($string, $format = 'Y-m-d H:i:s') {
1577 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);
1578 $tz = get_option('timezone_string');
1579 if( class_exists('DateTime') && $tz ) {
1581 date_default_timezone_set( $tz );
1582 $datetime = new DateTime( $string );
1583 $datetime->setTimezone( new DateTimeZone('UTC') );
1584 $offset = $datetime->getOffset();
1585 $datetime->modify( '+' . $offset / 3600 . ' hours');
1586 $string_gmt = gmdate($format, $datetime->format('U'));
1588 date_default_timezone_set('UTC');
1592 $string_time = gmmktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]);
1593 $string_gmt = gmdate($format, $string_time - get_option('gmt_offset') * 3600);
1599 * Converts a GMT date into the correct format for the blog.
1601 * Requires and returns in the Y-m-d H:i:s format. Simply adds the value of
1602 * gmt_offset.Return format can be overridden using the $format parameter
1606 * @param string $string The date to be converted.
1607 * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
1608 * @return string Formatted date relative to the GMT offset.
1610 function get_date_from_gmt($string, $format = 'Y-m-d H:i:s') {
1611 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);
1612 $string_time = gmmktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]);
1613 $string_localtime = gmdate($format, $string_time + get_option('gmt_offset')*3600);
1614 return $string_localtime;
1618 * Computes an offset in seconds from an iso8601 timezone.
1622 * @param string $timezone Either 'Z' for 0 offset or '±hhmm'.
1623 * @return int|float The offset in seconds.
1625 function iso8601_timezone_to_offset($timezone) {
1626 // $timezone is either 'Z' or '[+|-]hhmm'
1627 if ($timezone == 'Z') {
1630 $sign = (substr($timezone, 0, 1) == '+') ? 1 : -1;
1631 $hours = intval(substr($timezone, 1, 2));
1632 $minutes = intval(substr($timezone, 3, 4)) / 60;
1633 $offset = $sign * 3600 * ($hours + $minutes);
1639 * Converts an iso8601 date to MySQL DateTime format used by post_date[_gmt].
1643 * @param string $date_string Date and time in ISO 8601 format {@link http://en.wikipedia.org/wiki/ISO_8601}.
1644 * @param string $timezone Optional. If set to GMT returns the time minus gmt_offset. Default is 'user'.
1645 * @return string The date and time in MySQL DateTime format - Y-m-d H:i:s.
1647 function iso8601_to_datetime($date_string, $timezone = 'user') {
1648 $timezone = strtolower($timezone);
1650 if ($timezone == 'gmt') {
1652 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);
1654 if (!empty($date_bits[7])) { // we have a timezone, so let's compute an offset
1655 $offset = iso8601_timezone_to_offset($date_bits[7]);
1656 } else { // we don't have a timezone, so we assume user local timezone (not server's!)
1657 $offset = 3600 * get_option('gmt_offset');
1660 $timestamp = gmmktime($date_bits[4], $date_bits[5], $date_bits[6], $date_bits[2], $date_bits[3], $date_bits[1]);
1661 $timestamp -= $offset;
1663 return gmdate('Y-m-d H:i:s', $timestamp);
1665 } else if ($timezone == 'user') {
1666 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);
1671 * Adds a element attributes to open links in new windows.
1673 * Comment text in popup windows should be filtered through this. Right now it's
1674 * a moderately dumb function, ideally it would detect whether a target or rel
1675 * attribute was already there and adjust its actions accordingly.
1679 * @param string $text Content to replace links to open in a new window.
1680 * @return string Content that has filtered links.
1682 function popuplinks($text) {
1683 $text = preg_replace('/<a (.+?)>/i', "<a $1 target='_blank' rel='external'>", $text);
1688 * Strips out all characters that are not allowable in an email.
1692 * @param string $email Email address to filter.
1693 * @return string Filtered email address.
1695 function sanitize_email( $email ) {
1696 // Test for the minimum length the email can be
1697 if ( strlen( $email ) < 3 ) {
1698 return apply_filters( 'sanitize_email', '', $email, 'email_too_short' );
1701 // Test for an @ character after the first position
1702 if ( strpos( $email, '@', 1 ) === false ) {
1703 return apply_filters( 'sanitize_email', '', $email, 'email_no_at' );
1706 // Split out the local and domain parts
1707 list( $local, $domain ) = explode( '@', $email, 2 );
1710 // Test for invalid characters
1711 $local = preg_replace( '/[^a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]/', '', $local );
1712 if ( '' === $local ) {
1713 return apply_filters( 'sanitize_email', '', $email, 'local_invalid_chars' );
1717 // Test for sequences of periods
1718 $domain = preg_replace( '/\.{2,}/', '', $domain );
1719 if ( '' === $domain ) {
1720 return apply_filters( 'sanitize_email', '', $email, 'domain_period_sequence' );
1723 // Test for leading and trailing periods and whitespace
1724 $domain = trim( $domain, " \t\n\r\0\x0B." );
1725 if ( '' === $domain ) {
1726 return apply_filters( 'sanitize_email', '', $email, 'domain_period_limits' );
1729 // Split the domain into subs
1730 $subs = explode( '.', $domain );
1732 // Assume the domain will have at least two subs
1733 if ( 2 > count( $subs ) ) {
1734 return apply_filters( 'sanitize_email', '', $email, 'domain_no_periods' );
1737 // Create an array that will contain valid subs
1738 $new_subs = array();
1740 // Loop through each sub
1741 foreach ( $subs as $sub ) {
1742 // Test for leading and trailing hyphens
1743 $sub = trim( $sub, " \t\n\r\0\x0B-" );
1745 // Test for invalid characters
1746 $sub = preg_replace( '/^[^a-z0-9-]+$/i', '', $sub );
1748 // If there's anything left, add it to the valid subs
1749 if ( '' !== $sub ) {
1754 // If there aren't 2 or more valid subs
1755 if ( 2 > count( $new_subs ) ) {
1756 return apply_filters( 'sanitize_email', '', $email, 'domain_no_valid_subs' );
1759 // Join valid subs into the new domain
1760 $domain = join( '.', $new_subs );
1762 // Put the email back together
1763 $email = $local . '@' . $domain;
1765 // Congratulations your email made it!
1766 return apply_filters( 'sanitize_email', $email, $email, null );
1770 * Determines the difference between two timestamps.
1772 * The difference is returned in a human readable format such as "1 hour",
1773 * "5 mins", "2 days".
1777 * @param int $from Unix timestamp from which the difference begins.
1778 * @param int $to Optional. Unix timestamp to end the time difference. Default becomes time() if not set.
1779 * @return string Human readable time difference.
1781 function human_time_diff( $from, $to = '' ) {
1784 $diff = (int) abs($to - $from);
1785 if ($diff <= 3600) {
1786 $mins = round($diff / 60);
1790 /* translators: min=minute */
1791 $since = sprintf(_n('%s min', '%s mins', $mins), $mins);
1792 } else if (($diff <= 86400) && ($diff > 3600)) {
1793 $hours = round($diff / 3600);
1797 $since = sprintf(_n('%s hour', '%s hours', $hours), $hours);
1798 } elseif ($diff >= 86400) {
1799 $days = round($diff / 86400);
1803 $since = sprintf(_n('%s day', '%s days', $days), $days);
1809 * Generates an excerpt from the content, if needed.
1811 * The excerpt word amount will be 55 words and if the amount is greater than
1812 * that, then the string ' [...]' will be appended to the excerpt. If the string
1813 * is less than 55 words, then the content will be returned as is.
1815 * The 55 word limit can be modified by plugins/themes using the excerpt_length filter
1816 * The ' [...]' string can be modified by plugins/themes using the excerpt_more filter
1820 * @param string $text The excerpt. If set to empty an excerpt is generated.
1821 * @return string The excerpt.
1823 function wp_trim_excerpt($text) {
1824 $raw_excerpt = $text;
1825 if ( '' == $text ) {
1826 $text = get_the_content('');
1828 $text = strip_shortcodes( $text );
1830 $text = apply_filters('the_content', $text);
1831 $text = str_replace(']]>', ']]>', $text);
1832 $text = strip_tags($text);
1833 $excerpt_length = apply_filters('excerpt_length', 55);
1834 $excerpt_more = apply_filters('excerpt_more', ' ' . '[...]');
1835 $words = preg_split("/[\n\r\t ]+/", $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY);
1836 if ( count($words) > $excerpt_length ) {
1838 $text = implode(' ', $words);
1839 $text = $text . $excerpt_more;
1841 $text = implode(' ', $words);
1844 return apply_filters('wp_trim_excerpt', $text, $raw_excerpt);
1848 * Converts named entities into numbered entities.
1852 * @param string $text The text within which entities will be converted.
1853 * @return string Text with converted entities.
1855 function ent2ncr($text) {
1857 '"' => '"',
1859 '⁄' => '/',
1863 ' ' => ' ',
1864 '¡' => '¡',
1865 '¢' => '¢',
1866 '£' => '£',
1867 '¤' => '¤',
1868 '¥' => '¥',
1869 '¦' => '¦',
1870 '&brkbar;' => '¦',
1871 '§' => '§',
1872 '¨' => '¨',
1873 '¨' => '¨',
1874 '©' => '©',
1875 'ª' => 'ª',
1876 '«' => '«',
1877 '¬' => '¬',
1878 '­' => '­',
1879 '®' => '®',
1880 '¯' => '¯',
1881 '&hibar;' => '¯',
1882 '°' => '°',
1883 '±' => '±',
1884 '²' => '²',
1885 '³' => '³',
1886 '´' => '´',
1887 'µ' => 'µ',
1888 '¶' => '¶',
1889 '·' => '·',
1890 '¸' => '¸',
1891 '¹' => '¹',
1892 'º' => 'º',
1893 '»' => '»',
1894 '¼' => '¼',
1895 '½' => '½',
1896 '¾' => '¾',
1897 '¿' => '¿',
1898 'À' => 'À',
1899 'Á' => 'Á',
1900 'Â' => 'Â',
1901 'Ã' => 'Ã',
1902 'Ä' => 'Ä',
1903 'Å' => 'Å',
1904 'Æ' => 'Æ',
1905 'Ç' => 'Ç',
1906 'È' => 'È',
1907 'É' => 'É',
1908 'Ê' => 'Ê',
1909 'Ë' => 'Ë',
1910 'Ì' => 'Ì',
1911 'Í' => 'Í',
1912 'Î' => 'Î',
1913 'Ï' => 'Ï',
1914 'Ð' => 'Ð',
1915 'Ñ' => 'Ñ',
1916 'Ò' => 'Ò',
1917 'Ó' => 'Ó',
1918 'Ô' => 'Ô',
1919 'Õ' => 'Õ',
1920 'Ö' => 'Ö',
1921 '×' => '×',
1922 'Ø' => 'Ø',
1923 'Ù' => 'Ù',
1924 'Ú' => 'Ú',
1925 'Û' => 'Û',
1926 'Ü' => 'Ü',
1927 'Ý' => 'Ý',
1928 'Þ' => 'Þ',
1929 'ß' => 'ß',
1930 'à' => 'à',
1931 'á' => 'á',
1932 'â' => 'â',
1933 'ã' => 'ã',
1934 'ä' => 'ä',
1935 'å' => 'å',
1936 'æ' => 'æ',
1937 'ç' => 'ç',
1938 'è' => 'è',
1939 'é' => 'é',
1940 'ê' => 'ê',
1941 'ë' => 'ë',
1942 'ì' => 'ì',
1943 'í' => 'í',
1944 'î' => 'î',
1945 'ï' => 'ï',
1946 'ð' => 'ð',
1947 'ñ' => 'ñ',
1948 'ò' => 'ò',
1949 'ó' => 'ó',
1950 'ô' => 'ô',
1951 'õ' => 'õ',
1952 'ö' => 'ö',
1953 '÷' => '÷',
1954 'ø' => 'ø',
1955 'ù' => 'ù',
1956 'ú' => 'ú',
1957 'û' => 'û',
1958 'ü' => 'ü',
1959 'ý' => 'ý',
1960 'þ' => 'þ',
1961 'ÿ' => 'ÿ',
1962 'Œ' => 'Œ',
1963 'œ' => 'œ',
1964 'Š' => 'Š',
1965 'š' => 'š',
1966 'Ÿ' => 'Ÿ',
1967 'ƒ' => 'ƒ',
1968 'ˆ' => 'ˆ',
1969 '˜' => '˜',
1970 'Α' => 'Α',
1971 'Β' => 'Β',
1972 'Γ' => 'Γ',
1973 'Δ' => 'Δ',
1974 'Ε' => 'Ε',
1975 'Ζ' => 'Ζ',
1976 'Η' => 'Η',
1977 'Θ' => 'Θ',
1978 'Ι' => 'Ι',
1979 'Κ' => 'Κ',
1980 'Λ' => 'Λ',
1984 'Ο' => 'Ο',
1986 'Ρ' => 'Ρ',
1987 'Σ' => 'Σ',
1988 'Τ' => 'Τ',
1989 'Υ' => 'Υ',
1990 'Φ' => 'Φ',
1991 'Χ' => 'Χ',
1992 'Ψ' => 'Ψ',
1993 'Ω' => 'Ω',
1994 'α' => 'α',
1995 'β' => 'β',
1996 'γ' => 'γ',
1997 'δ' => 'δ',
1998 'ε' => 'ε',
1999 'ζ' => 'ζ',
2000 'η' => 'η',
2001 'θ' => 'θ',
2002 'ι' => 'ι',
2003 'κ' => 'κ',
2004 'λ' => 'λ',
2008 'ο' => 'ο',
2010 'ρ' => 'ρ',
2011 'ς' => 'ς',
2012 'σ' => 'σ',
2013 'τ' => 'τ',
2014 'υ' => 'υ',
2015 'φ' => 'φ',
2016 'χ' => 'χ',
2017 'ψ' => 'ψ',
2018 'ω' => 'ω',
2019 'ϑ' => 'ϑ',
2020 'ϒ' => 'ϒ',
2021 'ϖ' => 'ϖ',
2022 ' ' => ' ',
2023 ' ' => ' ',
2024 ' ' => ' ',
2025 '‌' => '‌',
2026 '‍' => '‍',
2027 '‎' => '‎',
2028 '‏' => '‏',
2029 '–' => '–',
2030 '—' => '—',
2031 '‘' => '‘',
2032 '’' => '’',
2033 '‚' => '‚',
2034 '“' => '“',
2035 '”' => '”',
2036 '„' => '„',
2037 '†' => '†',
2038 '‡' => '‡',
2039 '•' => '•',
2040 '…' => '…',
2041 '‰' => '‰',
2042 '′' => '′',
2043 '″' => '″',
2044 '‹' => '‹',
2045 '›' => '›',
2046 '‾' => '‾',
2047 '⁄' => '⁄',
2048 '€' => '€',
2049 'ℑ' => 'ℑ',
2050 '℘' => '℘',
2051 'ℜ' => 'ℜ',
2052 '™' => '™',
2053 'ℵ' => 'ℵ',
2054 '↵' => '↵',
2055 '⇐' => '⇐',
2056 '⇑' => '⇑',
2057 '⇒' => '⇒',
2058 '⇓' => '⇓',
2059 '⇔' => '⇔',
2060 '∀' => '∀',
2061 '∂' => '∂',
2062 '∃' => '∃',
2063 '∅' => '∅',
2064 '∇' => '∇',
2065 '∈' => '∈',
2066 '∉' => '∉',
2067 '∋' => '∋',
2068 '∏' => '∏',
2069 '∑' => '∑',
2070 '−' => '−',
2071 '∗' => '∗',
2072 '√' => '√',
2073 '∝' => '∝',
2074 '∞' => '∞',
2075 '∠' => '∠',
2076 '∧' => '∧',
2077 '∨' => '∨',
2078 '∩' => '∩',
2079 '∪' => '∪',
2080 '∫' => '∫',
2081 '∴' => '∴',
2082 '∼' => '∼',
2083 '≅' => '≅',
2084 '≈' => '≈',
2085 '≠' => '≠',
2086 '≡' => '≡',
2087 '≤' => '≤',
2088 '≥' => '≥',
2089 '⊂' => '⊂',
2090 '⊃' => '⊃',
2091 '⊄' => '⊄',
2092 '⊆' => '⊆',
2093 '⊇' => '⊇',
2094 '⊕' => '⊕',
2095 '⊗' => '⊗',
2096 '⊥' => '⊥',
2097 '⋅' => '⋅',
2098 '⌈' => '⌈',
2099 '⌉' => '⌉',
2100 '⌊' => '⌊',
2101 '⌋' => '⌋',
2102 '⟨' => '〈',
2103 '⟩' => '〉',
2104 '←' => '←',
2105 '↑' => '↑',
2106 '→' => '→',
2107 '↓' => '↓',
2108 '↔' => '↔',
2109 '◊' => '◊',
2110 '♠' => '♠',
2111 '♣' => '♣',
2112 '♥' => '♥',
2113 '♦' => '♦'
2116 return str_replace( array_keys($to_ncr), array_values($to_ncr), $text );
2120 * Formats text for the rich text editor.
2122 * The filter 'richedit_pre' is applied here. If $text is empty the filter will
2123 * be applied to an empty string.
2127 * @param string $text The text to be formatted.
2128 * @return string The formatted text after filter is applied.
2130 function wp_richedit_pre($text) {
2131 // Filtering a blank results in an annoying <br />\n
2132 if ( empty($text) ) return apply_filters('richedit_pre', '');
2134 $output = convert_chars($text);
2135 $output = wpautop($output);
2136 $output = htmlspecialchars($output, ENT_NOQUOTES);
2138 return apply_filters('richedit_pre', $output);
2142 * Formats text for the HTML editor.
2144 * Unless $output is empty it will pass through htmlspecialchars before the
2145 * 'htmledit_pre' filter is applied.
2149 * @param string $output The text to be formatted.
2150 * @return string Formatted text after filter applied.
2152 function wp_htmledit_pre($output) {
2153 if ( !empty($output) )
2154 $output = htmlspecialchars($output, ENT_NOQUOTES); // convert only < > &
2156 return apply_filters('htmledit_pre', $output);
2160 * Perform a deep string replace operation to ensure the values in $search are no longer present
2162 * Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values
2163 * e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that
2164 * str_replace would return
2169 * @param string|array $search
2170 * @param string $subject
2171 * @return string The processed string
2173 function _deep_replace( $search, $subject ) {
2175 $subject = (string) $subject;
2178 foreach ( (array) $search as $val ) {
2179 while ( strpos( $subject, $val ) !== false ) {
2181 $subject = str_replace( $val, '', $subject );
2190 * Escapes data for use in a MySQL query
2192 * This is just a handy shortcut for $wpdb->escape(), for completeness' sake
2195 * @param string $sql Unescaped SQL data
2196 * @return string The cleaned $sql
2198 function esc_sql( $sql ) {
2200 return $wpdb->escape( $sql );
2204 * Checks and cleans a URL.
2206 * A number of characters are removed from the URL. If the URL is for displaying
2207 * (the default behaviour) amperstands are also replaced. The 'clean_url' filter
2208 * is applied to the returned cleaned URL.
2211 * @uses wp_kses_bad_protocol() To only permit protocols in the URL set
2212 * via $protocols or the common ones set in the function.
2214 * @param string $url The URL to be cleaned.
2215 * @param array $protocols Optional. An array of acceptable protocols.
2216 * Defaults to 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet' if not set.
2217 * @param string $_context Private. Use esc_url_raw() for database usage.
2218 * @return string The cleaned $url after the 'clean_url' filter is applied.
2220 function esc_url( $url, $protocols = null, $_context = 'display' ) {
2221 $original_url = $url;
2225 $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);
2226 $strip = array('%0d', '%0a', '%0D', '%0A');
2227 $url = _deep_replace($strip, $url);
2228 $url = str_replace(';//', '://', $url);
2229 /* If the URL doesn't appear to contain a scheme, we
2230 * presume it needs http:// appended (unless a relative
2231 * link starting with / or a php file).
2233 if ( strpos($url, ':') === false &&
2234 substr( $url, 0, 1 ) != '/' && substr( $url, 0, 1 ) != '#' && !preg_match('/^[a-z0-9-]+?\.php/i', $url) )
2235 $url = 'http://' . $url;
2237 // Replace ampersands and single quotes only when displaying.
2238 if ( 'display' == $_context ) {
2239 $url = wp_kses_normalize_entities( $url );
2240 $url = str_replace( '&', '&', $url );
2241 $url = str_replace( "'", ''', $url );
2244 if ( !is_array($protocols) )
2245 $protocols = array ('http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn');
2246 if ( wp_kses_bad_protocol( $url, $protocols ) != $url )
2249 return apply_filters('clean_url', $url, $original_url, $_context);
2253 * Performs esc_url() for database usage.
2258 * @param string $url The URL to be cleaned.
2259 * @param array $protocols An array of acceptable protocols.
2260 * @return string The cleaned URL.
2262 function esc_url_raw( $url, $protocols = null ) {
2263 return esc_url( $url, $protocols, 'db' );
2267 * Convert entities, while preserving already-encoded entities.
2269 * @link http://www.php.net/htmlentities Borrowed from the PHP Manual user notes.
2273 * @param string $myHTML The text to be converted.
2274 * @return string Converted text.
2276 function htmlentities2($myHTML) {
2277 $translation_table = get_html_translation_table( HTML_ENTITIES, ENT_QUOTES );
2278 $translation_table[chr(38)] = '&';
2279 return preg_replace( "/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/", "&", strtr($myHTML, $translation_table) );
2283 * Escape single quotes, htmlspecialchar " < > &, and fix line endings.
2285 * Escapes text strings for echoing in JS. It is intended to be used for inline JS
2286 * (in a tag attribute, for example onclick="..."). Note that the strings have to
2287 * be in single quotes. The filter 'js_escape' is also applied here.
2291 * @param string $text The text to be escaped.
2292 * @return string Escaped text.
2294 function esc_js( $text ) {
2295 $safe_text = wp_check_invalid_utf8( $text );
2296 $safe_text = _wp_specialchars( $safe_text, ENT_COMPAT );
2297 $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) );
2298 $safe_text = str_replace( "\r", '', $safe_text );
2299 $safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) );
2300 return apply_filters( 'js_escape', $safe_text, $text );
2304 * Escaping for HTML blocks.
2308 * @param string $text
2311 function esc_html( $text ) {
2312 $safe_text = wp_check_invalid_utf8( $text );
2313 $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
2314 return apply_filters( 'esc_html', $safe_text, $text );
2318 * Escaping for HTML attributes.
2322 * @param string $text
2325 function esc_attr( $text ) {
2326 $safe_text = wp_check_invalid_utf8( $text );
2327 $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
2328 return apply_filters( 'attribute_escape', $safe_text, $text );
2332 * Escape a HTML tag name.
2336 * @param string $tag_name
2339 function tag_escape($tag_name) {
2340 $safe_tag = strtolower( preg_replace('/[^a-zA-Z_:]/', '', $tag_name) );
2341 return apply_filters('tag_escape', $safe_tag, $tag_name);
2345 * Escapes text for SQL LIKE special characters % and _.
2349 * @param string $text The text to be escaped.
2350 * @return string text, safe for inclusion in LIKE query.
2352 function like_escape($text) {
2353 return str_replace(array("%", "_"), array("\\%", "\\_"), $text);
2357 * Convert full URL paths to absolute paths.
2359 * Removes the http or https protocols and the domain. Keeps the path '/' at the
2360 * beginning, so it isn't a true relative link, but from the web root base.
2364 * @param string $link Full URL path.
2365 * @return string Absolute path.
2367 function wp_make_link_relative( $link ) {
2368 return preg_replace( '|https?://[^/]+(/.*)|i', '$1', $link );
2372 * Sanitises various option values based on the nature of the option.
2374 * This is basically a switch statement which will pass $value through a number
2375 * of functions depending on the $option.
2379 * @param string $option The name of the option.
2380 * @param string $value The unsanitised value.
2381 * @return string Sanitized value.
2383 function sanitize_option($option, $value) {
2385 switch ( $option ) {
2387 $value = sanitize_email($value);
2388 if ( !is_email($value) ) {
2389 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
2390 if ( function_exists('add_settings_error') )
2391 add_settings_error('admin_email', 'invalid_admin_email', __('The email address entered did not appear to be a valid email address. Please enter a valid email address.'));
2395 case 'thumbnail_size_w':
2396 case 'thumbnail_size_h':
2397 case 'medium_size_w':
2398 case 'medium_size_h':
2399 case 'large_size_w':
2400 case 'large_size_h':
2401 case 'embed_size_h':
2402 case 'default_post_edit_rows':
2403 case 'mailserver_port':
2404 case 'comment_max_links':
2405 case 'page_on_front':
2406 case 'page_for_posts':
2407 case 'rss_excerpt_length':
2408 case 'default_category':
2409 case 'default_email_category':
2410 case 'default_link_category':
2411 case 'close_comments_days_old':
2412 case 'comments_per_page':
2413 case 'thread_comments_depth':
2414 case 'users_can_register':
2415 case 'start_of_week':
2416 $value = absint( $value );
2419 case 'embed_size_w':
2420 if ( '' !== $value )
2421 $value = absint( $value );
2424 case 'posts_per_page':
2425 case 'posts_per_rss':
2426 $value = (int) $value;
2427 if ( empty($value) )
2430 $value = abs($value);
2433 case 'default_ping_status':
2434 case 'default_comment_status':
2435 // Options that if not there have 0 value but need to be something like "closed"
2436 if ( $value == '0' || $value == '')
2440 case 'blogdescription':
2442 $value = addslashes($value);
2443 $value = wp_filter_post_kses( $value ); // calls stripslashes then addslashes
2444 $value = stripslashes($value);
2445 $value = esc_html( $value );
2448 case 'blog_charset':
2449 $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value); // strips slashes
2454 case 'mailserver_url':
2455 case 'mailserver_login':
2456 case 'mailserver_pass':
2459 $value = strip_tags($value);
2460 $value = addslashes($value);
2461 $value = wp_filter_kses($value); // calls stripslashes then addslashes
2462 $value = stripslashes($value);
2466 $value = preg_replace('/[^0-9:.-]/', '', $value); // strips slashes
2470 if ( (bool)preg_match( '#http(s?)://(.+)#i', $value) ) {
2471 $value = esc_url_raw($value);
2473 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
2474 if ( function_exists('add_settings_error') )
2475 add_settings_error('siteurl', 'invalid_siteurl', __('The WordPress address you entered did not appear to be a valid URL. Please enter a valid URL.'));
2480 if ( (bool)preg_match( '#http(s?)://(.+)#i', $value) ) {
2481 $value = esc_url_raw($value);
2483 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
2484 if ( function_exists('add_settings_error') )
2485 add_settings_error('home', 'invalid_home', __('The Site address you entered did not appear to be a valid URL. Please enter a valid URL.'));
2490 $value = apply_filters("sanitize_option_{$option}", $value, $option);
2498 * Parses a string into variables to be stored in an array.
2500 * Uses {@link http://www.php.net/parse_str parse_str()} and stripslashes if
2501 * {@link http://www.php.net/magic_quotes magic_quotes_gpc} is on.
2504 * @uses apply_filters() for the 'wp_parse_str' filter.
2506 * @param string $string The string to be parsed.
2507 * @param array $array Variables will be stored in this array.
2509 function wp_parse_str( $string, &$array ) {
2510 parse_str( $string, $array );
2511 if ( get_magic_quotes_gpc() )
2512 $array = stripslashes_deep( $array );
2513 $array = apply_filters( 'wp_parse_str', $array );
2517 * Convert lone less than signs.
2519 * KSES already converts lone greater than signs.
2521 * @uses wp_pre_kses_less_than_callback in the callback function.
2524 * @param string $text Text to be converted.
2525 * @return string Converted text.
2527 function wp_pre_kses_less_than( $text ) {
2528 return preg_replace_callback('%<[^>]*?((?=<)|>|$)%', 'wp_pre_kses_less_than_callback', $text);
2532 * Callback function used by preg_replace.
2534 * @uses esc_html to format the $matches text.
2537 * @param array $matches Populated by matches to preg_replace.
2538 * @return string The text returned after esc_html if needed.
2540 function wp_pre_kses_less_than_callback( $matches ) {
2541 if ( false === strpos($matches[0], '>') )
2542 return esc_html($matches[0]);
2547 * WordPress implementation of PHP sprintf() with filters.
2550 * @link http://www.php.net/sprintf
2552 * @param string $pattern The string which formatted args are inserted.
2553 * @param mixed $args,... Arguments to be formatted into the $pattern string.
2554 * @return string The formatted string.
2556 function wp_sprintf( $pattern ) {
2557 $args = func_get_args( );
2558 $len = strlen($pattern);
2562 while ( $len > $start ) {
2563 // Last character: append and break
2564 if ( strlen($pattern) - 1 == $start ) {
2565 $result .= substr($pattern, -1);
2569 // Literal %: append and continue
2570 if ( substr($pattern, $start, 2) == '%%' ) {
2576 // Get fragment before next %
2577 $end = strpos($pattern, '%', $start + 1);
2578 if ( false === $end )
2580 $fragment = substr($pattern, $start, $end - $start);
2582 // Fragment has a specifier
2583 if ( $pattern{$start} == '%' ) {
2584 // Find numbered arguments or take the next one in order
2585 if ( preg_match('/^%(\d+)\$/', $fragment, $matches) ) {
2586 $arg = isset($args[$matches[1]]) ? $args[$matches[1]] : '';
2587 $fragment = str_replace("%{$matches[1]}$", '%', $fragment);
2590 $arg = isset($args[$arg_index]) ? $args[$arg_index] : '';
2593 // Apply filters OR sprintf
2594 $_fragment = apply_filters( 'wp_sprintf', $fragment, $arg );
2595 if ( $_fragment != $fragment )
2596 $fragment = $_fragment;
2598 $fragment = sprintf($fragment, strval($arg) );
2601 // Append to result and move to next fragment
2602 $result .= $fragment;
2609 * Localize list items before the rest of the content.
2611 * The '%l' must be at the first characters can then contain the rest of the
2612 * content. The list items will have ', ', ', and', and ' and ' added depending
2613 * on the amount of list items in the $args parameter.
2617 * @param string $pattern Content containing '%l' at the beginning.
2618 * @param array $args List items to prepend to the content and replace '%l'.
2619 * @return string Localized list items and rest of the content.
2621 function wp_sprintf_l($pattern, $args) {
2623 if ( substr($pattern, 0, 2) != '%l' )
2626 // Nothing to work with
2630 // Translate and filter the delimiter set (avoid ampersands and entities here)
2631 $l = apply_filters('wp_sprintf_l', array(
2632 /* translators: used between list items, there is a space after the coma */
2633 'between' => __(', '),
2634 /* translators: used between list items, there is a space after the and */
2635 'between_last_two' => __(', and '),
2636 /* translators: used between only two list items, there is a space after the and */
2637 'between_only_two' => __(' and '),
2640 $args = (array) $args;
2641 $result = array_shift($args);
2642 if ( count($args) == 1 )
2643 $result .= $l['between_only_two'] . array_shift($args);
2644 // Loop when more than two args
2647 $arg = array_shift($args);
2650 $result .= $l['between_last_two'] . $arg;
2652 $result .= $l['between'] . $arg;
2654 return $result . substr($pattern, 2);
2658 * Safely extracts not more than the first $count characters from html string.
2660 * UTF-8, tags and entities safe prefix extraction. Entities inside will *NOT*
2661 * be counted as one character. For example & will be counted as 4, < as
2666 * @param integer $str String to get the excerpt from.
2667 * @param integer $count Maximum number of characters to take.
2668 * @return string The excerpt.
2670 function wp_html_excerpt( $str, $count ) {
2671 $str = wp_strip_all_tags( $str, true );
2672 $str = mb_substr( $str, 0, $count );
2673 // remove part of an entity at the end
2674 $str = preg_replace( '/&[^;\s]{0,6}$/', '', $str );
2679 * Add a Base url to relative links in passed content.
2681 * By default it supports the 'src' and 'href' attributes. However this can be
2682 * changed via the 3rd param.
2686 * @param string $content String to search for links in.
2687 * @param string $base The base URL to prefix to links.
2688 * @param array $attrs The attributes which should be processed.
2689 * @return string The processed content.
2691 function links_add_base_url( $content, $base, $attrs = array('src', 'href') ) {
2692 $attrs = implode('|', (array)$attrs);
2693 return preg_replace_callback("!($attrs)=(['\"])(.+?)\\2!i",
2694 create_function('$m', 'return _links_add_base($m, "' . $base . '");'),
2699 * Callback to add a base url to relative links in passed content.
2704 * @param string $m The matched link.
2705 * @param string $base The base URL to prefix to links.
2706 * @return string The processed link.
2708 function _links_add_base($m, $base) {
2709 //1 = attribute name 2 = quotation mark 3 = URL
2710 return $m[1] . '=' . $m[2] .
2711 (strpos($m[3], 'http://') === false ?
2712 path_join($base, $m[3]) :
2718 * Adds a Target attribute to all links in passed content.
2720 * This function by default only applies to <a> tags, however this can be
2721 * modified by the 3rd param.
2723 * <b>NOTE:</b> Any current target attributed will be striped and replaced.
2727 * @param string $content String to search for links in.
2728 * @param string $target The Target to add to the links.
2729 * @param array $tags An array of tags to apply to.
2730 * @return string The processed content.
2732 function links_add_target( $content, $target = '_blank', $tags = array('a') ) {
2733 $tags = implode('|', (array)$tags);
2734 return preg_replace_callback("!<($tags)(.+?)>!i",
2735 create_function('$m', 'return _links_add_target($m, "' . $target . '");'),
2740 * Callback to add a target attribute to all links in passed content.
2745 * @param string $m The matched link.
2746 * @param string $target The Target to add to the links.
2747 * @return string The processed link.
2749 function _links_add_target( $m, $target ) {
2751 $link = preg_replace('|(target=[\'"](.*?)[\'"])|i', '', $m[2]);
2752 return '<' . $tag . $link . ' target="' . $target . '">';
2755 // normalize EOL characters and strip duplicate whitespace
2756 function normalize_whitespace( $str ) {
2758 $str = str_replace("\r", "\n", $str);
2759 $str = preg_replace( array( '/\n+/', '/[ \t]+/' ), array( "\n", ' ' ), $str );
2764 * Properly strip all HTML tags including script and style
2768 * @param string $string String containing HTML tags
2769 * @param bool $remove_breaks optional Whether to remove left over line breaks and white space chars
2770 * @return string The processed string.
2772 function wp_strip_all_tags($string, $remove_breaks = false) {
2773 $string = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $string );
2774 $string = strip_tags($string);
2776 if ( $remove_breaks )
2777 $string = preg_replace('/[\r\n\t ]+/', ' ', $string);
2779 return trim($string);
2783 * Sanitize a string from user input or from the db
2785 * check for invalid UTF-8,
2786 * Convert single < characters to entity,
2788 * remove line breaks, tabs and extra white space,
2793 * @param string $str
2796 function sanitize_text_field($str) {
2797 $filtered = wp_check_invalid_utf8( $str );
2799 if ( strpos($filtered, '<') !== false ) {
2800 $filtered = wp_pre_kses_less_than( $filtered );
2801 // This will strip extra whitespace for us.
2802 $filtered = wp_strip_all_tags( $filtered, true );
2804 $filtered = trim( preg_replace('/[\r\n\t ]+/', ' ', $filtered) );
2809 while ( preg_match('/%[a-f0-9]{2}/i', $filtered, $match) ) {
2810 $filtered = str_replace($match[0], '', $filtered);
2815 // Strip out the whitespace that may now exist after removing the octets.
2816 $filtered = trim( preg_replace('/ +/', ' ', $filtered) );
2819 return apply_filters('sanitize_text_field', $filtered, $str);
2823 * Forever eliminate "Wordpress" from the planet (or at least the little bit we can influence).
2825 * Violating our coding standards for a good function name.
2830 function capital_P_dangit( $text ) {
2831 // Simple replacement for titles
2832 if ( 'the_title' === current_filter() )
2833 return str_replace( 'Wordpress', 'WordPress', $text );
2834 // Still here? Use the more judicious replacement
2835 static $dblq = false;
2836 if ( false === $dblq )
2837 $dblq = _x('“', 'opening curly quote');
2839 array( ' Wordpress', '‘Wordpress', $dblq . 'Wordpress', '>Wordpress', '(Wordpress' ),
2840 array( ' WordPress', '‘WordPress', $dblq . 'WordPress', '>WordPress', '(WordPress' ),