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;
33 $textarr = preg_split('/(<.*>|\[.*\])/Us', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
34 $stop = count($textarr);
36 /* translators: opening curly quote */
37 $opening_quote = _x('“', 'opening curly quote');
38 /* translators: closing curly quote */
39 $closing_quote = _x('”', 'closing curly quote');
41 $no_texturize_tags = apply_filters('no_texturize_tags', array('pre', 'code', 'kbd', 'style', 'script', 'tt'));
42 $no_texturize_shortcodes = apply_filters('no_texturize_shortcodes', array('code'));
43 $no_texturize_tags_stack = array();
44 $no_texturize_shortcodes_stack = array();
46 // if a plugin has provided an autocorrect array, use it
47 if ( isset($wp_cockneyreplace) ) {
48 $cockney = array_keys($wp_cockneyreplace);
49 $cockneyreplace = array_values($wp_cockneyreplace);
51 $cockney = array("'tain't","'twere","'twas","'tis","'twill","'til","'bout","'nuff","'round","'cause");
52 $cockneyreplace = array("’tain’t","’twere","’twas","’tis","’twill","’til","’bout","’nuff","’round","’cause");
55 $static_characters = array_merge(array('---', ' -- ', '--', ' - ', 'xn–', '...', '``', '\'s', '\'\'', ' (tm)'), $cockney);
56 $static_replacements = array_merge(array('—', ' — ', '–', ' – ', 'xn--', '…', $opening_quote, '’s', $closing_quote, ' ™'), $cockneyreplace);
58 $dynamic_characters = array('/\'(\d\d(?:’|\')?s)/', '/(\s|\A|")\'/', '/(\d+)"/', '/(\d+)\'/', '/(\S)\'([^\'\s])/', '/(\s|\A)"(?!\s)/', '/"(\s|\S|\Z)/', '/\'([\s.]|\Z)/', '/(\d+)x(\d+)/');
59 $dynamic_replacements = array('’$1','$1‘', '$1″', '$1′', '$1’$2', '$1' . $opening_quote . '$2', $closing_quote . '$1', '’$1', '$1×$2');
61 for ( $i = 0; $i < $stop; $i++ ) {
64 if ( !empty($curl) && '<' != $curl{0} && '[' != $curl{0}
65 && empty($no_texturize_shortcodes_stack) && empty($no_texturize_tags_stack)) { // If it's not a tag
67 $curl = str_replace($static_characters, $static_replacements, $curl);
68 // regular expressions
69 $curl = preg_replace($dynamic_characters, $dynamic_replacements, $curl);
71 wptexturize_pushpop_element($curl, $no_texturize_tags_stack, $no_texturize_tags, '<', '>');
72 wptexturize_pushpop_element($curl, $no_texturize_shortcodes_stack, $no_texturize_shortcodes, '[', ']');
75 $curl = preg_replace('/&([^#])(?![a-zA-Z1-4]{1,8};)/', '&$1', $curl);
82 function wptexturize_pushpop_element($text, &$stack, $disabled_elements, $opening = '<', $closing = '>') {
83 $o = preg_quote($opening, '/');
84 $c = preg_quote($closing, '/');
85 foreach($disabled_elements as $element) {
86 if (preg_match('/^'.$o.$element.'\b/', $text)) array_push($stack, $element);
87 if (preg_match('/^'.$o.'\/'.$element.$c.'/', $text)) {
88 $last = array_pop($stack);
89 // disable texturize until we find a closing tag of our type (e.g. <pre>)
90 // even if there was invalid nesting before that
91 // Example: in the case <pre>sadsadasd</code>"baba"</pre> "baba" won't be texturized
92 if ($last != $element) array_push($stack, $last);
98 * Accepts matches array from preg_replace_callback in wpautop() or a string.
100 * Ensures that the contents of a <<pre>>...<</pre>> HTML block are not
101 * converted into paragraphs or line-breaks.
105 * @param array|string $matches The array or string
106 * @return string The pre block without paragraph/line-break conversion.
108 function clean_pre($matches) {
109 if ( is_array($matches) )
110 $text = $matches[1] . $matches[2] . "</pre>";
114 $text = str_replace('<br />', '', $text);
115 $text = str_replace('<p>', "\n", $text);
116 $text = str_replace('</p>', '', $text);
122 * Replaces double line-breaks with paragraph elements.
124 * A group of regex replaces used to identify text formatted with newlines and
125 * replace double line-breaks with HTML paragraph tags. The remaining
126 * line-breaks after conversion become <<br />> tags, unless $br is set to '0'
131 * @param string $pee The text which has to be formatted.
132 * @param int|bool $br Optional. If set, this will convert all remaining line-breaks after paragraphing. Default true.
133 * @return string Text which has been converted into correct paragraph tags.
135 function wpautop($pee, $br = 1) {
136 if ( trim($pee) === '' )
138 $pee = $pee . "\n"; // just to make things a little easier, pad the end
139 $pee = preg_replace('|<br />\s*<br />|', "\n\n", $pee);
140 // Space things out a little
141 $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)';
142 $pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee);
143 $pee = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $pee);
144 $pee = str_replace(array("\r\n", "\r"), "\n", $pee); // cross-platform newlines
145 if ( strpos($pee, '<object') !== false ) {
146 $pee = preg_replace('|\s*<param([^>]*)>\s*|', "<param$1>", $pee); // no pee inside object/embed
147 $pee = preg_replace('|\s*</embed>\s*|', '</embed>', $pee);
149 $pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates
150 // make paragraphs, including one at the end
151 $pees = preg_split('/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY);
153 foreach ( $pees as $tinkle )
154 $pee .= '<p>' . trim($tinkle, "\n") . "</p>\n";
155 $pee = preg_replace('|<p>\s*</p>|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace
156 $pee = preg_replace('!<p>([^<]+)</(div|address|form)>!', "<p>$1</p></$2>", $pee);
157 $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee); // don't pee all over a tag
158 $pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee); // problem with nested lists
159 $pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee);
160 $pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee);
161 $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)!', "$1", $pee);
162 $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
164 $pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', create_function('$matches', 'return str_replace("\n", "<WPPreserveNewline />", $matches[0]);'), $pee);
165 $pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee); // optionally make line breaks
166 $pee = str_replace('<WPPreserveNewline />', "\n", $pee);
168 $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', "$1", $pee);
169 $pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee);
170 if (strpos($pee, '<pre') !== false)
171 $pee = preg_replace_callback('!(<pre[^>]*>)(.*?)</pre>!is', 'clean_pre', $pee );
172 $pee = preg_replace( "|\n</p>$|", '</p>', $pee );
173 $pee = preg_replace('/<p>\s*?(' . get_shortcode_regex() . ')\s*<\/p>/s', '$1', $pee); // don't auto-p wrap shortcodes that stand alone
179 * Checks to see if a string is utf8 encoded.
181 * NOTE: This function checks for 5-Byte sequences, UTF8
182 * has Bytes Sequences with a maximum length of 4.
184 * @author bmorel at ssi dot fr (modified)
187 * @param string $str The string to be checked
188 * @return bool True if $str fits a UTF-8 model, false otherwise.
190 function seems_utf8($str) {
191 $length = strlen($str);
192 for ($i=0; $i < $length; $i++) {
194 if ($c < 0x80) $n = 0; # 0bbbbbbb
195 elseif (($c & 0xE0) == 0xC0) $n=1; # 110bbbbb
196 elseif (($c & 0xF0) == 0xE0) $n=2; # 1110bbbb
197 elseif (($c & 0xF8) == 0xF0) $n=3; # 11110bbb
198 elseif (($c & 0xFC) == 0xF8) $n=4; # 111110bb
199 elseif (($c & 0xFE) == 0xFC) $n=5; # 1111110b
200 else return false; # Does not match any model
201 for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
202 if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))
210 * Converts a number of special characters into their HTML entities.
212 * Specifically deals with: &, <, >, ", and '.
214 * $quote_style can be set to ENT_COMPAT to encode " to
215 * ", or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded.
219 * @param string $string The text which is to be encoded.
220 * @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.
221 * @param string $charset Optional. The character encoding of the string. Default is false.
222 * @param boolean $double_encode Optional. Whether or not to encode existing html entities. Default is false.
223 * @return string The encoded text with HTML entities.
225 function _wp_specialchars( $string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false ) {
226 $string = (string) $string;
228 if ( 0 === strlen( $string ) ) {
232 // Don't bother if there are no specialchars - saves some processing
233 if ( !preg_match( '/[&<>"\']/', $string ) ) {
237 // Account for the previous behaviour of the function when the $quote_style is not an accepted value
238 if ( empty( $quote_style ) ) {
239 $quote_style = ENT_NOQUOTES;
240 } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
241 $quote_style = ENT_QUOTES;
244 // Store the site charset as a static to avoid multiple calls to wp_load_alloptions()
247 if ( !isset( $_charset ) ) {
248 $alloptions = wp_load_alloptions();
249 $_charset = isset( $alloptions['blog_charset'] ) ? $alloptions['blog_charset'] : '';
251 $charset = $_charset;
253 if ( in_array( $charset, array( 'utf8', 'utf-8', 'UTF8' ) ) ) {
257 $_quote_style = $quote_style;
259 if ( $quote_style === 'double' ) {
260 $quote_style = ENT_COMPAT;
261 $_quote_style = ENT_COMPAT;
262 } elseif ( $quote_style === 'single' ) {
263 $quote_style = ENT_NOQUOTES;
266 // Handle double encoding ourselves
267 if ( !$double_encode ) {
268 $string = wp_specialchars_decode( $string, $_quote_style );
269 $string = preg_replace( '/&(#?x?[0-9a-z]+);/i', '|wp_entity|$1|/wp_entity|', $string );
272 $string = @htmlspecialchars( $string, $quote_style, $charset );
274 // Handle double encoding ourselves
275 if ( !$double_encode ) {
276 $string = str_replace( array( '|wp_entity|', '|/wp_entity|' ), array( '&', ';' ), $string );
279 // Backwards compatibility
280 if ( 'single' === $_quote_style ) {
281 $string = str_replace( "'", ''', $string );
288 * Converts a number of HTML entities into their special characters.
290 * Specifically deals with: &, <, >, ", and '.
292 * $quote_style can be set to ENT_COMPAT to decode " entities,
293 * or ENT_QUOTES to do both " and '. Default is ENT_NOQUOTES where no quotes are decoded.
297 * @param string $string The text which is to be decoded.
298 * @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.
299 * @return string The decoded text without HTML entities.
301 function wp_specialchars_decode( $string, $quote_style = ENT_NOQUOTES ) {
302 $string = (string) $string;
304 if ( 0 === strlen( $string ) ) {
308 // Don't bother if there are no entities - saves a lot of processing
309 if ( strpos( $string, '&' ) === false ) {
313 // Match the previous behaviour of _wp_specialchars() when the $quote_style is not an accepted value
314 if ( empty( $quote_style ) ) {
315 $quote_style = ENT_NOQUOTES;
316 } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
317 $quote_style = ENT_QUOTES;
320 // More complete than get_html_translation_table( HTML_SPECIALCHARS )
321 $single = array( ''' => '\'', ''' => '\'' );
322 $single_preg = array( '/�*39;/' => ''', '/�*27;/i' => ''' );
323 $double = array( '"' => '"', '"' => '"', '"' => '"' );
324 $double_preg = array( '/�*34;/' => '"', '/�*22;/i' => '"' );
325 $others = array( '<' => '<', '<' => '<', '>' => '>', '>' => '>', '&' => '&', '&' => '&', '&' => '&' );
326 $others_preg = array( '/�*60;/' => '<', '/�*62;/' => '>', '/�*38;/' => '&', '/�*26;/i' => '&' );
328 if ( $quote_style === ENT_QUOTES ) {
329 $translation = array_merge( $single, $double, $others );
330 $translation_preg = array_merge( $single_preg, $double_preg, $others_preg );
331 } elseif ( $quote_style === ENT_COMPAT || $quote_style === 'double' ) {
332 $translation = array_merge( $double, $others );
333 $translation_preg = array_merge( $double_preg, $others_preg );
334 } elseif ( $quote_style === 'single' ) {
335 $translation = array_merge( $single, $others );
336 $translation_preg = array_merge( $single_preg, $others_preg );
337 } elseif ( $quote_style === ENT_NOQUOTES ) {
338 $translation = $others;
339 $translation_preg = $others_preg;
342 // Remove zero padding on numeric entities
343 $string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string );
345 // Replace characters according to translation table
346 return strtr( $string, $translation );
350 * Checks for invalid UTF8 in a string.
354 * @param string $string The text which is to be checked.
355 * @param boolean $strip Optional. Whether to attempt to strip out invalid UTF8. Default is false.
356 * @return string The checked text.
358 function wp_check_invalid_utf8( $string, $strip = false ) {
359 $string = (string) $string;
361 if ( 0 === strlen( $string ) ) {
365 // Store the site charset as a static to avoid multiple calls to get_option()
367 if ( !isset( $is_utf8 ) ) {
368 $is_utf8 = in_array( get_option( 'blog_charset' ), array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ) );
374 // Check for support for utf8 in the installed PCRE library once and store the result in a static
376 if ( !isset( $utf8_pcre ) ) {
377 $utf8_pcre = @preg_match( '/^./u', 'a' );
379 // We can't demand utf8 in the PCRE installation, so just return the string in those cases
384 // preg_match fails when it encounters invalid UTF8 in $string
385 if ( 1 === @preg_match( '/^./us', $string ) ) {
389 // Attempt to strip the bad chars if requested (not recommended)
390 if ( $strip && function_exists( 'iconv' ) ) {
391 return iconv( 'utf-8', 'utf-8', $string );
398 * Encode the Unicode values to be used in the URI.
402 * @param string $utf8_string
403 * @param int $length Max length of the string
404 * @return string String with Unicode encoded for URI.
406 function utf8_uri_encode( $utf8_string, $length = 0 ) {
412 $string_length = strlen( $utf8_string );
413 for ($i = 0; $i < $string_length; $i++ ) {
415 $value = ord( $utf8_string[ $i ] );
417 if ( $value < 128 ) {
418 if ( $length && ( $unicode_length >= $length ) )
420 $unicode .= chr($value);
423 if ( count( $values ) == 0 ) $num_octets = ( $value < 224 ) ? 2 : 3;
427 if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length )
429 if ( count( $values ) == $num_octets ) {
430 if ($num_octets == 3) {
431 $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]) . '%' . dechex($values[2]);
432 $unicode_length += 9;
434 $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]);
435 $unicode_length += 6;
448 * Converts all accent characters to ASCII characters.
450 * If there are no accent characters, then the string given is just returned.
454 * @param string $string Text that might have accent characters
455 * @return string Filtered string with replaced "nice" characters.
457 function remove_accents($string) {
458 if ( !preg_match('/[\x80-\xff]/', $string) )
461 if (seems_utf8($string)) {
463 // Decompositions for Latin-1 Supplement
464 chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
465 chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
466 chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
467 chr(195).chr(135) => 'C', chr(195).chr(136) => 'E',
468 chr(195).chr(137) => 'E', chr(195).chr(138) => 'E',
469 chr(195).chr(139) => 'E', chr(195).chr(140) => 'I',
470 chr(195).chr(141) => 'I', chr(195).chr(142) => 'I',
471 chr(195).chr(143) => 'I', chr(195).chr(145) => 'N',
472 chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
473 chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
474 chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
475 chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
476 chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
477 chr(195).chr(159) => 's', chr(195).chr(160) => 'a',
478 chr(195).chr(161) => 'a', chr(195).chr(162) => 'a',
479 chr(195).chr(163) => 'a', chr(195).chr(164) => 'a',
480 chr(195).chr(165) => 'a', chr(195).chr(167) => 'c',
481 chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
482 chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
483 chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
484 chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
485 chr(195).chr(177) => 'n', chr(195).chr(178) => 'o',
486 chr(195).chr(179) => 'o', chr(195).chr(180) => 'o',
487 chr(195).chr(181) => 'o', chr(195).chr(182) => 'o',
488 chr(195).chr(182) => 'o', chr(195).chr(185) => 'u',
489 chr(195).chr(186) => 'u', chr(195).chr(187) => 'u',
490 chr(195).chr(188) => 'u', chr(195).chr(189) => 'y',
491 chr(195).chr(191) => 'y',
492 // Decompositions for Latin Extended-A
493 chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
494 chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
495 chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
496 chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
497 chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
498 chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
499 chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
500 chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
501 chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
502 chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
503 chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
504 chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
505 chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
506 chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
507 chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
508 chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
509 chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
510 chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
511 chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
512 chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
513 chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
514 chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
515 chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
516 chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
517 chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
518 chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
519 chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
520 chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
521 chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
522 chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
523 chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
524 chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
525 chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
526 chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
527 chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
528 chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
529 chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
530 chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
531 chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
532 chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
533 chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
534 chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
535 chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
536 chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
537 chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
538 chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
539 chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
540 chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
541 chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
542 chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
543 chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
544 chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
545 chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
546 chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
547 chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
548 chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
549 chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
550 chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
551 chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
552 chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
553 chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
554 chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
555 chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
556 chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
558 chr(226).chr(130).chr(172) => 'E',
560 chr(194).chr(163) => '');
562 $string = strtr($string, $chars);
564 // Assume ISO-8859-1 if not UTF-8
565 $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
566 .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
567 .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
568 .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
569 .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
570 .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
571 .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
572 .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
573 .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
574 .chr(252).chr(253).chr(255);
576 $chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";
578 $string = strtr($string, $chars['in'], $chars['out']);
579 $double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
580 $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
581 $string = str_replace($double_chars['in'], $double_chars['out'], $string);
588 * Sanitizes a filename replacing whitespace with dashes
590 * Removes special characters that are illegal in filenames on certain
591 * operating systems and special characters requiring special escaping
592 * to manipulate at the command line. Replaces spaces and consecutive
593 * dashes with a single dash. Trim period, dash and underscore from beginning
594 * and end of filename.
598 * @param string $filename The filename to be sanitized
599 * @return string The sanitized filename
601 function sanitize_file_name( $filename ) {
602 $filename_raw = $filename;
603 $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", chr(0));
604 $special_chars = apply_filters('sanitize_file_name_chars', $special_chars, $filename_raw);
605 $filename = str_replace($special_chars, '', $filename);
606 $filename = preg_replace('/[\s-]+/', '-', $filename);
607 $filename = trim($filename, '.-_');
608 return apply_filters('sanitize_file_name', $filename, $filename_raw);
612 * Sanitize username stripping out unsafe characters.
614 * If $strict is true, only alphanumeric characters (as well as _, space, ., -,
616 * Removes tags, octets, entities, and if strict is enabled, will remove all
617 * non-ASCII characters. After sanitizing, it passes the username, raw username
618 * (the username in the parameter), and the strict parameter as parameters for
622 * @uses apply_filters() Calls 'sanitize_user' hook on username, raw username,
623 * and $strict parameter.
625 * @param string $username The username to be sanitized.
626 * @param bool $strict If set limits $username to specific characters. Default false.
627 * @return string The sanitized username, after passing through filters.
629 function sanitize_user( $username, $strict = false ) {
630 $raw_username = $username;
631 $username = strip_tags($username);
633 $username = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '', $username);
634 $username = preg_replace('/&.+?;/', '', $username); // Kill entities
636 // If strict, reduce to ASCII for max portability.
638 $username = preg_replace('|[^a-z0-9 _.\-@]|i', '', $username);
640 // Consolidate contiguous whitespace
641 $username = preg_replace('|\s+|', ' ', $username);
643 return apply_filters('sanitize_user', $username, $raw_username, $strict);
647 * Sanitizes title or use fallback title.
649 * Specifically, HTML and PHP tags are stripped. Further actions can be added
650 * via the plugin API. If $title is empty and $fallback_title is set, the latter
655 * @param string $title The string to be sanitized.
656 * @param string $fallback_title Optional. A title to use if $title is empty.
657 * @return string The sanitized string.
659 function sanitize_title($title, $fallback_title = '') {
661 $title = strip_tags($title);
662 $title = apply_filters('sanitize_title', $title, $raw_title);
664 if ( '' === $title || false === $title )
665 $title = $fallback_title;
671 * Sanitizes title, replacing whitespace with dashes.
673 * Limits the output to alphanumeric characters, underscore (_) and dash (-).
674 * Whitespace becomes a dash.
678 * @param string $title The title to be sanitized.
679 * @return string The sanitized title.
681 function sanitize_title_with_dashes($title) {
682 $title = strip_tags($title);
683 // Preserve escaped octets.
684 $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
685 // Remove percent signs that are not part of an octet.
686 $title = str_replace('%', '', $title);
688 $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
690 $title = remove_accents($title);
691 if (seems_utf8($title)) {
692 if (function_exists('mb_strtolower')) {
693 $title = mb_strtolower($title, 'UTF-8');
695 $title = utf8_uri_encode($title, 200);
698 $title = strtolower($title);
699 $title = preg_replace('/&.+?;/', '', $title); // kill entities
700 $title = str_replace('.', '-', $title);
701 $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
702 $title = preg_replace('/\s+/', '-', $title);
703 $title = preg_replace('|-+|', '-', $title);
704 $title = trim($title, '-');
710 * Ensures a string is a valid SQL order by clause.
712 * Accepts one or more columns, with or without ASC/DESC, and also accepts
717 * @param string $orderby Order by string to be checked.
718 * @return string|false Returns the order by clause if it is a match, false otherwise.
720 function sanitize_sql_orderby( $orderby ){
721 preg_match('/^\s*([a-z0-9_]+(\s+(ASC|DESC))?(\s*,\s*|\s*$))+|^\s*RAND\(\s*\)\s*$/i', $orderby, $obmatches);
728 * Santizes a html classname to ensure it only contains valid characters
730 * Strips the string down to A-Z,a-z,0-9,'-' if this results in an empty
731 * string then it will return the alternative value supplied.
733 * @todo Expand to support the full range of CDATA that a class attribute can contain.
737 * @param string $class The classname to be sanitized
738 * @param string $fallback The value to return if the sanitization end's up as an empty string.
739 * @return string The sanitized value
741 function sanitize_html_class($class, $fallback){
742 //Strip out any % encoded octets
743 $sanitized = preg_replace('|%[a-fA-F0-9][a-fA-F0-9]|', '', $class);
745 //Limit to A-Z,a-z,0-9,'-'
746 $sanitized = preg_replace('/[^A-Za-z0-9-]/', '', $sanitized);
748 if ('' == $sanitized)
749 $sanitized = $fallback;
751 return apply_filters('sanitize_html_class',$sanitized, $class, $fallback);
755 * Converts a number of characters from a string.
757 * Metadata tags <<title>> and <<category>> are removed, <<br>> and <<hr>> are
758 * converted into correct XHTML and Unicode characters are converted to the
763 * @param string $content String of characters to be converted.
764 * @param string $deprecated Not used.
765 * @return string Converted string.
767 function convert_chars($content, $deprecated = '') {
768 // Translation of invalid Unicode references range to valid range
769 $wp_htmltranswinuni = array(
770 '€' => '€', // the Euro sign
772 '‚' => '‚', // these are Windows CP1252 specific characters
773 'ƒ' => 'ƒ', // they would look weird on non-Windows browsers
774 '„' => '„',
775 '…' => '…',
776 '†' => '†',
777 '‡' => '‡',
778 'ˆ' => 'ˆ',
779 '‰' => '‰',
780 'Š' => 'Š',
781 '‹' => '‹',
782 'Œ' => 'Œ',
784 'Ž' => 'ž',
787 '‘' => '‘',
788 '’' => '’',
789 '“' => '“',
790 '”' => '”',
791 '•' => '•',
792 '–' => '–',
793 '—' => '—',
794 '˜' => '˜',
795 '™' => '™',
796 'š' => 'š',
797 '›' => '›',
798 'œ' => 'œ',
804 // Remove metadata tags
805 $content = preg_replace('/<title>(.+?)<\/title>/','',$content);
806 $content = preg_replace('/<category>(.+?)<\/category>/','',$content);
808 // Converts lone & characters into & (a.k.a. &)
809 $content = preg_replace('/&([^#])(?![a-z1-4]{1,8};)/i', '&$1', $content);
812 $content = strtr($content, $wp_htmltranswinuni);
814 // Just a little XHTML help
815 $content = str_replace('<br>', '<br />', $content);
816 $content = str_replace('<hr>', '<hr />', $content);
822 * Callback used to change %uXXXX to &#YYY; syntax
826 * @param array $matches Single Match
827 * @return string An HTML entity
829 function funky_javascript_callback($matches) {
830 return "&#".base_convert($matches[1],16,10).";";
834 * Fixes javascript bugs in browsers.
836 * Converts unicode characters to HTML numbered entities.
842 * @param string $text Text to be made safe.
843 * @return string Fixed text.
845 function funky_javascript_fix($text) {
846 // Fixes for browsers' javascript bugs
847 global $is_macIE, $is_winIE;
849 if ( $is_winIE || $is_macIE )
850 $text = preg_replace_callback("/\%u([0-9A-F]{4,4})/",
851 "funky_javascript_callback",
858 * Will only balance the tags if forced to and the option is set to balance tags.
860 * The option 'use_balanceTags' is used for whether the tags will be balanced.
861 * Both the $force parameter and 'use_balanceTags' option will have to be true
862 * before the tags will be balanced.
866 * @param string $text Text to be balanced
867 * @param bool $force Forces balancing, ignoring the value of the option. Default false.
868 * @return string Balanced text
870 function balanceTags( $text, $force = false ) {
871 if ( !$force && get_option('use_balanceTags') == 0 )
873 return force_balance_tags( $text );
877 * Balances tags of string using a modified stack.
881 * @author Leonard Lin <leonard@acm.org>
883 * @copyright November 4, 2001
885 * @todo Make better - change loop condition to $text in 1.2
886 * @internal Modified by Scott Reilly (coffee2code) 02 Aug 2004
887 * 1.1 Fixed handling of append/stack pop order of end text
888 * Added Cleaning Hooks
891 * @param string $text Text to be balanced.
892 * @return string Balanced text.
894 function force_balance_tags( $text ) {
895 $tagstack = array(); $stacksize = 0; $tagqueue = ''; $newtext = '';
896 $single_tags = array('br', 'hr', 'img', 'input'); //Known single-entity/self-closing tags
897 $nestable_tags = array('blockquote', 'div', 'span'); //Tags that can be immediately nested within themselves
899 # WP bug fix for comments - in case you REALLY meant to type '< !--'
900 $text = str_replace('< !--', '< !--', $text);
901 # WP bug fix for LOVE <3 (and other situations with '<' before a number)
902 $text = preg_replace('#<([0-9]{1})#', '<$1', $text);
904 while (preg_match("/<(\/?\w*)\s*([^>]*)>/",$text,$regex)) {
905 $newtext .= $tagqueue;
907 $i = strpos($text,$regex[0]);
908 $l = strlen($regex[0]);
913 if ( isset($regex[1][0]) && '/' == $regex[1][0] ) { // End Tag
914 $tag = strtolower(substr($regex[1],1));
915 // if too many closing tags
916 if($stacksize <= 0) {
918 //or close to be safe $tag = '/' . $tag;
920 // if stacktop value = tag close value then pop
921 else if ($tagstack[$stacksize - 1] == $tag) { // found closing tag
922 $tag = '</' . $tag . '>'; // Close Tag
924 array_pop ($tagstack);
926 } else { // closing tag not at top, search for it
927 for ($j=$stacksize-1;$j>=0;$j--) {
928 if ($tagstack[$j] == $tag) {
929 // add tag to tagqueue
930 for ($k=$stacksize-1;$k>=$j;$k--){
931 $tagqueue .= '</' . array_pop ($tagstack) . '>';
939 } else { // Begin Tag
940 $tag = strtolower($regex[1]);
944 // If self-closing or '', don't do anything.
945 if((substr($regex[2],-1) == '/') || ($tag == '')) {
947 // ElseIf it's a known single-entity tag but it doesn't close itself, do so
948 elseif ( in_array($tag, $single_tags) ) {
950 } else { // Push the tag onto the stack
951 // If the top of the stack is the same as the tag we want to push, close previous tag
952 if (($stacksize > 0) && !in_array($tag, $nestable_tags) && ($tagstack[$stacksize - 1] == $tag)) {
953 $tagqueue = '</' . array_pop ($tagstack) . '>';
956 $stacksize = array_push ($tagstack, $tag);
960 $attributes = $regex[2];
962 $attributes = ' '.$attributes;
964 $tag = '<'.$tag.$attributes.'>';
965 //If already queuing a close tag, then put this tag on, too
971 $newtext .= substr($text,0,$i) . $tag;
972 $text = substr($text,$i+$l);
976 $newtext .= $tagqueue;
978 // Add Remaining text
982 while($x = array_pop($tagstack)) {
983 $newtext .= '</' . $x . '>'; // Add remaining tags to close
986 // WP fix for the bug with HTML comments
987 $newtext = str_replace("< !--","<!--",$newtext);
988 $newtext = str_replace("< !--","< !--",$newtext);
994 * Acts on text which is about to be edited.
996 * Unless $richedit is set, it is simply a holder for the 'format_to_edit'
997 * filter. If $richedit is set true htmlspecialchars() will be run on the
998 * content, converting special characters to HTMl entities.
1002 * @param string $content The text about to be edited.
1003 * @param bool $richedit Whether or not the $content should pass through htmlspecialchars(). Default false.
1004 * @return string The text after the filter (and possibly htmlspecialchars()) has been run.
1006 function format_to_edit($content, $richedit = false) {
1007 $content = apply_filters('format_to_edit', $content);
1009 $content = htmlspecialchars($content);
1014 * Holder for the 'format_to_post' filter.
1018 * @param string $content The text to pass through the filter.
1019 * @return string Text returned from the 'format_to_post' filter.
1021 function format_to_post($content) {
1022 $content = apply_filters('format_to_post', $content);
1027 * Add leading zeros when necessary.
1029 * If you set the threshold to '4' and the number is '10', then you will get
1030 * back '0010'. If you set the number to '4' and the number is '5000', then you
1031 * will get back '5000'.
1033 * Uses sprintf to append the amount of zeros based on the $threshold parameter
1034 * and the size of the number. If the number is large enough, then no zeros will
1039 * @param mixed $number Number to append zeros to if not greater than threshold.
1040 * @param int $threshold Digit places number needs to be to not have zeros added.
1041 * @return string Adds leading zeros to number if needed.
1043 function zeroise($number, $threshold) {
1044 return sprintf('%0'.$threshold.'s', $number);
1048 * Adds backslashes before letters and before a number at the start of a string.
1052 * @param string $string Value to which backslashes will be added.
1053 * @return string String with backslashes inserted.
1055 function backslashit($string) {
1056 $string = preg_replace('/^([0-9])/', '\\\\\\\\\1', $string);
1057 $string = preg_replace('/([a-z])/i', '\\\\\1', $string);
1062 * Appends a trailing slash.
1064 * Will remove trailing slash if it exists already before adding a trailing
1065 * slash. This prevents double slashing a string or path.
1067 * The primary use of this is for paths and thus should be used for paths. It is
1068 * not restricted to paths and offers no specific path support.
1071 * @uses untrailingslashit() Unslashes string if it was slashed already.
1073 * @param string $string What to add the trailing slash to.
1074 * @return string String with trailing slash added.
1076 function trailingslashit($string) {
1077 return untrailingslashit($string) . '/';
1081 * Removes trailing slash if it exists.
1083 * The primary use of this is for paths and thus should be used for paths. It is
1084 * not restricted to paths and offers no specific path support.
1088 * @param string $string What to remove the trailing slash from.
1089 * @return string String without the trailing slash.
1091 function untrailingslashit($string) {
1092 return rtrim($string, '/');
1096 * Adds slashes to escape strings.
1098 * Slashes will first be removed if magic_quotes_gpc is set, see {@link
1099 * http://www.php.net/magic_quotes} for more details.
1103 * @param string $gpc The string returned from HTTP request data.
1104 * @return string Returns a string escaped with slashes.
1106 function addslashes_gpc($gpc) {
1109 if (get_magic_quotes_gpc()) {
1110 $gpc = stripslashes($gpc);
1113 return $wpdb->escape($gpc);
1117 * Navigates through an array and removes slashes from the values.
1119 * If an array is passed, the array_map() function causes a callback to pass the
1120 * value back to the function. The slashes from this value will removed.
1124 * @param array|string $value The array or string to be striped.
1125 * @return array|string Stripped array (or string in the callback).
1127 function stripslashes_deep($value) {
1128 $value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value);
1133 * Navigates through an array and encodes the values to be used in a URL.
1135 * Uses a callback to pass the value of the array back to the function as a
1140 * @param array|string $value The array or string to be encoded.
1141 * @return array|string $value The encoded array (or string from the callback).
1143 function urlencode_deep($value) {
1144 $value = is_array($value) ? array_map('urlencode_deep', $value) : urlencode($value);
1149 * Converts email addresses characters to HTML entities to block spam bots.
1153 * @param string $emailaddy Email address.
1154 * @param int $mailto Optional. Range from 0 to 1. Used for encoding.
1155 * @return string Converted email address.
1157 function antispambot($emailaddy, $mailto=0) {
1158 $emailNOSPAMaddy = '';
1159 srand ((float) microtime() * 1000000);
1160 for ($i = 0; $i < strlen($emailaddy); $i = $i + 1) {
1161 $j = floor(rand(0, 1+$mailto));
1163 $emailNOSPAMaddy .= '&#'.ord(substr($emailaddy,$i,1)).';';
1165 $emailNOSPAMaddy .= substr($emailaddy,$i,1);
1167 $emailNOSPAMaddy .= '%'.zeroise(dechex(ord(substr($emailaddy, $i, 1))), 2);
1170 $emailNOSPAMaddy = str_replace('@','@',$emailNOSPAMaddy);
1171 return $emailNOSPAMaddy;
1175 * Callback to convert URI match to HTML A element.
1177 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1178 * make_clickable()}.
1183 * @param array $matches Single Regex Match.
1184 * @return string HTML A element with URI address.
1186 function _make_url_clickable_cb($matches) {
1188 $url = esc_url($url);
1191 return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>";
1195 * Callback to convert URL match to HTML A element.
1197 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1198 * make_clickable()}.
1203 * @param array $matches Single Regex Match.
1204 * @return string HTML A element with URL address.
1206 function _make_web_ftp_clickable_cb($matches) {
1208 $dest = $matches[2];
1209 $dest = 'http://' . $dest;
1210 $dest = esc_url($dest);
1213 // removed trailing [,;:] from URL
1214 if ( in_array(substr($dest, -1), array('.', ',', ';', ':')) === true ) {
1215 $ret = substr($dest, -1);
1216 $dest = substr($dest, 0, strlen($dest)-1);
1218 return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>" . $ret;
1222 * Callback to convert email address match to HTML A element.
1224 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1225 * make_clickable()}.
1230 * @param array $matches Single Regex Match.
1231 * @return string HTML A element with email address.
1233 function _make_email_clickable_cb($matches) {
1234 $email = $matches[2] . '@' . $matches[3];
1235 return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
1239 * Convert plaintext URI to HTML links.
1241 * Converts URI, www and ftp, and email addresses. Finishes by fixing links
1246 * @param string $ret Content to convert URIs.
1247 * @return string Content with converted URIs.
1249 function make_clickable($ret) {
1251 // in testing, using arrays here was found to be faster
1252 $ret = preg_replace_callback('#(?<=[\s>])(\()?([\w]+?://(?:[\w\\x80-\\xff\#$%&~/\-=?@\[\](+]|[.,;:](?![\s<])|(?(1)\)(?![\s<])|\)))+)#is', '_make_url_clickable_cb', $ret);
1253 $ret = preg_replace_callback('#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]+)#is', '_make_web_ftp_clickable_cb', $ret);
1254 $ret = preg_replace_callback('#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret);
1255 // this one is not in an array because we need it to run last, for cleanup of accidental links within links
1256 $ret = preg_replace("#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i", "$1$3</a>", $ret);
1262 * Adds rel nofollow string to all HTML A elements in content.
1266 * @param string $text Content that may contain HTML A elements.
1267 * @return string Converted content.
1269 function wp_rel_nofollow( $text ) {
1271 // This is a pre save filter, so text is already escaped.
1272 $text = stripslashes($text);
1273 $text = preg_replace_callback('|<a (.+?)>|i', 'wp_rel_nofollow_callback', $text);
1274 $text = $wpdb->escape($text);
1279 * Callback to used to add rel=nofollow string to HTML A element.
1281 * Will remove already existing rel="nofollow" and rel='nofollow' from the
1282 * string to prevent from invalidating (X)HTML.
1286 * @param array $matches Single Match
1287 * @return string HTML A Element with rel nofollow.
1289 function wp_rel_nofollow_callback( $matches ) {
1290 $text = $matches[1];
1291 $text = str_replace(array(' rel="nofollow"', " rel='nofollow'"), '', $text);
1292 return "<a $text rel=\"nofollow\">";
1297 * Convert one smiley code to the icon graphic file equivalent.
1299 * Looks up one smiley code in the $wpsmiliestrans global array and returns an
1300 * <img> string for that smiley.
1302 * @global array $wpsmiliestrans
1305 * @param string $smiley Smiley code to convert to image.
1306 * @return string Image string for smiley.
1308 function translate_smiley($smiley) {
1309 global $wpsmiliestrans;
1311 if (count($smiley) == 0) {
1315 $siteurl = get_option( 'siteurl' );
1317 $smiley = trim(reset($smiley));
1318 $img = $wpsmiliestrans[$smiley];
1319 $smiley_masked = esc_attr($smiley);
1321 return " <img src='$siteurl/wp-includes/images/smilies/$img' alt='$smiley_masked' class='wp-smiley' /> ";
1326 * Convert text equivalent of smilies to images.
1328 * Will only convert smilies if the option 'use_smilies' is true and the global
1329 * used in the function isn't empty.
1332 * @uses $wp_smiliessearch
1334 * @param string $text Content to convert smilies from text.
1335 * @return string Converted content with text smilies replaced with images.
1337 function convert_smilies($text) {
1338 global $wp_smiliessearch;
1340 if ( get_option('use_smilies') && !empty($wp_smiliessearch) ) {
1341 // HTML loop taken from texturize function, could possible be consolidated
1342 $textarr = preg_split("/(<.*>)/U", $text, -1, PREG_SPLIT_DELIM_CAPTURE); // capture the tags as well as in between
1343 $stop = count($textarr);// loop stuff
1344 for ($i = 0; $i < $stop; $i++) {
1345 $content = $textarr[$i];
1346 if ((strlen($content) > 0) && ('<' != $content{0})) { // If it's not a tag
1347 $content = preg_replace_callback($wp_smiliessearch, 'translate_smiley', $content);
1349 $output .= $content;
1352 // return default text.
1359 * Verifies that an email is valid.
1361 * Does not grok i18n domains. Not RFC compliant.
1365 * @param string $email Email address to verify.
1366 * @param boolean $check_dns Whether to check the DNS for the domain using checkdnsrr().
1367 * @return string|bool Either false or the valid email address.
1369 function is_email( $email, $check_dns = false ) {
1370 // Test for the minimum length the email can be
1371 if ( strlen( $email ) < 3 ) {
1372 return apply_filters( 'is_email', false, $email, 'email_too_short' );
1375 // Test for an @ character after the first position
1376 if ( strpos( $email, '@', 1 ) === false ) {
1377 return apply_filters( 'is_email', false, $email, 'email_no_at' );
1380 // Split out the local and domain parts
1381 list( $local, $domain ) = explode( '@', $email, 2 );
1384 // Test for invalid characters
1385 if ( !preg_match( '/^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]+$/', $local ) ) {
1386 return apply_filters( 'is_email', false, $email, 'local_invalid_chars' );
1390 // Test for sequences of periods
1391 if ( preg_match( '/\.{2,}/', $domain ) ) {
1392 return apply_filters( 'is_email', false, $email, 'domain_period_sequence' );
1395 // Test for leading and trailing periods and whitespace
1396 if ( trim( $domain, " \t\n\r\0\x0B." ) !== $domain ) {
1397 return apply_filters( 'is_email', false, $email, 'domain_period_limits' );
1400 // Split the domain into subs
1401 $subs = explode( '.', $domain );
1403 // Assume the domain will have at least two subs
1404 if ( 2 > count( $subs ) ) {
1405 return apply_filters( 'is_email', false, $email, 'domain_no_periods' );
1408 // Loop through each sub
1409 foreach ( $subs as $sub ) {
1410 // Test for leading and trailing hyphens and whitespace
1411 if ( trim( $sub, " \t\n\r\0\x0B-" ) !== $sub ) {
1412 return apply_filters( 'is_email', false, $email, 'sub_hyphen_limits' );
1415 // Test for invalid characters
1416 if ( !preg_match('/^[a-z0-9-]+$/i', $sub ) ) {
1417 return apply_filters( 'is_email', false, $email, 'sub_invalid_chars' );
1422 // Check the domain has a valid MX and A resource record
1423 if ( $check_dns && function_exists( 'checkdnsrr' ) && !( checkdnsrr( $domain . '.', 'MX' ) || checkdnsrr( $domain . '.', 'A' ) ) ) {
1424 return apply_filters( 'is_email', false, $email, 'dns_no_rr' );
1427 // Congratulations your email made it!
1428 return apply_filters( 'is_email', $email, $email, null );
1432 * Convert to ASCII from email subjects.
1435 * @usedby wp_mail() handles charsets in email subjects
1437 * @param string $string Subject line
1438 * @return string Converted string to ASCII
1440 function wp_iso_descrambler($string) {
1441 /* this may only work with iso-8859-1, I'm afraid */
1442 if (!preg_match('#\=\?(.+)\?Q\?(.+)\?\=#i', $string, $matches)) {
1445 $subject = str_replace('_', ' ', $matches[2]);
1446 $subject = preg_replace_callback('#\=([0-9a-f]{2})#i', create_function('$match', 'return chr(hexdec(strtolower($match[1])));'), $subject);
1452 * Returns a date in the GMT equivalent.
1454 * Requires and returns a date in the Y-m-d H:i:s format. Simply subtracts the
1455 * value of the 'gmt_offset' option. Return format can be overridden using the
1460 * @uses get_option() to retrieve the the value of 'gmt_offset'.
1461 * @param string $string The date to be converted.
1462 * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
1463 * @return string GMT version of the date provided.
1465 function get_gmt_from_date($string, $format = 'Y-m-d H:i:s') {
1466 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);
1467 $string_time = gmmktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]);
1468 $string_gmt = gmdate($format, $string_time - get_option('gmt_offset') * 3600);
1473 * Converts a GMT date into the correct format for the blog.
1475 * Requires and returns in the Y-m-d H:i:s format. Simply adds the value of
1476 * gmt_offset.Return format can be overridden using the $format parameter
1480 * @param string $string The date to be converted.
1481 * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
1482 * @return string Formatted date relative to the GMT offset.
1484 function get_date_from_gmt($string, $format = 'Y-m-d H:i:s') {
1485 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);
1486 $string_time = gmmktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]);
1487 $string_localtime = gmdate($format, $string_time + get_option('gmt_offset')*3600);
1488 return $string_localtime;
1492 * Computes an offset in seconds from an iso8601 timezone.
1496 * @param string $timezone Either 'Z' for 0 offset or '±hhmm'.
1497 * @return int|float The offset in seconds.
1499 function iso8601_timezone_to_offset($timezone) {
1500 // $timezone is either 'Z' or '[+|-]hhmm'
1501 if ($timezone == 'Z') {
1504 $sign = (substr($timezone, 0, 1) == '+') ? 1 : -1;
1505 $hours = intval(substr($timezone, 1, 2));
1506 $minutes = intval(substr($timezone, 3, 4)) / 60;
1507 $offset = $sign * 3600 * ($hours + $minutes);
1513 * Converts an iso8601 date to MySQL DateTime format used by post_date[_gmt].
1517 * @param string $date_string Date and time in ISO 8601 format {@link http://en.wikipedia.org/wiki/ISO_8601}.
1518 * @param string $timezone Optional. If set to GMT returns the time minus gmt_offset. Default is 'user'.
1519 * @return string The date and time in MySQL DateTime format - Y-m-d H:i:s.
1521 function iso8601_to_datetime($date_string, $timezone = 'user') {
1522 $timezone = strtolower($timezone);
1524 if ($timezone == 'gmt') {
1526 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);
1528 if (!empty($date_bits[7])) { // we have a timezone, so let's compute an offset
1529 $offset = iso8601_timezone_to_offset($date_bits[7]);
1530 } else { // we don't have a timezone, so we assume user local timezone (not server's!)
1531 $offset = 3600 * get_option('gmt_offset');
1534 $timestamp = gmmktime($date_bits[4], $date_bits[5], $date_bits[6], $date_bits[2], $date_bits[3], $date_bits[1]);
1535 $timestamp -= $offset;
1537 return gmdate('Y-m-d H:i:s', $timestamp);
1539 } else if ($timezone == 'user') {
1540 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);
1545 * Adds a element attributes to open links in new windows.
1547 * Comment text in popup windows should be filtered through this. Right now it's
1548 * a moderately dumb function, ideally it would detect whether a target or rel
1549 * attribute was already there and adjust its actions accordingly.
1553 * @param string $text Content to replace links to open in a new window.
1554 * @return string Content that has filtered links.
1556 function popuplinks($text) {
1557 $text = preg_replace('/<a (.+?)>/i', "<a $1 target='_blank' rel='external'>", $text);
1562 * Strips out all characters that are not allowable in an email.
1566 * @param string $email Email address to filter.
1567 * @return string Filtered email address.
1569 function sanitize_email( $email ) {
1570 // Test for the minimum length the email can be
1571 if ( strlen( $email ) < 3 ) {
1572 return apply_filters( 'sanitize_email', '', $email, 'email_too_short' );
1575 // Test for an @ character after the first position
1576 if ( strpos( $email, '@', 1 ) === false ) {
1577 return apply_filters( 'sanitize_email', '', $email, 'email_no_at' );
1580 // Split out the local and domain parts
1581 list( $local, $domain ) = explode( '@', $email, 2 );
1584 // Test for invalid characters
1585 $local = preg_replace( '/[^a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]/', '', $local );
1586 if ( '' === $local ) {
1587 return apply_filters( 'sanitize_email', '', $email, 'local_invalid_chars' );
1591 // Test for sequences of periods
1592 $domain = preg_replace( '/\.{2,}/', '', $domain );
1593 if ( '' === $domain ) {
1594 return apply_filters( 'sanitize_email', '', $email, 'domain_period_sequence' );
1597 // Test for leading and trailing periods and whitespace
1598 $domain = trim( $domain, " \t\n\r\0\x0B." );
1599 if ( '' === $domain ) {
1600 return apply_filters( 'sanitize_email', '', $email, 'domain_period_limits' );
1603 // Split the domain into subs
1604 $subs = explode( '.', $domain );
1606 // Assume the domain will have at least two subs
1607 if ( 2 > count( $subs ) ) {
1608 return apply_filters( 'sanitize_email', '', $email, 'domain_no_periods' );
1611 // Create an array that will contain valid subs
1612 $new_subs = array();
1614 // Loop through each sub
1615 foreach ( $subs as $sub ) {
1616 // Test for leading and trailing hyphens
1617 $sub = trim( $sub, " \t\n\r\0\x0B-" );
1619 // Test for invalid characters
1620 $sub = preg_replace( '/^[^a-z0-9-]+$/i', '', $sub );
1622 // If there's anything left, add it to the valid subs
1623 if ( '' !== $sub ) {
1628 // If there aren't 2 or more valid subs
1629 if ( 2 > count( $new_subs ) ) {
1630 return apply_filters( 'sanitize_email', '', $email, 'domain_no_valid_subs' );
1633 // Join valid subs into the new domain
1634 $domain = join( '.', $new_subs );
1636 // Put the email back together
1637 $email = $local . '@' . $domain;
1639 // Congratulations your email made it!
1640 return apply_filters( 'sanitize_email', $email, $email, null );
1644 * Determines the difference between two timestamps.
1646 * The difference is returned in a human readable format such as "1 hour",
1647 * "5 mins", "2 days".
1651 * @param int $from Unix timestamp from which the difference begins.
1652 * @param int $to Optional. Unix timestamp to end the time difference. Default becomes time() if not set.
1653 * @return string Human readable time difference.
1655 function human_time_diff( $from, $to = '' ) {
1658 $diff = (int) abs($to - $from);
1659 if ($diff <= 3600) {
1660 $mins = round($diff / 60);
1664 $since = sprintf(_n('%s min', '%s mins', $mins), $mins);
1665 } else if (($diff <= 86400) && ($diff > 3600)) {
1666 $hours = round($diff / 3600);
1670 $since = sprintf(_n('%s hour', '%s hours', $hours), $hours);
1671 } elseif ($diff >= 86400) {
1672 $days = round($diff / 86400);
1676 $since = sprintf(_n('%s day', '%s days', $days), $days);
1682 * Generates an excerpt from the content, if needed.
1684 * The excerpt word amount will be 55 words and if the amount is greater than
1685 * that, then the string '[...]' will be appended to the excerpt. If the string
1686 * is less than 55 words, then the content will be returned as is.
1690 * @param string $text The exerpt. If set to empty an excerpt is generated.
1691 * @return string The excerpt.
1693 function wp_trim_excerpt($text) {
1694 $raw_excerpt = $text;
1695 if ( '' == $text ) {
1696 $text = get_the_content('');
1698 $text = strip_shortcodes( $text );
1700 $text = apply_filters('the_content', $text);
1701 $text = str_replace(']]>', ']]>', $text);
1702 $text = strip_tags($text);
1703 $excerpt_length = apply_filters('excerpt_length', 55);
1704 $words = explode(' ', $text, $excerpt_length + 1);
1705 if (count($words) > $excerpt_length) {
1707 array_push($words, '[...]');
1708 $text = implode(' ', $words);
1711 return apply_filters('wp_trim_excerpt', $text, $raw_excerpt);
1715 * Converts named entities into numbered entities.
1719 * @param string $text The text within which entities will be converted.
1720 * @return string Text with converted entities.
1722 function ent2ncr($text) {
1724 '"' => '"',
1726 '⁄' => '/',
1730 ' ' => ' ',
1731 '¡' => '¡',
1732 '¢' => '¢',
1733 '£' => '£',
1734 '¤' => '¤',
1735 '¥' => '¥',
1736 '¦' => '¦',
1737 '&brkbar;' => '¦',
1738 '§' => '§',
1739 '¨' => '¨',
1740 '¨' => '¨',
1741 '©' => '©',
1742 'ª' => 'ª',
1743 '«' => '«',
1744 '¬' => '¬',
1745 '­' => '­',
1746 '®' => '®',
1747 '¯' => '¯',
1748 '&hibar;' => '¯',
1749 '°' => '°',
1750 '±' => '±',
1751 '²' => '²',
1752 '³' => '³',
1753 '´' => '´',
1754 'µ' => 'µ',
1755 '¶' => '¶',
1756 '·' => '·',
1757 '¸' => '¸',
1758 '¹' => '¹',
1759 'º' => 'º',
1760 '»' => '»',
1761 '¼' => '¼',
1762 '½' => '½',
1763 '¾' => '¾',
1764 '¿' => '¿',
1765 'À' => 'À',
1766 'Á' => 'Á',
1767 'Â' => 'Â',
1768 'Ã' => 'Ã',
1769 'Ä' => 'Ä',
1770 'Å' => 'Å',
1771 'Æ' => 'Æ',
1772 'Ç' => 'Ç',
1773 'È' => 'È',
1774 'É' => 'É',
1775 'Ê' => 'Ê',
1776 'Ë' => 'Ë',
1777 'Ì' => 'Ì',
1778 'Í' => 'Í',
1779 'Î' => 'Î',
1780 'Ï' => 'Ï',
1781 'Ð' => 'Ð',
1782 'Ñ' => 'Ñ',
1783 'Ò' => 'Ò',
1784 'Ó' => 'Ó',
1785 'Ô' => 'Ô',
1786 'Õ' => 'Õ',
1787 'Ö' => 'Ö',
1788 '×' => '×',
1789 'Ø' => 'Ø',
1790 'Ù' => 'Ù',
1791 'Ú' => 'Ú',
1792 'Û' => 'Û',
1793 'Ü' => 'Ü',
1794 'Ý' => 'Ý',
1795 'Þ' => 'Þ',
1796 'ß' => 'ß',
1797 'à' => 'à',
1798 'á' => 'á',
1799 'â' => 'â',
1800 'ã' => 'ã',
1801 'ä' => 'ä',
1802 'å' => 'å',
1803 'æ' => 'æ',
1804 'ç' => 'ç',
1805 'è' => 'è',
1806 'é' => 'é',
1807 'ê' => 'ê',
1808 'ë' => 'ë',
1809 'ì' => 'ì',
1810 'í' => 'í',
1811 'î' => 'î',
1812 'ï' => 'ï',
1813 'ð' => 'ð',
1814 'ñ' => 'ñ',
1815 'ò' => 'ò',
1816 'ó' => 'ó',
1817 'ô' => 'ô',
1818 'õ' => 'õ',
1819 'ö' => 'ö',
1820 '÷' => '÷',
1821 'ø' => 'ø',
1822 'ù' => 'ù',
1823 'ú' => 'ú',
1824 'û' => 'û',
1825 'ü' => 'ü',
1826 'ý' => 'ý',
1827 'þ' => 'þ',
1828 'ÿ' => 'ÿ',
1829 'Œ' => 'Œ',
1830 'œ' => 'œ',
1831 'Š' => 'Š',
1832 'š' => 'š',
1833 'Ÿ' => 'Ÿ',
1834 'ƒ' => 'ƒ',
1835 'ˆ' => 'ˆ',
1836 '˜' => '˜',
1837 'Α' => 'Α',
1838 'Β' => 'Β',
1839 'Γ' => 'Γ',
1840 'Δ' => 'Δ',
1841 'Ε' => 'Ε',
1842 'Ζ' => 'Ζ',
1843 'Η' => 'Η',
1844 'Θ' => 'Θ',
1845 'Ι' => 'Ι',
1846 'Κ' => 'Κ',
1847 'Λ' => 'Λ',
1851 'Ο' => 'Ο',
1853 'Ρ' => 'Ρ',
1854 'Σ' => 'Σ',
1855 'Τ' => 'Τ',
1856 'Υ' => 'Υ',
1857 'Φ' => 'Φ',
1858 'Χ' => 'Χ',
1859 'Ψ' => 'Ψ',
1860 'Ω' => 'Ω',
1861 'α' => 'α',
1862 'β' => 'β',
1863 'γ' => 'γ',
1864 'δ' => 'δ',
1865 'ε' => 'ε',
1866 'ζ' => 'ζ',
1867 'η' => 'η',
1868 'θ' => 'θ',
1869 'ι' => 'ι',
1870 'κ' => 'κ',
1871 'λ' => 'λ',
1875 'ο' => 'ο',
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 '⊃' => '⊃',
1958 '⊄' => '⊄',
1959 '⊆' => '⊆',
1960 '⊇' => '⊇',
1961 '⊕' => '⊕',
1962 '⊗' => '⊗',
1963 '⊥' => '⊥',
1964 '⋅' => '⋅',
1965 '⌈' => '⌈',
1966 '⌉' => '⌉',
1967 '⌊' => '⌊',
1968 '⌋' => '⌋',
1969 '⟨' => '〈',
1970 '⟩' => '〉',
1971 '←' => '←',
1972 '↑' => '↑',
1973 '→' => '→',
1974 '↓' => '↓',
1975 '↔' => '↔',
1976 '◊' => '◊',
1977 '♠' => '♠',
1978 '♣' => '♣',
1979 '♥' => '♥',
1980 '♦' => '♦'
1983 return str_replace( array_keys($to_ncr), array_values($to_ncr), $text );
1987 * Formats text for the rich text editor.
1989 * The filter 'richedit_pre' is applied here. If $text is empty the filter will
1990 * be applied to an empty string.
1994 * @param string $text The text to be formatted.
1995 * @return string The formatted text after filter is applied.
1997 function wp_richedit_pre($text) {
1998 // Filtering a blank results in an annoying <br />\n
1999 if ( empty($text) ) return apply_filters('richedit_pre', '');
2001 $output = convert_chars($text);
2002 $output = wpautop($output);
2003 $output = htmlspecialchars($output, ENT_NOQUOTES);
2005 return apply_filters('richedit_pre', $output);
2009 * Formats text for the HTML editor.
2011 * Unless $output is empty it will pass through htmlspecialchars before the
2012 * 'htmledit_pre' filter is applied.
2016 * @param string $output The text to be formatted.
2017 * @return string Formatted text after filter applied.
2019 function wp_htmledit_pre($output) {
2020 if ( !empty($output) )
2021 $output = htmlspecialchars($output, ENT_NOQUOTES); // convert only < > &
2023 return apply_filters('htmledit_pre', $output);
2027 * Checks and cleans a URL.
2029 * A number of characters are removed from the URL. If the URL is for displaying
2030 * (the default behaviour) amperstands are also replaced. The 'esc_url' filter
2031 * is applied to the returned cleaned URL.
2034 * @uses wp_kses_bad_protocol() To only permit protocols in the URL set
2035 * via $protocols or the common ones set in the function.
2037 * @param string $url The URL to be cleaned.
2038 * @param array $protocols Optional. An array of acceptable protocols.
2039 * Defaults to 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet' if not set.
2040 * @param string $context Optional. How the URL will be used. Default is 'display'.
2041 * @return string The cleaned $url after the 'cleaned_url' filter is applied.
2043 function clean_url( $url, $protocols = null, $context = 'display' ) {
2044 $original_url = $url;
2046 if ('' == $url) return $url;
2047 $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);
2048 $strip = array('%0d', '%0a', '%0D', '%0A');
2049 $url = _deep_replace($strip, $url);
2050 $url = str_replace(';//', '://', $url);
2051 /* If the URL doesn't appear to contain a scheme, we
2052 * presume it needs http:// appended (unless a relative
2053 * link starting with / or a php file).
2055 if ( strpos($url, ':') === false &&
2056 substr( $url, 0, 1 ) != '/' && substr( $url, 0, 1 ) != '#' && !preg_match('/^[a-z0-9-]+?\.php/i', $url) )
2057 $url = 'http://' . $url;
2059 // Replace ampersands and single quotes only when displaying.
2060 if ( 'display' == $context ) {
2061 $url = preg_replace('/&([^#])(?![a-z]{2,8};)/', '&$1', $url);
2062 $url = str_replace( "'", ''', $url );
2065 if ( !is_array($protocols) )
2066 $protocols = array('http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet');
2067 if ( wp_kses_bad_protocol( $url, $protocols ) != $url )
2070 return apply_filters('clean_url', $url, $original_url, $context);
2074 * Perform a deep string replace operation to ensure the values in $search are no longer present
2076 * Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values
2077 * e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that
2078 * str_replace would return
2083 * @param string|array $search
2084 * @param string $subject
2085 * @return string The processed string
2087 function _deep_replace($search, $subject){
2091 foreach( (array) $search as $val ) {
2092 while(strpos($subject, $val) !== false) {
2094 $subject = str_replace($val, '', $subject);
2103 * Escapes data for use in a MySQL query
2105 * This is just a handy shortcut for $wpdb->escape(), for completeness' sake
2108 * @param string $sql Unescaped SQL data
2109 * @return string The cleaned $sql
2111 function esc_sql( $sql ) {
2113 return $wpdb->escape( $sql );
2118 * Checks and cleans a URL.
2120 * A number of characters are removed from the URL. If the URL is for displaying
2121 * (the default behaviour) amperstands are also replaced. The 'esc_url' filter
2122 * is applied to the returned cleaned URL.
2126 * @uses wp_kses_bad_protocol() To only permit protocols in the URL set
2127 * via $protocols or the common ones set in the function.
2129 * @param string $url The URL to be cleaned.
2130 * @param array $protocols Optional. An array of acceptable protocols.
2131 * Defaults to 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet' if not set.
2132 * @return string The cleaned $url after the 'cleaned_url' filter is applied.
2134 function esc_url( $url, $protocols = null ) {
2135 return clean_url( $url, $protocols, 'display' );
2139 * Performs esc_url() for database usage.
2146 * @param string $url The URL to be cleaned.
2147 * @param array $protocols An array of acceptable protocols.
2148 * @return string The cleaned URL.
2150 function esc_url_raw( $url, $protocols = null ) {
2151 return clean_url( $url, $protocols, 'db' );
2155 * Performs esc_url() for database or redirect usage.
2162 * @param string $url The URL to be cleaned.
2163 * @param array $protocols An array of acceptable protocols.
2164 * @return string The cleaned URL.
2166 function sanitize_url( $url, $protocols = null ) {
2167 return clean_url( $url, $protocols, 'db' );
2171 * Convert entities, while preserving already-encoded entities.
2173 * @link http://www.php.net/htmlentities Borrowed from the PHP Manual user notes.
2177 * @param string $myHTML The text to be converted.
2178 * @return string Converted text.
2180 function htmlentities2($myHTML) {
2181 $translation_table = get_html_translation_table( HTML_ENTITIES, ENT_QUOTES );
2182 $translation_table[chr(38)] = '&';
2183 return preg_replace( "/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/", "&", strtr($myHTML, $translation_table) );
2187 * Escape single quotes, specialchar double quotes, and fix line endings.
2189 * The filter 'js_escape' is also applied here.
2193 * @param string $text The text to be escaped.
2194 * @return string Escaped text.
2196 function esc_js( $text ) {
2197 $safe_text = wp_check_invalid_utf8( $text );
2198 $safe_text = _wp_specialchars( $safe_text, ENT_COMPAT );
2199 $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) );
2200 $safe_text = preg_replace( "/\r?\n/", "\\n", addslashes( $safe_text ) );
2201 return apply_filters( 'js_escape', $safe_text, $text );
2205 * Escape single quotes, specialchar double quotes, and fix line endings.
2207 * The filter 'js_escape' is also applied by esc_js()
2214 * @param string $text The text to be escaped.
2215 * @return string Escaped text.
2217 function js_escape( $text ) {
2218 return esc_js( $text );
2222 * Escaping for HTML blocks.
2226 * @param string $text
2229 function esc_html( $text ) {
2230 $safe_text = wp_check_invalid_utf8( $text );
2231 $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
2232 return apply_filters( 'esc_html', $safe_text, $text );
2237 * Escaping for HTML blocks
2241 function wp_specialchars( $string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false ) {
2242 if ( func_num_args() > 1 ) { // Maintain backwards compat for people passing additional args
2243 $args = func_get_args();
2244 return call_user_func_array( '_wp_specialchars', $args );
2246 return esc_html( $string );
2251 * Escaping for HTML attributes.
2255 * @param string $text
2258 function esc_attr( $text ) {
2259 $safe_text = wp_check_invalid_utf8( $text );
2260 $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
2261 return apply_filters( 'attribute_escape', $safe_text, $text );
2265 * Escaping for HTML attributes.
2272 * @param string $text
2275 function attribute_escape( $text ) {
2276 return esc_attr( $text );
2280 * Escape a HTML tag name.
2284 * @param string $tag_name
2287 function tag_escape($tag_name) {
2288 $safe_tag = strtolower( preg_replace('/[^a-zA-Z_:]/', '', $tag_name) );
2289 return apply_filters('tag_escape', $safe_tag, $tag_name);
2293 * Escapes text for SQL LIKE special characters % and _.
2297 * @param string $text The text to be escaped.
2298 * @return string text, safe for inclusion in LIKE query.
2300 function like_escape($text) {
2301 return str_replace(array("%", "_"), array("\\%", "\\_"), $text);
2305 * Convert full URL paths to absolute paths.
2307 * Removes the http or https protocols and the domain. Keeps the path '/' at the
2308 * beginning, so it isn't a true relative link, but from the web root base.
2312 * @param string $link Full URL path.
2313 * @return string Absolute path.
2315 function wp_make_link_relative( $link ) {
2316 return preg_replace( '|https?://[^/]+(/.*)|i', '$1', $link );
2320 * Sanitises various option values based on the nature of the option.
2322 * This is basically a switch statement which will pass $value through a number
2323 * of functions depending on the $option.
2327 * @param string $option The name of the option.
2328 * @param string $value The unsanitised value.
2329 * @return string Sanitized value.
2331 function sanitize_option($option, $value) {
2335 $value = sanitize_email($value);
2338 case 'thumbnail_size_w':
2339 case 'thumbnail_size_h':
2340 case 'medium_size_w':
2341 case 'medium_size_h':
2342 case 'large_size_w':
2343 case 'large_size_h':
2344 case 'default_post_edit_rows':
2345 case 'mailserver_port':
2346 case 'comment_max_links':
2347 case 'page_on_front':
2348 case 'rss_excerpt_length':
2349 case 'default_category':
2350 case 'default_email_category':
2351 case 'default_link_category':
2352 case 'close_comments_days_old':
2353 case 'comments_per_page':
2354 case 'thread_comments_depth':
2355 $value = abs((int) $value);
2358 case 'posts_per_page':
2359 case 'posts_per_rss':
2360 $value = (int) $value;
2361 if ( empty($value) ) $value = 1;
2362 if ( $value < -1 ) $value = abs($value);
2365 case 'default_ping_status':
2366 case 'default_comment_status':
2367 // Options that if not there have 0 value but need to be something like "closed"
2368 if ( $value == '0' || $value == '')
2372 case 'blogdescription':
2374 $value = addslashes($value);
2375 $value = wp_filter_post_kses( $value ); // calls stripslashes then addslashes
2376 $value = stripslashes($value);
2377 $value = esc_html( $value );
2380 case 'blog_charset':
2381 $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value); // strips slashes
2386 case 'mailserver_url':
2387 case 'mailserver_login':
2388 case 'mailserver_pass':
2391 $value = strip_tags($value);
2392 $value = addslashes($value);
2393 $value = wp_filter_kses($value); // calls stripslashes then addslashes
2394 $value = stripslashes($value);
2398 $value = preg_replace('/[^0-9:.-]/', '', $value); // strips slashes
2403 $value = stripslashes($value);
2404 $value = esc_url($value);
2407 $value = apply_filters("sanitize_option_{$option}", $value, $option);
2415 * Parses a string into variables to be stored in an array.
2417 * Uses {@link http://www.php.net/parse_str parse_str()} and stripslashes if
2418 * {@link http://www.php.net/magic_quotes magic_quotes_gpc} is on.
2421 * @uses apply_filters() for the 'wp_parse_str' filter.
2423 * @param string $string The string to be parsed.
2424 * @param array $array Variables will be stored in this array.
2426 function wp_parse_str( $string, &$array ) {
2427 parse_str( $string, $array );
2428 if ( get_magic_quotes_gpc() )
2429 $array = stripslashes_deep( $array );
2430 $array = apply_filters( 'wp_parse_str', $array );
2434 * Convert lone less than signs.
2436 * KSES already converts lone greater than signs.
2438 * @uses wp_pre_kses_less_than_callback in the callback function.
2441 * @param string $text Text to be converted.
2442 * @return string Converted text.
2444 function wp_pre_kses_less_than( $text ) {
2445 return preg_replace_callback('%<[^>]*?((?=<)|>|$)%', 'wp_pre_kses_less_than_callback', $text);
2449 * Callback function used by preg_replace.
2451 * @uses esc_html to format the $matches text.
2454 * @param array $matches Populated by matches to preg_replace.
2455 * @return string The text returned after esc_html if needed.
2457 function wp_pre_kses_less_than_callback( $matches ) {
2458 if ( false === strpos($matches[0], '>') )
2459 return esc_html($matches[0]);
2464 * WordPress implementation of PHP sprintf() with filters.
2467 * @link http://www.php.net/sprintf
2469 * @param string $pattern The string which formatted args are inserted.
2470 * @param mixed $args,... Arguments to be formatted into the $pattern string.
2471 * @return string The formatted string.
2473 function wp_sprintf( $pattern ) {
2474 $args = func_get_args( );
2475 $len = strlen($pattern);
2479 while ( $len > $start ) {
2480 // Last character: append and break
2481 if ( strlen($pattern) - 1 == $start ) {
2482 $result .= substr($pattern, -1);
2486 // Literal %: append and continue
2487 if ( substr($pattern, $start, 2) == '%%' ) {
2493 // Get fragment before next %
2494 $end = strpos($pattern, '%', $start + 1);
2495 if ( false === $end )
2497 $fragment = substr($pattern, $start, $end - $start);
2499 // Fragment has a specifier
2500 if ( $pattern{$start} == '%' ) {
2501 // Find numbered arguments or take the next one in order
2502 if ( preg_match('/^%(\d+)\$/', $fragment, $matches) ) {
2503 $arg = isset($args[$matches[1]]) ? $args[$matches[1]] : '';
2504 $fragment = str_replace("%{$matches[1]}$", '%', $fragment);
2507 $arg = isset($args[$arg_index]) ? $args[$arg_index] : '';
2510 // Apply filters OR sprintf
2511 $_fragment = apply_filters( 'wp_sprintf', $fragment, $arg );
2512 if ( $_fragment != $fragment )
2513 $fragment = $_fragment;
2515 $fragment = sprintf($fragment, strval($arg) );
2518 // Append to result and move to next fragment
2519 $result .= $fragment;
2526 * Localize list items before the rest of the content.
2528 * The '%l' must be at the first characters can then contain the rest of the
2529 * content. The list items will have ', ', ', and', and ' and ' added depending
2530 * on the amount of list items in the $args parameter.
2534 * @param string $pattern Content containing '%l' at the beginning.
2535 * @param array $args List items to prepend to the content and replace '%l'.
2536 * @return string Localized list items and rest of the content.
2538 function wp_sprintf_l($pattern, $args) {
2540 if ( substr($pattern, 0, 2) != '%l' )
2543 // Nothing to work with
2547 // Translate and filter the delimiter set (avoid ampersands and entities here)
2548 $l = apply_filters('wp_sprintf_l', array(
2549 /* translators: used between list items, there is a space after the coma */
2550 'between' => __(', '),
2551 /* translators: used between list items, there is a space after the and */
2552 'between_last_two' => __(', and '),
2553 /* translators: used between only two list items, there is a space after the and */
2554 'between_only_two' => __(' and '),
2557 $args = (array) $args;
2558 $result = array_shift($args);
2559 if ( count($args) == 1 )
2560 $result .= $l['between_only_two'] . array_shift($args);
2561 // Loop when more than two args
2564 $arg = array_shift($args);
2567 $result .= $l['between_last_two'] . $arg;
2569 $result .= $l['between'] . $arg;
2571 return $result . substr($pattern, 2);
2575 * Safely extracts not more than the first $count characters from html string.
2577 * UTF-8, tags and entities safe prefix extraction. Entities inside will *NOT*
2578 * be counted as one character. For example & will be counted as 4, < as
2583 * @param integer $str String to get the excerpt from.
2584 * @param integer $count Maximum number of characters to take.
2585 * @return string The excerpt.
2587 function wp_html_excerpt( $str, $count ) {
2588 $str = strip_tags( $str );
2589 $str = mb_substr( $str, 0, $count );
2590 // remove part of an entity at the end
2591 $str = preg_replace( '/&[^;\s]{0,6}$/', '', $str );
2596 * Add a Base url to relative links in passed content.
2598 * By default it supports the 'src' and 'href' attributes. However this can be
2599 * changed via the 3rd param.
2603 * @param string $content String to search for links in.
2604 * @param string $base The base URL to prefix to links.
2605 * @param array $attrs The attributes which should be processed.
2606 * @return string The processed content.
2608 function links_add_base_url( $content, $base, $attrs = array('src', 'href') ) {
2609 $attrs = implode('|', (array)$attrs);
2610 return preg_replace_callback("!($attrs)=(['\"])(.+?)\\2!i",
2611 create_function('$m', 'return _links_add_base($m, "' . $base . '");'),
2616 * Callback to add a base url to relative links in passed content.
2621 * @param string $m The matched link.
2622 * @param string $base The base URL to prefix to links.
2623 * @return string The processed link.
2625 function _links_add_base($m, $base) {
2626 //1 = attribute name 2 = quotation mark 3 = URL
2627 return $m[1] . '=' . $m[2] .
2628 (strpos($m[3], 'http://') === false ?
2629 path_join($base, $m[3]) :
2635 * Adds a Target attribute to all links in passed content.
2637 * This function by default only applies to <a> tags, however this can be
2638 * modified by the 3rd param.
2640 * <b>NOTE:</b> Any current target attributed will be striped and replaced.
2644 * @param string $content String to search for links in.
2645 * @param string $target The Target to add to the links.
2646 * @param array $tags An array of tags to apply to.
2647 * @return string The processed content.
2649 function links_add_target( $content, $target = '_blank', $tags = array('a') ) {
2650 $tags = implode('|', (array)$tags);
2651 return preg_replace_callback("!<($tags)(.+?)>!i",
2652 create_function('$m', 'return _links_add_target($m, "' . $target . '");'),
2656 * Callback to add a target attribute to all links in passed content.
2661 * @param string $m The matched link.
2662 * @param string $target The Target to add to the links.
2663 * @return string The processed link.
2665 function _links_add_target( $m, $target ) {
2667 $link = preg_replace('|(target=[\'"](.*?)[\'"])|i', '', $m[2]);
2668 return '<' . $tag . $link . ' target="' . $target . '">';
2671 // normalize EOL characters and strip duplicate whitespace
2672 function normalize_whitespace( $str ) {
2674 $str = str_replace("\r", "\n", $str);
2675 $str = preg_replace( array( '/\n+/', '/[ \t]+/' ), array( "\n", ' ' ), $str );