OSDN Git Service

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