]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/formatting.php
Wordpress 2.6.2
[autoinstalls/wordpress.git] / wp-includes / formatting.php
1 <?php
2
3 function wptexturize($text) {
4         global $wp_cockneyreplace;
5         $next = true;
6         $has_pre_parent = false;
7         $output = '';
8         $curl = '';
9         $textarr = preg_split('/(<.*>|\[.*\])/Us', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
10         $stop = count($textarr);
11
12         // if a plugin has provided an autocorrect array, use it
13         if ( isset($wp_cockneyreplace) ) {
14                 $cockney = array_keys($wp_cockneyreplace);
15                 $cockneyreplace = array_values($wp_cockneyreplace);
16         } else {
17                 $cockney = array("'tain't","'twere","'twas","'tis","'twill","'til","'bout","'nuff","'round","'cause");
18                 $cockneyreplace = array("&#8217;tain&#8217;t","&#8217;twere","&#8217;twas","&#8217;tis","&#8217;twill","&#8217;til","&#8217;bout","&#8217;nuff","&#8217;round","&#8217;cause");
19         }
20
21         $static_characters = array_merge(array('---', ' -- ', '--', 'xn&#8211;', '...', '``', '\'s', '\'\'', ' (tm)'), $cockney);
22         $static_replacements = array_merge(array('&#8212;', ' &#8212; ', '&#8211;', 'xn--', '&#8230;', '&#8220;', '&#8217;s', '&#8221;', ' &#8482;'), $cockneyreplace);
23
24         $dynamic_characters = array('/\'(\d\d(?:&#8217;|\')?s)/', '/(\s|\A|")\'/', '/(\d+)"/', '/(\d+)\'/', '/(\S)\'([^\'\s])/', '/(\s|\A)"(?!\s)/', '/"(\s|\S|\Z)/', '/\'([\s.]|\Z)/', '/(\d+)x(\d+)/');
25         $dynamic_replacements = array('&#8217;$1','$1&#8216;', '$1&#8243;', '$1&#8242;', '$1&#8217;$2', '$1&#8220;$2', '&#8221;$1', '&#8217;$1', '$1&#215;$2');
26
27         for ( $i = 0; $i < $stop; $i++ ) {
28                 $curl = $textarr[$i];
29
30                 if (isset($curl{0}) && '<' != $curl{0} && '[' != $curl{0} && $next && !$has_pre_parent) { // If it's not a tag
31                         // static strings
32                         $curl = str_replace($static_characters, $static_replacements, $curl);
33                         // regular expressions
34                         $curl = preg_replace($dynamic_characters, $dynamic_replacements, $curl);
35                 } elseif (strpos($curl, '<code') !== false || strpos($curl, '<kbd') !== false || strpos($curl, '<style') !== false || strpos($curl, '<script') !== false) {
36                         $next = false;
37                 } elseif (strpos($curl, '<pre') !== false) {
38                         $has_pre_parent = true;
39                 } elseif (strpos($curl, '</pre>') !== false) {
40                         $has_pre_parent = false;
41                 } else {
42                         $next = true;
43                 }
44
45                 $curl = preg_replace('/&([^#])(?![a-zA-Z1-4]{1,8};)/', '&#038;$1', $curl);
46                 $output .= $curl;
47         }
48
49         return $output;
50 }
51
52 // Accepts matches array from preg_replace_callback in wpautop()
53 // or a string
54 function clean_pre($matches) {
55         if ( is_array($matches) )
56                 $text = $matches[1] . $matches[2] . "</pre>";
57         else
58                 $text = $matches;
59
60         $text = str_replace('<br />', '', $text);
61         $text = str_replace('<p>', "\n", $text);
62         $text = str_replace('</p>', '', $text);
63
64         return $text;
65 }
66
67 function wpautop($pee, $br = 1) {
68         $pee = $pee . "\n"; // just to make things a little easier, pad the end
69         $pee = preg_replace('|<br />\s*<br />|', "\n\n", $pee);
70         // Space things out a little
71         $allblocks = '(?:table|thead|tfoot|caption|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|form|map|area|blockquote|address|math|style|input|p|h[1-6]|hr)';
72         $pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee);
73         $pee = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $pee);
74         $pee = str_replace(array("\r\n", "\r"), "\n", $pee); // cross-platform newlines
75         if ( strpos($pee, '<object') !== false ) {
76                 $pee = preg_replace('|\s*<param([^>]*)>\s*|', "<param$1>", $pee); // no pee inside object/embed
77                 $pee = preg_replace('|\s*</embed>\s*|', '</embed>', $pee);
78         }
79         $pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates
80         $pee = preg_replace('/\n?(.+?)(?:\n\s*\n|\z)/s', "<p>$1</p>\n", $pee); // make paragraphs, including one at the end
81         $pee = preg_replace('|<p>\s*?</p>|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace
82         $pee = preg_replace('!<p>([^<]+)\s*?(</(?:div|address|form)[^>]*>)!', "<p>$1</p>$2", $pee);
83         $pee = preg_replace( '|<p>|', "$1<p>", $pee );
84         $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee); // don't pee all over a tag
85         $pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee); // problem with nested lists
86         $pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee);
87         $pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee);
88         $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)!', "$1", $pee);
89         $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
90         if ($br) {
91                 $pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', create_function('$matches', 'return str_replace("\n", "<WPPreserveNewline />", $matches[0]);'), $pee);
92                 $pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee); // optionally make line breaks
93                 $pee = str_replace('<WPPreserveNewline />', "\n", $pee);
94         }
95         $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', "$1", $pee);
96         $pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee);
97         if (strpos($pee, '<pre') !== false)
98                 $pee = preg_replace_callback('!(<pre.*?>)(.*?)</pre>!is', 'clean_pre', $pee );
99         $pee = preg_replace( "|\n</p>$|", '</p>', $pee );
100         $pee = preg_replace('/<p>\s*?(' . get_shortcode_regex() . ')\s*<\/p>/s', '$1', $pee); // don't auto-p wrap shortcodes that stand alone
101
102         return $pee;
103 }
104
105
106 function seems_utf8($Str) { # by bmorel at ssi dot fr
107         $length = strlen($Str);
108         for ($i=0; $i < $length; $i++) {
109                 if (ord($Str[$i]) < 0x80) continue; # 0bbbbbbb
110                 elseif ((ord($Str[$i]) & 0xE0) == 0xC0) $n=1; # 110bbbbb
111                 elseif ((ord($Str[$i]) & 0xF0) == 0xE0) $n=2; # 1110bbbb
112                 elseif ((ord($Str[$i]) & 0xF8) == 0xF0) $n=3; # 11110bbb
113                 elseif ((ord($Str[$i]) & 0xFC) == 0xF8) $n=4; # 111110bb
114                 elseif ((ord($Str[$i]) & 0xFE) == 0xFC) $n=5; # 1111110b
115                 else return false; # Does not match any model
116                 for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
117                         if ((++$i == $length) || ((ord($Str[$i]) & 0xC0) != 0x80))
118                         return false;
119                 }
120         }
121         return true;
122 }
123
124 function wp_specialchars( $text, $quotes = 0 ) {
125         // Like htmlspecialchars except don't double-encode HTML entities
126         $text = str_replace('&&', '&#038;&', $text);
127         $text = str_replace('&&', '&#038;&', $text);
128         $text = preg_replace('/&(?:$|([^#])(?![a-z1-4]{1,8};))/', '&#038;$1', $text);
129         $text = str_replace('<', '&lt;', $text);
130         $text = str_replace('>', '&gt;', $text);
131         if ( 'double' === $quotes ) {
132                 $text = str_replace('"', '&quot;', $text);
133         } elseif ( 'single' === $quotes ) {
134                 $text = str_replace("'", '&#039;', $text);
135         } elseif ( $quotes ) {
136                 $text = str_replace('"', '&quot;', $text);
137                 $text = str_replace("'", '&#039;', $text);
138         }
139         return $text;
140 }
141
142 function utf8_uri_encode( $utf8_string, $length = 0 ) {
143         $unicode = '';
144         $values = array();
145         $num_octets = 1;
146         $unicode_length = 0;
147
148         $string_length = strlen( $utf8_string );
149         for ($i = 0; $i < $string_length; $i++ ) {
150
151                 $value = ord( $utf8_string[ $i ] );
152
153                 if ( $value < 128 ) {
154                         if ( $length && ( $unicode_length >= $length ) )
155                                 break;
156                         $unicode .= chr($value);
157                         $unicode_length++;
158                 } else {
159                         if ( count( $values ) == 0 ) $num_octets = ( $value < 224 ) ? 2 : 3;
160
161                         $values[] = $value;
162
163                         if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length )
164                                 break;
165                         if ( count( $values ) == $num_octets ) {
166                                 if ($num_octets == 3) {
167                                         $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]) . '%' . dechex($values[2]);
168                                         $unicode_length += 9;
169                                 } else {
170                                         $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]);
171                                         $unicode_length += 6;
172                                 }
173
174                                 $values = array();
175                                 $num_octets = 1;
176                         }
177                 }
178         }
179
180         return $unicode;
181 }
182
183 function remove_accents($string) {
184         if ( !preg_match('/[\x80-\xff]/', $string) )
185                 return $string;
186
187         if (seems_utf8($string)) {
188                 $chars = array(
189                 // Decompositions for Latin-1 Supplement
190                 chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
191                 chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
192                 chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
193                 chr(195).chr(135) => 'C', chr(195).chr(136) => 'E',
194                 chr(195).chr(137) => 'E', chr(195).chr(138) => 'E',
195                 chr(195).chr(139) => 'E', chr(195).chr(140) => 'I',
196                 chr(195).chr(141) => 'I', chr(195).chr(142) => 'I',
197                 chr(195).chr(143) => 'I', chr(195).chr(145) => 'N',
198                 chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
199                 chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
200                 chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
201                 chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
202                 chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
203                 chr(195).chr(159) => 's', chr(195).chr(160) => 'a',
204                 chr(195).chr(161) => 'a', chr(195).chr(162) => 'a',
205                 chr(195).chr(163) => 'a', chr(195).chr(164) => 'a',
206                 chr(195).chr(165) => 'a', chr(195).chr(167) => 'c',
207                 chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
208                 chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
209                 chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
210                 chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
211                 chr(195).chr(177) => 'n', chr(195).chr(178) => 'o',
212                 chr(195).chr(179) => 'o', chr(195).chr(180) => 'o',
213                 chr(195).chr(181) => 'o', chr(195).chr(182) => 'o',
214                 chr(195).chr(182) => 'o', chr(195).chr(185) => 'u',
215                 chr(195).chr(186) => 'u', chr(195).chr(187) => 'u',
216                 chr(195).chr(188) => 'u', chr(195).chr(189) => 'y',
217                 chr(195).chr(191) => 'y',
218                 // Decompositions for Latin Extended-A
219                 chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
220                 chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
221                 chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
222                 chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
223                 chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
224                 chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
225                 chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
226                 chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
227                 chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
228                 chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
229                 chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
230                 chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
231                 chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
232                 chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
233                 chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
234                 chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
235                 chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
236                 chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
237                 chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
238                 chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
239                 chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
240                 chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
241                 chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
242                 chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
243                 chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
244                 chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
245                 chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
246                 chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
247                 chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
248                 chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
249                 chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
250                 chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
251                 chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
252                 chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
253                 chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
254                 chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
255                 chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
256                 chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
257                 chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
258                 chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
259                 chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
260                 chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
261                 chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
262                 chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
263                 chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
264                 chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
265                 chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
266                 chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
267                 chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
268                 chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
269                 chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
270                 chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
271                 chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
272                 chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
273                 chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
274                 chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
275                 chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
276                 chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
277                 chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
278                 chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
279                 chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
280                 chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
281                 chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
282                 chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
283                 // Euro Sign
284                 chr(226).chr(130).chr(172) => 'E',
285                 // GBP (Pound) Sign
286                 chr(194).chr(163) => '');
287
288                 $string = strtr($string, $chars);
289         } else {
290                 // Assume ISO-8859-1 if not UTF-8
291                 $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
292                         .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
293                         .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
294                         .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
295                         .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
296                         .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
297                         .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
298                         .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
299                         .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
300                         .chr(252).chr(253).chr(255);
301
302                 $chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";
303
304                 $string = strtr($string, $chars['in'], $chars['out']);
305                 $double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
306                 $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
307                 $string = str_replace($double_chars['in'], $double_chars['out'], $string);
308         }
309
310         return $string;
311 }
312
313 function sanitize_file_name( $name ) { // Like sanitize_title, but with periods
314         $name = strtolower( $name );
315         $name = preg_replace('/&.+?;/', '', $name); // kill entities
316         $name = str_replace( '_', '-', $name );
317         $name = preg_replace('/[^a-z0-9\s-.]/', '', $name);
318         $name = preg_replace('/\s+/', '-', $name);
319         $name = preg_replace('|-+|', '-', $name);
320         $name = trim($name, '-');
321         return $name;
322 }
323
324 function sanitize_user( $username, $strict = false ) {
325         $raw_username = $username;
326         $username = strip_tags($username);
327         // Kill octets
328         $username = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '', $username);
329         $username = preg_replace('/&.+?;/', '', $username); // Kill entities
330
331         // If strict, reduce to ASCII for max portability.
332         if ( $strict )
333                 $username = preg_replace('|[^a-z0-9 _.\-@]|i', '', $username);
334
335         // Consolidate contiguous whitespace
336         $username = preg_replace('|\s+|', ' ', $username);
337
338         return apply_filters('sanitize_user', $username, $raw_username, $strict);
339 }
340
341 function sanitize_title($title, $fallback_title = '') {
342         $title = strip_tags($title);
343         $title = apply_filters('sanitize_title', $title);
344
345         if ( '' === $title || false === $title )
346                 $title = $fallback_title;
347
348         return $title;
349 }
350
351 function sanitize_title_with_dashes($title) {
352         $title = strip_tags($title);
353         // Preserve escaped octets.
354         $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
355         // Remove percent signs that are not part of an octet.
356         $title = str_replace('%', '', $title);
357         // Restore octets.
358         $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
359
360         $title = remove_accents($title);
361         if (seems_utf8($title)) {
362                 if (function_exists('mb_strtolower')) {
363                         $title = mb_strtolower($title, 'UTF-8');
364                 }
365                 $title = utf8_uri_encode($title, 200);
366         }
367
368         $title = strtolower($title);
369         $title = preg_replace('/&.+?;/', '', $title); // kill entities
370         $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
371         $title = preg_replace('/\s+/', '-', $title);
372         $title = preg_replace('|-+|', '-', $title);
373         $title = trim($title, '-');
374
375         return $title;
376 }
377
378 // ensures a string is a valid SQL order by clause like: post_name ASC, ID DESC
379 // accepts one or more columns, with or without ASC/DESC, and also accepts RAND()
380 function sanitize_sql_orderby( $orderby ){
381         preg_match('/^\s*([a-z0-9_]+(\s+(ASC|DESC))?(\s*,\s*|\s*$))+|^\s*RAND\(\s*\)\s*$/i', $orderby, $obmatches);
382         if ( !$obmatches )
383                 return false;
384         return $orderby;
385 }
386
387 function convert_chars($content, $deprecated = '') {
388         // Translation of invalid Unicode references range to valid range
389         $wp_htmltranswinuni = array(
390         '&#128;' => '&#8364;', // the Euro sign
391         '&#129;' => '',
392         '&#130;' => '&#8218;', // these are Windows CP1252 specific characters
393         '&#131;' => '&#402;',  // they would look weird on non-Windows browsers
394         '&#132;' => '&#8222;',
395         '&#133;' => '&#8230;',
396         '&#134;' => '&#8224;',
397         '&#135;' => '&#8225;',
398         '&#136;' => '&#710;',
399         '&#137;' => '&#8240;',
400         '&#138;' => '&#352;',
401         '&#139;' => '&#8249;',
402         '&#140;' => '&#338;',
403         '&#141;' => '',
404         '&#142;' => '&#382;',
405         '&#143;' => '',
406         '&#144;' => '',
407         '&#145;' => '&#8216;',
408         '&#146;' => '&#8217;',
409         '&#147;' => '&#8220;',
410         '&#148;' => '&#8221;',
411         '&#149;' => '&#8226;',
412         '&#150;' => '&#8211;',
413         '&#151;' => '&#8212;',
414         '&#152;' => '&#732;',
415         '&#153;' => '&#8482;',
416         '&#154;' => '&#353;',
417         '&#155;' => '&#8250;',
418         '&#156;' => '&#339;',
419         '&#157;' => '',
420         '&#158;' => '',
421         '&#159;' => '&#376;'
422         );
423
424         // Remove metadata tags
425         $content = preg_replace('/<title>(.+?)<\/title>/','',$content);
426         $content = preg_replace('/<category>(.+?)<\/category>/','',$content);
427
428         // Converts lone & characters into &#38; (a.k.a. &amp;)
429         $content = preg_replace('/&([^#])(?![a-z1-4]{1,8};)/i', '&#038;$1', $content);
430
431         // Fix Word pasting
432         $content = strtr($content, $wp_htmltranswinuni);
433
434         // Just a little XHTML help
435         $content = str_replace('<br>', '<br />', $content);
436         $content = str_replace('<hr>', '<hr />', $content);
437
438         return $content;
439 }
440
441 function funky_javascript_fix($text) {
442         // Fixes for browsers' javascript bugs
443         global $is_macIE, $is_winIE;
444
445         if ( $is_winIE || $is_macIE )
446                 $text =  preg_replace("/\%u([0-9A-F]{4,4})/e",  "'&#'.base_convert('\\1',16,10).';'", $text);
447
448         return $text;
449 }
450
451 function balanceTags( $text, $force = false ) {
452         if ( !$force && get_option('use_balanceTags') == 0 )
453                 return $text;
454         return force_balance_tags( $text );
455 }
456
457 /*
458  force_balance_tags
459
460  Balances Tags of string using a modified stack.
461
462  @param text      Text to be balanced
463  @param force     Forces balancing, ignoring the value of the option
464  @return          Returns balanced text
465  @author          Leonard Lin (leonard@acm.org)
466  @version         v1.1
467  @date            November 4, 2001
468  @license         GPL v2.0
469  @notes
470  @changelog
471  ---  Modified by Scott Reilly (coffee2code) 02 Aug 2004
472         1.2  ***TODO*** Make better - change loop condition to $text
473         1.1  Fixed handling of append/stack pop order of end text
474              Added Cleaning Hooks
475         1.0  First Version
476 */
477 function force_balance_tags( $text ) {
478         $tagstack = array(); $stacksize = 0; $tagqueue = ''; $newtext = '';
479         $single_tags = array('br', 'hr', 'img', 'input'); //Known single-entity/self-closing tags
480         $nestable_tags = array('blockquote', 'div', 'span'); //Tags that can be immediately nested within themselves
481
482         # WP bug fix for comments - in case you REALLY meant to type '< !--'
483         $text = str_replace('< !--', '<    !--', $text);
484         # WP bug fix for LOVE <3 (and other situations with '<' before a number)
485         $text = preg_replace('#<([0-9]{1})#', '&lt;$1', $text);
486
487         while (preg_match("/<(\/?\w*)\s*([^>]*)>/",$text,$regex)) {
488                 $newtext .= $tagqueue;
489
490                 $i = strpos($text,$regex[0]);
491                 $l = strlen($regex[0]);
492
493                 // clear the shifter
494                 $tagqueue = '';
495                 // Pop or Push
496                 if ($regex[1][0] == "/") { // End Tag
497                         $tag = strtolower(substr($regex[1],1));
498                         // if too many closing tags
499                         if($stacksize <= 0) {
500                                 $tag = '';
501                                 //or close to be safe $tag = '/' . $tag;
502                         }
503                         // if stacktop value = tag close value then pop
504                         else if ($tagstack[$stacksize - 1] == $tag) { // found closing tag
505                                 $tag = '</' . $tag . '>'; // Close Tag
506                                 // Pop
507                                 array_pop ($tagstack);
508                                 $stacksize--;
509                         } else { // closing tag not at top, search for it
510                                 for ($j=$stacksize-1;$j>=0;$j--) {
511                                         if ($tagstack[$j] == $tag) {
512                                         // add tag to tagqueue
513                                                 for ($k=$stacksize-1;$k>=$j;$k--){
514                                                         $tagqueue .= '</' . array_pop ($tagstack) . '>';
515                                                         $stacksize--;
516                                                 }
517                                                 break;
518                                         }
519                                 }
520                                 $tag = '';
521                         }
522                 } else { // Begin Tag
523                         $tag = strtolower($regex[1]);
524
525                         // Tag Cleaning
526
527                         // If self-closing or '', don't do anything.
528                         if((substr($regex[2],-1) == '/') || ($tag == '')) {
529                         }
530                         // ElseIf it's a known single-entity tag but it doesn't close itself, do so
531                         elseif ( in_array($tag, $single_tags) ) {
532                                 $regex[2] .= '/';
533                         } else {        // Push the tag onto the stack
534                                 // If the top of the stack is the same as the tag we want to push, close previous tag
535                                 if (($stacksize > 0) && !in_array($tag, $nestable_tags) && ($tagstack[$stacksize - 1] == $tag)) {
536                                         $tagqueue = '</' . array_pop ($tagstack) . '>';
537                                         $stacksize--;
538                                 }
539                                 $stacksize = array_push ($tagstack, $tag);
540                         }
541
542                         // Attributes
543                         $attributes = $regex[2];
544                         if($attributes) {
545                                 $attributes = ' '.$attributes;
546                         }
547                         $tag = '<'.$tag.$attributes.'>';
548                         //If already queuing a close tag, then put this tag on, too
549                         if ($tagqueue) {
550                                 $tagqueue .= $tag;
551                                 $tag = '';
552                         }
553                 }
554                 $newtext .= substr($text,0,$i) . $tag;
555                 $text = substr($text,$i+$l);
556         }
557
558         // Clear Tag Queue
559         $newtext .= $tagqueue;
560
561         // Add Remaining text
562         $newtext .= $text;
563
564         // Empty Stack
565         while($x = array_pop($tagstack)) {
566                 $newtext .= '</' . $x . '>'; // Add remaining tags to close
567         }
568
569         // WP fix for the bug with HTML comments
570         $newtext = str_replace("< !--","<!--",$newtext);
571         $newtext = str_replace("<    !--","< !--",$newtext);
572
573         return $newtext;
574 }
575
576 function format_to_edit($content, $richedit = false) {
577         $content = apply_filters('format_to_edit', $content);
578         if (! $richedit )
579                 $content = htmlspecialchars($content);
580         return $content;
581 }
582
583 function format_to_post($content) {
584         $content = apply_filters('format_to_post', $content);
585         return $content;
586 }
587
588 function zeroise($number,$threshold) { // function to add leading zeros when necessary
589         return sprintf('%0'.$threshold.'s', $number);
590 }
591
592
593 function backslashit($string) {
594         $string = preg_replace('/^([0-9])/', '\\\\\\\\\1', $string);
595         $string = preg_replace('/([a-z])/i', '\\\\\1', $string);
596         return $string;
597 }
598
599 function trailingslashit($string) {
600         return untrailingslashit($string) . '/';
601 }
602
603 function untrailingslashit($string) {
604         return rtrim($string, '/');
605 }
606
607 function addslashes_gpc($gpc) {
608         global $wpdb;
609
610         if (get_magic_quotes_gpc()) {
611                 $gpc = stripslashes($gpc);
612         }
613
614         return $wpdb->escape($gpc);
615 }
616
617
618 function stripslashes_deep($value) {
619          $value = is_array($value) ?
620                  array_map('stripslashes_deep', $value) :
621                  stripslashes($value);
622
623          return $value;
624 }
625
626 function urlencode_deep($value) {
627          $value = is_array($value) ?
628                  array_map('urlencode_deep', $value) :
629                  urlencode($value);
630
631          return $value;
632 }
633
634 function antispambot($emailaddy, $mailto=0) {
635         $emailNOSPAMaddy = '';
636         srand ((float) microtime() * 1000000);
637         for ($i = 0; $i < strlen($emailaddy); $i = $i + 1) {
638                 $j = floor(rand(0, 1+$mailto));
639                 if ($j==0) {
640                         $emailNOSPAMaddy .= '&#'.ord(substr($emailaddy,$i,1)).';';
641                 } elseif ($j==1) {
642                         $emailNOSPAMaddy .= substr($emailaddy,$i,1);
643                 } elseif ($j==2) {
644                         $emailNOSPAMaddy .= '%'.zeroise(dechex(ord(substr($emailaddy, $i, 1))), 2);
645                 }
646         }
647         $emailNOSPAMaddy = str_replace('@','&#64;',$emailNOSPAMaddy);
648         return $emailNOSPAMaddy;
649 }
650
651 function _make_url_clickable_cb($matches) {
652         $ret = '';
653         $url = $matches[2];
654         $url = clean_url($url);
655         if ( empty($url) )
656                 return $matches[0];
657         // removed trailing [.,;:] from URL
658         if ( in_array(substr($url, -1), array('.', ',', ';', ':')) === true ) {
659                 $ret = substr($url, -1);
660                 $url = substr($url, 0, strlen($url)-1);
661         }
662         return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $ret;
663 }
664
665 function _make_web_ftp_clickable_cb($matches) {
666         $ret = '';
667         $dest = $matches[2];
668         $dest = 'http://' . $dest;
669         $dest = clean_url($dest);
670         if ( empty($dest) )
671                 return $matches[0];
672         // removed trailing [,;:] from URL
673         if ( in_array(substr($dest, -1), array('.', ',', ';', ':')) === true ) {
674                 $ret = substr($dest, -1);
675                 $dest = substr($dest, 0, strlen($dest)-1);
676         }
677         return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>" . $ret;
678 }
679
680 function _make_email_clickable_cb($matches) {
681         $email = $matches[2] . '@' . $matches[3];
682         return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
683 }
684
685 function make_clickable($ret) {
686         $ret = ' ' . $ret;
687         // in testing, using arrays here was found to be faster
688         $ret = preg_replace_callback('#([\s>])([\w]+?://[\w\#$%&~/.\-;:=,?@\[\]+]*)#is', '_make_url_clickable_cb', $ret);
689         $ret = preg_replace_callback('#([\s>])((www|ftp)\.[\w\#$%&~/.\-;:=,?@\[\]+]*)#is', '_make_web_ftp_clickable_cb', $ret);
690         $ret = preg_replace_callback('#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret);
691         // this one is not in an array because we need it to run last, for cleanup of accidental links within links
692         $ret = preg_replace("#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i", "$1$3</a>", $ret);
693         $ret = trim($ret);
694         return $ret;
695 }
696
697 function wp_rel_nofollow( $text ) {
698         global $wpdb;
699         // This is a pre save filter, so text is already escaped.
700         $text = stripslashes($text);
701         $text = preg_replace_callback('|<a (.+?)>|i', 'wp_rel_nofollow_callback', $text);
702         $text = $wpdb->escape($text);
703         return $text;
704 }
705
706 function wp_rel_nofollow_callback( $matches ) {
707         $text = $matches[1];
708         $text = str_replace(array(' rel="nofollow"', " rel='nofollow'"), '', $text);
709         return "<a $text rel=\"nofollow\">";
710 }
711
712 function convert_smilies($text) {
713         global $wp_smiliessearch, $wp_smiliesreplace;
714     $output = '';
715         if ( get_option('use_smilies') && !empty($wp_smiliessearch) && !empty($wp_smiliesreplace) ) {
716                 // HTML loop taken from texturize function, could possible be consolidated
717                 $textarr = preg_split("/(<.*>)/U", $text, -1, PREG_SPLIT_DELIM_CAPTURE); // capture the tags as well as in between
718                 $stop = count($textarr);// loop stuff
719                 for ($i = 0; $i < $stop; $i++) {
720                         $content = $textarr[$i];
721                         if ((strlen($content) > 0) && ('<' != $content{0})) { // If it's not a tag
722                                 $content = preg_replace($wp_smiliessearch, $wp_smiliesreplace, $content);
723                         }
724                         $output .= $content;
725                 }
726         } else {
727                 // return default text.
728                 $output = $text;
729         }
730         return $output;
731 }
732
733
734 function is_email($user_email) {
735         $chars = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i";
736         if (strpos($user_email, '@') !== false && strpos($user_email, '.') !== false) {
737                 if (preg_match($chars, $user_email)) {
738                         return true;
739                 } else {
740                         return false;
741                 }
742         } else {
743                 return false;
744         }
745 }
746
747 // used by wp-mail to handle charsets in email subjects
748 function wp_iso_descrambler($string) {
749   /* this may only work with iso-8859-1, I'm afraid */
750   if (!preg_match('#\=\?(.+)\?Q\?(.+)\?\=#i', $string, $matches)) {
751     return $string;
752   } else {
753     $subject = str_replace('_', ' ', $matches[2]);
754     $subject = preg_replace('#\=([0-9a-f]{2})#ei', "chr(hexdec(strtolower('$1')))", $subject);
755     return $subject;
756   }
757 }
758
759
760 // give it a date, it will give you the same date as GMT
761 function get_gmt_from_date($string) {
762   // note: this only substracts $time_difference from the given date
763   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);
764   $string_time = gmmktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]);
765   $string_gmt = gmdate('Y-m-d H:i:s', $string_time - get_option('gmt_offset') * 3600);
766   return $string_gmt;
767 }
768
769 // give it a GMT date, it will give you the same date with $time_difference added
770 function get_date_from_gmt($string) {
771   // note: this only adds $time_difference to the given date
772   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);
773   $string_time = gmmktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]);
774   $string_localtime = gmdate('Y-m-d H:i:s', $string_time + get_option('gmt_offset')*3600);
775   return $string_localtime;
776 }
777
778 // computes an offset in seconds from an iso8601 timezone
779 function iso8601_timezone_to_offset($timezone) {
780   // $timezone is either 'Z' or '[+|-]hhmm'
781   if ($timezone == 'Z') {
782     $offset = 0;
783   } else {
784     $sign    = (substr($timezone, 0, 1) == '+') ? 1 : -1;
785     $hours   = intval(substr($timezone, 1, 2));
786     $minutes = intval(substr($timezone, 3, 4)) / 60;
787     $offset  = $sign * 3600 * ($hours + $minutes);
788   }
789   return $offset;
790 }
791
792 // converts an iso8601 date to MySQL DateTime format used by post_date[_gmt]
793 function iso8601_to_datetime($date_string, $timezone = USER) {
794   if ($timezone == GMT) {
795     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);
796     if (!empty($date_bits[7])) { // we have a timezone, so let's compute an offset
797       $offset = iso8601_timezone_to_offset($date_bits[7]);
798     } else { // we don't have a timezone, so we assume user local timezone (not server's!)
799       $offset = 3600 * get_option('gmt_offset');
800     }
801     $timestamp = gmmktime($date_bits[4], $date_bits[5], $date_bits[6], $date_bits[2], $date_bits[3], $date_bits[1]);
802     $timestamp -= $offset;
803     return gmdate('Y-m-d H:i:s', $timestamp);
804   } elseif ($timezone == USER) {
805     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);
806   }
807 }
808
809 function popuplinks($text) {
810         // Comment text in popup windows should be filtered through this.
811         // Right now it's a moderately dumb function, ideally it would detect whether
812         // a target or rel attribute was already there and adjust its actions accordingly.
813         $text = preg_replace('/<a (.+?)>/i', "<a $1 target='_blank' rel='external'>", $text);
814         return $text;
815 }
816
817 function sanitize_email($email) {
818         return preg_replace('/[^a-z0-9+_.@-]/i', '', $email);
819 }
820
821 function human_time_diff( $from, $to = '' ) {
822         if ( empty($to) )
823                 $to = time();
824         $diff = (int) abs($to - $from);
825         if ($diff <= 3600) {
826                 $mins = round($diff / 60);
827                 if ($mins <= 1) {
828                         $mins = 1;
829                 }
830                 $since = sprintf(__ngettext('%s min', '%s mins', $mins), $mins);
831         } else if (($diff <= 86400) && ($diff > 3600)) {
832                 $hours = round($diff / 3600);
833                 if ($hours <= 1) {
834                         $hours = 1;
835                 }
836                 $since = sprintf(__ngettext('%s hour', '%s hours', $hours), $hours);
837         } elseif ($diff >= 86400) {
838                 $days = round($diff / 86400);
839                 if ($days <= 1) {
840                         $days = 1;
841                 }
842                 $since = sprintf(__ngettext('%s day', '%s days', $days), $days);
843         }
844         return $since;
845 }
846
847 function wp_trim_excerpt($text) { // Fakes an excerpt if needed
848         if ( '' == $text ) {
849                 $text = get_the_content('');
850                 
851                 $text = strip_shortcodes( $text ); 
852                 
853                 $text = apply_filters('the_content', $text);
854                 $text = str_replace(']]>', ']]&gt;', $text);
855                 $text = strip_tags($text);
856                 $excerpt_length = 55;
857                 $words = explode(' ', $text, $excerpt_length + 1);
858                 if (count($words) > $excerpt_length) {
859                         array_pop($words);
860                         array_push($words, '[...]');
861                         $text = implode(' ', $words);
862                 }
863         }
864         return $text;
865 }
866
867 function ent2ncr($text) {
868         $to_ncr = array(
869                 '&quot;' => '&#34;',
870                 '&amp;' => '&#38;',
871                 '&frasl;' => '&#47;',
872                 '&lt;' => '&#60;',
873                 '&gt;' => '&#62;',
874                 '|' => '&#124;',
875                 '&nbsp;' => '&#160;',
876                 '&iexcl;' => '&#161;',
877                 '&cent;' => '&#162;',
878                 '&pound;' => '&#163;',
879                 '&curren;' => '&#164;',
880                 '&yen;' => '&#165;',
881                 '&brvbar;' => '&#166;',
882                 '&brkbar;' => '&#166;',
883                 '&sect;' => '&#167;',
884                 '&uml;' => '&#168;',
885                 '&die;' => '&#168;',
886                 '&copy;' => '&#169;',
887                 '&ordf;' => '&#170;',
888                 '&laquo;' => '&#171;',
889                 '&not;' => '&#172;',
890                 '&shy;' => '&#173;',
891                 '&reg;' => '&#174;',
892                 '&macr;' => '&#175;',
893                 '&hibar;' => '&#175;',
894                 '&deg;' => '&#176;',
895                 '&plusmn;' => '&#177;',
896                 '&sup2;' => '&#178;',
897                 '&sup3;' => '&#179;',
898                 '&acute;' => '&#180;',
899                 '&micro;' => '&#181;',
900                 '&para;' => '&#182;',
901                 '&middot;' => '&#183;',
902                 '&cedil;' => '&#184;',
903                 '&sup1;' => '&#185;',
904                 '&ordm;' => '&#186;',
905                 '&raquo;' => '&#187;',
906                 '&frac14;' => '&#188;',
907                 '&frac12;' => '&#189;',
908                 '&frac34;' => '&#190;',
909                 '&iquest;' => '&#191;',
910                 '&Agrave;' => '&#192;',
911                 '&Aacute;' => '&#193;',
912                 '&Acirc;' => '&#194;',
913                 '&Atilde;' => '&#195;',
914                 '&Auml;' => '&#196;',
915                 '&Aring;' => '&#197;',
916                 '&AElig;' => '&#198;',
917                 '&Ccedil;' => '&#199;',
918                 '&Egrave;' => '&#200;',
919                 '&Eacute;' => '&#201;',
920                 '&Ecirc;' => '&#202;',
921                 '&Euml;' => '&#203;',
922                 '&Igrave;' => '&#204;',
923                 '&Iacute;' => '&#205;',
924                 '&Icirc;' => '&#206;',
925                 '&Iuml;' => '&#207;',
926                 '&ETH;' => '&#208;',
927                 '&Ntilde;' => '&#209;',
928                 '&Ograve;' => '&#210;',
929                 '&Oacute;' => '&#211;',
930                 '&Ocirc;' => '&#212;',
931                 '&Otilde;' => '&#213;',
932                 '&Ouml;' => '&#214;',
933                 '&times;' => '&#215;',
934                 '&Oslash;' => '&#216;',
935                 '&Ugrave;' => '&#217;',
936                 '&Uacute;' => '&#218;',
937                 '&Ucirc;' => '&#219;',
938                 '&Uuml;' => '&#220;',
939                 '&Yacute;' => '&#221;',
940                 '&THORN;' => '&#222;',
941                 '&szlig;' => '&#223;',
942                 '&agrave;' => '&#224;',
943                 '&aacute;' => '&#225;',
944                 '&acirc;' => '&#226;',
945                 '&atilde;' => '&#227;',
946                 '&auml;' => '&#228;',
947                 '&aring;' => '&#229;',
948                 '&aelig;' => '&#230;',
949                 '&ccedil;' => '&#231;',
950                 '&egrave;' => '&#232;',
951                 '&eacute;' => '&#233;',
952                 '&ecirc;' => '&#234;',
953                 '&euml;' => '&#235;',
954                 '&igrave;' => '&#236;',
955                 '&iacute;' => '&#237;',
956                 '&icirc;' => '&#238;',
957                 '&iuml;' => '&#239;',
958                 '&eth;' => '&#240;',
959                 '&ntilde;' => '&#241;',
960                 '&ograve;' => '&#242;',
961                 '&oacute;' => '&#243;',
962                 '&ocirc;' => '&#244;',
963                 '&otilde;' => '&#245;',
964                 '&ouml;' => '&#246;',
965                 '&divide;' => '&#247;',
966                 '&oslash;' => '&#248;',
967                 '&ugrave;' => '&#249;',
968                 '&uacute;' => '&#250;',
969                 '&ucirc;' => '&#251;',
970                 '&uuml;' => '&#252;',
971                 '&yacute;' => '&#253;',
972                 '&thorn;' => '&#254;',
973                 '&yuml;' => '&#255;',
974                 '&OElig;' => '&#338;',
975                 '&oelig;' => '&#339;',
976                 '&Scaron;' => '&#352;',
977                 '&scaron;' => '&#353;',
978                 '&Yuml;' => '&#376;',
979                 '&fnof;' => '&#402;',
980                 '&circ;' => '&#710;',
981                 '&tilde;' => '&#732;',
982                 '&Alpha;' => '&#913;',
983                 '&Beta;' => '&#914;',
984                 '&Gamma;' => '&#915;',
985                 '&Delta;' => '&#916;',
986                 '&Epsilon;' => '&#917;',
987                 '&Zeta;' => '&#918;',
988                 '&Eta;' => '&#919;',
989                 '&Theta;' => '&#920;',
990                 '&Iota;' => '&#921;',
991                 '&Kappa;' => '&#922;',
992                 '&Lambda;' => '&#923;',
993                 '&Mu;' => '&#924;',
994                 '&Nu;' => '&#925;',
995                 '&Xi;' => '&#926;',
996                 '&Omicron;' => '&#927;',
997                 '&Pi;' => '&#928;',
998                 '&Rho;' => '&#929;',
999                 '&Sigma;' => '&#931;',
1000                 '&Tau;' => '&#932;',
1001                 '&Upsilon;' => '&#933;',
1002                 '&Phi;' => '&#934;',
1003                 '&Chi;' => '&#935;',
1004                 '&Psi;' => '&#936;',
1005                 '&Omega;' => '&#937;',
1006                 '&alpha;' => '&#945;',
1007                 '&beta;' => '&#946;',
1008                 '&gamma;' => '&#947;',
1009                 '&delta;' => '&#948;',
1010                 '&epsilon;' => '&#949;',
1011                 '&zeta;' => '&#950;',
1012                 '&eta;' => '&#951;',
1013                 '&theta;' => '&#952;',
1014                 '&iota;' => '&#953;',
1015                 '&kappa;' => '&#954;',
1016                 '&lambda;' => '&#955;',
1017                 '&mu;' => '&#956;',
1018                 '&nu;' => '&#957;',
1019                 '&xi;' => '&#958;',
1020                 '&omicron;' => '&#959;',
1021                 '&pi;' => '&#960;',
1022                 '&rho;' => '&#961;',
1023                 '&sigmaf;' => '&#962;',
1024                 '&sigma;' => '&#963;',
1025                 '&tau;' => '&#964;',
1026                 '&upsilon;' => '&#965;',
1027                 '&phi;' => '&#966;',
1028                 '&chi;' => '&#967;',
1029                 '&psi;' => '&#968;',
1030                 '&omega;' => '&#969;',
1031                 '&thetasym;' => '&#977;',
1032                 '&upsih;' => '&#978;',
1033                 '&piv;' => '&#982;',
1034                 '&ensp;' => '&#8194;',
1035                 '&emsp;' => '&#8195;',
1036                 '&thinsp;' => '&#8201;',
1037                 '&zwnj;' => '&#8204;',
1038                 '&zwj;' => '&#8205;',
1039                 '&lrm;' => '&#8206;',
1040                 '&rlm;' => '&#8207;',
1041                 '&ndash;' => '&#8211;',
1042                 '&mdash;' => '&#8212;',
1043                 '&lsquo;' => '&#8216;',
1044                 '&rsquo;' => '&#8217;',
1045                 '&sbquo;' => '&#8218;',
1046                 '&ldquo;' => '&#8220;',
1047                 '&rdquo;' => '&#8221;',
1048                 '&bdquo;' => '&#8222;',
1049                 '&dagger;' => '&#8224;',
1050                 '&Dagger;' => '&#8225;',
1051                 '&bull;' => '&#8226;',
1052                 '&hellip;' => '&#8230;',
1053                 '&permil;' => '&#8240;',
1054                 '&prime;' => '&#8242;',
1055                 '&Prime;' => '&#8243;',
1056                 '&lsaquo;' => '&#8249;',
1057                 '&rsaquo;' => '&#8250;',
1058                 '&oline;' => '&#8254;',
1059                 '&frasl;' => '&#8260;',
1060                 '&euro;' => '&#8364;',
1061                 '&image;' => '&#8465;',
1062                 '&weierp;' => '&#8472;',
1063                 '&real;' => '&#8476;',
1064                 '&trade;' => '&#8482;',
1065                 '&alefsym;' => '&#8501;',
1066                 '&crarr;' => '&#8629;',
1067                 '&lArr;' => '&#8656;',
1068                 '&uArr;' => '&#8657;',
1069                 '&rArr;' => '&#8658;',
1070                 '&dArr;' => '&#8659;',
1071                 '&hArr;' => '&#8660;',
1072                 '&forall;' => '&#8704;',
1073                 '&part;' => '&#8706;',
1074                 '&exist;' => '&#8707;',
1075                 '&empty;' => '&#8709;',
1076                 '&nabla;' => '&#8711;',
1077                 '&isin;' => '&#8712;',
1078                 '&notin;' => '&#8713;',
1079                 '&ni;' => '&#8715;',
1080                 '&prod;' => '&#8719;',
1081                 '&sum;' => '&#8721;',
1082                 '&minus;' => '&#8722;',
1083                 '&lowast;' => '&#8727;',
1084                 '&radic;' => '&#8730;',
1085                 '&prop;' => '&#8733;',
1086                 '&infin;' => '&#8734;',
1087                 '&ang;' => '&#8736;',
1088                 '&and;' => '&#8743;',
1089                 '&or;' => '&#8744;',
1090                 '&cap;' => '&#8745;',
1091                 '&cup;' => '&#8746;',
1092                 '&int;' => '&#8747;',
1093                 '&there4;' => '&#8756;',
1094                 '&sim;' => '&#8764;',
1095                 '&cong;' => '&#8773;',
1096                 '&asymp;' => '&#8776;',
1097                 '&ne;' => '&#8800;',
1098                 '&equiv;' => '&#8801;',
1099                 '&le;' => '&#8804;',
1100                 '&ge;' => '&#8805;',
1101                 '&sub;' => '&#8834;',
1102                 '&sup;' => '&#8835;',
1103                 '&nsub;' => '&#8836;',
1104                 '&sube;' => '&#8838;',
1105                 '&supe;' => '&#8839;',
1106                 '&oplus;' => '&#8853;',
1107                 '&otimes;' => '&#8855;',
1108                 '&perp;' => '&#8869;',
1109                 '&sdot;' => '&#8901;',
1110                 '&lceil;' => '&#8968;',
1111                 '&rceil;' => '&#8969;',
1112                 '&lfloor;' => '&#8970;',
1113                 '&rfloor;' => '&#8971;',
1114                 '&lang;' => '&#9001;',
1115                 '&rang;' => '&#9002;',
1116                 '&larr;' => '&#8592;',
1117                 '&uarr;' => '&#8593;',
1118                 '&rarr;' => '&#8594;',
1119                 '&darr;' => '&#8595;',
1120                 '&harr;' => '&#8596;',
1121                 '&loz;' => '&#9674;',
1122                 '&spades;' => '&#9824;',
1123                 '&clubs;' => '&#9827;',
1124                 '&hearts;' => '&#9829;',
1125                 '&diams;' => '&#9830;'
1126         );
1127
1128         return str_replace( array_keys($to_ncr), array_values($to_ncr), $text );
1129 }
1130
1131 function wp_richedit_pre($text) {
1132         // Filtering a blank results in an annoying <br />\n
1133         if ( empty($text) ) return apply_filters('richedit_pre', '');
1134
1135         $output = convert_chars($text);
1136         $output = wpautop($output);
1137         $output = htmlspecialchars($output, ENT_NOQUOTES);
1138
1139         return apply_filters('richedit_pre', $output);
1140 }
1141
1142 function wp_htmledit_pre($output) {
1143         if ( !empty($output) )
1144                 $output = htmlspecialchars($output, ENT_NOQUOTES); // convert only < > &
1145
1146         return apply_filters('htmledit_pre', $output);
1147 }
1148
1149 function clean_url( $url, $protocols = null, $context = 'display' ) {
1150         $original_url = $url;
1151
1152         if ('' == $url) return $url;
1153         $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@()]|i', '', $url);
1154         $strip = array('%0d', '%0a');
1155         $url = str_replace($strip, '', $url);
1156         $url = str_replace(';//', '://', $url);
1157         /* If the URL doesn't appear to contain a scheme, we
1158          * presume it needs http:// appended (unless a relative
1159          * link starting with / or a php file).
1160         */
1161         if ( strpos($url, ':') === false &&
1162                 substr( $url, 0, 1 ) != '/' && !preg_match('/^[a-z0-9-]+?\.php/i', $url) )
1163                 $url = 'http://' . $url;
1164
1165         // Replace ampersands ony when displaying.
1166         if ( 'display' == $context )
1167                 $url = preg_replace('/&([^#])(?![a-z]{2,8};)/', '&#038;$1', $url);
1168
1169         if ( !is_array($protocols) )
1170                 $protocols = array('http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet');
1171         if ( wp_kses_bad_protocol( $url, $protocols ) != $url )
1172                 return '';
1173
1174         return apply_filters('clean_url', $url, $original_url, $context);
1175 }
1176
1177 function sanitize_url( $url, $protocols = null ) {
1178         return clean_url( $url, $protocols, 'db');
1179 }
1180
1181 // Borrowed from the PHP Manual user notes. Convert entities, while
1182 // preserving already-encoded entities:
1183 function htmlentities2($myHTML) {
1184         $translation_table=get_html_translation_table (HTML_ENTITIES,ENT_QUOTES);
1185         $translation_table[chr(38)] = '&';
1186         return preg_replace("/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/","&amp;" , strtr($myHTML, $translation_table));
1187 }
1188
1189 // Escape single quotes, specialchar double quotes, and fix line endings.
1190 function js_escape($text) {
1191         $safe_text = wp_specialchars($text, 'double');
1192         $safe_text = preg_replace('/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes($safe_text));
1193         $safe_text = preg_replace("/\r?\n/", "\\n", addslashes($safe_text));
1194         return apply_filters('js_escape', $safe_text, $text);
1195 }
1196
1197 // Escaping for HTML attributes
1198 function attribute_escape($text) {
1199         $safe_text = wp_specialchars($text, true);
1200         return apply_filters('attribute_escape', $safe_text, $text);
1201 }
1202
1203 // Escape a HTML tag name
1204 function tag_escape($tag_name) {
1205         $safe_tag = strtolower( preg_replace('[^a-zA-Z_:]', '', $tag_name) );
1206         return apply_filters('tag_escape', $safe_tag, $tag_name);
1207 }
1208
1209 /**
1210  * Escapes text for SQL LIKE special characters % and _
1211  *
1212  * @param string text the text to be escaped
1213  * @return string text, safe for inclusion in LIKE query
1214  */
1215 function like_escape($text) {
1216         return str_replace(array("%", "_"), array("\\%", "\\_"), $text);
1217 }
1218
1219 function wp_make_link_relative( $link ) {
1220         return preg_replace('|https?://[^/]+(/.*)|i', '$1', $link );
1221 }
1222
1223 function sanitize_option($option, $value) { // Remember to call stripslashes!
1224
1225         switch ($option) {
1226                 case 'admin_email':
1227                         $value = sanitize_email($value);
1228                         break;
1229
1230                 case 'default_post_edit_rows':
1231                 case 'mailserver_port':
1232                 case 'comment_max_links':
1233                 case 'page_on_front':
1234                 case 'rss_excerpt_length':
1235                 case 'default_category':
1236                 case 'default_email_category':
1237                 case 'default_link_category':
1238                         $value = abs((int) $value);
1239                         break;
1240
1241                 case 'posts_per_page':
1242                 case 'posts_per_rss':
1243                         $value = (int) $value;
1244                         if ( empty($value) ) $value = 1;
1245                         if ( $value < -1 ) $value = abs($value);
1246                         break;
1247
1248                 case 'default_ping_status':
1249                 case 'default_comment_status':
1250                         // Options that if not there have 0 value but need to be something like "closed"
1251                         if ( $value == '0' || $value == '')
1252                                 $value = 'closed';
1253                         break;
1254
1255                 case 'blogdescription':
1256                 case 'blogname':
1257                         $value = addslashes($value);
1258                         $value = wp_filter_post_kses( $value ); // calls stripslashes then addslashes
1259                         $value = stripslashes($value);
1260                         $value = wp_specialchars( $value );
1261                         break;
1262
1263                 case 'blog_charset':
1264                         $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value); // strips slashes
1265                         break;
1266
1267                 case 'date_format':
1268                 case 'time_format':
1269                 case 'mailserver_url':
1270                 case 'mailserver_login':
1271                 case 'mailserver_pass':
1272                 case 'ping_sites':
1273                 case 'upload_path':
1274                         $value = strip_tags($value);
1275                         $value = addslashes($value);
1276                         $value = wp_filter_kses($value); // calls stripslashes then addslashes
1277                         $value = stripslashes($value);
1278                         break;
1279
1280                 case 'gmt_offset':
1281                         $value = preg_replace('/[^0-9:.-]/', '', $value); // strips slashes
1282                         break;
1283
1284                 case 'siteurl':
1285                 case 'home':
1286                         $value = stripslashes($value);
1287                         $value = clean_url($value);
1288                         break;
1289                 default :
1290                         $value = apply_filters("sanitize_option_{$option}", $value, $option);
1291                         break;
1292         }
1293
1294         return $value;
1295 }
1296
1297 function wp_parse_str( $string, &$array ) {
1298         parse_str( $string, $array );
1299         if ( get_magic_quotes_gpc() )
1300                 $array = stripslashes_deep( $array ); // parse_str() adds slashes if magicquotes is on.  See: http://php.net/parse_str
1301         $array = apply_filters( 'wp_parse_str', $array );
1302 }
1303
1304 // Convert lone less than signs.  KSES already converts lone greater than signs.
1305 function wp_pre_kses_less_than( $text ) {
1306         return preg_replace_callback('%<[^>]*?((?=<)|>|$)%', 'wp_pre_kses_less_than_callback', $text);
1307 }
1308
1309 function wp_pre_kses_less_than_callback( $matches ) {
1310         if ( false === strpos($matches[0], '>') )
1311                 return wp_specialchars($matches[0]);
1312         return $matches[0];
1313 }
1314
1315 /**
1316  * wp_sprintf() - sprintf() with filters
1317  */
1318 function wp_sprintf( $pattern ) {
1319         $args = func_get_args( );
1320         $len = strlen($pattern);
1321         $start = 0;
1322         $result = '';
1323         $arg_index = 0;
1324         while ( $len > $start ) {
1325                 // Last character: append and break
1326                 if ( strlen($pattern) - 1 == $start ) {
1327                         $result .= substr($pattern, -1);
1328                         break;
1329                 }
1330
1331                 // Literal %: append and continue
1332                 if ( substr($pattern, $start, 2) == '%%' ) {
1333                         $start += 2;
1334                         $result .= '%';
1335                         continue;
1336                 }
1337
1338                 // Get fragment before next %
1339                 $end = strpos($pattern, '%', $start + 1);
1340                 if ( false === $end )
1341                         $end = $len;
1342                 $fragment = substr($pattern, $start, $end - $start);
1343
1344                 // Fragment has a specifier
1345                 if ( $pattern{$start} == '%' ) {
1346                         // Find numbered arguments or take the next one in order
1347                         if ( preg_match('/^%(\d+)\$/', $fragment, $matches) ) {
1348                                 $arg = isset($args[$matches[1]]) ? $args[$matches[1]] : '';
1349                                 $fragment = str_replace("%{$matches[1]}$", '%', $fragment);
1350                         } else {
1351                                 ++$arg_index;
1352                                 $arg = isset($args[$arg_index]) ? $args[$arg_index] : '';
1353                         }
1354
1355                         // Apply filters OR sprintf
1356                         $_fragment = apply_filters( 'wp_sprintf', $fragment, $arg );
1357                         if ( $_fragment != $fragment )
1358                                 $fragment = $_fragment;
1359                         else
1360                                 $fragment = sprintf($fragment, strval($arg) );
1361                 }
1362
1363                 // Append to result and move to next fragment
1364                 $result .= $fragment;
1365                 $start = $end;
1366         }
1367         return $result;
1368 }
1369
1370 /**
1371  * wp_sprintf_l - List specifier %l for wp_sprintf
1372  *
1373  * @param unknown_type $pattern
1374  * @param unknown_type $args
1375  * @return unknown
1376  */
1377 function wp_sprintf_l($pattern, $args) {
1378         // Not a match
1379         if ( substr($pattern, 0, 2) != '%l' )
1380                 return $pattern;
1381
1382         // Nothing to work with
1383         if ( empty($args) )
1384                 return '';
1385
1386         // Translate and filter the delimiter set (avoid ampersands and entities here)
1387         $l = apply_filters('wp_sprintf_l', array(
1388                 'between'          => _c(', |between list items'),
1389                 'between_last_two' => _c(', and |between last two list items'),
1390                 'between_only_two' => _c(' and |between only two list items'),
1391                 ));
1392
1393         $args = (array) $args;
1394         $result = array_shift($args);
1395         if ( count($args) == 1 )
1396                 $result .= $l['between_only_two'] . array_shift($args);
1397         // Loop when more than two args
1398         while ( count($args) ) {
1399                 $arg = array_shift($args);
1400                 if ( $i == 1 )
1401                         $result .= $l['between_last_two'] . $arg;
1402                 else
1403                         $result .= $l['between'] . $arg;
1404         }
1405         return $result . substr($pattern, 2);
1406 }
1407
1408 /**
1409  * Safely extracts not more than the first $count characters from html string
1410  *
1411  * UTF-8, tags and entities safe prefix extraction. Entities inside will *NOT* be
1412  * counted as one character. For example &amp; will be counted as 4, &lt; as 3, etc.
1413  *
1414  * @param integer $str String to get the excerpt from
1415  * @param integer $count Maximum number of characters to take
1416  * @eaturn string the excerpt
1417  */
1418 function wp_html_excerpt( $str, $count ) {
1419         $str = strip_tags( $str );
1420         $str = mb_strcut( $str, 0, $count );
1421         // remove part of an entity at the end
1422         $str = preg_replace( '/&[^;\s]{0,6}$/', '', $str );
1423         return $str;
1424 }
1425
1426 ?>