OSDN Git Service

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