OSDN Git Service

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