OSDN Git Service

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