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 setup 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–', '...', '``', '\'s', '\'\'', ' (tm)'), $cockney);
57 $static_replacements = array_merge(array('—', ' — ', '–', ' – ', 'xn--', '…', $opening_quote, '’s', $closing_quote, ' ™'), $cockneyreplace);
59 $dynamic_characters = array('/\'(\d\d(?:’|\')?s)/', '/(\s|\A|[([{<]|")\'/', '/(\d+)"/', '/(\d+)\'/', '/(\S)\'([^\'\s])/', '/(\s|\A|[([{<])"(?!\s)/', '/"(\s|\S|\Z)/', '/\'([\s.]|\Z)/', '/(\d+)x(\d+)/');
60 $dynamic_replacements = array('’$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|form|map|area|blockquote|address|math|style|input|p|h[1-6]|hr|fieldset|legend)';
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 or not 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 );
337 $string = preg_replace( '/&(#?x?[0-9a-z]+);/i', '|wp_entity|$1|/wp_entity|', $string );
340 $string = @htmlspecialchars( $string, $quote_style, $charset );
342 // Handle double encoding ourselves
343 if ( !$double_encode ) {
344 $string = str_replace( array( '|wp_entity|', '|/wp_entity|' ), array( '&', ';' ), $string );
347 // Backwards compatibility
348 if ( 'single' === $_quote_style ) {
349 $string = str_replace( "'", ''', $string );
356 * Converts a number of HTML entities into their special characters.
358 * Specifically deals with: &, <, >, ", and '.
360 * $quote_style can be set to ENT_COMPAT to decode " entities,
361 * or ENT_QUOTES to do both " and '. Default is ENT_NOQUOTES where no quotes are decoded.
365 * @param string $string The text which is to be decoded.
366 * @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.
367 * @return string The decoded text without HTML entities.
369 function wp_specialchars_decode( $string, $quote_style = ENT_NOQUOTES ) {
370 $string = (string) $string;
372 if ( 0 === strlen( $string ) ) {
376 // Don't bother if there are no entities - saves a lot of processing
377 if ( strpos( $string, '&' ) === false ) {
381 // Match the previous behaviour of _wp_specialchars() when the $quote_style is not an accepted value
382 if ( empty( $quote_style ) ) {
383 $quote_style = ENT_NOQUOTES;
384 } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
385 $quote_style = ENT_QUOTES;
388 // More complete than get_html_translation_table( HTML_SPECIALCHARS )
389 $single = array( ''' => '\'', ''' => '\'' );
390 $single_preg = array( '/�*39;/' => ''', '/�*27;/i' => ''' );
391 $double = array( '"' => '"', '"' => '"', '"' => '"' );
392 $double_preg = array( '/�*34;/' => '"', '/�*22;/i' => '"' );
393 $others = array( '<' => '<', '<' => '<', '>' => '>', '>' => '>', '&' => '&', '&' => '&', '&' => '&' );
394 $others_preg = array( '/�*60;/' => '<', '/�*62;/' => '>', '/�*38;/' => '&', '/�*26;/i' => '&' );
396 if ( $quote_style === ENT_QUOTES ) {
397 $translation = array_merge( $single, $double, $others );
398 $translation_preg = array_merge( $single_preg, $double_preg, $others_preg );
399 } elseif ( $quote_style === ENT_COMPAT || $quote_style === 'double' ) {
400 $translation = array_merge( $double, $others );
401 $translation_preg = array_merge( $double_preg, $others_preg );
402 } elseif ( $quote_style === 'single' ) {
403 $translation = array_merge( $single, $others );
404 $translation_preg = array_merge( $single_preg, $others_preg );
405 } elseif ( $quote_style === ENT_NOQUOTES ) {
406 $translation = $others;
407 $translation_preg = $others_preg;
410 // Remove zero padding on numeric entities
411 $string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string );
413 // Replace characters according to translation table
414 return strtr( $string, $translation );
418 * Checks for invalid UTF8 in a string.
422 * @param string $string The text which is to be checked.
423 * @param boolean $strip Optional. Whether to attempt to strip out invalid UTF8. Default is false.
424 * @return string The checked text.
426 function wp_check_invalid_utf8( $string, $strip = false ) {
427 $string = (string) $string;
429 if ( 0 === strlen( $string ) ) {
433 // Store the site charset as a static to avoid multiple calls to get_option()
435 if ( !isset( $is_utf8 ) ) {
436 $is_utf8 = in_array( get_option( 'blog_charset' ), array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ) );
442 // Check for support for utf8 in the installed PCRE library once and store the result in a static
444 if ( !isset( $utf8_pcre ) ) {
445 $utf8_pcre = @preg_match( '/^./u', 'a' );
447 // We can't demand utf8 in the PCRE installation, so just return the string in those cases
452 // preg_match fails when it encounters invalid UTF8 in $string
453 if ( 1 === @preg_match( '/^./us', $string ) ) {
457 // Attempt to strip the bad chars if requested (not recommended)
458 if ( $strip && function_exists( 'iconv' ) ) {
459 return iconv( 'utf-8', 'utf-8', $string );
466 * Encode the Unicode values to be used in the URI.
470 * @param string $utf8_string
471 * @param int $length Max length of the string
472 * @return string String with Unicode encoded for URI.
474 function utf8_uri_encode( $utf8_string, $length = 0 ) {
480 $string_length = strlen( $utf8_string );
481 for ($i = 0; $i < $string_length; $i++ ) {
483 $value = ord( $utf8_string[ $i ] );
485 if ( $value < 128 ) {
486 if ( $length && ( $unicode_length >= $length ) )
488 $unicode .= chr($value);
491 if ( count( $values ) == 0 ) $num_octets = ( $value < 224 ) ? 2 : 3;
495 if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length )
497 if ( count( $values ) == $num_octets ) {
498 if ($num_octets == 3) {
499 $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]) . '%' . dechex($values[2]);
500 $unicode_length += 9;
502 $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]);
503 $unicode_length += 6;
516 * Converts all accent characters to ASCII characters.
518 * If there are no accent characters, then the string given is just returned.
522 * @param string $string Text that might have accent characters
523 * @return string Filtered string with replaced "nice" characters.
525 function remove_accents($string) {
526 if ( !preg_match('/[\x80-\xff]/', $string) )
529 if (seems_utf8($string)) {
531 // Decompositions for Latin-1 Supplement
532 chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
533 chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
534 chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
535 chr(195).chr(135) => 'C', chr(195).chr(136) => 'E',
536 chr(195).chr(137) => 'E', chr(195).chr(138) => 'E',
537 chr(195).chr(139) => 'E', chr(195).chr(140) => 'I',
538 chr(195).chr(141) => 'I', chr(195).chr(142) => 'I',
539 chr(195).chr(143) => 'I', chr(195).chr(145) => 'N',
540 chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
541 chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
542 chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
543 chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
544 chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
545 chr(195).chr(159) => 's', chr(195).chr(160) => 'a',
546 chr(195).chr(161) => 'a', chr(195).chr(162) => 'a',
547 chr(195).chr(163) => 'a', chr(195).chr(164) => 'a',
548 chr(195).chr(165) => 'a', chr(195).chr(167) => 'c',
549 chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
550 chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
551 chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
552 chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
553 chr(195).chr(177) => 'n', chr(195).chr(178) => 'o',
554 chr(195).chr(179) => 'o', chr(195).chr(180) => 'o',
555 chr(195).chr(181) => 'o', chr(195).chr(182) => 'o',
556 chr(195).chr(182) => 'o', chr(195).chr(185) => 'u',
557 chr(195).chr(186) => 'u', chr(195).chr(187) => 'u',
558 chr(195).chr(188) => 'u', chr(195).chr(189) => 'y',
559 chr(195).chr(191) => 'y',
560 // Decompositions for Latin Extended-A
561 chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
562 chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
563 chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
564 chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
565 chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
566 chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
567 chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
568 chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
569 chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
570 chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
571 chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
572 chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
573 chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
574 chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
575 chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
576 chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
577 chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
578 chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
579 chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
580 chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
581 chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
582 chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
583 chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
584 chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
585 chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
586 chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
587 chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
588 chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
589 chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
590 chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
591 chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
592 chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
593 chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
594 chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
595 chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
596 chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
597 chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
598 chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
599 chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
600 chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
601 chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
602 chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
603 chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
604 chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
605 chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
606 chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
607 chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
608 chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
609 chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
610 chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
611 chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
612 chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
613 chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
614 chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
615 chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
616 chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
617 chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
618 chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
619 chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
620 chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
621 chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
622 chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
623 chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
624 chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
626 chr(226).chr(130).chr(172) => 'E',
628 chr(194).chr(163) => '');
630 $string = strtr($string, $chars);
632 // Assume ISO-8859-1 if not UTF-8
633 $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
634 .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
635 .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
636 .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
637 .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
638 .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
639 .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
640 .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
641 .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
642 .chr(252).chr(253).chr(255);
644 $chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";
646 $string = strtr($string, $chars['in'], $chars['out']);
647 $double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
648 $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
649 $string = str_replace($double_chars['in'], $double_chars['out'], $string);
656 * Sanitizes a filename replacing whitespace with dashes
658 * Removes special characters that are illegal in filenames on certain
659 * operating systems and special characters requiring special escaping
660 * to manipulate at the command line. Replaces spaces and consecutive
661 * dashes with a single dash. Trim period, dash and underscore from beginning
662 * and end of filename.
666 * @param string $filename The filename to be sanitized
667 * @return string The sanitized filename
669 function sanitize_file_name( $filename ) {
670 $filename_raw = $filename;
671 $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", chr(0));
672 $special_chars = apply_filters('sanitize_file_name_chars', $special_chars, $filename_raw);
673 $filename = str_replace($special_chars, '', $filename);
674 $filename = preg_replace('/[\s-]+/', '-', $filename);
675 $filename = trim($filename, '.-_');
677 // Split the filename into a base and extension[s]
678 $parts = explode('.', $filename);
680 // Return if only one extension
681 if ( count($parts) <= 2 )
682 return apply_filters('sanitize_file_name', $filename, $filename_raw);
684 // Process multiple extensions
685 $filename = array_shift($parts);
686 $extension = array_pop($parts);
687 $mimes = get_allowed_mime_types();
689 // Loop over any intermediate extensions. Munge them with a trailing underscore if they are a 2 - 5 character
690 // long alpha string not in the extension whitelist.
691 foreach ( (array) $parts as $part) {
692 $filename .= '.' . $part;
694 if ( preg_match("/^[a-zA-Z]{2,5}\d?$/", $part) ) {
696 foreach ( $mimes as $ext_preg => $mime_match ) {
697 $ext_preg = '!(^' . $ext_preg . ')$!i';
698 if ( preg_match( $ext_preg, $part ) ) {
707 $filename .= '.' . $extension;
709 return apply_filters('sanitize_file_name', $filename, $filename_raw);
713 * Sanitize username stripping out unsafe characters.
715 * If $strict is true, only alphanumeric characters (as well as _, space, ., -,
717 * Removes tags, octets, entities, and if strict is enabled, will remove all
718 * non-ASCII characters. After sanitizing, it passes the username, raw username
719 * (the username in the parameter), and the strict parameter as parameters for
723 * @uses apply_filters() Calls 'sanitize_user' hook on username, raw username,
724 * and $strict parameter.
726 * @param string $username The username to be sanitized.
727 * @param bool $strict If set limits $username to specific characters. Default false.
728 * @return string The sanitized username, after passing through filters.
730 function sanitize_user( $username, $strict = false ) {
731 $raw_username = $username;
732 $username = wp_strip_all_tags($username);
734 $username = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '', $username);
735 $username = preg_replace('/&.+?;/', '', $username); // Kill entities
737 // If strict, reduce to ASCII for max portability.
739 $username = preg_replace('|[^a-z0-9 _.\-@]|i', '', $username);
741 // Consolidate contiguous whitespace
742 $username = preg_replace('|\s+|', ' ', $username);
744 return apply_filters('sanitize_user', $username, $raw_username, $strict);
748 * Sanitizes title or use fallback title.
750 * Specifically, HTML and PHP tags are stripped. Further actions can be added
751 * via the plugin API. If $title is empty and $fallback_title is set, the latter
756 * @param string $title The string to be sanitized.
757 * @param string $fallback_title Optional. A title to use if $title is empty.
758 * @return string The sanitized string.
760 function sanitize_title($title, $fallback_title = '') {
762 $title = strip_tags($title);
763 $title = apply_filters('sanitize_title', $title, $raw_title);
765 if ( '' === $title || false === $title )
766 $title = $fallback_title;
772 * Sanitizes title, replacing whitespace with dashes.
774 * Limits the output to alphanumeric characters, underscore (_) and dash (-).
775 * Whitespace becomes a dash.
779 * @param string $title The title to be sanitized.
780 * @return string The sanitized title.
782 function sanitize_title_with_dashes($title) {
783 $title = strip_tags($title);
784 // Preserve escaped octets.
785 $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
786 // Remove percent signs that are not part of an octet.
787 $title = str_replace('%', '', $title);
789 $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
791 $title = remove_accents($title);
792 if (seems_utf8($title)) {
793 if (function_exists('mb_strtolower')) {
794 $title = mb_strtolower($title, 'UTF-8');
796 $title = utf8_uri_encode($title, 200);
799 $title = strtolower($title);
800 $title = preg_replace('/&.+?;/', '', $title); // kill entities
801 $title = str_replace('.', '-', $title);
802 $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
803 $title = preg_replace('/\s+/', '-', $title);
804 $title = preg_replace('|-+|', '-', $title);
805 $title = trim($title, '-');
811 * Ensures a string is a valid SQL order by clause.
813 * Accepts one or more columns, with or without ASC/DESC, and also accepts
818 * @param string $orderby Order by string to be checked.
819 * @return string|false Returns the order by clause if it is a match, false otherwise.
821 function sanitize_sql_orderby( $orderby ){
822 preg_match('/^\s*([a-z0-9_]+(\s+(ASC|DESC))?(\s*,\s*|\s*$))+|^\s*RAND\(\s*\)\s*$/i', $orderby, $obmatches);
829 * Santizes a html classname to ensure it only contains valid characters
831 * Strips the string down to A-Z,a-z,0-9,'-' if this results in an empty
832 * string then it will return the alternative value supplied.
834 * @todo Expand to support the full range of CDATA that a class attribute can contain.
838 * @param string $class The classname to be sanitized
839 * @param string $fallback The value to return if the sanitization end's up as an empty string.
840 * @return string The sanitized value
842 function sanitize_html_class($class, $fallback){
843 //Strip out any % encoded octets
844 $sanitized = preg_replace('|%[a-fA-F0-9][a-fA-F0-9]|', '', $class);
846 //Limit to A-Z,a-z,0-9,'-'
847 $sanitized = preg_replace('/[^A-Za-z0-9-]/', '', $sanitized);
849 if ('' == $sanitized)
850 $sanitized = $fallback;
852 return apply_filters('sanitize_html_class',$sanitized, $class, $fallback);
856 * Converts a number of characters from a string.
858 * Metadata tags <<title>> and <<category>> are removed, <<br>> and <<hr>> are
859 * converted into correct XHTML and Unicode characters are converted to the
864 * @param string $content String of characters to be converted.
865 * @param string $deprecated Not used.
866 * @return string Converted string.
868 function convert_chars($content, $deprecated = '') {
869 // Translation of invalid Unicode references range to valid range
870 $wp_htmltranswinuni = array(
871 '€' => '€', // the Euro sign
873 '‚' => '‚', // these are Windows CP1252 specific characters
874 'ƒ' => 'ƒ', // they would look weird on non-Windows browsers
875 '„' => '„',
876 '…' => '…',
877 '†' => '†',
878 '‡' => '‡',
879 'ˆ' => 'ˆ',
880 '‰' => '‰',
881 'Š' => 'Š',
882 '‹' => '‹',
883 'Œ' => 'Œ',
885 'Ž' => 'ž',
888 '‘' => '‘',
889 '’' => '’',
890 '“' => '“',
891 '”' => '”',
892 '•' => '•',
893 '–' => '–',
894 '—' => '—',
895 '˜' => '˜',
896 '™' => '™',
897 'š' => 'š',
898 '›' => '›',
899 'œ' => 'œ',
905 // Remove metadata tags
906 $content = preg_replace('/<title>(.+?)<\/title>/','',$content);
907 $content = preg_replace('/<category>(.+?)<\/category>/','',$content);
909 // Converts lone & characters into & (a.k.a. &)
910 $content = preg_replace('/&([^#])(?![a-z1-4]{1,8};)/i', '&$1', $content);
913 $content = strtr($content, $wp_htmltranswinuni);
915 // Just a little XHTML help
916 $content = str_replace('<br>', '<br />', $content);
917 $content = str_replace('<hr>', '<hr />', $content);
923 * Callback used to change %uXXXX to &#YYY; syntax
927 * @param array $matches Single Match
928 * @return string An HTML entity
930 function funky_javascript_callback($matches) {
931 return "&#".base_convert($matches[1],16,10).";";
935 * Fixes javascript bugs in browsers.
937 * Converts unicode characters to HTML numbered entities.
943 * @param string $text Text to be made safe.
944 * @return string Fixed text.
946 function funky_javascript_fix($text) {
947 // Fixes for browsers' javascript bugs
948 global $is_macIE, $is_winIE;
950 if ( $is_winIE || $is_macIE )
951 $text = preg_replace_callback("/\%u([0-9A-F]{4,4})/",
952 "funky_javascript_callback",
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 ) {
996 $tagstack = array(); $stacksize = 0; $tagqueue = ''; $newtext = '';
997 $single_tags = array('br', 'hr', 'img', 'input'); //Known single-entity/self-closing tags
998 $nestable_tags = array('blockquote', 'div', 'span'); //Tags that can be immediately nested within themselves
1000 # WP bug fix for comments - in case you REALLY meant to type '< !--'
1001 $text = str_replace('< !--', '< !--', $text);
1002 # WP bug fix for LOVE <3 (and other situations with '<' before a number)
1003 $text = preg_replace('#<([0-9]{1})#', '<$1', $text);
1005 while (preg_match("/<(\/?\w*)\s*([^>]*)>/",$text,$regex)) {
1006 $newtext .= $tagqueue;
1008 $i = strpos($text,$regex[0]);
1009 $l = strlen($regex[0]);
1011 // clear the shifter
1014 if ( isset($regex[1][0]) && '/' == $regex[1][0] ) { // End Tag
1015 $tag = strtolower(substr($regex[1],1));
1016 // if too many closing tags
1017 if($stacksize <= 0) {
1019 //or close to be safe $tag = '/' . $tag;
1021 // if stacktop value = tag close value then pop
1022 else if ($tagstack[$stacksize - 1] == $tag) { // found closing tag
1023 $tag = '</' . $tag . '>'; // Close Tag
1025 array_pop ($tagstack);
1027 } else { // closing tag not at top, search for it
1028 for ($j=$stacksize-1;$j>=0;$j--) {
1029 if ($tagstack[$j] == $tag) {
1030 // add tag to tagqueue
1031 for ($k=$stacksize-1;$k>=$j;$k--){
1032 $tagqueue .= '</' . array_pop ($tagstack) . '>';
1040 } else { // Begin Tag
1041 $tag = strtolower($regex[1]);
1045 // If self-closing or '', don't do anything.
1046 if((substr($regex[2],-1) == '/') || ($tag == '')) {
1048 // ElseIf it's a known single-entity tag but it doesn't close itself, do so
1049 elseif ( in_array($tag, $single_tags) ) {
1051 } else { // Push the tag onto the stack
1052 // If the top of the stack is the same as the tag we want to push, close previous tag
1053 if (($stacksize > 0) && !in_array($tag, $nestable_tags) && ($tagstack[$stacksize - 1] == $tag)) {
1054 $tagqueue = '</' . array_pop ($tagstack) . '>';
1057 $stacksize = array_push ($tagstack, $tag);
1061 $attributes = $regex[2];
1063 $attributes = ' '.$attributes;
1065 $tag = '<'.$tag.$attributes.'>';
1066 //If already queuing a close tag, then put this tag on, too
1072 $newtext .= substr($text,0,$i) . $tag;
1073 $text = substr($text,$i+$l);
1077 $newtext .= $tagqueue;
1079 // Add Remaining text
1083 while($x = array_pop($tagstack)) {
1084 $newtext .= '</' . $x . '>'; // Add remaining tags to close
1087 // WP fix for the bug with HTML comments
1088 $newtext = str_replace("< !--","<!--",$newtext);
1089 $newtext = str_replace("< !--","< !--",$newtext);
1095 * Acts on text which is about to be edited.
1097 * Unless $richedit is set, it is simply a holder for the 'format_to_edit'
1098 * filter. If $richedit is set true htmlspecialchars() will be run on the
1099 * content, converting special characters to HTMl entities.
1103 * @param string $content The text about to be edited.
1104 * @param bool $richedit Whether or not the $content should pass through htmlspecialchars(). Default false.
1105 * @return string The text after the filter (and possibly htmlspecialchars()) has been run.
1107 function format_to_edit($content, $richedit = false) {
1108 $content = apply_filters('format_to_edit', $content);
1110 $content = htmlspecialchars($content);
1115 * Holder for the 'format_to_post' filter.
1119 * @param string $content The text to pass through the filter.
1120 * @return string Text returned from the 'format_to_post' filter.
1122 function format_to_post($content) {
1123 $content = apply_filters('format_to_post', $content);
1128 * Add leading zeros when necessary.
1130 * If you set the threshold to '4' and the number is '10', then you will get
1131 * back '0010'. If you set the number to '4' and the number is '5000', then you
1132 * will get back '5000'.
1134 * Uses sprintf to append the amount of zeros based on the $threshold parameter
1135 * and the size of the number. If the number is large enough, then no zeros will
1140 * @param mixed $number Number to append zeros to if not greater than threshold.
1141 * @param int $threshold Digit places number needs to be to not have zeros added.
1142 * @return string Adds leading zeros to number if needed.
1144 function zeroise($number, $threshold) {
1145 return sprintf('%0'.$threshold.'s', $number);
1149 * Adds backslashes before letters and before a number at the start of a string.
1153 * @param string $string Value to which backslashes will be added.
1154 * @return string String with backslashes inserted.
1156 function backslashit($string) {
1157 $string = preg_replace('/^([0-9])/', '\\\\\\\\\1', $string);
1158 $string = preg_replace('/([a-z])/i', '\\\\\1', $string);
1163 * Appends a trailing slash.
1165 * Will remove trailing slash if it exists already before adding a trailing
1166 * slash. This prevents double slashing a string or path.
1168 * The primary use of this is for paths and thus should be used for paths. It is
1169 * not restricted to paths and offers no specific path support.
1172 * @uses untrailingslashit() Unslashes string if it was slashed already.
1174 * @param string $string What to add the trailing slash to.
1175 * @return string String with trailing slash added.
1177 function trailingslashit($string) {
1178 return untrailingslashit($string) . '/';
1182 * Removes trailing slash if it exists.
1184 * The primary use of this is for paths and thus should be used for paths. It is
1185 * not restricted to paths and offers no specific path support.
1189 * @param string $string What to remove the trailing slash from.
1190 * @return string String without the trailing slash.
1192 function untrailingslashit($string) {
1193 return rtrim($string, '/');
1197 * Adds slashes to escape strings.
1199 * Slashes will first be removed if magic_quotes_gpc is set, see {@link
1200 * http://www.php.net/magic_quotes} for more details.
1204 * @param string $gpc The string returned from HTTP request data.
1205 * @return string Returns a string escaped with slashes.
1207 function addslashes_gpc($gpc) {
1210 if (get_magic_quotes_gpc()) {
1211 $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 $value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value);
1234 * Navigates through an array and encodes the values to be used in a URL.
1236 * Uses a callback to pass the value of the array back to the function as a
1241 * @param array|string $value The array or string to be encoded.
1242 * @return array|string $value The encoded array (or string from the callback).
1244 function urlencode_deep($value) {
1245 $value = is_array($value) ? array_map('urlencode_deep', $value) : urlencode($value);
1250 * Converts email addresses characters to HTML entities to block spam bots.
1254 * @param string $emailaddy Email address.
1255 * @param int $mailto Optional. Range from 0 to 1. Used for encoding.
1256 * @return string Converted email address.
1258 function antispambot($emailaddy, $mailto=0) {
1259 $emailNOSPAMaddy = '';
1260 srand ((float) microtime() * 1000000);
1261 for ($i = 0; $i < strlen($emailaddy); $i = $i + 1) {
1262 $j = floor(rand(0, 1+$mailto));
1264 $emailNOSPAMaddy .= '&#'.ord(substr($emailaddy,$i,1)).';';
1266 $emailNOSPAMaddy .= substr($emailaddy,$i,1);
1268 $emailNOSPAMaddy .= '%'.zeroise(dechex(ord(substr($emailaddy, $i, 1))), 2);
1271 $emailNOSPAMaddy = str_replace('@','@',$emailNOSPAMaddy);
1272 return $emailNOSPAMaddy;
1276 * Callback to convert URI match to HTML A element.
1278 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1279 * make_clickable()}.
1284 * @param array $matches Single Regex Match.
1285 * @return string HTML A element with URI address.
1287 function _make_url_clickable_cb($matches) {
1290 $url = esc_url($url);
1294 return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>";
1298 * Callback to convert URL match to HTML A element.
1300 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1301 * make_clickable()}.
1306 * @param array $matches Single Regex Match.
1307 * @return string HTML A element with URL address.
1309 function _make_web_ftp_clickable_cb($matches) {
1311 $dest = $matches[2];
1312 $dest = 'http://' . $dest;
1313 $dest = esc_url($dest);
1317 // removed trailing [.,;:)] from URL
1318 if ( in_array( substr($dest, -1), array('.', ',', ';', ':', ')') ) === true ) {
1319 $ret = substr($dest, -1);
1320 $dest = substr($dest, 0, strlen($dest)-1);
1322 return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>$ret";
1326 * Callback to convert email address match to HTML A element.
1328 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1329 * make_clickable()}.
1334 * @param array $matches Single Regex Match.
1335 * @return string HTML A element with email address.
1337 function _make_email_clickable_cb($matches) {
1338 $email = $matches[2] . '@' . $matches[3];
1339 return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
1343 * Convert plaintext URI to HTML links.
1345 * Converts URI, www and ftp, and email addresses. Finishes by fixing links
1350 * @param string $ret Content to convert URIs.
1351 * @return string Content with converted URIs.
1353 function make_clickable($ret) {
1355 // in testing, using arrays here was found to be faster
1356 $ret = preg_replace_callback('#(?<=[\s>])(\()?([\w]+?://(?:[\w\\x80-\\xff\#$%&~/=?@\[\](+-]|[.,;:](?![\s<]|(\))?([\s]|$))|(?(1)\)(?![\s<.,;:]|$)|\)))+)#is', '_make_url_clickable_cb', $ret);
1357 $ret = preg_replace_callback('#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]+)#is', '_make_web_ftp_clickable_cb', $ret);
1358 $ret = preg_replace_callback('#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret);
1359 // this one is not in an array because we need it to run last, for cleanup of accidental links within links
1360 $ret = preg_replace("#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i", "$1$3</a>", $ret);
1366 * Adds rel nofollow string to all HTML A elements in content.
1370 * @param string $text Content that may contain HTML A elements.
1371 * @return string Converted content.
1373 function wp_rel_nofollow( $text ) {
1375 // This is a pre save filter, so text is already escaped.
1376 $text = stripslashes($text);
1377 $text = preg_replace_callback('|<a (.+?)>|i', 'wp_rel_nofollow_callback', $text);
1378 $text = esc_sql($text);
1383 * Callback to used to add rel=nofollow string to HTML A element.
1385 * Will remove already existing rel="nofollow" and rel='nofollow' from the
1386 * string to prevent from invalidating (X)HTML.
1390 * @param array $matches Single Match
1391 * @return string HTML A Element with rel nofollow.
1393 function wp_rel_nofollow_callback( $matches ) {
1394 $text = $matches[1];
1395 $text = str_replace(array(' rel="nofollow"', " rel='nofollow'"), '', $text);
1396 return "<a $text rel=\"nofollow\">";
1401 * Convert one smiley code to the icon graphic file equivalent.
1403 * Looks up one smiley code in the $wpsmiliestrans global array and returns an
1404 * <img> string for that smiley.
1406 * @global array $wpsmiliestrans
1409 * @param string $smiley Smiley code to convert to image.
1410 * @return string Image string for smiley.
1412 function translate_smiley($smiley) {
1413 global $wpsmiliestrans;
1415 if (count($smiley) == 0) {
1419 $siteurl = get_option( 'siteurl' );
1421 $smiley = trim(reset($smiley));
1422 $img = $wpsmiliestrans[$smiley];
1423 $smiley_masked = esc_attr($smiley);
1425 $srcurl = apply_filters('smilies_src', "$siteurl/wp-includes/images/smilies/$img", $img, $siteurl);
1427 return " <img src='$srcurl' alt='$smiley_masked' class='wp-smiley' /> ";
1432 * Convert text equivalent of smilies to images.
1434 * Will only convert smilies if the option 'use_smilies' is true and the global
1435 * used in the function isn't empty.
1438 * @uses $wp_smiliessearch
1440 * @param string $text Content to convert smilies from text.
1441 * @return string Converted content with text smilies replaced with images.
1443 function convert_smilies($text) {
1444 global $wp_smiliessearch;
1446 if ( get_option('use_smilies') && !empty($wp_smiliessearch) ) {
1447 // HTML loop taken from texturize function, could possible be consolidated
1448 $textarr = preg_split("/(<.*>)/U", $text, -1, PREG_SPLIT_DELIM_CAPTURE); // capture the tags as well as in between
1449 $stop = count($textarr);// loop stuff
1450 for ($i = 0; $i < $stop; $i++) {
1451 $content = $textarr[$i];
1452 if ((strlen($content) > 0) && ('<' != $content{0})) { // If it's not a tag
1453 $content = preg_replace_callback($wp_smiliessearch, 'translate_smiley', $content);
1455 $output .= $content;
1458 // return default text.
1465 * Verifies that an email is valid.
1467 * Does not grok i18n domains. Not RFC compliant.
1471 * @param string $email Email address to verify.
1472 * @param boolean $check_dns Whether to check the DNS for the domain using checkdnsrr().
1473 * @return string|bool Either false or the valid email address.
1475 function is_email( $email, $check_dns = false ) {
1476 // Test for the minimum length the email can be
1477 if ( strlen( $email ) < 3 ) {
1478 return apply_filters( 'is_email', false, $email, 'email_too_short' );
1481 // Test for an @ character after the first position
1482 if ( strpos( $email, '@', 1 ) === false ) {
1483 return apply_filters( 'is_email', false, $email, 'email_no_at' );
1486 // Split out the local and domain parts
1487 list( $local, $domain ) = explode( '@', $email, 2 );
1490 // Test for invalid characters
1491 if ( !preg_match( '/^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]+$/', $local ) ) {
1492 return apply_filters( 'is_email', false, $email, 'local_invalid_chars' );
1496 // Test for sequences of periods
1497 if ( preg_match( '/\.{2,}/', $domain ) ) {
1498 return apply_filters( 'is_email', false, $email, 'domain_period_sequence' );
1501 // Test for leading and trailing periods and whitespace
1502 if ( trim( $domain, " \t\n\r\0\x0B." ) !== $domain ) {
1503 return apply_filters( 'is_email', false, $email, 'domain_period_limits' );
1506 // Split the domain into subs
1507 $subs = explode( '.', $domain );
1509 // Assume the domain will have at least two subs
1510 if ( 2 > count( $subs ) ) {
1511 return apply_filters( 'is_email', false, $email, 'domain_no_periods' );
1514 // Loop through each sub
1515 foreach ( $subs as $sub ) {
1516 // Test for leading and trailing hyphens and whitespace
1517 if ( trim( $sub, " \t\n\r\0\x0B-" ) !== $sub ) {
1518 return apply_filters( 'is_email', false, $email, 'sub_hyphen_limits' );
1521 // Test for invalid characters
1522 if ( !preg_match('/^[a-z0-9-]+$/i', $sub ) ) {
1523 return apply_filters( 'is_email', false, $email, 'sub_invalid_chars' );
1528 // Check the domain has a valid MX and A resource record
1529 if ( $check_dns && function_exists( 'checkdnsrr' ) && !( checkdnsrr( $domain . '.', 'MX' ) || checkdnsrr( $domain . '.', 'A' ) ) ) {
1530 return apply_filters( 'is_email', false, $email, 'dns_no_rr' );
1533 // Congratulations your email made it!
1534 return apply_filters( 'is_email', $email, $email, null );
1538 * Convert to ASCII from email subjects.
1541 * @usedby wp_mail() handles charsets in email subjects
1543 * @param string $string Subject line
1544 * @return string Converted string to ASCII
1546 function wp_iso_descrambler($string) {
1547 /* this may only work with iso-8859-1, I'm afraid */
1548 if (!preg_match('#\=\?(.+)\?Q\?(.+)\?\=#i', $string, $matches)) {
1551 $subject = str_replace('_', ' ', $matches[2]);
1552 $subject = preg_replace_callback('#\=([0-9a-f]{2})#i', create_function('$match', 'return chr(hexdec(strtolower($match[1])));'), $subject);
1558 * Returns a date in the GMT equivalent.
1560 * Requires and returns a date in the Y-m-d H:i:s format. Simply subtracts the
1561 * value of the 'gmt_offset' option. Return format can be overridden using the
1566 * @uses get_option() to retrieve the the value of 'gmt_offset'.
1567 * @param string $string The date to be converted.
1568 * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
1569 * @return string GMT version of the date provided.
1571 function get_gmt_from_date($string, $format = 'Y-m-d H:i:s') {
1572 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);
1573 $string_time = gmmktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]);
1574 $string_gmt = gmdate($format, $string_time - get_option('gmt_offset') * 3600);
1579 * Converts a GMT date into the correct format for the blog.
1581 * Requires and returns in the Y-m-d H:i:s format. Simply adds the value of
1582 * gmt_offset.Return format can be overridden using the $format parameter
1586 * @param string $string The date to be converted.
1587 * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
1588 * @return string Formatted date relative to the GMT offset.
1590 function get_date_from_gmt($string, $format = 'Y-m-d H:i:s') {
1591 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);
1592 $string_time = gmmktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]);
1593 $string_localtime = gmdate($format, $string_time + get_option('gmt_offset')*3600);
1594 return $string_localtime;
1598 * Computes an offset in seconds from an iso8601 timezone.
1602 * @param string $timezone Either 'Z' for 0 offset or '±hhmm'.
1603 * @return int|float The offset in seconds.
1605 function iso8601_timezone_to_offset($timezone) {
1606 // $timezone is either 'Z' or '[+|-]hhmm'
1607 if ($timezone == 'Z') {
1610 $sign = (substr($timezone, 0, 1) == '+') ? 1 : -1;
1611 $hours = intval(substr($timezone, 1, 2));
1612 $minutes = intval(substr($timezone, 3, 4)) / 60;
1613 $offset = $sign * 3600 * ($hours + $minutes);
1619 * Converts an iso8601 date to MySQL DateTime format used by post_date[_gmt].
1623 * @param string $date_string Date and time in ISO 8601 format {@link http://en.wikipedia.org/wiki/ISO_8601}.
1624 * @param string $timezone Optional. If set to GMT returns the time minus gmt_offset. Default is 'user'.
1625 * @return string The date and time in MySQL DateTime format - Y-m-d H:i:s.
1627 function iso8601_to_datetime($date_string, $timezone = 'user') {
1628 $timezone = strtolower($timezone);
1630 if ($timezone == 'gmt') {
1632 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);
1634 if (!empty($date_bits[7])) { // we have a timezone, so let's compute an offset
1635 $offset = iso8601_timezone_to_offset($date_bits[7]);
1636 } else { // we don't have a timezone, so we assume user local timezone (not server's!)
1637 $offset = 3600 * get_option('gmt_offset');
1640 $timestamp = gmmktime($date_bits[4], $date_bits[5], $date_bits[6], $date_bits[2], $date_bits[3], $date_bits[1]);
1641 $timestamp -= $offset;
1643 return gmdate('Y-m-d H:i:s', $timestamp);
1645 } else if ($timezone == 'user') {
1646 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);
1651 * Adds a element attributes to open links in new windows.
1653 * Comment text in popup windows should be filtered through this. Right now it's
1654 * a moderately dumb function, ideally it would detect whether a target or rel
1655 * attribute was already there and adjust its actions accordingly.
1659 * @param string $text Content to replace links to open in a new window.
1660 * @return string Content that has filtered links.
1662 function popuplinks($text) {
1663 $text = preg_replace('/<a (.+?)>/i', "<a $1 target='_blank' rel='external'>", $text);
1668 * Strips out all characters that are not allowable in an email.
1672 * @param string $email Email address to filter.
1673 * @return string Filtered email address.
1675 function sanitize_email( $email ) {
1676 // Test for the minimum length the email can be
1677 if ( strlen( $email ) < 3 ) {
1678 return apply_filters( 'sanitize_email', '', $email, 'email_too_short' );
1681 // Test for an @ character after the first position
1682 if ( strpos( $email, '@', 1 ) === false ) {
1683 return apply_filters( 'sanitize_email', '', $email, 'email_no_at' );
1686 // Split out the local and domain parts
1687 list( $local, $domain ) = explode( '@', $email, 2 );
1690 // Test for invalid characters
1691 $local = preg_replace( '/[^a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]/', '', $local );
1692 if ( '' === $local ) {
1693 return apply_filters( 'sanitize_email', '', $email, 'local_invalid_chars' );
1697 // Test for sequences of periods
1698 $domain = preg_replace( '/\.{2,}/', '', $domain );
1699 if ( '' === $domain ) {
1700 return apply_filters( 'sanitize_email', '', $email, 'domain_period_sequence' );
1703 // Test for leading and trailing periods and whitespace
1704 $domain = trim( $domain, " \t\n\r\0\x0B." );
1705 if ( '' === $domain ) {
1706 return apply_filters( 'sanitize_email', '', $email, 'domain_period_limits' );
1709 // Split the domain into subs
1710 $subs = explode( '.', $domain );
1712 // Assume the domain will have at least two subs
1713 if ( 2 > count( $subs ) ) {
1714 return apply_filters( 'sanitize_email', '', $email, 'domain_no_periods' );
1717 // Create an array that will contain valid subs
1718 $new_subs = array();
1720 // Loop through each sub
1721 foreach ( $subs as $sub ) {
1722 // Test for leading and trailing hyphens
1723 $sub = trim( $sub, " \t\n\r\0\x0B-" );
1725 // Test for invalid characters
1726 $sub = preg_replace( '/^[^a-z0-9-]+$/i', '', $sub );
1728 // If there's anything left, add it to the valid subs
1729 if ( '' !== $sub ) {
1734 // If there aren't 2 or more valid subs
1735 if ( 2 > count( $new_subs ) ) {
1736 return apply_filters( 'sanitize_email', '', $email, 'domain_no_valid_subs' );
1739 // Join valid subs into the new domain
1740 $domain = join( '.', $new_subs );
1742 // Put the email back together
1743 $email = $local . '@' . $domain;
1745 // Congratulations your email made it!
1746 return apply_filters( 'sanitize_email', $email, $email, null );
1750 * Determines the difference between two timestamps.
1752 * The difference is returned in a human readable format such as "1 hour",
1753 * "5 mins", "2 days".
1757 * @param int $from Unix timestamp from which the difference begins.
1758 * @param int $to Optional. Unix timestamp to end the time difference. Default becomes time() if not set.
1759 * @return string Human readable time difference.
1761 function human_time_diff( $from, $to = '' ) {
1764 $diff = (int) abs($to - $from);
1765 if ($diff <= 3600) {
1766 $mins = round($diff / 60);
1770 $since = sprintf(_n('%s min', '%s mins', $mins), $mins);
1771 } else if (($diff <= 86400) && ($diff > 3600)) {
1772 $hours = round($diff / 3600);
1776 $since = sprintf(_n('%s hour', '%s hours', $hours), $hours);
1777 } elseif ($diff >= 86400) {
1778 $days = round($diff / 86400);
1782 $since = sprintf(_n('%s day', '%s days', $days), $days);
1788 * Generates an excerpt from the content, if needed.
1790 * The excerpt word amount will be 55 words and if the amount is greater than
1791 * that, then the string ' [...]' will be appended to the excerpt. If the string
1792 * is less than 55 words, then the content will be returned as is.
1794 * The 55 word limit can be modified by plugins/themes using the excerpt_length filter
1795 * The ' [...]' string can be modified by plugins/themes using the excerpt_more filter
1799 * @param string $text The excerpt. If set to empty an excerpt is generated.
1800 * @return string The excerpt.
1802 function wp_trim_excerpt($text) {
1803 $raw_excerpt = $text;
1804 if ( '' == $text ) {
1805 $text = get_the_content('');
1807 $text = strip_shortcodes( $text );
1809 $text = apply_filters('the_content', $text);
1810 $text = str_replace(']]>', ']]>', $text);
1811 $text = strip_tags($text);
1812 $excerpt_length = apply_filters('excerpt_length', 55);
1813 $excerpt_more = apply_filters('excerpt_more', ' ' . '[...]');
1814 $words = explode(' ', $text, $excerpt_length + 1);
1815 if (count($words) > $excerpt_length) {
1817 $text = implode(' ', $words);
1818 $text = $text . $excerpt_more;
1821 return apply_filters('wp_trim_excerpt', $text, $raw_excerpt);
1825 * Converts named entities into numbered entities.
1829 * @param string $text The text within which entities will be converted.
1830 * @return string Text with converted entities.
1832 function ent2ncr($text) {
1834 '"' => '"',
1836 '⁄' => '/',
1840 ' ' => ' ',
1841 '¡' => '¡',
1842 '¢' => '¢',
1843 '£' => '£',
1844 '¤' => '¤',
1845 '¥' => '¥',
1846 '¦' => '¦',
1847 '&brkbar;' => '¦',
1848 '§' => '§',
1849 '¨' => '¨',
1850 '¨' => '¨',
1851 '©' => '©',
1852 'ª' => 'ª',
1853 '«' => '«',
1854 '¬' => '¬',
1855 '­' => '­',
1856 '®' => '®',
1857 '¯' => '¯',
1858 '&hibar;' => '¯',
1859 '°' => '°',
1860 '±' => '±',
1861 '²' => '²',
1862 '³' => '³',
1863 '´' => '´',
1864 'µ' => 'µ',
1865 '¶' => '¶',
1866 '·' => '·',
1867 '¸' => '¸',
1868 '¹' => '¹',
1869 'º' => 'º',
1870 '»' => '»',
1871 '¼' => '¼',
1872 '½' => '½',
1873 '¾' => '¾',
1874 '¿' => '¿',
1875 'À' => 'À',
1876 'Á' => 'Á',
1877 'Â' => 'Â',
1878 'Ã' => 'Ã',
1879 'Ä' => 'Ä',
1880 'Å' => 'Å',
1881 'Æ' => 'Æ',
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 'Λ' => 'Λ',
1961 'Ο' => 'Ο',
1963 'Ρ' => 'Ρ',
1964 'Σ' => 'Σ',
1965 'Τ' => 'Τ',
1966 'Υ' => 'Υ',
1967 'Φ' => 'Φ',
1968 'Χ' => 'Χ',
1969 'Ψ' => 'Ψ',
1970 'Ω' => 'Ω',
1971 'α' => 'α',
1972 'β' => 'β',
1973 'γ' => 'γ',
1974 'δ' => 'δ',
1975 'ε' => 'ε',
1976 'ζ' => 'ζ',
1977 'η' => 'η',
1978 'θ' => 'θ',
1979 'ι' => 'ι',
1980 'κ' => 'κ',
1981 'λ' => 'λ',
1985 'ο' => 'ο',
1987 'ρ' => 'ρ',
1988 'ς' => 'ς',
1989 'σ' => 'σ',
1990 'τ' => 'τ',
1991 'υ' => 'υ',
1992 'φ' => 'φ',
1993 'χ' => 'χ',
1994 'ψ' => 'ψ',
1995 'ω' => 'ω',
1996 'ϑ' => 'ϑ',
1997 'ϒ' => 'ϒ',
1998 'ϖ' => 'ϖ',
1999 ' ' => ' ',
2000 ' ' => ' ',
2001 ' ' => ' ',
2002 '‌' => '‌',
2003 '‍' => '‍',
2004 '‎' => '‎',
2005 '‏' => '‏',
2006 '–' => '–',
2007 '—' => '—',
2008 '‘' => '‘',
2009 '’' => '’',
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 '♦' => '♦'
2093 return str_replace( array_keys($to_ncr), array_values($to_ncr), $text );
2097 * Formats text for the rich text editor.
2099 * The filter 'richedit_pre' is applied here. If $text is empty the filter will
2100 * be applied to an empty string.
2104 * @param string $text The text to be formatted.
2105 * @return string The formatted text after filter is applied.
2107 function wp_richedit_pre($text) {
2108 // Filtering a blank results in an annoying <br />\n
2109 if ( empty($text) ) return apply_filters('richedit_pre', '');
2111 $output = convert_chars($text);
2112 $output = wpautop($output);
2113 $output = htmlspecialchars($output, ENT_NOQUOTES);
2115 return apply_filters('richedit_pre', $output);
2119 * Formats text for the HTML editor.
2121 * Unless $output is empty it will pass through htmlspecialchars before the
2122 * 'htmledit_pre' filter is applied.
2126 * @param string $output The text to be formatted.
2127 * @return string Formatted text after filter applied.
2129 function wp_htmledit_pre($output) {
2130 if ( !empty($output) )
2131 $output = htmlspecialchars($output, ENT_NOQUOTES); // convert only < > &
2133 return apply_filters('htmledit_pre', $output);
2137 * Checks and cleans a URL.
2139 * A number of characters are removed from the URL. If the URL is for displaying
2140 * (the default behaviour) amperstands are also replaced. The 'esc_url' filter
2141 * is applied to the returned cleaned URL.
2144 * @uses wp_kses_bad_protocol() To only permit protocols in the URL set
2145 * via $protocols or the common ones set in the function.
2147 * @param string $url The URL to be cleaned.
2148 * @param array $protocols Optional. An array of acceptable protocols.
2149 * Defaults to 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet' if not set.
2150 * @param string $context Optional. How the URL will be used. Default is 'display'.
2151 * @return string The cleaned $url after the 'cleaned_url' filter is applied.
2153 function clean_url( $url, $protocols = null, $context = 'display' ) {
2154 $original_url = $url;
2156 if ('' == $url) return $url;
2157 $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);
2158 $strip = array('%0d', '%0a', '%0D', '%0A');
2159 $url = _deep_replace($strip, $url);
2160 $url = str_replace(';//', '://', $url);
2161 /* If the URL doesn't appear to contain a scheme, we
2162 * presume it needs http:// appended (unless a relative
2163 * link starting with / or a php file).
2165 if ( strpos($url, ':') === false &&
2166 substr( $url, 0, 1 ) != '/' && substr( $url, 0, 1 ) != '#' && !preg_match('/^[a-z0-9-]+?\.php/i', $url) )
2167 $url = 'http://' . $url;
2169 // Replace ampersands and single quotes only when displaying.
2170 if ( 'display' == $context ) {
2171 $url = preg_replace('/&([^#])(?![a-z]{2,8};)/', '&$1', $url);
2172 $url = str_replace( "'", ''', $url );
2175 if ( !is_array($protocols) )
2176 $protocols = array('http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet');
2177 if ( wp_kses_bad_protocol( $url, $protocols ) != $url )
2180 return apply_filters('clean_url', $url, $original_url, $context);
2184 * Perform a deep string replace operation to ensure the values in $search are no longer present
2186 * Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values
2187 * e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that
2188 * str_replace would return
2193 * @param string|array $search
2194 * @param string $subject
2195 * @return string The processed string
2197 function _deep_replace($search, $subject){
2201 foreach( (array) $search as $val ) {
2202 while(strpos($subject, $val) !== false) {
2204 $subject = str_replace($val, '', $subject);
2213 * Escapes data for use in a MySQL query
2215 * This is just a handy shortcut for $wpdb->escape(), for completeness' sake
2218 * @param string $sql Unescaped SQL data
2219 * @return string The cleaned $sql
2221 function esc_sql( $sql ) {
2223 return $wpdb->escape( $sql );
2228 * Checks and cleans a URL.
2230 * A number of characters are removed from the URL. If the URL is for displaying
2231 * (the default behaviour) amperstands are also replaced. The 'esc_url' filter
2232 * is applied to the returned cleaned URL.
2236 * @uses wp_kses_bad_protocol() To only permit protocols in the URL set
2237 * via $protocols or the common ones set in the function.
2239 * @param string $url The URL to be cleaned.
2240 * @param array $protocols Optional. An array of acceptable protocols.
2241 * Defaults to 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet' if not set.
2242 * @return string The cleaned $url after the 'cleaned_url' filter is applied.
2244 function esc_url( $url, $protocols = null ) {
2245 return clean_url( $url, $protocols, 'display' );
2249 * Performs esc_url() for database usage.
2256 * @param string $url The URL to be cleaned.
2257 * @param array $protocols An array of acceptable protocols.
2258 * @return string The cleaned URL.
2260 function esc_url_raw( $url, $protocols = null ) {
2261 return clean_url( $url, $protocols, 'db' );
2265 * Performs esc_url() for database or redirect usage.
2272 * @param string $url The URL to be cleaned.
2273 * @param array $protocols An array of acceptable protocols.
2274 * @return string The cleaned URL.
2276 function sanitize_url( $url, $protocols = null ) {
2277 return clean_url( $url, $protocols, 'db' );
2281 * Convert entities, while preserving already-encoded entities.
2283 * @link http://www.php.net/htmlentities Borrowed from the PHP Manual user notes.
2287 * @param string $myHTML The text to be converted.
2288 * @return string Converted text.
2290 function htmlentities2($myHTML) {
2291 $translation_table = get_html_translation_table( HTML_ENTITIES, ENT_QUOTES );
2292 $translation_table[chr(38)] = '&';
2293 return preg_replace( "/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/", "&", strtr($myHTML, $translation_table) );
2297 * Escape single quotes, htmlspecialchar " < > &, and fix line endings.
2299 * Escapes text strings for echoing in JS, both inline (for example in onclick="...")
2300 * and inside <script> tag. Note that the strings have to be in single quotes.
2301 * The filter 'js_escape' is also applied here.
2305 * @param string $text The text to be escaped.
2306 * @return string Escaped text.
2308 function esc_js( $text ) {
2309 $safe_text = wp_check_invalid_utf8( $text );
2310 $safe_text = _wp_specialchars( $safe_text, ENT_COMPAT );
2311 $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) );
2312 $safe_text = str_replace( "\r", '', $safe_text );
2313 $safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) );
2314 return apply_filters( 'js_escape', $safe_text, $text );
2318 * Escape single quotes, specialchar double quotes, and fix line endings.
2320 * The filter 'js_escape' is also applied by esc_js()
2327 * @param string $text The text to be escaped.
2328 * @return string Escaped text.
2330 function js_escape( $text ) {
2331 return esc_js( $text );
2335 * Escaping for HTML blocks.
2339 * @param string $text
2342 function esc_html( $text ) {
2343 $safe_text = wp_check_invalid_utf8( $text );
2344 $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
2345 return apply_filters( 'esc_html', $safe_text, $text );
2349 * Escaping for HTML blocks
2353 function wp_specialchars( $string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false ) {
2354 if ( func_num_args() > 1 ) { // Maintain backwards compat for people passing additional args
2355 $args = func_get_args();
2356 return call_user_func_array( '_wp_specialchars', $args );
2358 return esc_html( $string );
2363 * Escaping for HTML attributes.
2367 * @param string $text
2370 function esc_attr( $text ) {
2371 $safe_text = wp_check_invalid_utf8( $text );
2372 $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
2373 return apply_filters( 'attribute_escape', $safe_text, $text );
2377 * Escaping for HTML attributes.
2384 * @param string $text
2387 function attribute_escape( $text ) {
2388 return esc_attr( $text );
2392 * Escape a HTML tag name.
2396 * @param string $tag_name
2399 function tag_escape($tag_name) {
2400 $safe_tag = strtolower( preg_replace('/[^a-zA-Z_:]/', '', $tag_name) );
2401 return apply_filters('tag_escape', $safe_tag, $tag_name);
2405 * Escapes text for SQL LIKE special characters % and _.
2409 * @param string $text The text to be escaped.
2410 * @return string text, safe for inclusion in LIKE query.
2412 function like_escape($text) {
2413 return str_replace(array("%", "_"), array("\\%", "\\_"), $text);
2417 * Convert full URL paths to absolute paths.
2419 * Removes the http or https protocols and the domain. Keeps the path '/' at the
2420 * beginning, so it isn't a true relative link, but from the web root base.
2424 * @param string $link Full URL path.
2425 * @return string Absolute path.
2427 function wp_make_link_relative( $link ) {
2428 return preg_replace( '|https?://[^/]+(/.*)|i', '$1', $link );
2432 * Sanitises various option values based on the nature of the option.
2434 * This is basically a switch statement which will pass $value through a number
2435 * of functions depending on the $option.
2439 * @param string $option The name of the option.
2440 * @param string $value The unsanitised value.
2441 * @return string Sanitized value.
2443 function sanitize_option($option, $value) {
2447 $value = sanitize_email($value);
2450 case 'thumbnail_size_w':
2451 case 'thumbnail_size_h':
2452 case 'medium_size_w':
2453 case 'medium_size_h':
2454 case 'large_size_w':
2455 case 'large_size_h':
2456 case 'embed_size_h':
2457 case 'default_post_edit_rows':
2458 case 'mailserver_port':
2459 case 'comment_max_links':
2460 case 'page_on_front':
2461 case 'rss_excerpt_length':
2462 case 'default_category':
2463 case 'default_email_category':
2464 case 'default_link_category':
2465 case 'close_comments_days_old':
2466 case 'comments_per_page':
2467 case 'thread_comments_depth':
2468 case 'users_can_register':
2469 $value = absint( $value );
2472 case 'embed_size_w':
2473 if ( '' !== $value )
2474 $value = absint( $value );
2477 case 'posts_per_page':
2478 case 'posts_per_rss':
2479 $value = (int) $value;
2480 if ( empty($value) ) $value = 1;
2481 if ( $value < -1 ) $value = abs($value);
2484 case 'default_ping_status':
2485 case 'default_comment_status':
2486 // Options that if not there have 0 value but need to be something like "closed"
2487 if ( $value == '0' || $value == '')
2491 case 'blogdescription':
2493 $value = addslashes($value);
2494 $value = wp_filter_post_kses( $value ); // calls stripslashes then addslashes
2495 $value = stripslashes($value);
2496 $value = esc_html( $value );
2499 case 'blog_charset':
2500 $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value); // strips slashes
2505 case 'mailserver_url':
2506 case 'mailserver_login':
2507 case 'mailserver_pass':
2510 $value = strip_tags($value);
2511 $value = addslashes($value);
2512 $value = wp_filter_kses($value); // calls stripslashes then addslashes
2513 $value = stripslashes($value);
2517 $value = preg_replace('/[^0-9:.-]/', '', $value); // strips slashes
2522 $value = stripslashes($value);
2523 $value = esc_url($value);
2526 $value = apply_filters("sanitize_option_{$option}", $value, $option);
2534 * Parses a string into variables to be stored in an array.
2536 * Uses {@link http://www.php.net/parse_str parse_str()} and stripslashes if
2537 * {@link http://www.php.net/magic_quotes magic_quotes_gpc} is on.
2540 * @uses apply_filters() for the 'wp_parse_str' filter.
2542 * @param string $string The string to be parsed.
2543 * @param array $array Variables will be stored in this array.
2545 function wp_parse_str( $string, &$array ) {
2546 parse_str( $string, $array );
2547 if ( get_magic_quotes_gpc() )
2548 $array = stripslashes_deep( $array );
2549 $array = apply_filters( 'wp_parse_str', $array );
2553 * Convert lone less than signs.
2555 * KSES already converts lone greater than signs.
2557 * @uses wp_pre_kses_less_than_callback in the callback function.
2560 * @param string $text Text to be converted.
2561 * @return string Converted text.
2563 function wp_pre_kses_less_than( $text ) {
2564 return preg_replace_callback('%<[^>]*?((?=<)|>|$)%', 'wp_pre_kses_less_than_callback', $text);
2568 * Callback function used by preg_replace.
2570 * @uses esc_html to format the $matches text.
2573 * @param array $matches Populated by matches to preg_replace.
2574 * @return string The text returned after esc_html if needed.
2576 function wp_pre_kses_less_than_callback( $matches ) {
2577 if ( false === strpos($matches[0], '>') )
2578 return esc_html($matches[0]);
2583 * WordPress implementation of PHP sprintf() with filters.
2586 * @link http://www.php.net/sprintf
2588 * @param string $pattern The string which formatted args are inserted.
2589 * @param mixed $args,... Arguments to be formatted into the $pattern string.
2590 * @return string The formatted string.
2592 function wp_sprintf( $pattern ) {
2593 $args = func_get_args( );
2594 $len = strlen($pattern);
2598 while ( $len > $start ) {
2599 // Last character: append and break
2600 if ( strlen($pattern) - 1 == $start ) {
2601 $result .= substr($pattern, -1);
2605 // Literal %: append and continue
2606 if ( substr($pattern, $start, 2) == '%%' ) {
2612 // Get fragment before next %
2613 $end = strpos($pattern, '%', $start + 1);
2614 if ( false === $end )
2616 $fragment = substr($pattern, $start, $end - $start);
2618 // Fragment has a specifier
2619 if ( $pattern{$start} == '%' ) {
2620 // Find numbered arguments or take the next one in order
2621 if ( preg_match('/^%(\d+)\$/', $fragment, $matches) ) {
2622 $arg = isset($args[$matches[1]]) ? $args[$matches[1]] : '';
2623 $fragment = str_replace("%{$matches[1]}$", '%', $fragment);
2626 $arg = isset($args[$arg_index]) ? $args[$arg_index] : '';
2629 // Apply filters OR sprintf
2630 $_fragment = apply_filters( 'wp_sprintf', $fragment, $arg );
2631 if ( $_fragment != $fragment )
2632 $fragment = $_fragment;
2634 $fragment = sprintf($fragment, strval($arg) );
2637 // Append to result and move to next fragment
2638 $result .= $fragment;
2645 * Localize list items before the rest of the content.
2647 * The '%l' must be at the first characters can then contain the rest of the
2648 * content. The list items will have ', ', ', and', and ' and ' added depending
2649 * on the amount of list items in the $args parameter.
2653 * @param string $pattern Content containing '%l' at the beginning.
2654 * @param array $args List items to prepend to the content and replace '%l'.
2655 * @return string Localized list items and rest of the content.
2657 function wp_sprintf_l($pattern, $args) {
2659 if ( substr($pattern, 0, 2) != '%l' )
2662 // Nothing to work with
2666 // Translate and filter the delimiter set (avoid ampersands and entities here)
2667 $l = apply_filters('wp_sprintf_l', array(
2668 /* translators: used between list items, there is a space after the coma */
2669 'between' => __(', '),
2670 /* translators: used between list items, there is a space after the and */
2671 'between_last_two' => __(', and '),
2672 /* translators: used between only two list items, there is a space after the and */
2673 'between_only_two' => __(' and '),
2676 $args = (array) $args;
2677 $result = array_shift($args);
2678 if ( count($args) == 1 )
2679 $result .= $l['between_only_two'] . array_shift($args);
2680 // Loop when more than two args
2683 $arg = array_shift($args);
2686 $result .= $l['between_last_two'] . $arg;
2688 $result .= $l['between'] . $arg;
2690 return $result . substr($pattern, 2);
2694 * Safely extracts not more than the first $count characters from html string.
2696 * UTF-8, tags and entities safe prefix extraction. Entities inside will *NOT*
2697 * be counted as one character. For example & will be counted as 4, < as
2702 * @param integer $str String to get the excerpt from.
2703 * @param integer $count Maximum number of characters to take.
2704 * @return string The excerpt.
2706 function wp_html_excerpt( $str, $count ) {
2707 $str = wp_strip_all_tags( $str, true );
2708 $str = mb_substr( $str, 0, $count );
2709 // remove part of an entity at the end
2710 $str = preg_replace( '/&[^;\s]{0,6}$/', '', $str );
2715 * Add a Base url to relative links in passed content.
2717 * By default it supports the 'src' and 'href' attributes. However this can be
2718 * changed via the 3rd param.
2722 * @param string $content String to search for links in.
2723 * @param string $base The base URL to prefix to links.
2724 * @param array $attrs The attributes which should be processed.
2725 * @return string The processed content.
2727 function links_add_base_url( $content, $base, $attrs = array('src', 'href') ) {
2728 $attrs = implode('|', (array)$attrs);
2729 return preg_replace_callback("!($attrs)=(['\"])(.+?)\\2!i",
2730 create_function('$m', 'return _links_add_base($m, "' . $base . '");'),
2735 * Callback to add a base url to relative links in passed content.
2740 * @param string $m The matched link.
2741 * @param string $base The base URL to prefix to links.
2742 * @return string The processed link.
2744 function _links_add_base($m, $base) {
2745 //1 = attribute name 2 = quotation mark 3 = URL
2746 return $m[1] . '=' . $m[2] .
2747 (strpos($m[3], 'http://') === false ?
2748 path_join($base, $m[3]) :
2754 * Adds a Target attribute to all links in passed content.
2756 * This function by default only applies to <a> tags, however this can be
2757 * modified by the 3rd param.
2759 * <b>NOTE:</b> Any current target attributed will be striped and replaced.
2763 * @param string $content String to search for links in.
2764 * @param string $target The Target to add to the links.
2765 * @param array $tags An array of tags to apply to.
2766 * @return string The processed content.
2768 function links_add_target( $content, $target = '_blank', $tags = array('a') ) {
2769 $tags = implode('|', (array)$tags);
2770 return preg_replace_callback("!<($tags)(.+?)>!i",
2771 create_function('$m', 'return _links_add_target($m, "' . $target . '");'),
2776 * Callback to add a target attribute to all links in passed content.
2781 * @param string $m The matched link.
2782 * @param string $target The Target to add to the links.
2783 * @return string The processed link.
2785 function _links_add_target( $m, $target ) {
2787 $link = preg_replace('|(target=[\'"](.*?)[\'"])|i', '', $m[2]);
2788 return '<' . $tag . $link . ' target="' . $target . '">';
2791 // normalize EOL characters and strip duplicate whitespace
2792 function normalize_whitespace( $str ) {
2794 $str = str_replace("\r", "\n", $str);
2795 $str = preg_replace( array( '/\n+/', '/[ \t]+/' ), array( "\n", ' ' ), $str );
2800 * Properly strip all HTML tags including script and style
2804 * @param string $string String containing HTML tags
2805 * @param bool $remove_breaks optional Whether to remove left over line breaks and white space chars
2806 * @return string The processed string.
2808 function wp_strip_all_tags($string, $remove_breaks = false) {
2809 $string = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $string );
2810 $string = strip_tags($string);
2812 if ( $remove_breaks )
2813 $string = preg_replace('/[\r\n\t ]+/', ' ', $string);
2815 return trim($string);
2819 * Sanitize a string from user input or from the db
2821 * check for invalid UTF-8,
2822 * Convert single < characters to entity,
2824 * remove line breaks, tabs and extra whitre space,
2829 * @param string $str
2832 function sanitize_text_field($str) {
2833 $filtered = wp_check_invalid_utf8( $str );
2835 if ( strpos($filtered, '<') !== false ) {
2836 $filtered = wp_pre_kses_less_than( $filtered );
2837 $filtered = wp_strip_all_tags( $filtered, true );
2839 $filtered = trim( preg_replace('/[\r\n\t ]+/', ' ', $filtered) );
2843 while ( preg_match('/%[a-f0-9]{2}/i', $filtered, $match) )
2844 $filtered = str_replace($match[0], '', $filtered);
2846 return apply_filters('sanitize_text_field', $filtered, $str);