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