OSDN Git Service

BugTrack2/140: check_non_list() handles
[pukiwiki/pukiwiki.git] / lib / func.php
1 <?php
2 // PukiWiki - Yet another WikiWikiWeb clone.
3 // $Id: func.php,v 1.52 2005/12/18 15:11:08 henoheno Exp $
4 // Copyright (C)
5 //   2002-2005 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: ' . htmlspecialchars($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: ' . htmlspecialchars($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 ? htmlspecialchars($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;
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
221         $_pages = get_existpages();
222         if ($base != '') {
223                 $_pages = preg_grep('/^' . $base . '/', $_pages);
224         }
225         $pages = array();
226
227         $non_list_pattern = '/' . $non_list . '/';
228         foreach ($_pages as $page) {
229                 if ($page == $whatsnew || (! $search_non_list && preg_match($non_list_pattern, $page)))
230                         continue;
231
232                 // ¸¡º÷Âоݥڡ¼¥¸¤ÎÀ©¸Â¤ò¤«¤±¤ë¤«¤É¤¦¤« (¥Ú¡¼¥¸Ì¾¤ÏÀ©¸Â³°)
233                 if ($search_auth && ! check_readable($page, false, false)) {
234                         $source = get_source(); // Empty
235                 } else {
236                         $source = get_source($page);
237                 }
238                 if (! $non_format)
239                         array_unshift($source, $page); // ¥Ú¡¼¥¸Ì¾¤â¸¡º÷ÂоݤË
240
241                 $b_match = FALSE;
242                 foreach ($keys as $key) {
243                         $tmp     = preg_grep('/' . $key . '/', $source);
244                         $b_match = ! empty($tmp);
245                         if ($b_match xor $b_type) break;
246                 }
247                 if ($b_match) $pages[$page] = get_filetime($page);
248         }
249         if ($non_format) return array_keys($pages);
250
251         $r_word = rawurlencode($word);
252         $s_word = htmlspecialchars($word);
253         if (empty($pages))
254                 return str_replace('$1', $s_word, $_msg_notfoundresult);
255
256         ksort($pages);
257         $retval = '<ul>' . "\n";
258         foreach ($pages as $page=>$time) {
259                 $r_page  = rawurlencode($page);
260                 $s_page  = htmlspecialchars($page);
261                 $passage = get_passage($time);
262                 $retval .= ' <li><a href="' . $script . '?cmd=read&amp;page=' .
263                         $r_page . '&amp;word=' . $r_word . '">' . $s_page .
264                         '</a>' . $passage . '</li>' . "\n";
265         }
266         $retval .= '</ul>' . "\n";
267
268         $retval .= str_replace('$1', $s_word, str_replace('$2', count($pages),
269                 str_replace('$3', count($_pages), $b_type ? $_msg_andresult : $_msg_orresult)));
270
271         return $retval;
272 }
273
274 // Argument check for program
275 function arg_check($str)
276 {
277         global $vars;
278         return isset($vars['cmd']) && (strpos($vars['cmd'], $str) === 0);
279 }
280
281 // Encode page-name
282 function encode($key)
283 {
284         return ($key == '') ? '' : strtoupper(bin2hex($key));
285         // Equal to strtoupper(join('', unpack('H*0', $key)));
286         // But PHP 4.3.10 says 'Warning: unpack(): Type H: outside of string in ...'
287 }
288
289 // Decode page name
290 function decode($key)
291 {
292         return hex2bin($key);
293 }
294
295 // Inversion of bin2hex()
296 function hex2bin($hex_string)
297 {
298         // preg_match : Avoid warning : pack(): Type H: illegal hex digit ...
299         // (string)   : Always treat as string (not int etc). See BugTrack2/31
300         return preg_match('/^[0-9a-f]+$/i', $hex_string) ?
301                 pack('H*', (string)$hex_string) : $hex_string;
302 }
303
304 // Remove [[ ]] (brackets)
305 function strip_bracket($str)
306 {
307         $match = array();
308         if (preg_match('/^\[\[(.*)\]\]$/', $str, $match)) {
309                 return $match[1];
310         } else {
311                 return $str;
312         }
313 }
314
315 // Create list of pages
316 function page_list($pages, $cmd = 'read', $withfilename = FALSE)
317 {
318         global $script, $list_index;
319         global $_msg_symbol, $_msg_other;
320         global $pagereading_enable;
321
322         // ¥½¡¼¥È¥­¡¼¤ò·èÄꤹ¤ë¡£ ' ' < '[a-zA-Z]' < 'zz'¤È¤¤¤¦Á°Äó¡£
323         $symbol = ' ';
324         $other = 'zz';
325
326         $retval = '';
327
328         if($pagereading_enable) {
329                 mb_regex_encoding(SOURCE_ENCODING);
330                 $readings = get_readings($pages);
331         }
332
333         $list = $matches = array();
334
335         // Shrink URI for read
336         if ($cmd == 'read') {
337                 $href = $script . '?';
338         } else {
339                 $href = $script . '?cmd=' . $cmd . '&amp;page=';
340         }
341
342         foreach($pages as $file=>$page) {
343                 $r_page  = rawurlencode($page);
344                 $s_page  = htmlspecialchars($page, ENT_QUOTES);
345                 $passage = get_pg_passage($page);
346
347                 $str = '   <li><a href="' . $href . $r_page . '">' .
348                         $s_page . '</a>' . $passage;
349
350                 if ($withfilename) {
351                         $s_file = htmlspecialchars($file);
352                         $str .= "\n" . '    <ul><li>' . $s_file . '</li></ul>' .
353                                 "\n" . '   ';
354                 }
355                 $str .= '</li>';
356
357                 // WARNING: Japanese code hard-wired
358                 if($pagereading_enable) {
359                         if(mb_ereg('^([A-Za-z])', mb_convert_kana($page, 'a'), $matches)) {
360                                 $head = $matches[1];
361                         } elseif (isset($readings[$page]) && mb_ereg('^([¥¡-¥ö])', $readings[$page], $matches)) { // here
362                                 $head = $matches[1];
363                         } elseif (mb_ereg('^[ -~]|[^¤¡-¤ó°¡-ô¦]', $page)) { // and here
364                                 $head = $symbol;
365                         } else {
366                                 $head = $other;
367                         }
368                 } else {
369                         $head = (preg_match('/^([A-Za-z])/', $page, $matches)) ? $matches[1] :
370                                 (preg_match('/^([ -~])/', $page, $matches) ? $symbol : $other);
371                 }
372
373                 $list[$head][$page] = $str;
374         }
375         ksort($list);
376
377         $cnt = 0;
378         $arr_index = array();
379         $retval .= '<ul>' . "\n";
380         foreach ($list as $head=>$pages) {
381                 if ($head === $symbol) {
382                         $head = $_msg_symbol;
383                 } else if ($head === $other) {
384                         $head = $_msg_other;
385                 }
386
387                 if ($list_index) {
388                         ++$cnt;
389                         $arr_index[] = '<a id="top_' . $cnt .
390                                 '" href="#head_' . $cnt . '"><strong>' .
391                                 $head . '</strong></a>';
392                         $retval .= ' <li><a id="head_' . $cnt . '" href="#top_' . $cnt .
393                                 '"><strong>' . $head . '</strong></a>' . "\n" .
394                                 '  <ul>' . "\n";
395                 }
396                 ksort($pages);
397                 $retval .= join("\n", $pages);
398                 if ($list_index)
399                         $retval .= "\n  </ul>\n </li>\n";
400         }
401         $retval .= '</ul>' . "\n";
402         if ($list_index && $cnt > 0) {
403                 $top = array();
404                 while (! empty($arr_index))
405                         $top[] = join(' | ' . "\n", array_splice($arr_index, 0, 16)) . "\n";
406
407                 $retval = '<div id="top" style="text-align:center">' . "\n" .
408                         join('<br />', $top) . '</div>' . "\n" . $retval;
409         }
410         return $retval;
411 }
412
413 // Show text formatting rules
414 function catrule()
415 {
416         global $rule_page;
417
418         if (! is_page($rule_page)) {
419                 return '<p>Sorry, page \'' . htmlspecialchars($rule_page) .
420                         '\' unavailable.</p>';
421         } else {
422                 return convert_html(get_source($rule_page));
423         }
424 }
425
426 // Show (critical) error message
427 function die_message($msg)
428 {
429         $title = $page = 'Runtime error';
430         $body = <<<EOD
431 <h3>Runtime error</h3>
432 <strong>Error message : $msg</strong>
433 EOD;
434
435         pkwk_common_headers();
436         if(defined('SKIN_FILE') && file_exists(SKIN_FILE) && is_readable(SKIN_FILE)) {
437                 catbody($title, $page, $body);
438         } else {
439                 header('Content-Type: text/html; charset=euc-jp');
440                 print <<<EOD
441 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
442 <html>
443  <head>
444   <title>$title</title>
445   <meta http-equiv="content-type" content="text/html; charset=euc-jp">
446  </head>
447  <body>
448  $body
449  </body>
450 </html>
451 EOD;
452         }
453         exit;
454 }
455
456 // Have the time (as microtime)
457 function getmicrotime()
458 {
459         list($usec, $sec) = explode(' ', microtime());
460         return ((float)$sec + (float)$usec);
461 }
462
463 // Get the date
464 function get_date($format, $timestamp = NULL)
465 {
466         $format = preg_replace('/(?<!\\\)T/',
467                 preg_replace('/(.)/', '\\\$1', ZONE), $format);
468
469         $time = ZONETIME + (($timestamp !== NULL) ? $timestamp : UTIME);
470
471         return date($format, $time);
472 }
473
474 // Format date string
475 function format_date($val, $paren = FALSE)
476 {
477         global $date_format, $time_format, $weeklabels;
478
479         $val += ZONETIME;
480
481         $date = date($date_format, $val) .
482                 ' (' . $weeklabels[date('w', $val)] . ') ' .
483                 date($time_format, $val);
484
485         return $paren ? '(' . $date . ')' : $date;
486 }
487
488 // Get short string of the passage, 'N seconds/minutes/hours/days/years ago'
489 function get_passage($time, $paren = TRUE)
490 {
491         static $units = array('m'=>60, 'h'=>24, 'd'=>1);
492
493         $time = max(0, (UTIME - $time) / 60); // minutes
494
495         foreach ($units as $unit=>$card) {
496                 if ($time < $card) break;
497                 $time /= $card;
498         }
499         $time = floor($time) . $unit;
500
501         return $paren ? '(' . $time . ')' : $time;
502 }
503
504 // Hide <input type="(submit|button|image)"...>
505 function drop_submit($str)
506 {
507         return preg_replace('/<input([^>]+)type="(submit|button|image)"/i',
508                 '<input$1type="hidden"', $str);
509 }
510
511 // Generate AutoLink patterns (thx to hirofummy)
512 function get_autolink_pattern(& $pages)
513 {
514         global $WikiName, $autolink, $nowikiname;
515
516         $config = &new Config('AutoLink');
517         $config->read();
518         $ignorepages      = $config->get('IgnoreList');
519         $forceignorepages = $config->get('ForceIgnoreList');
520         unset($config);
521         $auto_pages = array_merge($ignorepages, $forceignorepages);
522
523         foreach ($pages as $page)
524                 if (preg_match('/^' . $WikiName . '$/', $page) ?
525                     $nowikiname : strlen($page) >= $autolink)
526                         $auto_pages[] = $page;
527
528         if (empty($auto_pages)) {
529                 $result = $result_a = $nowikiname ? '(?!)' : $WikiName;
530         } else {
531                 $auto_pages = array_unique($auto_pages);
532                 sort($auto_pages, SORT_STRING);
533
534                 $auto_pages_a = array_values(preg_grep('/^[A-Z]+$/i', $auto_pages));
535                 $auto_pages   = array_values(array_diff($auto_pages,  $auto_pages_a));
536
537                 $result   = get_autolink_pattern_sub($auto_pages,   0, count($auto_pages),   0);
538                 $result_a = get_autolink_pattern_sub($auto_pages_a, 0, count($auto_pages_a), 0);
539         }
540         return array($result, $result_a, $forceignorepages);
541 }
542
543 function get_autolink_pattern_sub(& $pages, $start, $end, $pos)
544 {
545         if ($end == 0) return '(?!)';
546
547         $result = '';
548         $count = $i = $j = 0;
549         $x = (mb_strlen($pages[$start]) <= $pos);
550         if ($x) ++$start;
551
552         for ($i = $start; $i < $end; $i = $j) {
553                 $char = mb_substr($pages[$i], $pos, 1);
554                 for ($j = $i; $j < $end; $j++)
555                         if (mb_substr($pages[$j], $pos, 1) != $char) break;
556
557                 if ($i != $start) $result .= '|';
558                 if ($i >= ($j - 1)) {
559                         $result .= str_replace(' ', '\\ ', preg_quote(mb_substr($pages[$i], $pos), '/'));
560                 } else {
561                         $result .= str_replace(' ', '\\ ', preg_quote($char, '/')) .
562                                 get_autolink_pattern_sub($pages, $i, $j, $pos + 1);
563                 }
564                 ++$count;
565         }
566         if ($x || $count > 1) $result = '(?:' . $result . ')';
567         if ($x)               $result .= '?';
568
569         return $result;
570 }
571
572 // Get absolute-URI of this script
573 function get_script_uri($init_uri = '')
574 {
575         global $script_directory_index;
576         static $script;
577
578         if ($init_uri == '') {
579                 // Get
580                 if (isset($script)) return $script;
581
582                 // Set automatically
583                 $msg     = 'get_script_uri() failed: Please set $script at INI_FILE manually';
584
585                 $script  = (SERVER_PORT == 443 ? 'https://' : 'http://'); // scheme
586                 $script .= SERVER_NAME; // host
587                 $script .= (SERVER_PORT == 80 ? '' : ':' . SERVER_PORT);  // port
588
589                 // SCRIPT_NAME ¤¬'/'¤Ç»Ï¤Þ¤Ã¤Æ¤¤¤Ê¤¤¾ì¹ç(cgi¤Ê¤É) REQUEST_URI¤ò»È¤Ã¤Æ¤ß¤ë
590                 $path    = SCRIPT_NAME;
591                 if ($path{0} != '/') {
592                         if (! isset($_SERVER['REQUEST_URI']) || $_SERVER['REQUEST_URI']{0} != '/')
593                                 die_message($msg);
594
595                         // REQUEST_URI¤ò¥Ñ¡¼¥¹¤·¡¢pathÉôʬ¤À¤±¤ò¼è¤ê½Ð¤¹
596                         $parse_url = parse_url($script . $_SERVER['REQUEST_URI']);
597                         if (! isset($parse_url['path']) || $parse_url['path']{0} != '/')
598                                 die_message($msg);
599
600                         $path = $parse_url['path'];
601                 }
602                 $script .= $path;
603
604                 if (! is_url($script, TRUE) && php_sapi_name() == 'cgi')
605                         die_message($msg);
606                 unset($msg);
607
608         } else {
609                 // Set manually
610                 if (isset($script)) die_message('$script: Already init');
611                 if (! is_url($init_uri, TRUE)) die_message('$script: Invalid URI');
612                 $script = $init_uri;
613         }
614
615         // Cut filename or not
616         if (isset($script_directory_index)) {
617                 if (! file_exists($script_directory_index))
618                         die_message('Directory index file not found: ' .
619                                 htmlspecialchars($script_directory_index));
620                 $matches = array();
621                 if (preg_match('#^(.+/)' . preg_quote($script_directory_index, '#') . '$#',
622                         $script, $matches)) $script = $matches[1];
623         }
624
625         return $script;
626 }
627
628 // Remove null(\0) bytes from variables
629 //
630 // NOTE: PHP had vulnerabilities that opens "hoge.php" via fopen("hoge.php\0.txt") etc.
631 // [PHP-users 12736] null byte attack
632 // http://ns1.php.gr.jp/pipermail/php-users/2003-January/012742.html
633 //
634 // 2003-05-16: magic quotes gpc¤ÎÉü¸µ½èÍý¤òÅý¹ç
635 // 2003-05-21: Ï¢ÁÛÇÛÎó¤Î¥­¡¼¤Ïbinary safe
636 //
637 function input_filter($param)
638 {
639         static $magic_quotes_gpc = NULL;
640         if ($magic_quotes_gpc === NULL)
641             $magic_quotes_gpc = get_magic_quotes_gpc();
642
643         if (is_array($param)) {
644                 return array_map('input_filter', $param);
645         } else {
646                 $result = str_replace("\0", '', $param);
647                 if ($magic_quotes_gpc) $result = stripslashes($result);
648                 return $result;
649         }
650 }
651
652 // Compat for 3rd party plugins. Remove this later
653 function sanitize($param) {
654         return input_filter($param);
655 }
656
657 // Explode Comma-Separated Values to an array
658 function csv_explode($separator, $string)
659 {
660         $retval = $matches = array();
661
662         $_separator = preg_quote($separator, '/');
663         if (! preg_match_all('/("[^"]*(?:""[^"]*)*"|[^' . $_separator . ']*)' .
664             $_separator . '/', $string . $separator, $matches))
665                 return array();
666
667         foreach ($matches[1] as $str) {
668                 $len = strlen($str);
669                 if ($len > 1 && $str{0} == '"' && $str{$len - 1} == '"')
670                         $str = str_replace('""', '"', substr($str, 1, -1));
671                 $retval[] = $str;
672         }
673         return $retval;
674 }
675
676 // Implode an array with CSV data format (escape double quotes)
677 function csv_implode($glue, $pieces)
678 {
679         $_glue = ($glue != '') ? '\\' . $glue{0} : '';
680         $arr = array();
681         foreach ($pieces as $str) {
682                 if (ereg('[' . $_glue . '"' . "\n\r" . ']', $str))
683                         $str = '"' . str_replace('"', '""', $str) . '"';
684                 $arr[] = $str;
685         }
686         return join($glue, $arr);
687 }
688
689 //// Compat ////
690
691 // is_a --  Returns TRUE if the object is of this class or has this class as one of its parents
692 // (PHP 4 >= 4.2.0)
693 if (! function_exists('is_a')) {
694
695         function is_a($class, $match)
696         {
697                 if (empty($class)) return FALSE; 
698
699                 $class = is_object($class) ? get_class($class) : $class;
700                 if (strtolower($class) == strtolower($match)) {
701                         return TRUE;
702                 } else {
703                         return is_a(get_parent_class($class), $match);  // Recurse
704                 }
705         }
706 }
707
708 // array_fill -- Fill an array with values
709 // (PHP 4 >= 4.2.0)
710 if (! function_exists('array_fill')) {
711
712         function array_fill($start_index, $num, $value)
713         {
714                 $ret = array();
715                 while ($num-- > 0) $ret[$start_index++] = $value;
716                 return $ret;
717         }
718 }
719
720 // md5_file -- Calculates the md5 hash of a given filename
721 // (PHP 4 >= 4.2.0)
722 if (! function_exists('md5_file')) {
723
724         function md5_file($filename)
725         {
726                 if (! file_exists($filename)) return FALSE;
727
728                 $fd = fopen($filename, 'rb');
729                 if ($fd === FALSE ) return FALSE;
730                 $data = fread($fd, filesize($filename));
731                 fclose($fd);
732                 return md5($data);
733         }
734 }
735
736 // sha1 -- Compute SHA-1 hash
737 // (PHP 4 >= 4.3.0, PHP5)
738 if (! function_exists('sha1')) {
739         if (extension_loaded('mhash')) {
740                 function sha1($str, $raw_output = FALSE)
741                 {
742                         if ($raw_output) {
743                                 // PHP 5.0.0 or lator only :)
744                                 return mhash(MHASH_SHA1, $str);
745                         } else {
746                                 return bin2hex(mhash(MHASH_SHA1, $str));
747                         }
748                 }
749         } else {
750                 function sha1($str, $raw_output = FALSE)
751                 {
752                         die('Function sha1() not found and extension \'mhash\' not exists');
753                 }
754         }
755 }
756 ?>