OSDN Git Service

BugTrack/2392 Fix encoding: die_message() outputs suitable charset
[pukiwiki/pukiwiki.git] / lib / func.php
1 <?php
2 // PukiWiki - Yet another WikiWikiWeb clone.
3 // $Id: func.php,v 1.104 2011/01/25 15:01:01 henoheno Exp $
4 // Copyright (C)
5 //   2002-2006 PukiWiki Developers Team
6 //   2001-2002 Originally written by yu-ji
7 // License: GPL v2 or (at your option) any later version
8 //
9 // General functions
10
11 function is_interwiki($str)
12 {
13         global $InterWikiName;
14         return preg_match('/^' . $InterWikiName . '$/', $str);
15 }
16
17 function is_pagename($str)
18 {
19         global $BracketName;
20
21         $is_pagename = (! is_interwiki($str) &&
22                   preg_match('/^(?!\/)' . $BracketName . '$(?<!\/$)/', $str) &&
23                 ! preg_match('#(^|/)\.{1,2}(/|$)#', $str));
24
25         if (defined('SOURCE_ENCODING')) {
26                 switch(SOURCE_ENCODING){
27                 case 'UTF-8': $pattern =
28                         '/^(?:[\x00-\x7F]|(?:[\xC0-\xDF][\x80-\xBF])|(?:[\xE0-\xEF][\x80-\xBF][\x80-\xBF]))+$/';
29                         break;
30                 case 'EUC-JP': $pattern =
31                         '/^(?:[\x00-\x7F]|(?:[\x8E\xA1-\xFE][\xA1-\xFE])|(?:\x8F[\xA1-\xFE][\xA1-\xFE]))+$/';
32                         break;
33                 }
34                 if (isset($pattern) && $pattern != '')
35                         $is_pagename = ($is_pagename && preg_match($pattern, $str));
36         }
37
38         return $is_pagename;
39 }
40
41 function is_url($str, $only_http = FALSE)
42 {
43         $scheme = $only_http ? 'https?' : 'https?|ftp|news';
44         return preg_match('/^(' . $scheme . ')(:\/\/[-_.!~*\'()a-zA-Z0-9;\/?:\@&=+\$,%#]*)$/', $str);
45 }
46
47 // If the page exists
48 function is_page($page, $clearcache = FALSE)
49 {
50         if ($clearcache) clearstatcache();
51         return file_exists(get_filename($page));
52 }
53
54 function is_editable($page)
55 {
56         global $cantedit;
57         static $is_editable = array();
58
59         if (! isset($is_editable[$page])) {
60                 $is_editable[$page] = (
61                         is_pagename($page) &&
62                         ! is_freeze($page) &&
63                         ! in_array($page, $cantedit)
64                 );
65         }
66
67         return $is_editable[$page];
68 }
69
70 function is_freeze($page, $clearcache = FALSE)
71 {
72         global $function_freeze;
73         static $is_freeze = array();
74
75         if ($clearcache === TRUE) $is_freeze = array();
76         if (isset($is_freeze[$page])) return $is_freeze[$page];
77
78         if (! $function_freeze || ! is_page($page)) {
79                 $is_freeze[$page] = FALSE;
80                 return FALSE;
81         } else {
82                 $fp = fopen(get_filename($page), 'rb') or
83                         die('is_freeze(): fopen() failed: ' . htmlsc($page));
84                 flock($fp, LOCK_SH) or die('is_freeze(): flock() failed');
85                 rewind($fp);
86                 $buffer = fgets($fp, 9);
87                 flock($fp, LOCK_UN) or die('is_freeze(): flock() failed');
88                 fclose($fp) or die('is_freeze(): fclose() failed: ' . htmlsc($page));
89
90                 $is_freeze[$page] = ($buffer != FALSE && rtrim($buffer, "\r\n") == '#freeze');
91                 return $is_freeze[$page];
92         }
93 }
94
95 // Handling $non_list
96 // $non_list will be preg_quote($str, '/') later.
97 function check_non_list($page = '')
98 {
99         global $non_list;
100         static $regex;
101
102         if (! isset($regex)) $regex = '/' . $non_list . '/';
103
104         return preg_match($regex, $page);
105 }
106
107 // Auto template
108 function auto_template($page)
109 {
110         global $auto_template_func, $auto_template_rules;
111
112         if (! $auto_template_func) return '';
113
114         $body = '';
115         $matches = array();
116         foreach ($auto_template_rules as $rule => $template) {
117                 $rule_pattrn = '/' . $rule . '/';
118
119                 if (! preg_match($rule_pattrn, $page, $matches)) continue;
120
121                 $template_page = preg_replace($rule_pattrn, $template, $page);
122                 if (! is_page($template_page)) continue;
123
124                 $body = join('', get_source($template_page));
125
126                 // Remove fixed-heading anchors
127                 $body = preg_replace('/^(\*{1,3}.*)\[#[A-Za-z][\w-]+\](.*)$/m', '$1$2', $body);
128
129                 // Remove '#freeze'
130                 $body = preg_replace('/^#freeze\s*$/m', '', $body);
131
132                 $count = count($matches);
133                 for ($i = 0; $i < $count; $i++)
134                         $body = str_replace('$' . $i, $matches[$i], $body);
135
136                 break;
137         }
138         return $body;
139 }
140
141 // Expand all search-words to regexes and push them into an array
142 function get_search_words($words = array(), $do_escape = FALSE)
143 {
144         static $init, $mb_convert_kana, $pre, $post, $quote = '/';
145
146         if (! isset($init)) {
147                 // function: mb_convert_kana() is for Japanese code only
148                 if (LANG == 'ja' && function_exists('mb_convert_kana')) {
149                         $mb_convert_kana = create_function('$str, $option',
150                                 'return mb_convert_kana($str, $option, SOURCE_ENCODING);');
151                 } else {
152                         $mb_convert_kana = create_function('$str, $option',
153                                 'return $str;');
154                 }
155                 if (SOURCE_ENCODING == 'EUC-JP') {
156                         // Perl memo - Correct pattern-matching with EUC-JP
157                         // http://www.din.or.jp/~ohzaki/perl.htm#JP_Match (Japanese)
158                         $pre  = '(?<!\x8F)';
159                         $post = '(?=(?:[\xA1-\xFE][\xA1-\xFE])*' . // JIS X 0208
160                                 '(?:[\x00-\x7F\x8E\x8F]|\z))';     // ASCII, SS2, SS3, or the last
161                 } else {
162                         $pre = $post = '';
163                 }
164                 $init = TRUE;
165         }
166
167         if (! is_array($words)) $words = array($words);
168
169         // Generate regex for the words
170         $regex = array();
171         foreach ($words as $word) {
172                 $word = trim($word);
173                 if ($word == '') continue;
174
175                 // Normalize: ASCII letters = to single-byte. Others = to Zenkaku and Katakana
176                 $word_nm = $mb_convert_kana($word, 'aKCV');
177                 $nmlen   = mb_strlen($word_nm, SOURCE_ENCODING);
178
179                 // Each chars may be served ...
180                 $chars = array();
181                 for ($pos = 0; $pos < $nmlen; $pos++) {
182                         $char = mb_substr($word_nm, $pos, 1, SOURCE_ENCODING);
183
184                         // Just normalized one? (ASCII char or Zenkaku-Katakana?)
185                         $or = array(preg_quote($do_escape ? htmlsc($char) : $char, $quote));
186                         if (strlen($char) == 1) {
187                                 // An ASCII (single-byte) character
188                                 foreach (array(strtoupper($char), strtolower($char)) as $_char) {
189                                         if ($char != '&') $or[] = preg_quote($_char, $quote); // As-is?
190                                         $ascii = ord($_char);
191                                         $or[] = sprintf('&#(?:%d|x%x);', $ascii, $ascii); // As an entity reference?
192                                         $or[] = preg_quote($mb_convert_kana($_char, 'A'), $quote); // As Zenkaku?
193                                 }
194                         } else {
195                                 // NEVER COME HERE with mb_substr(string, start, length, 'ASCII')
196                                 // A multi-byte character
197                                 $or[] = preg_quote($mb_convert_kana($char, 'c'), $quote); // As Hiragana?
198                                 $or[] = preg_quote($mb_convert_kana($char, 'k'), $quote); // As Hankaku-Katakana?
199                         }
200                         $chars[] = '(?:' . join('|', array_unique($or)) . ')'; // Regex for the character
201                 }
202
203                 $regex[$word] = $pre . join('', $chars) . $post; // For the word
204         }
205
206         return $regex; // For all words
207 }
208
209 // 'Search' main function
210 function do_search($word, $type = 'AND', $non_format = FALSE, $base = '')
211 {
212         global $script, $whatsnew, $non_list, $search_non_list;
213         global $_msg_andresult, $_msg_orresult, $_msg_notfoundresult;
214         global $search_auth, $show_passage;
215
216         $retval = array();
217
218         $b_type = ($type == 'AND'); // AND:TRUE OR:FALSE
219         $keys = get_search_words(preg_split('/\s+/', $word, -1, PREG_SPLIT_NO_EMPTY));
220         foreach ($keys as $key=>$value)
221                 $keys[$key] = '/' . $value . '/S';
222
223         $pages = get_existpages();
224
225         // Avoid
226         if ($base != '') {
227                 $pages = preg_grep('/^' . preg_quote($base, '/') . '/S', $pages);
228         }
229         if (! $search_non_list) {
230                 $pages = array_diff($pages, preg_grep('/' . $non_list . '/S', $pages));
231         }
232         $pages = array_flip($pages);
233         unset($pages[$whatsnew]);
234
235         $count = count($pages);
236         foreach (array_keys($pages) as $page) {
237                 $b_match = FALSE;
238
239                 // Search for page name
240                 if (! $non_format) {
241                         foreach ($keys as $key) {
242                                 $b_match = preg_match($key, $page);
243                                 if ($b_type xor $b_match) break; // OR
244                         }
245                         if ($b_match) continue;
246                 }
247
248                 // Search auth for page contents
249                 if ($search_auth && ! check_readable($page, false, false)) {
250                         unset($pages[$page]);
251                         --$count;
252                 }
253
254                 // Search for page contents
255                 foreach ($keys as $key) {
256                         $b_match = preg_match($key, get_source($page, TRUE, TRUE));
257                         if ($b_type xor $b_match) break; // OR
258                 }
259                 if ($b_match) continue;
260
261                 unset($pages[$page]); // Miss
262         }
263         if ($non_format) return array_keys($pages);
264
265         $r_word = rawurlencode($word);
266         $s_word = htmlsc($word);
267         if (empty($pages))
268                 return str_replace('$1', $s_word, $_msg_notfoundresult);
269
270         ksort($pages, SORT_STRING);
271
272         $retval = '<ul>' . "\n";
273         foreach (array_keys($pages) as $page) {
274                 $r_page  = rawurlencode($page);
275                 $s_page  = htmlsc($page);
276                 $passage = $show_passage ? ' ' . get_passage(get_filetime($page)) : '';
277                 $retval .= ' <li><a href="' . $script . '?cmd=read&amp;page=' .
278                         $r_page . '&amp;word=' . $r_word . '">' . $s_page .
279                         '</a>' . $passage . '</li>' . "\n";
280         }
281         $retval .= '</ul>' . "\n";
282
283         $retval .= str_replace('$1', $s_word, str_replace('$2', count($pages),
284                 str_replace('$3', $count, $b_type ? $_msg_andresult : $_msg_orresult)));
285
286         return $retval;
287 }
288
289 // Argument check for program
290 function arg_check($str)
291 {
292         global $vars;
293         return isset($vars['cmd']) && (strpos($vars['cmd'], $str) === 0);
294 }
295
296 function _pagename_urlencode_callback($matches)
297 {
298         return rawurlencode($matches[0]);
299 }
300
301 function pagename_urlencode($page)
302 {
303         return preg_replace_callback('|[^/:]+|', '_pagename_urlencode_callback', $page);
304 }
305
306 // Encode page-name
307 function encode($str)
308 {
309         $str = strval($str);
310         return ($str == '') ? '' : strtoupper(bin2hex($str));
311         // Equal to strtoupper(join('', unpack('H*0', $key)));
312         // But PHP 4.3.10 says 'Warning: unpack(): Type H: outside of string in ...'
313 }
314
315 // Decode page name
316 function decode($str)
317 {
318         return pkwk_hex2bin($str);
319 }
320
321 // Inversion of bin2hex()
322 function pkwk_hex2bin($hex_string)
323 {
324         // preg_match : Avoid warning : pack(): Type H: illegal hex digit ...
325         // (string)   : Always treat as string (not int etc). See BugTrack2/31
326         return preg_match('/^[0-9a-f]+$/i', $hex_string) ?
327                 pack('H*', (string)$hex_string) : $hex_string;
328 }
329
330 // Remove [[ ]] (brackets)
331 function strip_bracket($str)
332 {
333         $match = array();
334         if (preg_match('/^\[\[(.*)\]\]$/', $str, $match)) {
335                 return $match[1];
336         } else {
337                 return $str;
338         }
339 }
340
341 // Create list of pages
342 function page_list($pages, $cmd = 'read', $withfilename = FALSE)
343 {
344         global $script, $list_index;
345         global $_msg_symbol, $_msg_other;
346         global $pagereading_enable;
347
348         // ソートキーを決定する。 ' ' < '[a-zA-Z]' < 'zz'という前提。
349         $symbol = ' ';
350         $other = 'zz';
351
352         $retval = '';
353
354         if($pagereading_enable) {
355                 mb_regex_encoding(SOURCE_ENCODING);
356                 $readings = get_readings($pages);
357         }
358
359         $list = $matches = array();
360
361         // Shrink URI for read
362         if ($cmd == 'read') {
363                 $href = $script . '?';
364         } else {
365                 $href = $script . '?cmd=' . $cmd . '&amp;page=';
366         }
367
368         foreach($pages as $file=>$page) {
369                 $r_page  = pagename_urlencode($page);
370                 $s_page  = htmlsc($page, ENT_QUOTES);
371                 $passage = get_pg_passage($page);
372
373                 $str = '   <li><a href="' . $href . $r_page . '">' .
374                         $s_page . '</a>' . $passage;
375
376                 if ($withfilename) {
377                         $s_file = htmlsc($file);
378                         $str .= "\n" . '    <ul><li>' . $s_file . '</li></ul>' .
379                                 "\n" . '   ';
380                 }
381                 $str .= '</li>';
382
383                 // WARNING: Japanese code hard-wired
384                 if($pagereading_enable) {
385                         if(mb_ereg('^([A-Za-z])', mb_convert_kana($page, 'a'), $matches)) {
386                                 $head = $matches[1];
387                         } elseif (isset($readings[$page]) && mb_ereg('^([ァ-ヶ])', $readings[$page], $matches)) { // here
388                                 $head = $matches[1];
389                         } elseif (mb_ereg('^[ -~]|[^ぁ-ん亜-熙]', $page)) { // and here
390                                 $head = $symbol;
391                         } else {
392                                 $head = $other;
393                         }
394                 } else {
395                         $head = (preg_match('/^([A-Za-z])/', $page, $matches)) ? $matches[1] :
396                                 (preg_match('/^([ -~])/', $page) ? $symbol : $other);
397                 }
398
399                 $list[$head][$page] = $str;
400         }
401         ksort($list, SORT_STRING);
402
403         $cnt = 0;
404         $arr_index = array();
405         $retval .= '<ul>' . "\n";
406         foreach ($list as $head=>$pages) {
407                 if ($head === $symbol) {
408                         $head = $_msg_symbol;
409                 } else if ($head === $other) {
410                         $head = $_msg_other;
411                 }
412
413                 if ($list_index) {
414                         ++$cnt;
415                         $arr_index[] = '<a id="top_' . $cnt .
416                                 '" href="#head_' . $cnt . '"><strong>' .
417                                 $head . '</strong></a>';
418                         $retval .= ' <li><a id="head_' . $cnt . '" href="#top_' . $cnt .
419                                 '"><strong>' . $head . '</strong></a>' . "\n" .
420                                 '  <ul>' . "\n";
421                 }
422                 ksort($pages, SORT_STRING);
423                 $retval .= join("\n", $pages);
424                 if ($list_index)
425                         $retval .= "\n  </ul>\n </li>\n";
426         }
427         $retval .= '</ul>' . "\n";
428         if ($list_index && $cnt > 0) {
429                 $top = array();
430                 while (! empty($arr_index))
431                         $top[] = join(' | ' . "\n", array_splice($arr_index, 0, 16)) . "\n";
432
433                 $retval = '<div id="top" style="text-align:center">' . "\n" .
434                         join('<br />', $top) . '</div>' . "\n" . $retval;
435         }
436         return $retval;
437 }
438
439 // Show text formatting rules
440 function catrule()
441 {
442         global $rule_page;
443
444         if (! is_page($rule_page)) {
445                 return '<p>Sorry, page \'' . htmlsc($rule_page) .
446                         '\' unavailable.</p>';
447         } else {
448                 return convert_html(get_source($rule_page));
449         }
450 }
451
452 // Show (critical) error message
453 function die_message($msg)
454 {
455         $title = $page = 'Runtime error';
456         $body = <<<EOD
457 <h3>Runtime error</h3>
458 <strong>Error message : $msg</strong>
459 EOD;
460
461         pkwk_common_headers();
462         if(defined('SKIN_FILE') && file_exists(SKIN_FILE) && is_readable(SKIN_FILE)) {
463                 catbody($title, $page, $body);
464         } else {
465                 $charset = 'utf-8';
466                 if(defined('CONTENT_CHARSET')) {
467                         $charset = CONTENT_CHARSET;
468                 }
469                 header("Content-Type: text/html; charset=$charset");
470                 print <<<EOD
471 <!DOCTYPE html>
472 <html>
473  <head>
474   <meta http-equiv="content-type" content="text/html; charset=$charset">
475   <title>$title</title>
476  </head>
477  <body>
478  $body
479  </body>
480 </html>
481 EOD;
482         }
483         exit;
484 }
485
486 // Have the time (as microtime)
487 function getmicrotime()
488 {
489         list($usec, $sec) = explode(' ', microtime());
490         return ((float)$sec + (float)$usec);
491 }
492
493 // Elapsed time by second
494 //define('MUTIME', getmicrotime());
495 function elapsedtime()
496 {
497         $at_the_microtime = MUTIME;
498         return sprintf('%01.03f', getmicrotime() - $at_the_microtime);
499 }
500
501 // Get the date
502 function get_date($format, $timestamp = NULL)
503 {
504         $format = preg_replace('/(?<!\\\)T/',
505                 preg_replace('/(.)/', '\\\$1', ZONE), $format);
506
507         $time = ZONETIME + (($timestamp !== NULL) ? $timestamp : UTIME);
508
509         return date($format, $time);
510 }
511
512 // Format date string
513 function format_date($val, $paren = FALSE)
514 {
515         global $date_format, $time_format, $weeklabels;
516
517         $val += ZONETIME;
518
519         $date = date($date_format, $val) .
520                 ' (' . $weeklabels[date('w', $val)] . ') ' .
521                 date($time_format, $val);
522
523         return $paren ? '(' . $date . ')' : $date;
524 }
525
526 // Get short string of the passage, 'N seconds/minutes/hours/days/years ago'
527 function get_passage($time, $paren = TRUE)
528 {
529         static $units = array('m'=>60, 'h'=>24, 'd'=>1);
530
531         $time = max(0, (UTIME - $time) / 60); // minutes
532
533         foreach ($units as $unit=>$card) {
534                 if ($time < $card) break;
535                 $time /= $card;
536         }
537         $time = floor($time) . $unit;
538
539         return $paren ? '(' . $time . ')' : $time;
540 }
541
542 // Hide <input type="(submit|button|image)"...>
543 function drop_submit($str)
544 {
545         return preg_replace('/<input([^>]+)type="(submit|button|image)"/i',
546                 '<input$1type="hidden"', $str);
547 }
548
549 // Generate AutoLink patterns (thx to hirofummy)
550 function get_autolink_pattern(& $pages)
551 {
552         global $WikiName, $autolink, $nowikiname;
553
554         $config = new Config('AutoLink');
555         $config->read();
556         $ignorepages      = $config->get('IgnoreList');
557         $forceignorepages = $config->get('ForceIgnoreList');
558         unset($config);
559         $auto_pages = array_merge($ignorepages, $forceignorepages);
560
561         foreach ($pages as $page)
562                 if (preg_match('/^' . $WikiName . '$/', $page) ?
563                     $nowikiname : strlen($page) >= $autolink)
564                         $auto_pages[] = $page;
565
566         if (empty($auto_pages)) {
567                 $result = $result_a = $nowikiname ? '(?!)' : $WikiName;
568         } else {
569                 $auto_pages = array_unique($auto_pages);
570                 sort($auto_pages, SORT_STRING);
571
572                 $auto_pages_a = array_values(preg_grep('/^[A-Z]+$/i', $auto_pages));
573                 $auto_pages   = array_values(array_diff($auto_pages,  $auto_pages_a));
574
575                 $result   = get_autolink_pattern_sub($auto_pages,   0, count($auto_pages),   0);
576                 $result_a = get_autolink_pattern_sub($auto_pages_a, 0, count($auto_pages_a), 0);
577         }
578         return array($result, $result_a, $forceignorepages);
579 }
580
581 function get_autolink_pattern_sub(& $pages, $start, $end, $pos)
582 {
583         if ($end == 0) return '(?!)';
584
585         $result = '';
586         $count = $i = $j = 0;
587         $x = (mb_strlen($pages[$start]) <= $pos);
588         if ($x) ++$start;
589
590         for ($i = $start; $i < $end; $i = $j) {
591                 $char = mb_substr($pages[$i], $pos, 1);
592                 for ($j = $i; $j < $end; $j++)
593                         if (mb_substr($pages[$j], $pos, 1) != $char) break;
594
595                 if ($i != $start) $result .= '|';
596                 if ($i >= ($j - 1)) {
597                         $result .= str_replace(' ', '\\ ', preg_quote(mb_substr($pages[$i], $pos), '/'));
598                 } else {
599                         $result .= str_replace(' ', '\\ ', preg_quote($char, '/')) .
600                                 get_autolink_pattern_sub($pages, $i, $j, $pos + 1);
601                 }
602                 ++$count;
603         }
604         if ($x || $count > 1) $result = '(?:' . $result . ')';
605         if ($x)               $result .= '?';
606
607         return $result;
608 }
609
610 // Get absolute-URI of this script
611 function get_script_uri($init_uri = '')
612 {
613         global $script_directory_index;
614         static $script;
615
616         if ($init_uri == '') {
617                 // Get
618                 if (isset($script)) return $script;
619
620                 // Set automatically
621                 $msg     = 'get_script_uri() failed: Please set $script at INI_FILE manually';
622
623                 $script  = (SERVER_PORT == 443 ? 'https://' : 'http://'); // scheme
624                 $script .= SERVER_NAME; // host
625                 $script .= (SERVER_PORT == 80 ? '' : ':' . SERVER_PORT);  // port
626
627                 // SCRIPT_NAME が'/'で始まっていない場合(cgiなど) REQUEST_URIを使ってみる
628                 $path    = SCRIPT_NAME;
629                 if ($path{0} != '/') {
630                         if (! isset($_SERVER['REQUEST_URI']) || $_SERVER['REQUEST_URI']{0} != '/')
631                                 die_message($msg);
632
633                         // REQUEST_URIをパースし、path部分だけを取り出す
634                         $parse_url = parse_url($script . $_SERVER['REQUEST_URI']);
635                         if (! isset($parse_url['path']) || $parse_url['path']{0} != '/')
636                                 die_message($msg);
637
638                         $path = $parse_url['path'];
639                 }
640                 $script .= $path;
641
642                 if (! is_url($script, TRUE) && php_sapi_name() == 'cgi')
643                         die_message($msg);
644                 unset($msg);
645
646         } else {
647                 // Set manually
648                 if (isset($script)) die_message('$script: Already init');
649                 if (! is_url($init_uri, TRUE)) die_message('$script: Invalid URI');
650                 $script = $init_uri;
651         }
652
653         // Cut filename or not
654         if (isset($script_directory_index)) {
655                 if (! file_exists($script_directory_index))
656                         die_message('Directory index file not found: ' .
657                                 htmlsc($script_directory_index));
658                 $matches = array();
659                 if (preg_match('#^(.+/)' . preg_quote($script_directory_index, '#') . '$#',
660                         $script, $matches)) $script = $matches[1];
661         }
662
663         return $script;
664 }
665
666 // Remove null(\0) bytes from variables
667 //
668 // NOTE: PHP had vulnerabilities that opens "hoge.php" via fopen("hoge.php\0.txt") etc.
669 // [PHP-users 12736] null byte attack
670 // http://ns1.php.gr.jp/pipermail/php-users/2003-January/012742.html
671 //
672 // 2003-05-16: magic quotes gpcの復元処理を統合
673 // 2003-05-21: 連想配列のキーはbinary safe
674 //
675 function input_filter($param)
676 {
677         static $magic_quotes_gpc = NULL;
678         if ($magic_quotes_gpc === NULL)
679             $magic_quotes_gpc = get_magic_quotes_gpc();
680
681         if (is_array($param)) {
682                 return array_map('input_filter', $param);
683         } else {
684                 $result = str_replace("\0", '', $param);
685                 if ($magic_quotes_gpc) $result = stripslashes($result);
686                 return $result;
687         }
688 }
689
690 // Compat for 3rd party plugins. Remove this later
691 function sanitize($param) {
692         return input_filter($param);
693 }
694
695 // Explode Comma-Separated Values to an array
696 function csv_explode($separator, $string)
697 {
698         $retval = $matches = array();
699
700         $_separator = preg_quote($separator, '/');
701         if (! preg_match_all('/("[^"]*(?:""[^"]*)*"|[^' . $_separator . ']*)' .
702             $_separator . '/', $string . $separator, $matches))
703                 return array();
704
705         foreach ($matches[1] as $str) {
706                 $len = strlen($str);
707                 if ($len > 1 && $str{0} == '"' && $str{$len - 1} == '"')
708                         $str = str_replace('""', '"', substr($str, 1, -1));
709                 $retval[] = $str;
710         }
711         return $retval;
712 }
713
714 // Implode an array with CSV data format (escape double quotes)
715 function csv_implode($glue, $pieces)
716 {
717         $_glue = ($glue != '') ? '\\' . $glue{0} : '';
718         $arr = array();
719         foreach ($pieces as $str) {
720                 if (preg_match('/[' . '"' . "\n\r" . $_glue . ']/', $str))
721                         $str = '"' . str_replace('"', '""', $str) . '"';
722                 $arr[] = $str;
723         }
724         return join($glue, $arr);
725 }
726
727 // Sugar with default settings
728 function htmlsc($string = '', $flags = ENT_COMPAT, $charset = CONTENT_CHARSET)
729 {
730         return htmlspecialchars($string, $flags, $charset);     // htmlsc()
731 }
732
733
734 //// Compat ////
735
736 // is_a --  Returns TRUE if the object is of this class or has this class as one of its parents
737 // (PHP 4 >= 4.2.0)
738 if (! function_exists('is_a')) {
739
740         function is_a($class, $match)
741         {
742                 if (empty($class)) return FALSE; 
743
744                 $class = is_object($class) ? get_class($class) : $class;
745                 if (strtolower($class) == strtolower($match)) {
746                         return TRUE;
747                 } else {
748                         return is_a(get_parent_class($class), $match);  // Recurse
749                 }
750         }
751 }
752
753 // array_fill -- Fill an array with values
754 // (PHP 4 >= 4.2.0)
755 if (! function_exists('array_fill')) {
756
757         function array_fill($start_index, $num, $value)
758         {
759                 $ret = array();
760                 while ($num-- > 0) $ret[$start_index++] = $value;
761                 return $ret;
762         }
763 }
764
765 // md5_file -- Calculates the md5 hash of a given filename
766 // (PHP 4 >= 4.2.0)
767 if (! function_exists('md5_file')) {
768
769         function md5_file($filename)
770         {
771                 if (! file_exists($filename)) return FALSE;
772
773                 $fd = fopen($filename, 'rb');
774                 if ($fd === FALSE ) return FALSE;
775                 $data = fread($fd, filesize($filename));
776                 fclose($fd);
777                 return md5($data);
778         }
779 }
780
781 // sha1 -- Compute SHA-1 hash
782 // (PHP 4 >= 4.3.0, PHP5)
783 if (! function_exists('sha1')) {
784         if (extension_loaded('mhash')) {
785                 function sha1($str)
786                 {
787                         return bin2hex(mhash(MHASH_SHA1, $str));
788                 }
789         }
790 }
791