OSDN Git Service

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