OSDN Git Service

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