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_characters, $static_replacements, $dynamic_characters, $dynamic_replacements,
32 $default_no_texturize_tags, $default_no_texturize_shortcodes;
34 // No need to set up these static variables more than once
35 if ( ! isset( $static_characters ) ) {
36 /* translators: opening curly double quote */
37 $opening_quote = _x( '“', 'opening curly double quote' );
38 /* translators: closing curly double quote */
39 $closing_quote = _x( '”', 'closing curly double quote' );
41 /* translators: apostrophe, for example in 'cause or can't */
42 $apos = _x( '’', 'apostrophe' );
44 /* translators: prime, for example in 9' (nine feet) */
45 $prime = _x( '′', 'prime' );
46 /* translators: double prime, for example in 9" (nine inches) */
47 $double_prime = _x( '″', 'double prime' );
49 /* translators: opening curly single quote */
50 $opening_single_quote = _x( '‘', 'opening curly single quote' );
51 /* translators: closing curly single quote */
52 $closing_single_quote = _x( '’', 'closing curly single quote' );
54 /* translators: en dash */
55 $en_dash = _x( '–', 'en dash' );
56 /* translators: em dash */
57 $em_dash = _x( '—', 'em dash' );
59 $default_no_texturize_tags = array('pre', 'code', 'kbd', 'style', 'script', 'tt');
60 $default_no_texturize_shortcodes = array('code');
62 // if a plugin has provided an autocorrect array, use it
63 if ( isset($wp_cockneyreplace) ) {
64 $cockney = array_keys($wp_cockneyreplace);
65 $cockneyreplace = array_values($wp_cockneyreplace);
66 } elseif ( "'" != $apos ) { // Only bother if we're doing a replacement.
67 $cockney = array( "'tain't", "'twere", "'twas", "'tis", "'twill", "'til", "'bout", "'nuff", "'round", "'cause" );
68 $cockneyreplace = array( $apos . "tain" . $apos . "t", $apos . "twere", $apos . "twas", $apos . "tis", $apos . "twill", $apos . "til", $apos . "bout", $apos . "nuff", $apos . "round", $apos . "cause" );
70 $cockney = $cockneyreplace = array();
73 $static_characters = array_merge( array( '---', ' -- ', '--', ' - ', 'xn–', '...', '``', '\'\'', ' (tm)' ), $cockney );
74 $static_replacements = array_merge( array( $em_dash, ' ' . $em_dash . ' ', $en_dash, ' ' . $en_dash . ' ', 'xn--', '…', $opening_quote, $closing_quote, ' ™' ), $cockneyreplace );
78 $dynamic[ '/\'(\d\d(?:’|\')?s)/' ] = $apos . '$1'; // '99's
79 $dynamic[ '/\'(\d)/' ] = $apos . '$1'; // '99
81 if ( "'" != $opening_single_quote )
82 $dynamic[ '/(\s|\A|[([{<]|")\'/' ] = '$1' . $opening_single_quote; // opening single quote, even after (, {, <, [
83 if ( '"' != $double_prime )
84 $dynamic[ '/(\d)"/' ] = '$1' . $double_prime; // 9" (double prime)
86 $dynamic[ '/(\d)\'/' ] = '$1' . $prime; // 9' (prime)
88 $dynamic[ '/(\S)\'([^\'\s])/' ] = '$1' . $apos . '$2'; // apostrophe in a word
89 if ( '"' != $opening_quote )
90 $dynamic[ '/(\s|\A|[([{<])"(?!\s)/' ] = '$1' . $opening_quote . '$2'; // opening double quote, even after (, {, <, [
91 if ( '"' != $closing_quote )
92 $dynamic[ '/"(\s|\S|\Z)/' ] = $closing_quote . '$1'; // closing double quote
93 if ( "'" != $closing_single_quote )
94 $dynamic[ '/\'([\s.]|\Z)/' ] = $closing_single_quote . '$1'; // closing single quote
96 $dynamic[ '/\b(\d+)x(\d+)\b/' ] = '$1×$2'; // 9x9 (times)
98 $dynamic_characters = array_keys( $dynamic );
99 $dynamic_replacements = array_values( $dynamic );
102 // Transform into regexp sub-expression used in _wptexturize_pushpop_element
103 // Must do this everytime in case plugins use these filters in a context sensitive manner
104 $no_texturize_tags = '(' . implode('|', apply_filters('no_texturize_tags', $default_no_texturize_tags) ) . ')';
105 $no_texturize_shortcodes = '(' . implode('|', apply_filters('no_texturize_shortcodes', $default_no_texturize_shortcodes) ) . ')';
107 $no_texturize_tags_stack = array();
108 $no_texturize_shortcodes_stack = array();
110 $textarr = preg_split('/(<.*>|\[.*\])/Us', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
112 foreach ( $textarr as &$curl ) {
113 if ( empty( $curl ) )
116 // Only call _wptexturize_pushpop_element if first char is correct tag opening
118 if ( '<' === $first ) {
119 _wptexturize_pushpop_element($curl, $no_texturize_tags_stack, $no_texturize_tags, '<', '>');
120 } elseif ( '[' === $first ) {
121 _wptexturize_pushpop_element($curl, $no_texturize_shortcodes_stack, $no_texturize_shortcodes, '[', ']');
122 } elseif ( empty($no_texturize_shortcodes_stack) && empty($no_texturize_tags_stack) ) {
123 // This is not a tag, nor is the texturization disabled static strings
124 $curl = str_replace($static_characters, $static_replacements, $curl);
125 // regular expressions
126 $curl = preg_replace($dynamic_characters, $dynamic_replacements, $curl);
128 $curl = preg_replace('/&([^#])(?![a-zA-Z1-4]{1,8};)/', '&$1', $curl);
130 return implode( '', $textarr );
134 * Search for disabled element tags. Push element to stack on tag open and pop
135 * on tag close. Assumes first character of $text is tag opening.
140 * @param string $text Text to check. First character is assumed to be $opening
141 * @param array $stack Array used as stack of opened tag elements
142 * @param string $disabled_elements Tags to match against formatted as regexp sub-expression
143 * @param string $opening Tag opening character, assumed to be 1 character long
144 * @param string $opening Tag closing character
147 function _wptexturize_pushpop_element($text, &$stack, $disabled_elements, $opening = '<', $closing = '>') {
148 // Check if it is a closing tag -- otherwise assume opening tag
149 if (strncmp($opening . '/', $text, 2)) {
150 // Opening? Check $text+1 against disabled elements
151 if (preg_match('/^' . $disabled_elements . '\b/', substr($text, 1), $matches)) {
153 * This disables texturize until we find a closing tag of our type
154 * (e.g. <pre>) even if there was invalid nesting before that
156 * Example: in the case <pre>sadsadasd</code>"baba"</pre>
157 * "baba" won't be texturize
160 array_push($stack, $matches[1]);
163 // Closing? Check $text+2 against disabled elements
164 $c = preg_quote($closing, '/');
165 if (preg_match('/^' . $disabled_elements . $c . '/', substr($text, 2), $matches)) {
166 $last = array_pop($stack);
168 // Make sure it matches the opening tag
169 if ($last != $matches[1])
170 array_push($stack, $last);
176 * Replaces double line-breaks with paragraph elements.
178 * A group of regex replaces used to identify text formatted with newlines and
179 * replace double line-breaks with HTML paragraph tags. The remaining
180 * line-breaks after conversion become <<br />> tags, unless $br is set to '0'
185 * @param string $pee The text which has to be formatted.
186 * @param bool $br Optional. If set, this will convert all remaining line-breaks after paragraphing. Default true.
187 * @return string Text which has been converted into correct paragraph tags.
189 function wpautop($pee, $br = true) {
192 if ( trim($pee) === '' )
195 $pee = $pee . "\n"; // just to make things a little easier, pad the end
197 if ( strpos($pee, '<pre') !== false ) {
198 $pee_parts = explode( '</pre>', $pee );
199 $last_pee = array_pop($pee_parts);
203 foreach ( $pee_parts as $pee_part ) {
204 $start = strpos($pee_part, '<pre');
207 if ( $start === false ) {
212 $name = "<pre wp-pre-tag-$i></pre>";
213 $pre_tags[$name] = substr( $pee_part, $start ) . '</pre>';
215 $pee .= substr( $pee_part, 0, $start ) . $name;
222 $pee = preg_replace('|<br />\s*<br />|', "\n\n", $pee);
223 // Space things out a little
224 $allblocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|option|form|map|area|blockquote|address|math|style|p|h[1-6]|hr|fieldset|legend|section|article|aside|hgroup|header|footer|nav|figure|figcaption|details|menu|summary)';
225 $pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee);
226 $pee = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $pee);
227 $pee = str_replace(array("\r\n", "\r"), "\n", $pee); // cross-platform newlines
228 if ( strpos($pee, '<object') !== false ) {
229 $pee = preg_replace('|\s*<param([^>]*)>\s*|', "<param$1>", $pee); // no pee inside object/embed
230 $pee = preg_replace('|\s*</embed>\s*|', '</embed>', $pee);
232 $pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates
233 // make paragraphs, including one at the end
234 $pees = preg_split('/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY);
236 foreach ( $pees as $tinkle )
237 $pee .= '<p>' . trim($tinkle, "\n") . "</p>\n";
238 $pee = preg_replace('|<p>\s*</p>|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace
239 $pee = preg_replace('!<p>([^<]+)</(div|address|form)>!', "<p>$1</p></$2>", $pee);
240 $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee); // don't pee all over a tag
241 $pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee); // problem with nested lists
242 $pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee);
243 $pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee);
244 $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)!', "$1", $pee);
245 $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
247 $pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', '_autop_newline_preservation_helper', $pee);
248 $pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee); // optionally make line breaks
249 $pee = str_replace('<WPPreserveNewline />', "\n", $pee);
251 $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', "$1", $pee);
252 $pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee);
253 $pee = preg_replace( "|\n</p>$|", '</p>', $pee );
255 if ( !empty($pre_tags) )
256 $pee = str_replace(array_keys($pre_tags), array_values($pre_tags), $pee);
262 * Newline preservation help function for wpautop
266 * @param array $matches preg_replace_callback matches array
269 function _autop_newline_preservation_helper( $matches ) {
270 return str_replace("\n", "<WPPreserveNewline />", $matches[0]);
274 * Don't auto-p wrap shortcodes that stand alone
276 * Ensures that shortcodes are not wrapped in <<p>>...<</p>>.
280 * @param string $pee The content.
281 * @return string The filtered content.
283 function shortcode_unautop( $pee ) {
284 global $shortcode_tags;
286 if ( empty( $shortcode_tags ) || !is_array( $shortcode_tags ) ) {
290 $tagregexp = join( '|', array_map( 'preg_quote', array_keys( $shortcode_tags ) ) );
294 . '<p>' // Opening paragraph
295 . '\\s*+' // Optional leading whitespace
296 . '(' // 1: The shortcode
297 . '\\[' // Opening bracket
298 . "($tagregexp)" // 2: Shortcode name
299 . '\\b' // Word boundary
300 // Unroll the loop: Inside the opening shortcode tag
301 . '[^\\]\\/]*' // Not a closing bracket or forward slash
303 . '\\/(?!\\])' // A forward slash not followed by a closing bracket
304 . '[^\\]\\/]*' // Not a closing bracket or forward slash
307 . '\\/\\]' // Self closing tag and closing bracket
309 . '\\]' // Closing bracket
310 . '(?:' // Unroll the loop: Optionally, anything between the opening and closing shortcode tags
311 . '[^\\[]*+' // Not an opening bracket
313 . '\\[(?!\\/\\2\\])' // An opening bracket not followed by the closing shortcode tag
314 . '[^\\[]*+' // Not an opening bracket
316 . '\\[\\/\\2\\]' // Closing shortcode tag
320 . '\\s*+' // optional trailing whitespace
321 . '<\\/p>' // closing paragraph
324 return preg_replace( $pattern, '$1', $pee );
328 * Checks to see if a string is utf8 encoded.
330 * NOTE: This function checks for 5-Byte sequences, UTF8
331 * has Bytes Sequences with a maximum length of 4.
333 * @author bmorel at ssi dot fr (modified)
336 * @param string $str The string to be checked
337 * @return bool True if $str fits a UTF-8 model, false otherwise.
339 function seems_utf8($str) {
340 $length = strlen($str);
341 for ($i=0; $i < $length; $i++) {
343 if ($c < 0x80) $n = 0; # 0bbbbbbb
344 elseif (($c & 0xE0) == 0xC0) $n=1; # 110bbbbb
345 elseif (($c & 0xF0) == 0xE0) $n=2; # 1110bbbb
346 elseif (($c & 0xF8) == 0xF0) $n=3; # 11110bbb
347 elseif (($c & 0xFC) == 0xF8) $n=4; # 111110bb
348 elseif (($c & 0xFE) == 0xFC) $n=5; # 1111110b
349 else return false; # Does not match any model
350 for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
351 if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))
359 * Converts a number of special characters into their HTML entities.
361 * Specifically deals with: &, <, >, ", and '.
363 * $quote_style can be set to ENT_COMPAT to encode " to
364 * ", or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded.
368 * @param string $string The text which is to be encoded.
369 * @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.
370 * @param string $charset Optional. The character encoding of the string. Default is false.
371 * @param boolean $double_encode Optional. Whether to encode existing html entities. Default is false.
372 * @return string The encoded text with HTML entities.
374 function _wp_specialchars( $string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false ) {
375 $string = (string) $string;
377 if ( 0 === strlen( $string ) )
380 // Don't bother if there are no specialchars - saves some processing
381 if ( ! preg_match( '/[&<>"\']/', $string ) )
384 // Account for the previous behaviour of the function when the $quote_style is not an accepted value
385 if ( empty( $quote_style ) )
386 $quote_style = ENT_NOQUOTES;
387 elseif ( ! in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) )
388 $quote_style = ENT_QUOTES;
390 // Store the site charset as a static to avoid multiple calls to wp_load_alloptions()
393 if ( ! isset( $_charset ) ) {
394 $alloptions = wp_load_alloptions();
395 $_charset = isset( $alloptions['blog_charset'] ) ? $alloptions['blog_charset'] : '';
397 $charset = $_charset;
400 if ( in_array( $charset, array( 'utf8', 'utf-8', 'UTF8' ) ) )
403 $_quote_style = $quote_style;
405 if ( $quote_style === 'double' ) {
406 $quote_style = ENT_COMPAT;
407 $_quote_style = ENT_COMPAT;
408 } elseif ( $quote_style === 'single' ) {
409 $quote_style = ENT_NOQUOTES;
412 // Handle double encoding ourselves
413 if ( $double_encode ) {
414 $string = @htmlspecialchars( $string, $quote_style, $charset );
416 // Decode & into &
417 $string = wp_specialchars_decode( $string, $_quote_style );
419 // Guarantee every &entity; is valid or re-encode the &
420 $string = wp_kses_normalize_entities( $string );
422 // Now re-encode everything except &entity;
423 $string = preg_split( '/(&#?x?[0-9a-z]+;)/i', $string, -1, PREG_SPLIT_DELIM_CAPTURE );
425 for ( $i = 0; $i < count( $string ); $i += 2 )
426 $string[$i] = @htmlspecialchars( $string[$i], $quote_style, $charset );
428 $string = implode( '', $string );
431 // Backwards compatibility
432 if ( 'single' === $_quote_style )
433 $string = str_replace( "'", ''', $string );
439 * Converts a number of HTML entities into their special characters.
441 * Specifically deals with: &, <, >, ", and '.
443 * $quote_style can be set to ENT_COMPAT to decode " entities,
444 * or ENT_QUOTES to do both " and '. Default is ENT_NOQUOTES where no quotes are decoded.
448 * @param string $string The text which is to be decoded.
449 * @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.
450 * @return string The decoded text without HTML entities.
452 function wp_specialchars_decode( $string, $quote_style = ENT_NOQUOTES ) {
453 $string = (string) $string;
455 if ( 0 === strlen( $string ) ) {
459 // Don't bother if there are no entities - saves a lot of processing
460 if ( strpos( $string, '&' ) === false ) {
464 // Match the previous behaviour of _wp_specialchars() when the $quote_style is not an accepted value
465 if ( empty( $quote_style ) ) {
466 $quote_style = ENT_NOQUOTES;
467 } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
468 $quote_style = ENT_QUOTES;
471 // More complete than get_html_translation_table( HTML_SPECIALCHARS )
472 $single = array( ''' => '\'', ''' => '\'' );
473 $single_preg = array( '/�*39;/' => ''', '/�*27;/i' => ''' );
474 $double = array( '"' => '"', '"' => '"', '"' => '"' );
475 $double_preg = array( '/�*34;/' => '"', '/�*22;/i' => '"' );
476 $others = array( '<' => '<', '<' => '<', '>' => '>', '>' => '>', '&' => '&', '&' => '&', '&' => '&' );
477 $others_preg = array( '/�*60;/' => '<', '/�*62;/' => '>', '/�*38;/' => '&', '/�*26;/i' => '&' );
479 if ( $quote_style === ENT_QUOTES ) {
480 $translation = array_merge( $single, $double, $others );
481 $translation_preg = array_merge( $single_preg, $double_preg, $others_preg );
482 } elseif ( $quote_style === ENT_COMPAT || $quote_style === 'double' ) {
483 $translation = array_merge( $double, $others );
484 $translation_preg = array_merge( $double_preg, $others_preg );
485 } elseif ( $quote_style === 'single' ) {
486 $translation = array_merge( $single, $others );
487 $translation_preg = array_merge( $single_preg, $others_preg );
488 } elseif ( $quote_style === ENT_NOQUOTES ) {
489 $translation = $others;
490 $translation_preg = $others_preg;
493 // Remove zero padding on numeric entities
494 $string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string );
496 // Replace characters according to translation table
497 return strtr( $string, $translation );
501 * Checks for invalid UTF8 in a string.
505 * @param string $string The text which is to be checked.
506 * @param boolean $strip Optional. Whether to attempt to strip out invalid UTF8. Default is false.
507 * @return string The checked text.
509 function wp_check_invalid_utf8( $string, $strip = false ) {
510 $string = (string) $string;
512 if ( 0 === strlen( $string ) ) {
516 // Store the site charset as a static to avoid multiple calls to get_option()
518 if ( !isset( $is_utf8 ) ) {
519 $is_utf8 = in_array( get_option( 'blog_charset' ), array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ) );
525 // Check for support for utf8 in the installed PCRE library once and store the result in a static
527 if ( !isset( $utf8_pcre ) ) {
528 $utf8_pcre = @preg_match( '/^./u', 'a' );
530 // We can't demand utf8 in the PCRE installation, so just return the string in those cases
535 // preg_match fails when it encounters invalid UTF8 in $string
536 if ( 1 === @preg_match( '/^./us', $string ) ) {
540 // Attempt to strip the bad chars if requested (not recommended)
541 if ( $strip && function_exists( 'iconv' ) ) {
542 return iconv( 'utf-8', 'utf-8', $string );
549 * Encode the Unicode values to be used in the URI.
553 * @param string $utf8_string
554 * @param int $length Max length of the string
555 * @return string String with Unicode encoded for URI.
557 function utf8_uri_encode( $utf8_string, $length = 0 ) {
563 $string_length = strlen( $utf8_string );
564 for ($i = 0; $i < $string_length; $i++ ) {
566 $value = ord( $utf8_string[ $i ] );
568 if ( $value < 128 ) {
569 if ( $length && ( $unicode_length >= $length ) )
571 $unicode .= chr($value);
574 if ( count( $values ) == 0 ) $num_octets = ( $value < 224 ) ? 2 : 3;
578 if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length )
580 if ( count( $values ) == $num_octets ) {
581 if ($num_octets == 3) {
582 $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]) . '%' . dechex($values[2]);
583 $unicode_length += 9;
585 $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]);
586 $unicode_length += 6;
599 * Converts all accent characters to ASCII characters.
601 * If there are no accent characters, then the string given is just returned.
605 * @param string $string Text that might have accent characters
606 * @return string Filtered string with replaced "nice" characters.
608 function remove_accents($string) {
609 if ( !preg_match('/[\x80-\xff]/', $string) )
612 if (seems_utf8($string)) {
614 // Decompositions for Latin-1 Supplement
615 chr(194).chr(170) => 'a', chr(194).chr(186) => 'o',
616 chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
617 chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
618 chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
619 chr(195).chr(134) => 'AE',chr(195).chr(135) => 'C',
620 chr(195).chr(136) => 'E', chr(195).chr(137) => 'E',
621 chr(195).chr(138) => 'E', chr(195).chr(139) => 'E',
622 chr(195).chr(140) => 'I', chr(195).chr(141) => 'I',
623 chr(195).chr(142) => 'I', chr(195).chr(143) => 'I',
624 chr(195).chr(144) => 'D', chr(195).chr(145) => 'N',
625 chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
626 chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
627 chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
628 chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
629 chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
630 chr(195).chr(158) => 'TH',chr(195).chr(159) => 's',
631 chr(195).chr(160) => 'a', chr(195).chr(161) => 'a',
632 chr(195).chr(162) => 'a', chr(195).chr(163) => 'a',
633 chr(195).chr(164) => 'a', chr(195).chr(165) => 'a',
634 chr(195).chr(166) => 'ae',chr(195).chr(167) => 'c',
635 chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
636 chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
637 chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
638 chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
639 chr(195).chr(176) => 'd', chr(195).chr(177) => 'n',
640 chr(195).chr(178) => 'o', chr(195).chr(179) => 'o',
641 chr(195).chr(180) => 'o', chr(195).chr(181) => 'o',
642 chr(195).chr(182) => 'o', chr(195).chr(184) => 'o',
643 chr(195).chr(185) => 'u', chr(195).chr(186) => 'u',
644 chr(195).chr(187) => 'u', chr(195).chr(188) => 'u',
645 chr(195).chr(189) => 'y', chr(195).chr(190) => 'th',
646 chr(195).chr(191) => 'y', chr(195).chr(152) => 'O',
647 // Decompositions for Latin Extended-A
648 chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
649 chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
650 chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
651 chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
652 chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
653 chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
654 chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
655 chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
656 chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
657 chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
658 chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
659 chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
660 chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
661 chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
662 chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
663 chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
664 chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
665 chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
666 chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
667 chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
668 chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
669 chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
670 chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
671 chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
672 chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
673 chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
674 chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
675 chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
676 chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
677 chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
678 chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
679 chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
680 chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
681 chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
682 chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
683 chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
684 chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
685 chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
686 chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
687 chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
688 chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
689 chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
690 chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
691 chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
692 chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
693 chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
694 chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
695 chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
696 chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
697 chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
698 chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
699 chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
700 chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
701 chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
702 chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
703 chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
704 chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
705 chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
706 chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
707 chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
708 chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
709 chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
710 chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
711 chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
712 // Decompositions for Latin Extended-B
713 chr(200).chr(152) => 'S', chr(200).chr(153) => 's',
714 chr(200).chr(154) => 'T', chr(200).chr(155) => 't',
716 chr(226).chr(130).chr(172) => 'E',
718 chr(194).chr(163) => '',
719 // Vowels with diacritic (Vietnamese)
721 chr(198).chr(160) => 'O', chr(198).chr(161) => 'o',
722 chr(198).chr(175) => 'U', chr(198).chr(176) => 'u',
724 chr(225).chr(186).chr(166) => 'A', chr(225).chr(186).chr(167) => 'a',
725 chr(225).chr(186).chr(176) => 'A', chr(225).chr(186).chr(177) => 'a',
726 chr(225).chr(187).chr(128) => 'E', chr(225).chr(187).chr(129) => 'e',
727 chr(225).chr(187).chr(146) => 'O', chr(225).chr(187).chr(147) => 'o',
728 chr(225).chr(187).chr(156) => 'O', chr(225).chr(187).chr(157) => 'o',
729 chr(225).chr(187).chr(170) => 'U', chr(225).chr(187).chr(171) => 'u',
730 chr(225).chr(187).chr(178) => 'Y', chr(225).chr(187).chr(179) => 'y',
732 chr(225).chr(186).chr(162) => 'A', chr(225).chr(186).chr(163) => 'a',
733 chr(225).chr(186).chr(168) => 'A', chr(225).chr(186).chr(169) => 'a',
734 chr(225).chr(186).chr(178) => 'A', chr(225).chr(186).chr(179) => 'a',
735 chr(225).chr(186).chr(186) => 'E', chr(225).chr(186).chr(187) => 'e',
736 chr(225).chr(187).chr(130) => 'E', chr(225).chr(187).chr(131) => 'e',
737 chr(225).chr(187).chr(136) => 'I', chr(225).chr(187).chr(137) => 'i',
738 chr(225).chr(187).chr(142) => 'O', chr(225).chr(187).chr(143) => 'o',
739 chr(225).chr(187).chr(148) => 'O', chr(225).chr(187).chr(149) => 'o',
740 chr(225).chr(187).chr(158) => 'O', chr(225).chr(187).chr(159) => 'o',
741 chr(225).chr(187).chr(166) => 'U', chr(225).chr(187).chr(167) => 'u',
742 chr(225).chr(187).chr(172) => 'U', chr(225).chr(187).chr(173) => 'u',
743 chr(225).chr(187).chr(182) => 'Y', chr(225).chr(187).chr(183) => 'y',
745 chr(225).chr(186).chr(170) => 'A', chr(225).chr(186).chr(171) => 'a',
746 chr(225).chr(186).chr(180) => 'A', chr(225).chr(186).chr(181) => 'a',
747 chr(225).chr(186).chr(188) => 'E', chr(225).chr(186).chr(189) => 'e',
748 chr(225).chr(187).chr(132) => 'E', chr(225).chr(187).chr(133) => 'e',
749 chr(225).chr(187).chr(150) => 'O', chr(225).chr(187).chr(151) => 'o',
750 chr(225).chr(187).chr(160) => 'O', chr(225).chr(187).chr(161) => 'o',
751 chr(225).chr(187).chr(174) => 'U', chr(225).chr(187).chr(175) => 'u',
752 chr(225).chr(187).chr(184) => 'Y', chr(225).chr(187).chr(185) => 'y',
754 chr(225).chr(186).chr(164) => 'A', chr(225).chr(186).chr(165) => 'a',
755 chr(225).chr(186).chr(174) => 'A', chr(225).chr(186).chr(175) => 'a',
756 chr(225).chr(186).chr(190) => 'E', chr(225).chr(186).chr(191) => 'e',
757 chr(225).chr(187).chr(144) => 'O', chr(225).chr(187).chr(145) => 'o',
758 chr(225).chr(187).chr(154) => 'O', chr(225).chr(187).chr(155) => 'o',
759 chr(225).chr(187).chr(168) => 'U', chr(225).chr(187).chr(169) => 'u',
761 chr(225).chr(186).chr(160) => 'A', chr(225).chr(186).chr(161) => 'a',
762 chr(225).chr(186).chr(172) => 'A', chr(225).chr(186).chr(173) => 'a',
763 chr(225).chr(186).chr(182) => 'A', chr(225).chr(186).chr(183) => 'a',
764 chr(225).chr(186).chr(184) => 'E', chr(225).chr(186).chr(185) => 'e',
765 chr(225).chr(187).chr(134) => 'E', chr(225).chr(187).chr(135) => 'e',
766 chr(225).chr(187).chr(138) => 'I', chr(225).chr(187).chr(139) => 'i',
767 chr(225).chr(187).chr(140) => 'O', chr(225).chr(187).chr(141) => 'o',
768 chr(225).chr(187).chr(152) => 'O', chr(225).chr(187).chr(153) => 'o',
769 chr(225).chr(187).chr(162) => 'O', chr(225).chr(187).chr(163) => 'o',
770 chr(225).chr(187).chr(164) => 'U', chr(225).chr(187).chr(165) => 'u',
771 chr(225).chr(187).chr(176) => 'U', chr(225).chr(187).chr(177) => 'u',
772 chr(225).chr(187).chr(180) => 'Y', chr(225).chr(187).chr(181) => 'y',
775 $string = strtr($string, $chars);
777 // Assume ISO-8859-1 if not UTF-8
778 $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
779 .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
780 .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
781 .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
782 .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
783 .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
784 .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
785 .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
786 .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
787 .chr(252).chr(253).chr(255);
789 $chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";
791 $string = strtr($string, $chars['in'], $chars['out']);
792 $double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
793 $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
794 $string = str_replace($double_chars['in'], $double_chars['out'], $string);
801 * Sanitizes a filename replacing whitespace with dashes
803 * Removes special characters that are illegal in filenames on certain
804 * operating systems and special characters requiring special escaping
805 * to manipulate at the command line. Replaces spaces and consecutive
806 * dashes with a single dash. Trim period, dash and underscore from beginning
807 * and end of filename.
811 * @param string $filename The filename to be sanitized
812 * @return string The sanitized filename
814 function sanitize_file_name( $filename ) {
815 $filename_raw = $filename;
816 $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", chr(0));
817 $special_chars = apply_filters('sanitize_file_name_chars', $special_chars, $filename_raw);
818 $filename = str_replace($special_chars, '', $filename);
819 $filename = preg_replace('/[\s-]+/', '-', $filename);
820 $filename = trim($filename, '.-_');
822 // Split the filename into a base and extension[s]
823 $parts = explode('.', $filename);
825 // Return if only one extension
826 if ( count($parts) <= 2 )
827 return apply_filters('sanitize_file_name', $filename, $filename_raw);
829 // Process multiple extensions
830 $filename = array_shift($parts);
831 $extension = array_pop($parts);
832 $mimes = get_allowed_mime_types();
834 // Loop over any intermediate extensions. Munge them with a trailing underscore if they are a 2 - 5 character
835 // long alpha string not in the extension whitelist.
836 foreach ( (array) $parts as $part) {
837 $filename .= '.' . $part;
839 if ( preg_match("/^[a-zA-Z]{2,5}\d?$/", $part) ) {
841 foreach ( $mimes as $ext_preg => $mime_match ) {
842 $ext_preg = '!^(' . $ext_preg . ')$!i';
843 if ( preg_match( $ext_preg, $part ) ) {
852 $filename .= '.' . $extension;
854 return apply_filters('sanitize_file_name', $filename, $filename_raw);
858 * Sanitize username stripping out unsafe characters.
860 * Removes tags, octets, entities, and if strict is enabled, will only keep
861 * alphanumeric, _, space, ., -, @. After sanitizing, it passes the username,
862 * raw username (the username in the parameter), and the value of $strict as
863 * parameters for the 'sanitize_user' filter.
866 * @uses apply_filters() Calls 'sanitize_user' hook on username, raw username,
867 * and $strict parameter.
869 * @param string $username The username to be sanitized.
870 * @param bool $strict If set limits $username to specific characters. Default false.
871 * @return string The sanitized username, after passing through filters.
873 function sanitize_user( $username, $strict = false ) {
874 $raw_username = $username;
875 $username = wp_strip_all_tags( $username );
876 $username = remove_accents( $username );
878 $username = preg_replace( '|%([a-fA-F0-9][a-fA-F0-9])|', '', $username );
879 $username = preg_replace( '/&.+?;/', '', $username ); // Kill entities
881 // If strict, reduce to ASCII for max portability.
883 $username = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $username );
885 $username = trim( $username );
886 // Consolidate contiguous whitespace
887 $username = preg_replace( '|\s+|', ' ', $username );
889 return apply_filters( 'sanitize_user', $username, $raw_username, $strict );
893 * Sanitize a string key.
895 * Keys are used as internal identifiers. Lowercase alphanumeric characters, dashes and underscores are allowed.
899 * @param string $key String key
900 * @return string Sanitized key
902 function sanitize_key( $key ) {
904 $key = strtolower( $key );
905 $key = preg_replace( '/[^a-z0-9_\-]/', '', $key );
906 return apply_filters( 'sanitize_key', $key, $raw_key );
910 * Sanitizes title or use fallback title.
912 * Specifically, HTML and PHP tags are stripped. Further actions can be added
913 * via the plugin API. If $title is empty and $fallback_title is set, the latter
918 * @param string $title The string to be sanitized.
919 * @param string $fallback_title Optional. A title to use if $title is empty.
920 * @param string $context Optional. The operation for which the string is sanitized
921 * @return string The sanitized string.
923 function sanitize_title($title, $fallback_title = '', $context = 'save') {
926 if ( 'save' == $context )
927 $title = remove_accents($title);
929 $title = apply_filters('sanitize_title', $title, $raw_title, $context);
931 if ( '' === $title || false === $title )
932 $title = $fallback_title;
937 function sanitize_title_for_query($title) {
938 return sanitize_title($title, '', 'query');
942 * Sanitizes title, replacing whitespace and a few other characters with dashes.
944 * Limits the output to alphanumeric characters, underscore (_) and dash (-).
945 * Whitespace becomes a dash.
949 * @param string $title The title to be sanitized.
950 * @param string $raw_title Optional. Not used.
951 * @param string $context Optional. The operation for which the string is sanitized.
952 * @return string The sanitized title.
954 function sanitize_title_with_dashes($title, $raw_title = '', $context = 'display') {
955 $title = strip_tags($title);
956 // Preserve escaped octets.
957 $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
958 // Remove percent signs that are not part of an octet.
959 $title = str_replace('%', '', $title);
961 $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
963 if (seems_utf8($title)) {
964 if (function_exists('mb_strtolower')) {
965 $title = mb_strtolower($title, 'UTF-8');
967 $title = utf8_uri_encode($title, 200);
970 $title = strtolower($title);
971 $title = preg_replace('/&.+?;/', '', $title); // kill entities
972 $title = str_replace('.', '-', $title);
974 if ( 'save' == $context ) {
975 // Convert nbsp, ndash and mdash to hyphens
976 $title = str_replace( array( '%c2%a0', '%e2%80%93', '%e2%80%94' ), '-', $title );
978 // Strip these characters entirely
979 $title = str_replace( array(
983 '%c2%ab', '%c2%bb', '%e2%80%b9', '%e2%80%ba',
985 '%e2%80%98', '%e2%80%99', '%e2%80%9c', '%e2%80%9d',
986 '%e2%80%9a', '%e2%80%9b', '%e2%80%9e', '%e2%80%9f',
987 // copy, reg, deg, hellip and trade
988 '%c2%a9', '%c2%ae', '%c2%b0', '%e2%80%a6', '%e2%84%a2',
991 // Convert times to x
992 $title = str_replace( '%c3%97', 'x', $title );
995 $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
996 $title = preg_replace('/\s+/', '-', $title);
997 $title = preg_replace('|-+|', '-', $title);
998 $title = trim($title, '-');
1004 * Ensures a string is a valid SQL order by clause.
1006 * Accepts one or more columns, with or without ASC/DESC, and also accepts
1011 * @param string $orderby Order by string to be checked.
1012 * @return string|false Returns the order by clause if it is a match, false otherwise.
1014 function sanitize_sql_orderby( $orderby ){
1015 preg_match('/^\s*([a-z0-9_]+(\s+(ASC|DESC))?(\s*,\s*|\s*$))+|^\s*RAND\(\s*\)\s*$/i', $orderby, $obmatches);
1022 * Santizes a html classname to ensure it only contains valid characters
1024 * Strips the string down to A-Z,a-z,0-9,_,-. If this results in an empty
1025 * string then it will return the alternative value supplied.
1027 * @todo Expand to support the full range of CDATA that a class attribute can contain.
1031 * @param string $class The classname to be sanitized
1032 * @param string $fallback Optional. The value to return if the sanitization end's up as an empty string.
1033 * Defaults to an empty string.
1034 * @return string The sanitized value
1036 function sanitize_html_class( $class, $fallback = '' ) {
1037 //Strip out any % encoded octets
1038 $sanitized = preg_replace( '|%[a-fA-F0-9][a-fA-F0-9]|', '', $class );
1040 //Limit to A-Z,a-z,0-9,_,-
1041 $sanitized = preg_replace( '/[^A-Za-z0-9_-]/', '', $sanitized );
1043 if ( '' == $sanitized )
1044 $sanitized = $fallback;
1046 return apply_filters( 'sanitize_html_class', $sanitized, $class, $fallback );
1050 * Converts a number of characters from a string.
1052 * Metadata tags <<title>> and <<category>> are removed, <<br>> and <<hr>> are
1053 * converted into correct XHTML and Unicode characters are converted to the
1058 * @param string $content String of characters to be converted.
1059 * @param string $deprecated Not used.
1060 * @return string Converted string.
1062 function convert_chars($content, $deprecated = '') {
1063 if ( !empty( $deprecated ) )
1064 _deprecated_argument( __FUNCTION__, '0.71' );
1066 // Translation of invalid Unicode references range to valid range
1067 $wp_htmltranswinuni = array(
1068 '€' => '€', // the Euro sign
1070 '‚' => '‚', // these are Windows CP1252 specific characters
1071 'ƒ' => 'ƒ', // they would look weird on non-Windows browsers
1072 '„' => '„',
1073 '…' => '…',
1074 '†' => '†',
1075 '‡' => '‡',
1076 'ˆ' => 'ˆ',
1077 '‰' => '‰',
1078 'Š' => 'Š',
1079 '‹' => '‹',
1080 'Œ' => 'Œ',
1082 'Ž' => 'Ž',
1085 '‘' => '‘',
1086 '’' => '’',
1087 '“' => '“',
1088 '”' => '”',
1089 '•' => '•',
1090 '–' => '–',
1091 '—' => '—',
1092 '˜' => '˜',
1093 '™' => '™',
1094 'š' => 'š',
1095 '›' => '›',
1096 'œ' => 'œ',
1098 'ž' => 'ž',
1099 'Ÿ' => 'Ÿ'
1102 // Remove metadata tags
1103 $content = preg_replace('/<title>(.+?)<\/title>/','',$content);
1104 $content = preg_replace('/<category>(.+?)<\/category>/','',$content);
1106 // Converts lone & characters into & (a.k.a. &)
1107 $content = preg_replace('/&([^#])(?![a-z1-4]{1,8};)/i', '&$1', $content);
1110 $content = strtr($content, $wp_htmltranswinuni);
1112 // Just a little XHTML help
1113 $content = str_replace('<br>', '<br />', $content);
1114 $content = str_replace('<hr>', '<hr />', $content);
1120 * Will only balance the tags if forced to and the option is set to balance tags.
1122 * The option 'use_balanceTags' is used to determine whether the tags will be balanced.
1126 * @param string $text Text to be balanced
1127 * @param bool $force If true, forces balancing, ignoring the value of the option. Default false.
1128 * @return string Balanced text
1130 function balanceTags( $text, $force = false ) {
1131 if ( !$force && get_option('use_balanceTags') == 0 )
1133 return force_balance_tags( $text );
1137 * Balances tags of string using a modified stack.
1141 * @author Leonard Lin <leonard@acm.org>
1143 * @copyright November 4, 2001
1145 * @todo Make better - change loop condition to $text in 1.2
1146 * @internal Modified by Scott Reilly (coffee2code) 02 Aug 2004
1147 * 1.1 Fixed handling of append/stack pop order of end text
1148 * Added Cleaning Hooks
1151 * @param string $text Text to be balanced.
1152 * @return string Balanced text.
1154 function force_balance_tags( $text ) {
1155 $tagstack = array();
1159 $single_tags = array( 'br', 'hr', 'img', 'input' ); // Known single-entity/self-closing tags
1160 $nestable_tags = array( 'blockquote', 'div', 'span', 'q' ); // Tags that can be immediately nested within themselves
1162 // WP bug fix for comments - in case you REALLY meant to type '< !--'
1163 $text = str_replace('< !--', '< !--', $text);
1164 // WP bug fix for LOVE <3 (and other situations with '<' before a number)
1165 $text = preg_replace('#<([0-9]{1})#', '<$1', $text);
1167 while ( preg_match("/<(\/?[\w:]*)\s*([^>]*)>/", $text, $regex) ) {
1168 $newtext .= $tagqueue;
1170 $i = strpos($text, $regex[0]);
1171 $l = strlen($regex[0]);
1173 // clear the shifter
1176 if ( isset($regex[1][0]) && '/' == $regex[1][0] ) { // End Tag
1177 $tag = strtolower(substr($regex[1],1));
1178 // if too many closing tags
1179 if( $stacksize <= 0 ) {
1181 // or close to be safe $tag = '/' . $tag;
1183 // if stacktop value = tag close value then pop
1184 else if ( $tagstack[$stacksize - 1] == $tag ) { // found closing tag
1185 $tag = '</' . $tag . '>'; // Close Tag
1187 array_pop( $tagstack );
1189 } else { // closing tag not at top, search for it
1190 for ( $j = $stacksize-1; $j >= 0; $j-- ) {
1191 if ( $tagstack[$j] == $tag ) {
1192 // add tag to tagqueue
1193 for ( $k = $stacksize-1; $k >= $j; $k--) {
1194 $tagqueue .= '</' . array_pop( $tagstack ) . '>';
1202 } else { // Begin Tag
1203 $tag = strtolower($regex[1]);
1207 // If self-closing or '', don't do anything.
1208 if ( substr($regex[2],-1) == '/' || $tag == '' ) {
1211 // ElseIf it's a known single-entity tag but it doesn't close itself, do so
1212 elseif ( in_array($tag, $single_tags) ) {
1214 } else { // Push the tag onto the stack
1215 // If the top of the stack is the same as the tag we want to push, close previous tag
1216 if ( $stacksize > 0 && !in_array($tag, $nestable_tags) && $tagstack[$stacksize - 1] == $tag ) {
1217 $tagqueue = '</' . array_pop ($tagstack) . '>';
1220 $stacksize = array_push ($tagstack, $tag);
1224 $attributes = $regex[2];
1225 if( !empty($attributes) )
1226 $attributes = ' '.$attributes;
1228 $tag = '<' . $tag . $attributes . '>';
1229 //If already queuing a close tag, then put this tag on, too
1230 if ( !empty($tagqueue) ) {
1235 $newtext .= substr($text, 0, $i) . $tag;
1236 $text = substr($text, $i + $l);
1240 $newtext .= $tagqueue;
1242 // Add Remaining text
1246 while( $x = array_pop($tagstack) )
1247 $newtext .= '</' . $x . '>'; // Add remaining tags to close
1249 // WP fix for the bug with HTML comments
1250 $newtext = str_replace("< !--","<!--",$newtext);
1251 $newtext = str_replace("< !--","< !--",$newtext);
1257 * Acts on text which is about to be edited.
1259 * The $content is run through esc_textarea(), which uses htmlspecialchars()
1260 * to convert special characters to HTML entities. If $richedit is set to true,
1261 * it is simply a holder for the 'format_to_edit' filter.
1265 * @param string $content The text about to be edited.
1266 * @param bool $richedit Whether the $content should not pass through htmlspecialchars(). Default false (meaning it will be passed).
1267 * @return string The text after the filter (and possibly htmlspecialchars()) has been run.
1269 function format_to_edit( $content, $richedit = false ) {
1270 $content = apply_filters( 'format_to_edit', $content );
1272 $content = esc_textarea( $content );
1277 * Holder for the 'format_to_post' filter.
1281 * @param string $content The text to pass through the filter.
1282 * @return string Text returned from the 'format_to_post' filter.
1284 function format_to_post($content) {
1285 $content = apply_filters('format_to_post', $content);
1290 * Add leading zeros when necessary.
1292 * If you set the threshold to '4' and the number is '10', then you will get
1293 * back '0010'. If you set the threshold to '4' and the number is '5000', then you
1294 * will get back '5000'.
1296 * Uses sprintf to append the amount of zeros based on the $threshold parameter
1297 * and the size of the number. If the number is large enough, then no zeros will
1302 * @param mixed $number Number to append zeros to if not greater than threshold.
1303 * @param int $threshold Digit places number needs to be to not have zeros added.
1304 * @return string Adds leading zeros to number if needed.
1306 function zeroise($number, $threshold) {
1307 return sprintf('%0'.$threshold.'s', $number);
1311 * Adds backslashes before letters and before a number at the start of a string.
1315 * @param string $string Value to which backslashes will be added.
1316 * @return string String with backslashes inserted.
1318 function backslashit($string) {
1319 $string = preg_replace('/^([0-9])/', '\\\\\\\\\1', $string);
1320 $string = preg_replace('/([a-z])/i', '\\\\\1', $string);
1325 * Appends a trailing slash.
1327 * Will remove trailing slash if it exists already before adding a trailing
1328 * slash. This prevents double slashing a string or path.
1330 * The primary use of this is for paths and thus should be used for paths. It is
1331 * not restricted to paths and offers no specific path support.
1334 * @uses untrailingslashit() Unslashes string if it was slashed already.
1336 * @param string $string What to add the trailing slash to.
1337 * @return string String with trailing slash added.
1339 function trailingslashit($string) {
1340 return untrailingslashit($string) . '/';
1344 * Removes trailing slash if it exists.
1346 * The primary use of this is for paths and thus should be used for paths. It is
1347 * not restricted to paths and offers no specific path support.
1351 * @param string $string What to remove the trailing slash from.
1352 * @return string String without the trailing slash.
1354 function untrailingslashit($string) {
1355 return rtrim($string, '/');
1359 * Adds slashes to escape strings.
1361 * Slashes will first be removed if magic_quotes_gpc is set, see {@link
1362 * http://www.php.net/magic_quotes} for more details.
1366 * @param string $gpc The string returned from HTTP request data.
1367 * @return string Returns a string escaped with slashes.
1369 function addslashes_gpc($gpc) {
1370 if ( get_magic_quotes_gpc() )
1371 $gpc = stripslashes($gpc);
1373 return esc_sql($gpc);
1377 * Navigates through an array and removes slashes from the values.
1379 * If an array is passed, the array_map() function causes a callback to pass the
1380 * value back to the function. The slashes from this value will removed.
1384 * @param array|string $value The array or string to be stripped.
1385 * @return array|string Stripped array (or string in the callback).
1387 function stripslashes_deep($value) {
1388 if ( is_array($value) ) {
1389 $value = array_map('stripslashes_deep', $value);
1390 } elseif ( is_object($value) ) {
1391 $vars = get_object_vars( $value );
1392 foreach ($vars as $key=>$data) {
1393 $value->{$key} = stripslashes_deep( $data );
1396 $value = stripslashes($value);
1403 * Navigates through an array and encodes the values to be used in a URL.
1408 * @param array|string $value The array or string to be encoded.
1409 * @return array|string $value The encoded array (or string from the callback).
1411 function urlencode_deep($value) {
1412 $value = is_array($value) ? array_map('urlencode_deep', $value) : urlencode($value);
1417 * Navigates through an array and raw encodes the values to be used in a URL.
1421 * @param array|string $value The array or string to be encoded.
1422 * @return array|string $value The encoded array (or string from the callback).
1424 function rawurlencode_deep( $value ) {
1425 return is_array( $value ) ? array_map( 'rawurlencode_deep', $value ) : rawurlencode( $value );
1429 * Converts email addresses characters to HTML entities to block spam bots.
1433 * @param string $emailaddy Email address.
1434 * @param int $mailto Optional. Range from 0 to 1. Used for encoding.
1435 * @return string Converted email address.
1437 function antispambot($emailaddy, $mailto=0) {
1438 $emailNOSPAMaddy = '';
1439 srand ((float) microtime() * 1000000);
1440 for ($i = 0; $i < strlen($emailaddy); $i = $i + 1) {
1441 $j = floor(rand(0, 1+$mailto));
1443 $emailNOSPAMaddy .= '&#'.ord(substr($emailaddy,$i,1)).';';
1445 $emailNOSPAMaddy .= substr($emailaddy,$i,1);
1447 $emailNOSPAMaddy .= '%'.zeroise(dechex(ord(substr($emailaddy, $i, 1))), 2);
1450 $emailNOSPAMaddy = str_replace('@','@',$emailNOSPAMaddy);
1451 return $emailNOSPAMaddy;
1455 * Callback to convert URI match to HTML A element.
1457 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1458 * make_clickable()}.
1463 * @param array $matches Single Regex Match.
1464 * @return string HTML A element with URI address.
1466 function _make_url_clickable_cb($matches) {
1469 if ( ')' == $matches[3] && strpos( $url, '(' ) ) {
1470 // If the trailing character is a closing parethesis, and the URL has an opening parenthesis in it, add the closing parenthesis to the URL.
1471 // Then we can let the parenthesis balancer do its thing below.
1472 $url .= $matches[3];
1475 $suffix = $matches[3];
1478 // Include parentheses in the URL only if paired
1479 while ( substr_count( $url, '(' ) < substr_count( $url, ')' ) ) {
1480 $suffix = strrchr( $url, ')' ) . $suffix;
1481 $url = substr( $url, 0, strrpos( $url, ')' ) );
1484 $url = esc_url($url);
1488 return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $suffix;
1492 * Callback to convert URL match to HTML A element.
1494 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1495 * make_clickable()}.
1500 * @param array $matches Single Regex Match.
1501 * @return string HTML A element with URL address.
1503 function _make_web_ftp_clickable_cb($matches) {
1505 $dest = $matches[2];
1506 $dest = 'http://' . $dest;
1507 $dest = esc_url($dest);
1511 // removed trailing [.,;:)] from URL
1512 if ( in_array( substr($dest, -1), array('.', ',', ';', ':', ')') ) === true ) {
1513 $ret = substr($dest, -1);
1514 $dest = substr($dest, 0, strlen($dest)-1);
1516 return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>$ret";
1520 * Callback to convert email address match to HTML A element.
1522 * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1523 * make_clickable()}.
1528 * @param array $matches Single Regex Match.
1529 * @return string HTML A element with email address.
1531 function _make_email_clickable_cb($matches) {
1532 $email = $matches[2] . '@' . $matches[3];
1533 return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
1537 * Convert plaintext URI to HTML links.
1539 * Converts URI, www and ftp, and email addresses. Finishes by fixing links
1544 * @param string $text Content to convert URIs.
1545 * @return string Content with converted URIs.
1547 function make_clickable( $text ) {
1549 $textarr = preg_split( '/(<[^<>]+>)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // split out HTML tags
1550 foreach ( $textarr as $piece ) {
1551 if ( empty( $piece ) || ( $piece[0] == '<' && ! preg_match('|^<\s*[\w]{1,20}+://|', $piece) ) ) {
1556 // Long strings might contain expensive edge cases ...
1557 if ( 10000 < strlen( $piece ) ) {
1559 foreach ( _split_str_by_whitespace( $piece, 2100 ) as $chunk ) { // 2100: Extra room for scheme and leading and trailing paretheses
1560 if ( 2101 < strlen( $chunk ) ) {
1561 $r .= $chunk; // Too big, no whitespace: bail.
1563 $r .= make_clickable( $chunk );
1567 $ret = " $piece "; // Pad with whitespace to simplify the regexes
1570 ([\\s(<.,;:!?]) # 1: Leading whitespace, or punctuation
1572 [\\w]{1,20}+:// # Scheme and hier-part prefix
1573 (?=\S{1,2000}\s) # Limit to URLs less than about 2000 characters long
1574 [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]*+ # Non-punctuation URL character
1575 (?: # Unroll the Loop: Only allow puctuation URL character if followed by a non-punctuation URL character
1576 [\'.,;:!?)] # Punctuation URL character
1577 [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]++ # Non-punctuation URL character
1580 (\)?) # 3: Trailing closing parenthesis (for parethesis balancing post processing)
1581 ~xS'; // The regex is a non-anchored pattern and does not have a single fixed starting character.
1582 // Tell PCRE to spend more time optimizing since, when used on a page load, it will probably be used several times.
1584 $ret = preg_replace_callback( $url_clickable, '_make_url_clickable_cb', $ret );
1586 $ret = preg_replace_callback( '#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]+)#is', '_make_web_ftp_clickable_cb', $ret );
1587 $ret = preg_replace_callback( '#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret );
1589 $ret = substr( $ret, 1, -1 ); // Remove our whitespace padding.
1594 // Cleanup of accidental links within links
1595 $r = preg_replace( '#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i', "$1$3</a>", $r );
1600 * Breaks a string into chunks by splitting at whitespace characters.
1601 * The length of each returned chunk is as close to the specified length goal as possible,
1602 * with the caveat that each chunk includes its trailing delimiter.
1603 * Chunks longer than the goal are guaranteed to not have any inner whitespace.
1605 * Joining the returned chunks with empty delimiters reconstructs the input string losslessly.
1607 * Input string must have no null characters (or eventual transformations on output chunks must not care about null characters)
1610 * _split_str_by_whitespace( "1234 67890 1234 67890a cd 1234 890 123456789 1234567890a 45678 1 3 5 7 90 ", 10 ) ==
1612 * 0 => '1234 67890 ', // 11 characters: Perfect split
1613 * 1 => '1234 ', // 5 characters: '1234 67890a' was too long
1614 * 2 => '67890a cd ', // 10 characters: '67890a cd 1234' was too long
1615 * 3 => '1234 890 ', // 11 characters: Perfect split
1616 * 4 => '123456789 ', // 10 characters: '123456789 1234567890a' was too long
1617 * 5 => '1234567890a ', // 12 characters: Too long, but no inner whitespace on which to split
1618 * 6 => ' 45678 ', // 11 characters: Perfect split
1619 * 7 => '1 3 5 7 9', // 9 characters: End of $string
1626 * @param string $string The string to split
1627 * @param int $goal The desired chunk length.
1628 * @return array Numeric array of chunks.
1630 function _split_str_by_whitespace( $string, $goal ) {
1633 $string_nullspace = strtr( $string, "\r\n\t\v\f ", "\000\000\000\000\000\000" );
1635 while ( $goal < strlen( $string_nullspace ) ) {
1636 $pos = strrpos( substr( $string_nullspace, 0, $goal + 1 ), "\000" );
1638 if ( false === $pos ) {
1639 $pos = strpos( $string_nullspace, "\000", $goal + 1 );
1640 if ( false === $pos ) {
1645 $chunks[] = substr( $string, 0, $pos + 1 );
1646 $string = substr( $string, $pos + 1 );
1647 $string_nullspace = substr( $string_nullspace, $pos + 1 );
1651 $chunks[] = $string;
1658 * Adds rel nofollow string to all HTML A elements in content.
1662 * @param string $text Content that may contain HTML A elements.
1663 * @return string Converted content.
1665 function wp_rel_nofollow( $text ) {
1666 // This is a pre save filter, so text is already escaped.
1667 $text = stripslashes($text);
1668 $text = preg_replace_callback('|<a (.+?)>|i', 'wp_rel_nofollow_callback', $text);
1669 $text = esc_sql($text);
1674 * Callback to used to add rel=nofollow string to HTML A element.
1676 * Will remove already existing rel="nofollow" and rel='nofollow' from the
1677 * string to prevent from invalidating (X)HTML.
1681 * @param array $matches Single Match
1682 * @return string HTML A Element with rel nofollow.
1684 function wp_rel_nofollow_callback( $matches ) {
1685 $text = $matches[1];
1686 $text = str_replace(array(' rel="nofollow"', " rel='nofollow'"), '', $text);
1687 return "<a $text rel=\"nofollow\">";
1691 * Convert one smiley code to the icon graphic file equivalent.
1693 * Looks up one smiley code in the $wpsmiliestrans global array and returns an
1694 * <img> string for that smiley.
1696 * @global array $wpsmiliestrans
1699 * @param string $smiley Smiley code to convert to image.
1700 * @return string Image string for smiley.
1702 function translate_smiley($smiley) {
1703 global $wpsmiliestrans;
1705 if (count($smiley) == 0) {
1709 $smiley = trim(reset($smiley));
1710 $img = $wpsmiliestrans[$smiley];
1711 $smiley_masked = esc_attr($smiley);
1713 $srcurl = apply_filters('smilies_src', includes_url("images/smilies/$img"), $img, site_url());
1715 return " <img src='$srcurl' alt='$smiley_masked' class='wp-smiley' /> ";
1719 * Convert text equivalent of smilies to images.
1721 * Will only convert smilies if the option 'use_smilies' is true and the global
1722 * used in the function isn't empty.
1725 * @uses $wp_smiliessearch
1727 * @param string $text Content to convert smilies from text.
1728 * @return string Converted content with text smilies replaced with images.
1730 function convert_smilies($text) {
1731 global $wp_smiliessearch;
1733 if ( get_option('use_smilies') && !empty($wp_smiliessearch) ) {
1734 // HTML loop taken from texturize function, could possible be consolidated
1735 $textarr = preg_split("/(<.*>)/U", $text, -1, PREG_SPLIT_DELIM_CAPTURE); // capture the tags as well as in between
1736 $stop = count($textarr);// loop stuff
1737 for ($i = 0; $i < $stop; $i++) {
1738 $content = $textarr[$i];
1739 if ((strlen($content) > 0) && ('<' != $content[0])) { // If it's not a tag
1740 $content = preg_replace_callback($wp_smiliessearch, 'translate_smiley', $content);
1742 $output .= $content;
1745 // return default text.
1752 * Verifies that an email is valid.
1754 * Does not grok i18n domains. Not RFC compliant.
1758 * @param string $email Email address to verify.
1759 * @param boolean $deprecated Deprecated.
1760 * @return string|bool Either false or the valid email address.
1762 function is_email( $email, $deprecated = false ) {
1763 if ( ! empty( $deprecated ) )
1764 _deprecated_argument( __FUNCTION__, '3.0' );
1766 // Test for the minimum length the email can be
1767 if ( strlen( $email ) < 3 ) {
1768 return apply_filters( 'is_email', false, $email, 'email_too_short' );
1771 // Test for an @ character after the first position
1772 if ( strpos( $email, '@', 1 ) === false ) {
1773 return apply_filters( 'is_email', false, $email, 'email_no_at' );
1776 // Split out the local and domain parts
1777 list( $local, $domain ) = explode( '@', $email, 2 );
1780 // Test for invalid characters
1781 if ( !preg_match( '/^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]+$/', $local ) ) {
1782 return apply_filters( 'is_email', false, $email, 'local_invalid_chars' );
1786 // Test for sequences of periods
1787 if ( preg_match( '/\.{2,}/', $domain ) ) {
1788 return apply_filters( 'is_email', false, $email, 'domain_period_sequence' );
1791 // Test for leading and trailing periods and whitespace
1792 if ( trim( $domain, " \t\n\r\0\x0B." ) !== $domain ) {
1793 return apply_filters( 'is_email', false, $email, 'domain_period_limits' );
1796 // Split the domain into subs
1797 $subs = explode( '.', $domain );
1799 // Assume the domain will have at least two subs
1800 if ( 2 > count( $subs ) ) {
1801 return apply_filters( 'is_email', false, $email, 'domain_no_periods' );
1804 // Loop through each sub
1805 foreach ( $subs as $sub ) {
1806 // Test for leading and trailing hyphens and whitespace
1807 if ( trim( $sub, " \t\n\r\0\x0B-" ) !== $sub ) {
1808 return apply_filters( 'is_email', false, $email, 'sub_hyphen_limits' );
1811 // Test for invalid characters
1812 if ( !preg_match('/^[a-z0-9-]+$/i', $sub ) ) {
1813 return apply_filters( 'is_email', false, $email, 'sub_invalid_chars' );
1817 // Congratulations your email made it!
1818 return apply_filters( 'is_email', $email, $email, null );
1822 * Convert to ASCII from email subjects.
1825 * @usedby wp_mail() handles charsets in email subjects
1827 * @param string $string Subject line
1828 * @return string Converted string to ASCII
1830 function wp_iso_descrambler($string) {
1831 /* this may only work with iso-8859-1, I'm afraid */
1832 if (!preg_match('#\=\?(.+)\?Q\?(.+)\?\=#i', $string, $matches)) {
1835 $subject = str_replace('_', ' ', $matches[2]);
1836 $subject = preg_replace_callback('#\=([0-9a-f]{2})#i', '_wp_iso_convert', $subject);
1842 * Helper function to convert hex encoded chars to ascii
1846 * @param array $match the preg_replace_callback matches array
1848 function _wp_iso_convert( $match ) {
1849 return chr( hexdec( strtolower( $match[1] ) ) );
1853 * Returns a date in the GMT equivalent.
1855 * Requires and returns a date in the Y-m-d H:i:s format. Simply subtracts the
1856 * value of the 'gmt_offset' option. Return format can be overridden using the
1857 * $format parameter. The DateTime and DateTimeZone classes are used to respect
1858 * time zone differences in DST.
1862 * @uses get_option() to retrieve the the value of 'gmt_offset'.
1863 * @param string $string The date to be converted.
1864 * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
1865 * @return string GMT version of the date provided.
1867 function get_gmt_from_date($string, $format = 'Y-m-d H:i:s') {
1868 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);
1869 $tz = get_option('timezone_string');
1871 date_default_timezone_set( $tz );
1872 $datetime = new DateTime( $string );
1873 $datetime->setTimezone( new DateTimeZone('UTC') );
1874 $offset = $datetime->getOffset();
1875 $datetime->modify( '+' . $offset / 3600 . ' hours');
1876 $string_gmt = gmdate($format, $datetime->format('U'));
1878 date_default_timezone_set('UTC');
1880 $string_time = gmmktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]);
1881 $string_gmt = gmdate($format, $string_time - get_option('gmt_offset') * 3600);
1887 * Converts a GMT date into the correct format for the blog.
1889 * Requires and returns in the Y-m-d H:i:s format. Simply adds the value of
1890 * gmt_offset.Return format can be overridden using the $format parameter
1894 * @param string $string The date to be converted.
1895 * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
1896 * @return string Formatted date relative to the GMT offset.
1898 function get_date_from_gmt($string, $format = 'Y-m-d H:i:s') {
1899 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);
1900 $string_time = gmmktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]);
1901 $string_localtime = gmdate($format, $string_time + get_option('gmt_offset')*3600);
1902 return $string_localtime;
1906 * Computes an offset in seconds from an iso8601 timezone.
1910 * @param string $timezone Either 'Z' for 0 offset or '±hhmm'.
1911 * @return int|float The offset in seconds.
1913 function iso8601_timezone_to_offset($timezone) {
1914 // $timezone is either 'Z' or '[+|-]hhmm'
1915 if ($timezone == 'Z') {
1918 $sign = (substr($timezone, 0, 1) == '+') ? 1 : -1;
1919 $hours = intval(substr($timezone, 1, 2));
1920 $minutes = intval(substr($timezone, 3, 4)) / 60;
1921 $offset = $sign * 3600 * ($hours + $minutes);
1927 * Converts an iso8601 date to MySQL DateTime format used by post_date[_gmt].
1931 * @param string $date_string Date and time in ISO 8601 format {@link http://en.wikipedia.org/wiki/ISO_8601}.
1932 * @param string $timezone Optional. If set to GMT returns the time minus gmt_offset. Default is 'user'.
1933 * @return string The date and time in MySQL DateTime format - Y-m-d H:i:s.
1935 function iso8601_to_datetime($date_string, $timezone = 'user') {
1936 $timezone = strtolower($timezone);
1938 if ($timezone == 'gmt') {
1940 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);
1942 if (!empty($date_bits[7])) { // we have a timezone, so let's compute an offset
1943 $offset = iso8601_timezone_to_offset($date_bits[7]);
1944 } else { // we don't have a timezone, so we assume user local timezone (not server's!)
1945 $offset = 3600 * get_option('gmt_offset');
1948 $timestamp = gmmktime($date_bits[4], $date_bits[5], $date_bits[6], $date_bits[2], $date_bits[3], $date_bits[1]);
1949 $timestamp -= $offset;
1951 return gmdate('Y-m-d H:i:s', $timestamp);
1953 } else if ($timezone == 'user') {
1954 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);
1959 * Adds a element attributes to open links in new windows.
1961 * Comment text in popup windows should be filtered through this. Right now it's
1962 * a moderately dumb function, ideally it would detect whether a target or rel
1963 * attribute was already there and adjust its actions accordingly.
1967 * @param string $text Content to replace links to open in a new window.
1968 * @return string Content that has filtered links.
1970 function popuplinks($text) {
1971 $text = preg_replace('/<a (.+?)>/i', "<a $1 target='_blank' rel='external'>", $text);
1976 * Strips out all characters that are not allowable in an email.
1980 * @param string $email Email address to filter.
1981 * @return string Filtered email address.
1983 function sanitize_email( $email ) {
1984 // Test for the minimum length the email can be
1985 if ( strlen( $email ) < 3 ) {
1986 return apply_filters( 'sanitize_email', '', $email, 'email_too_short' );
1989 // Test for an @ character after the first position
1990 if ( strpos( $email, '@', 1 ) === false ) {
1991 return apply_filters( 'sanitize_email', '', $email, 'email_no_at' );
1994 // Split out the local and domain parts
1995 list( $local, $domain ) = explode( '@', $email, 2 );
1998 // Test for invalid characters
1999 $local = preg_replace( '/[^a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]/', '', $local );
2000 if ( '' === $local ) {
2001 return apply_filters( 'sanitize_email', '', $email, 'local_invalid_chars' );
2005 // Test for sequences of periods
2006 $domain = preg_replace( '/\.{2,}/', '', $domain );
2007 if ( '' === $domain ) {
2008 return apply_filters( 'sanitize_email', '', $email, 'domain_period_sequence' );
2011 // Test for leading and trailing periods and whitespace
2012 $domain = trim( $domain, " \t\n\r\0\x0B." );
2013 if ( '' === $domain ) {
2014 return apply_filters( 'sanitize_email', '', $email, 'domain_period_limits' );
2017 // Split the domain into subs
2018 $subs = explode( '.', $domain );
2020 // Assume the domain will have at least two subs
2021 if ( 2 > count( $subs ) ) {
2022 return apply_filters( 'sanitize_email', '', $email, 'domain_no_periods' );
2025 // Create an array that will contain valid subs
2026 $new_subs = array();
2028 // Loop through each sub
2029 foreach ( $subs as $sub ) {
2030 // Test for leading and trailing hyphens
2031 $sub = trim( $sub, " \t\n\r\0\x0B-" );
2033 // Test for invalid characters
2034 $sub = preg_replace( '/[^a-z0-9-]+/i', '', $sub );
2036 // If there's anything left, add it to the valid subs
2037 if ( '' !== $sub ) {
2042 // If there aren't 2 or more valid subs
2043 if ( 2 > count( $new_subs ) ) {
2044 return apply_filters( 'sanitize_email', '', $email, 'domain_no_valid_subs' );
2047 // Join valid subs into the new domain
2048 $domain = join( '.', $new_subs );
2050 // Put the email back together
2051 $email = $local . '@' . $domain;
2053 // Congratulations your email made it!
2054 return apply_filters( 'sanitize_email', $email, $email, null );
2058 * Determines the difference between two timestamps.
2060 * The difference is returned in a human readable format such as "1 hour",
2061 * "5 mins", "2 days".
2065 * @param int $from Unix timestamp from which the difference begins.
2066 * @param int $to Optional. Unix timestamp to end the time difference. Default becomes time() if not set.
2067 * @return string Human readable time difference.
2069 function human_time_diff( $from, $to = '' ) {
2072 $diff = (int) abs($to - $from);
2073 if ($diff <= 3600) {
2074 $mins = round($diff / 60);
2078 /* translators: min=minute */
2079 $since = sprintf(_n('%s min', '%s mins', $mins), $mins);
2080 } else if (($diff <= 86400) && ($diff > 3600)) {
2081 $hours = round($diff / 3600);
2085 $since = sprintf(_n('%s hour', '%s hours', $hours), $hours);
2086 } elseif ($diff >= 86400) {
2087 $days = round($diff / 86400);
2091 $since = sprintf(_n('%s day', '%s days', $days), $days);
2097 * Generates an excerpt from the content, if needed.
2099 * The excerpt word amount will be 55 words and if the amount is greater than
2100 * that, then the string ' [...]' will be appended to the excerpt. If the string
2101 * is less than 55 words, then the content will be returned as is.
2103 * The 55 word limit can be modified by plugins/themes using the excerpt_length filter
2104 * The ' [...]' string can be modified by plugins/themes using the excerpt_more filter
2108 * @param string $text Optional. The excerpt. If set to empty, an excerpt is generated.
2109 * @return string The excerpt.
2111 function wp_trim_excerpt($text = '') {
2112 $raw_excerpt = $text;
2113 if ( '' == $text ) {
2114 $text = get_the_content('');
2116 $text = strip_shortcodes( $text );
2118 $text = apply_filters('the_content', $text);
2119 $text = str_replace(']]>', ']]>', $text);
2120 $excerpt_length = apply_filters('excerpt_length', 55);
2121 $excerpt_more = apply_filters('excerpt_more', ' ' . '[...]');
2122 $text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
2124 return apply_filters('wp_trim_excerpt', $text, $raw_excerpt);
2128 * Trims text to a certain number of words.
2130 * This function is localized. For languages that count 'words' by the individual
2131 * character (such as East Asian languages), the $num_words argument will apply
2132 * to the number of individual characters.
2136 * @param string $text Text to trim.
2137 * @param int $num_words Number of words. Default 55.
2138 * @param string $more What to append if $text needs to be trimmed. Default '…'.
2139 * @return string Trimmed text.
2141 function wp_trim_words( $text, $num_words = 55, $more = null ) {
2142 if ( null === $more )
2143 $more = __( '…' );
2144 $original_text = $text;
2145 $text = wp_strip_all_tags( $text );
2146 /* translators: If your word count is based on single characters (East Asian characters),
2147 enter 'characters'. Otherwise, enter 'words'. Do not translate into your own language. */
2148 if ( 'characters' == _x( 'words', 'word count: words or characters?' ) && preg_match( '/^utf\-?8$/i', get_option( 'blog_charset' ) ) ) {
2149 $text = trim( preg_replace( "/[\n\r\t ]+/", ' ', $text ), ' ' );
2150 preg_match_all( '/./u', $text, $words_array );
2151 $words_array = array_slice( $words_array[0], 0, $num_words + 1 );
2154 $words_array = preg_split( "/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY );
2157 if ( count( $words_array ) > $num_words ) {
2158 array_pop( $words_array );
2159 $text = implode( $sep, $words_array );
2160 $text = $text . $more;
2162 $text = implode( $sep, $words_array );
2164 return apply_filters( 'wp_trim_words', $text, $num_words, $more, $original_text );
2168 * Converts named entities into numbered entities.
2172 * @param string $text The text within which entities will be converted.
2173 * @return string Text with converted entities.
2175 function ent2ncr($text) {
2177 // Allow a plugin to short-circuit and override the mappings.
2178 $filtered = apply_filters( 'pre_ent2ncr', null, $text );
2179 if( null !== $filtered )
2183 '"' => '"',
2185 '⁄' => '/',
2189 ' ' => ' ',
2190 '¡' => '¡',
2191 '¢' => '¢',
2192 '£' => '£',
2193 '¤' => '¤',
2194 '¥' => '¥',
2195 '¦' => '¦',
2196 '&brkbar;' => '¦',
2197 '§' => '§',
2198 '¨' => '¨',
2199 '¨' => '¨',
2200 '©' => '©',
2201 'ª' => 'ª',
2202 '«' => '«',
2203 '¬' => '¬',
2204 '­' => '­',
2205 '®' => '®',
2206 '¯' => '¯',
2207 '&hibar;' => '¯',
2208 '°' => '°',
2209 '±' => '±',
2210 '²' => '²',
2211 '³' => '³',
2212 '´' => '´',
2213 'µ' => 'µ',
2214 '¶' => '¶',
2215 '·' => '·',
2216 '¸' => '¸',
2217 '¹' => '¹',
2218 'º' => 'º',
2219 '»' => '»',
2220 '¼' => '¼',
2221 '½' => '½',
2222 '¾' => '¾',
2223 '¿' => '¿',
2224 'À' => 'À',
2225 'Á' => 'Á',
2226 'Â' => 'Â',
2227 'Ã' => 'Ã',
2228 'Ä' => 'Ä',
2229 'Å' => 'Å',
2230 'Æ' => 'Æ',
2231 'Ç' => 'Ç',
2232 'È' => 'È',
2233 'É' => 'É',
2234 'Ê' => 'Ê',
2235 'Ë' => 'Ë',
2236 'Ì' => 'Ì',
2237 'Í' => 'Í',
2238 'Î' => 'Î',
2239 'Ï' => 'Ï',
2240 'Ð' => 'Ð',
2241 'Ñ' => 'Ñ',
2242 'Ò' => 'Ò',
2243 'Ó' => 'Ó',
2244 'Ô' => 'Ô',
2245 'Õ' => 'Õ',
2246 'Ö' => 'Ö',
2247 '×' => '×',
2248 'Ø' => 'Ø',
2249 'Ù' => 'Ù',
2250 'Ú' => 'Ú',
2251 'Û' => 'Û',
2252 'Ü' => 'Ü',
2253 'Ý' => 'Ý',
2254 'Þ' => 'Þ',
2255 'ß' => 'ß',
2256 'à' => 'à',
2257 'á' => 'á',
2258 'â' => 'â',
2259 'ã' => 'ã',
2260 'ä' => 'ä',
2261 'å' => 'å',
2262 'æ' => 'æ',
2263 'ç' => 'ç',
2264 'è' => 'è',
2265 'é' => 'é',
2266 'ê' => 'ê',
2267 'ë' => 'ë',
2268 'ì' => 'ì',
2269 'í' => 'í',
2270 'î' => 'î',
2271 'ï' => 'ï',
2272 'ð' => 'ð',
2273 'ñ' => 'ñ',
2274 'ò' => 'ò',
2275 'ó' => 'ó',
2276 'ô' => 'ô',
2277 'õ' => 'õ',
2278 'ö' => 'ö',
2279 '÷' => '÷',
2280 'ø' => 'ø',
2281 'ù' => 'ù',
2282 'ú' => 'ú',
2283 'û' => 'û',
2284 'ü' => 'ü',
2285 'ý' => 'ý',
2286 'þ' => 'þ',
2287 'ÿ' => 'ÿ',
2288 'Œ' => 'Œ',
2289 'œ' => 'œ',
2290 'Š' => 'Š',
2291 'š' => 'š',
2292 'Ÿ' => 'Ÿ',
2293 'ƒ' => 'ƒ',
2294 'ˆ' => 'ˆ',
2295 '˜' => '˜',
2296 'Α' => 'Α',
2297 'Β' => 'Β',
2298 'Γ' => 'Γ',
2299 'Δ' => 'Δ',
2300 'Ε' => 'Ε',
2301 'Ζ' => 'Ζ',
2302 'Η' => 'Η',
2303 'Θ' => 'Θ',
2304 'Ι' => 'Ι',
2305 'Κ' => 'Κ',
2306 'Λ' => 'Λ',
2310 'Ο' => 'Ο',
2312 'Ρ' => 'Ρ',
2313 'Σ' => 'Σ',
2314 'Τ' => 'Τ',
2315 'Υ' => 'Υ',
2316 'Φ' => 'Φ',
2317 'Χ' => 'Χ',
2318 'Ψ' => 'Ψ',
2319 'Ω' => 'Ω',
2320 'α' => 'α',
2321 'β' => 'β',
2322 'γ' => 'γ',
2323 'δ' => 'δ',
2324 'ε' => 'ε',
2325 'ζ' => 'ζ',
2326 'η' => 'η',
2327 'θ' => 'θ',
2328 'ι' => 'ι',
2329 'κ' => 'κ',
2330 'λ' => 'λ',
2334 'ο' => 'ο',
2336 'ρ' => 'ρ',
2337 'ς' => 'ς',
2338 'σ' => 'σ',
2339 'τ' => 'τ',
2340 'υ' => 'υ',
2341 'φ' => 'φ',
2342 'χ' => 'χ',
2343 'ψ' => 'ψ',
2344 'ω' => 'ω',
2345 'ϑ' => 'ϑ',
2346 'ϒ' => 'ϒ',
2347 'ϖ' => 'ϖ',
2348 ' ' => ' ',
2349 ' ' => ' ',
2350 ' ' => ' ',
2351 '‌' => '‌',
2352 '‍' => '‍',
2353 '‎' => '‎',
2354 '‏' => '‏',
2355 '–' => '–',
2356 '—' => '—',
2357 '‘' => '‘',
2358 '’' => '’',
2359 '‚' => '‚',
2360 '“' => '“',
2361 '”' => '”',
2362 '„' => '„',
2363 '†' => '†',
2364 '‡' => '‡',
2365 '•' => '•',
2366 '…' => '…',
2367 '‰' => '‰',
2368 '′' => '′',
2369 '″' => '″',
2370 '‹' => '‹',
2371 '›' => '›',
2372 '‾' => '‾',
2373 '⁄' => '⁄',
2374 '€' => '€',
2375 'ℑ' => 'ℑ',
2376 '℘' => '℘',
2377 'ℜ' => 'ℜ',
2378 '™' => '™',
2379 'ℵ' => 'ℵ',
2380 '↵' => '↵',
2381 '⇐' => '⇐',
2382 '⇑' => '⇑',
2383 '⇒' => '⇒',
2384 '⇓' => '⇓',
2385 '⇔' => '⇔',
2386 '∀' => '∀',
2387 '∂' => '∂',
2388 '∃' => '∃',
2389 '∅' => '∅',
2390 '∇' => '∇',
2391 '∈' => '∈',
2392 '∉' => '∉',
2393 '∋' => '∋',
2394 '∏' => '∏',
2395 '∑' => '∑',
2396 '−' => '−',
2397 '∗' => '∗',
2398 '√' => '√',
2399 '∝' => '∝',
2400 '∞' => '∞',
2401 '∠' => '∠',
2402 '∧' => '∧',
2403 '∨' => '∨',
2404 '∩' => '∩',
2405 '∪' => '∪',
2406 '∫' => '∫',
2407 '∴' => '∴',
2408 '∼' => '∼',
2409 '≅' => '≅',
2410 '≈' => '≈',
2411 '≠' => '≠',
2412 '≡' => '≡',
2413 '≤' => '≤',
2414 '≥' => '≥',
2415 '⊂' => '⊂',
2416 '⊃' => '⊃',
2417 '⊄' => '⊄',
2418 '⊆' => '⊆',
2419 '⊇' => '⊇',
2420 '⊕' => '⊕',
2421 '⊗' => '⊗',
2422 '⊥' => '⊥',
2423 '⋅' => '⋅',
2424 '⌈' => '⌈',
2425 '⌉' => '⌉',
2426 '⌊' => '⌊',
2427 '⌋' => '⌋',
2428 '⟨' => '〈',
2429 '⟩' => '〉',
2430 '←' => '←',
2431 '↑' => '↑',
2432 '→' => '→',
2433 '↓' => '↓',
2434 '↔' => '↔',
2435 '◊' => '◊',
2436 '♠' => '♠',
2437 '♣' => '♣',
2438 '♥' => '♥',
2439 '♦' => '♦'
2442 return str_replace( array_keys($to_ncr), array_values($to_ncr), $text );
2446 * Formats text for the rich text editor.
2448 * The filter 'richedit_pre' is applied here. If $text is empty the filter will
2449 * be applied to an empty string.
2453 * @param string $text The text to be formatted.
2454 * @return string The formatted text after filter is applied.
2456 function wp_richedit_pre($text) {
2457 // Filtering a blank results in an annoying <br />\n
2458 if ( empty($text) ) return apply_filters('richedit_pre', '');
2460 $output = convert_chars($text);
2461 $output = wpautop($output);
2462 $output = htmlspecialchars($output, ENT_NOQUOTES);
2464 return apply_filters('richedit_pre', $output);
2468 * Formats text for the HTML editor.
2470 * Unless $output is empty it will pass through htmlspecialchars before the
2471 * 'htmledit_pre' filter is applied.
2475 * @param string $output The text to be formatted.
2476 * @return string Formatted text after filter applied.
2478 function wp_htmledit_pre($output) {
2479 if ( !empty($output) )
2480 $output = htmlspecialchars($output, ENT_NOQUOTES); // convert only < > &
2482 return apply_filters('htmledit_pre', $output);
2486 * Perform a deep string replace operation to ensure the values in $search are no longer present
2488 * Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values
2489 * e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that
2490 * str_replace would return
2495 * @param string|array $search
2496 * @param string $subject
2497 * @return string The processed string
2499 function _deep_replace( $search, $subject ) {
2501 $subject = (string) $subject;
2504 foreach ( (array) $search as $val ) {
2505 while ( strpos( $subject, $val ) !== false ) {
2507 $subject = str_replace( $val, '', $subject );
2516 * Escapes data for use in a MySQL query
2518 * This is just a handy shortcut for $wpdb->escape(), for completeness' sake
2521 * @param string $sql Unescaped SQL data
2522 * @return string The cleaned $sql
2524 function esc_sql( $sql ) {
2526 return $wpdb->escape( $sql );
2530 * Checks and cleans a URL.
2532 * A number of characters are removed from the URL. If the URL is for displaying
2533 * (the default behaviour) ampersands are also replaced. The 'clean_url' filter
2534 * is applied to the returned cleaned URL.
2537 * @uses wp_kses_bad_protocol() To only permit protocols in the URL set
2538 * via $protocols or the common ones set in the function.
2540 * @param string $url The URL to be cleaned.
2541 * @param array $protocols Optional. An array of acceptable protocols.
2542 * Defaults to 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn' if not set.
2543 * @param string $_context Private. Use esc_url_raw() for database usage.
2544 * @return string The cleaned $url after the 'clean_url' filter is applied.
2546 function esc_url( $url, $protocols = null, $_context = 'display' ) {
2547 $original_url = $url;
2551 $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);
2552 $strip = array('%0d', '%0a', '%0D', '%0A');
2553 $url = _deep_replace($strip, $url);
2554 $url = str_replace(';//', '://', $url);
2555 /* If the URL doesn't appear to contain a scheme, we
2556 * presume it needs http:// appended (unless a relative
2557 * link starting with /, # or ? or a php file).
2559 if ( strpos($url, ':') === false && ! in_array( $url[0], array( '/', '#', '?' ) ) &&
2560 ! preg_match('/^[a-z0-9-]+?\.php/i', $url) )
2561 $url = 'http://' . $url;
2563 // Replace ampersands and single quotes only when displaying.
2564 if ( 'display' == $_context ) {
2565 $url = wp_kses_normalize_entities( $url );
2566 $url = str_replace( '&', '&', $url );
2567 $url = str_replace( "'", ''', $url );
2570 if ( ! is_array( $protocols ) )
2571 $protocols = wp_allowed_protocols();
2572 if ( wp_kses_bad_protocol( $url, $protocols ) != $url )
2575 return apply_filters('clean_url', $url, $original_url, $_context);
2579 * Performs esc_url() for database usage.
2584 * @param string $url The URL to be cleaned.
2585 * @param array $protocols An array of acceptable protocols.
2586 * @return string The cleaned URL.
2588 function esc_url_raw( $url, $protocols = null ) {
2589 return esc_url( $url, $protocols, 'db' );
2593 * Convert entities, while preserving already-encoded entities.
2595 * @link http://www.php.net/htmlentities Borrowed from the PHP Manual user notes.
2599 * @param string $myHTML The text to be converted.
2600 * @return string Converted text.
2602 function htmlentities2($myHTML) {
2603 $translation_table = get_html_translation_table( HTML_ENTITIES, ENT_QUOTES );
2604 $translation_table[chr(38)] = '&';
2605 return preg_replace( "/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/", "&", strtr($myHTML, $translation_table) );
2609 * Escape single quotes, htmlspecialchar " < > &, and fix line endings.
2611 * Escapes text strings for echoing in JS. It is intended to be used for inline JS
2612 * (in a tag attribute, for example onclick="..."). Note that the strings have to
2613 * be in single quotes. The filter 'js_escape' is also applied here.
2617 * @param string $text The text to be escaped.
2618 * @return string Escaped text.
2620 function esc_js( $text ) {
2621 $safe_text = wp_check_invalid_utf8( $text );
2622 $safe_text = _wp_specialchars( $safe_text, ENT_COMPAT );
2623 $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) );
2624 $safe_text = str_replace( "\r", '', $safe_text );
2625 $safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) );
2626 return apply_filters( 'js_escape', $safe_text, $text );
2630 * Escaping for HTML blocks.
2634 * @param string $text
2637 function esc_html( $text ) {
2638 $safe_text = wp_check_invalid_utf8( $text );
2639 $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
2640 return apply_filters( 'esc_html', $safe_text, $text );
2644 * Escaping for HTML attributes.
2648 * @param string $text
2651 function esc_attr( $text ) {
2652 $safe_text = wp_check_invalid_utf8( $text );
2653 $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
2654 return apply_filters( 'attribute_escape', $safe_text, $text );
2658 * Escaping for textarea values.
2662 * @param string $text
2665 function esc_textarea( $text ) {
2666 $safe_text = htmlspecialchars( $text, ENT_QUOTES );
2667 return apply_filters( 'esc_textarea', $safe_text, $text );
2671 * Escape a HTML tag name.
2675 * @param string $tag_name
2678 function tag_escape($tag_name) {
2679 $safe_tag = strtolower( preg_replace('/[^a-zA-Z0-9_:]/', '', $tag_name) );
2680 return apply_filters('tag_escape', $safe_tag, $tag_name);
2684 * Escapes text for SQL LIKE special characters % and _.
2688 * @param string $text The text to be escaped.
2689 * @return string text, safe for inclusion in LIKE query.
2691 function like_escape($text) {
2692 return str_replace(array("%", "_"), array("\\%", "\\_"), $text);
2696 * Convert full URL paths to absolute paths.
2698 * Removes the http or https protocols and the domain. Keeps the path '/' at the
2699 * beginning, so it isn't a true relative link, but from the web root base.
2703 * @param string $link Full URL path.
2704 * @return string Absolute path.
2706 function wp_make_link_relative( $link ) {
2707 return preg_replace( '|https?://[^/]+(/.*)|i', '$1', $link );
2711 * Sanitises various option values based on the nature of the option.
2713 * This is basically a switch statement which will pass $value through a number
2714 * of functions depending on the $option.
2718 * @param string $option The name of the option.
2719 * @param string $value The unsanitised value.
2720 * @return string Sanitized value.
2722 function sanitize_option($option, $value) {
2724 switch ( $option ) {
2725 case 'admin_email' :
2726 case 'new_admin_email' :
2727 $value = sanitize_email( $value );
2728 if ( ! is_email( $value ) ) {
2729 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
2730 if ( function_exists( 'add_settings_error' ) )
2731 add_settings_error( $option, 'invalid_admin_email', __( 'The email address entered did not appear to be a valid email address. Please enter a valid email address.' ) );
2735 case 'thumbnail_size_w':
2736 case 'thumbnail_size_h':
2737 case 'medium_size_w':
2738 case 'medium_size_h':
2739 case 'large_size_w':
2740 case 'large_size_h':
2741 case 'embed_size_h':
2742 case 'default_post_edit_rows':
2743 case 'mailserver_port':
2744 case 'comment_max_links':
2745 case 'page_on_front':
2746 case 'page_for_posts':
2747 case 'rss_excerpt_length':
2748 case 'default_category':
2749 case 'default_email_category':
2750 case 'default_link_category':
2751 case 'close_comments_days_old':
2752 case 'comments_per_page':
2753 case 'thread_comments_depth':
2754 case 'users_can_register':
2755 case 'start_of_week':
2756 $value = absint( $value );
2759 case 'embed_size_w':
2760 if ( '' !== $value )
2761 $value = absint( $value );
2764 case 'posts_per_page':
2765 case 'posts_per_rss':
2766 $value = (int) $value;
2767 if ( empty($value) )
2770 $value = abs($value);
2773 case 'default_ping_status':
2774 case 'default_comment_status':
2775 // Options that if not there have 0 value but need to be something like "closed"
2776 if ( $value == '0' || $value == '')
2780 case 'blogdescription':
2782 $value = addslashes($value);
2783 $value = wp_filter_post_kses( $value ); // calls stripslashes then addslashes
2784 $value = stripslashes($value);
2785 $value = esc_html( $value );
2788 case 'blog_charset':
2789 $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value); // strips slashes
2794 case 'mailserver_url':
2795 case 'mailserver_login':
2796 case 'mailserver_pass':
2799 $value = strip_tags($value);
2800 $value = addslashes($value);
2801 $value = wp_filter_kses($value); // calls stripslashes then addslashes
2802 $value = stripslashes($value);
2806 $value = preg_replace('/[^0-9:.-]/', '', $value); // strips slashes
2810 if ( (bool)preg_match( '#http(s?)://(.+)#i', $value) ) {
2811 $value = esc_url_raw($value);
2813 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
2814 if ( function_exists('add_settings_error') )
2815 add_settings_error('siteurl', 'invalid_siteurl', __('The WordPress address you entered did not appear to be a valid URL. Please enter a valid URL.'));
2820 if ( (bool)preg_match( '#http(s?)://(.+)#i', $value) ) {
2821 $value = esc_url_raw($value);
2823 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
2824 if ( function_exists('add_settings_error') )
2825 add_settings_error('home', 'invalid_home', __('The Site address you entered did not appear to be a valid URL. Please enter a valid URL.'));
2830 $allowed = get_available_languages();
2831 if ( ! in_array( $value, $allowed ) && ! empty( $value ) )
2832 $value = get_option( $option );
2835 case 'timezone_string':
2836 $allowed_zones = timezone_identifiers_list();
2837 if ( ! in_array( $value, $allowed_zones ) && ! empty( $value ) ) {
2838 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
2839 if ( function_exists('add_settings_error') )
2840 add_settings_error('timezone_string', 'invalid_timezone_string', __('The timezone you have entered is not valid. Please select a valid timezone.') );
2844 case 'permalink_structure':
2845 case 'category_base':
2847 $value = esc_url_raw( $value );
2848 $value = str_replace( 'http://', '', $value );
2852 $value = apply_filters("sanitize_option_{$option}", $value, $option);
2858 * Parses a string into variables to be stored in an array.
2860 * Uses {@link http://www.php.net/parse_str parse_str()} and stripslashes if
2861 * {@link http://www.php.net/magic_quotes magic_quotes_gpc} is on.
2864 * @uses apply_filters() for the 'wp_parse_str' filter.
2866 * @param string $string The string to be parsed.
2867 * @param array $array Variables will be stored in this array.
2869 function wp_parse_str( $string, &$array ) {
2870 parse_str( $string, $array );
2871 if ( get_magic_quotes_gpc() )
2872 $array = stripslashes_deep( $array );
2873 $array = apply_filters( 'wp_parse_str', $array );
2877 * Convert lone less than signs.
2879 * KSES already converts lone greater than signs.
2881 * @uses wp_pre_kses_less_than_callback in the callback function.
2884 * @param string $text Text to be converted.
2885 * @return string Converted text.
2887 function wp_pre_kses_less_than( $text ) {
2888 return preg_replace_callback('%<[^>]*?((?=<)|>|$)%', 'wp_pre_kses_less_than_callback', $text);
2892 * Callback function used by preg_replace.
2894 * @uses esc_html to format the $matches text.
2897 * @param array $matches Populated by matches to preg_replace.
2898 * @return string The text returned after esc_html if needed.
2900 function wp_pre_kses_less_than_callback( $matches ) {
2901 if ( false === strpos($matches[0], '>') )
2902 return esc_html($matches[0]);
2907 * WordPress implementation of PHP sprintf() with filters.
2910 * @link http://www.php.net/sprintf
2912 * @param string $pattern The string which formatted args are inserted.
2913 * @param mixed $args,... Arguments to be formatted into the $pattern string.
2914 * @return string The formatted string.
2916 function wp_sprintf( $pattern ) {
2917 $args = func_get_args( );
2918 $len = strlen($pattern);
2922 while ( $len > $start ) {
2923 // Last character: append and break
2924 if ( strlen($pattern) - 1 == $start ) {
2925 $result .= substr($pattern, -1);
2929 // Literal %: append and continue
2930 if ( substr($pattern, $start, 2) == '%%' ) {
2936 // Get fragment before next %
2937 $end = strpos($pattern, '%', $start + 1);
2938 if ( false === $end )
2940 $fragment = substr($pattern, $start, $end - $start);
2942 // Fragment has a specifier
2943 if ( $pattern[$start] == '%' ) {
2944 // Find numbered arguments or take the next one in order
2945 if ( preg_match('/^%(\d+)\$/', $fragment, $matches) ) {
2946 $arg = isset($args[$matches[1]]) ? $args[$matches[1]] : '';
2947 $fragment = str_replace("%{$matches[1]}$", '%', $fragment);
2950 $arg = isset($args[$arg_index]) ? $args[$arg_index] : '';
2953 // Apply filters OR sprintf
2954 $_fragment = apply_filters( 'wp_sprintf', $fragment, $arg );
2955 if ( $_fragment != $fragment )
2956 $fragment = $_fragment;
2958 $fragment = sprintf($fragment, strval($arg) );
2961 // Append to result and move to next fragment
2962 $result .= $fragment;
2969 * Localize list items before the rest of the content.
2971 * The '%l' must be at the first characters can then contain the rest of the
2972 * content. The list items will have ', ', ', and', and ' and ' added depending
2973 * on the amount of list items in the $args parameter.
2977 * @param string $pattern Content containing '%l' at the beginning.
2978 * @param array $args List items to prepend to the content and replace '%l'.
2979 * @return string Localized list items and rest of the content.
2981 function wp_sprintf_l($pattern, $args) {
2983 if ( substr($pattern, 0, 2) != '%l' )
2986 // Nothing to work with
2990 // Translate and filter the delimiter set (avoid ampersands and entities here)
2991 $l = apply_filters('wp_sprintf_l', array(
2992 /* translators: used between list items, there is a space after the comma */
2993 'between' => __(', '),
2994 /* translators: used between list items, there is a space after the and */
2995 'between_last_two' => __(', and '),
2996 /* translators: used between only two list items, there is a space after the and */
2997 'between_only_two' => __(' and '),
3000 $args = (array) $args;
3001 $result = array_shift($args);
3002 if ( count($args) == 1 )
3003 $result .= $l['between_only_two'] . array_shift($args);
3004 // Loop when more than two args
3007 $arg = array_shift($args);
3010 $result .= $l['between_last_two'] . $arg;
3012 $result .= $l['between'] . $arg;
3014 return $result . substr($pattern, 2);
3018 * Safely extracts not more than the first $count characters from html string.
3020 * UTF-8, tags and entities safe prefix extraction. Entities inside will *NOT*
3021 * be counted as one character. For example & will be counted as 4, < as
3026 * @param integer $str String to get the excerpt from.
3027 * @param integer $count Maximum number of characters to take.
3028 * @return string The excerpt.
3030 function wp_html_excerpt( $str, $count ) {
3031 $str = wp_strip_all_tags( $str, true );
3032 $str = mb_substr( $str, 0, $count );
3033 // remove part of an entity at the end
3034 $str = preg_replace( '/&[^;\s]{0,6}$/', '', $str );
3039 * Add a Base url to relative links in passed content.
3041 * By default it supports the 'src' and 'href' attributes. However this can be
3042 * changed via the 3rd param.
3046 * @param string $content String to search for links in.
3047 * @param string $base The base URL to prefix to links.
3048 * @param array $attrs The attributes which should be processed.
3049 * @return string The processed content.
3051 function links_add_base_url( $content, $base, $attrs = array('src', 'href') ) {
3052 global $_links_add_base;
3053 $_links_add_base = $base;
3054 $attrs = implode('|', (array)$attrs);
3055 return preg_replace_callback( "!($attrs)=(['\"])(.+?)\\2!i", '_links_add_base', $content );
3059 * Callback to add a base url to relative links in passed content.
3064 * @param string $m The matched link.
3065 * @return string The processed link.
3067 function _links_add_base($m) {
3068 global $_links_add_base;
3069 //1 = attribute name 2 = quotation mark 3 = URL
3070 return $m[1] . '=' . $m[2] .
3071 ( preg_match( '#^(\w{1,20}):#', $m[3], $protocol ) && in_array( $protocol[1], wp_allowed_protocols() ) ?
3073 path_join( $_links_add_base, $m[3] ) )
3078 * Adds a Target attribute to all links in passed content.
3080 * This function by default only applies to <a> tags, however this can be
3081 * modified by the 3rd param.
3083 * <b>NOTE:</b> Any current target attributed will be stripped and replaced.
3087 * @param string $content String to search for links in.
3088 * @param string $target The Target to add to the links.
3089 * @param array $tags An array of tags to apply to.
3090 * @return string The processed content.
3092 function links_add_target( $content, $target = '_blank', $tags = array('a') ) {
3093 global $_links_add_target;
3094 $_links_add_target = $target;
3095 $tags = implode('|', (array)$tags);
3096 return preg_replace_callback( "!<($tags)(.+?)>!i", '_links_add_target', $content );
3100 * Callback to add a target attribute to all links in passed content.
3105 * @param string $m The matched link.
3106 * @return string The processed link.
3108 function _links_add_target( $m ) {
3109 global $_links_add_target;
3111 $link = preg_replace('|(target=[\'"](.*?)[\'"])|i', '', $m[2]);
3112 return '<' . $tag . $link . ' target="' . esc_attr( $_links_add_target ) . '">';
3115 // normalize EOL characters and strip duplicate whitespace
3116 function normalize_whitespace( $str ) {
3118 $str = str_replace("\r", "\n", $str);
3119 $str = preg_replace( array( '/\n+/', '/[ \t]+/' ), array( "\n", ' ' ), $str );
3124 * Properly strip all HTML tags including script and style
3128 * @param string $string String containing HTML tags
3129 * @param bool $remove_breaks optional Whether to remove left over line breaks and white space chars
3130 * @return string The processed string.
3132 function wp_strip_all_tags($string, $remove_breaks = false) {
3133 $string = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $string );
3134 $string = strip_tags($string);
3136 if ( $remove_breaks )
3137 $string = preg_replace('/[\r\n\t ]+/', ' ', $string);
3139 return trim( $string );
3143 * Sanitize a string from user input or from the db
3145 * check for invalid UTF-8,
3146 * Convert single < characters to entity,
3148 * remove line breaks, tabs and extra white space,
3153 * @param string $str
3156 function sanitize_text_field($str) {
3157 $filtered = wp_check_invalid_utf8( $str );
3159 if ( strpos($filtered, '<') !== false ) {
3160 $filtered = wp_pre_kses_less_than( $filtered );
3161 // This will strip extra whitespace for us.
3162 $filtered = wp_strip_all_tags( $filtered, true );
3164 $filtered = trim( preg_replace('/[\r\n\t ]+/', ' ', $filtered) );
3169 while ( preg_match('/%[a-f0-9]{2}/i', $filtered, $match) ) {
3170 $filtered = str_replace($match[0], '', $filtered);
3175 // Strip out the whitespace that may now exist after removing the octets.
3176 $filtered = trim( preg_replace('/ +/', ' ', $filtered) );
3179 return apply_filters('sanitize_text_field', $filtered, $str);
3183 * i18n friendly version of basename()
3187 * @param string $path A path.
3188 * @param string $suffix If the filename ends in suffix this will also be cut off.
3191 function wp_basename( $path, $suffix = '' ) {
3192 return urldecode( basename( str_replace( '%2F', '/', urlencode( $path ) ), $suffix ) );
3196 * Forever eliminate "Wordpress" from the planet (or at least the little bit we can influence).
3198 * Violating our coding standards for a good function name.
3202 function capital_P_dangit( $text ) {
3203 // Simple replacement for titles
3204 if ( 'the_title' === current_filter() )
3205 return str_replace( 'Wordpress', 'WordPress', $text );
3206 // Still here? Use the more judicious replacement
3207 static $dblq = false;
3208 if ( false === $dblq )
3209 $dblq = _x('“', 'opening curly quote');
3211 array( ' Wordpress', '‘Wordpress', $dblq . 'Wordpress', '>Wordpress', '(Wordpress' ),
3212 array( ' WordPress', '‘WordPress', $dblq . 'WordPress', '>WordPress', '(WordPress' ),
3218 * Sanitize a mime type
3222 * @param string $mime_type Mime type
3223 * @return string Sanitized mime type
3225 function sanitize_mime_type( $mime_type ) {
3226 $sani_mime_type = preg_replace( '/[^-+*.a-zA-Z0-9\/]/', '', $mime_type );
3227 return apply_filters( 'sanitize_mime_type', $sani_mime_type, $mime_type );
3231 * Sanitize space or carriage return separated URLs that are used to send trackbacks.
3235 * @param string $to_ping Space or carriage return separated URLs
3236 * @return string URLs starting with the http or https protocol, separated by a carriage return.
3238 function sanitize_trackback_urls( $to_ping ) {
3239 $urls_to_ping = preg_split( '/[\r\n\t ]/', trim( $to_ping ), -1, PREG_SPLIT_NO_EMPTY );
3240 foreach ( $urls_to_ping as $k => $url ) {
3241 if ( !preg_match( '#^https?://.#i', $url ) )
3242 unset( $urls_to_ping[$k] );
3244 $urls_to_ping = array_map( 'esc_url_raw', $urls_to_ping );
3245 $urls_to_ping = implode( "\n", $urls_to_ping );
3246 return apply_filters( 'sanitize_trackback_urls', $urls_to_ping, $to_ping );