OSDN Git Service

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