OSDN Git Service

BugTrack/2425 Fix today param handling of popular plugin
[pukiwiki/pukiwiki.git] / lib / func.php
1 <?php
2 // PukiWiki - Yet another WikiWikiWeb clone.
3 // func.php
4 // Copyright
5 //   2002-2016 PukiWiki Development 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 pkwk_log($message)
12 {
13         $log_filepath = 'log/error.log.php';
14         static $dateTimeExists;
15         if (!isset($dateTimeExists)) {
16                 $dateTimeExists = class_exists('DateTime');
17                 error_log("<?php\n", 3, $log_filepath);
18         }
19         if ($dateTimeExists) {
20                 // for PHP5.2+
21                 $d = \DateTime::createFromFormat('U.u', sprintf('%6F', microtime(true)));
22                 $timestamp = substr($d->format('Y-m-d H:i:s.u'), 0, 23);
23         } else {
24                 $timestamp = date('Y-m-d H:i:s');
25         }
26         error_log($timestamp . ' ' . $message . "\n", 3, $log_filepath);
27 }
28
29 /**
30  * ctype_digit that supports PHP4+.
31  *
32  * PHP official document says PHP4 has ctype_digit() function.
33  * But sometimes it doen't exists on PHP 4.1.
34  */
35 function pkwk_ctype_digit($s) {
36         static $ctype_digit_exists;
37         if (!isset($ctype_digit_exists)) {
38                 $ctype_digit_exists = function_exists('ctype_digit');
39         }
40         if ($ctype_digit_exists) {
41                 return ctype_digit($s);
42         }
43         return preg_match('/^[0-9]+$/', $s) ? true : false;
44 }
45
46 function is_interwiki($str)
47 {
48         global $InterWikiName;
49         return preg_match('/^' . $InterWikiName . '$/', $str);
50 }
51
52 function is_pagename($str)
53 {
54         global $BracketName;
55
56         $is_pagename = (! is_interwiki($str) &&
57                   preg_match('/^(?!\/)' . $BracketName . '$(?<!\/$)/', $str) &&
58                 ! preg_match('#(^|/)\.{1,2}(/|$)#', $str));
59
60         if (defined('SOURCE_ENCODING')) {
61                 switch(SOURCE_ENCODING){
62                 case 'UTF-8': $pattern =
63                         '/^(?:[\x00-\x7F]|(?:[\xC0-\xDF][\x80-\xBF])|(?:[\xE0-\xEF][\x80-\xBF][\x80-\xBF]))+$/';
64                         break;
65                 case 'EUC-JP': $pattern =
66                         '/^(?:[\x00-\x7F]|(?:[\x8E\xA1-\xFE][\xA1-\xFE])|(?:\x8F[\xA1-\xFE][\xA1-\xFE]))+$/';
67                         break;
68                 }
69                 if (isset($pattern) && $pattern != '')
70                         $is_pagename = ($is_pagename && preg_match($pattern, $str));
71         }
72
73         return $is_pagename;
74 }
75
76 function is_url($str, $only_http = FALSE)
77 {
78         $scheme = $only_http ? 'https?' : 'https?|ftp|news';
79         return preg_match('/^(' . $scheme . ')(:\/\/[-_.!~*\'()a-zA-Z0-9;\/?:\@&=+\$,%#]*)$/', $str);
80 }
81
82 // If the page exists
83 function is_page($page, $clearcache = FALSE)
84 {
85         if ($clearcache) clearstatcache();
86         return file_exists(get_filename($page));
87 }
88
89 function is_editable($page)
90 {
91         global $cantedit;
92         static $is_editable = array();
93
94         if (! isset($is_editable[$page])) {
95                 $is_editable[$page] = (
96                         is_pagename($page) &&
97                         ! is_freeze($page) &&
98                         ! in_array($page, $cantedit)
99                 );
100         }
101
102         return $is_editable[$page];
103 }
104
105 function is_freeze($page, $clearcache = FALSE)
106 {
107         global $function_freeze;
108         static $is_freeze = array();
109
110         if ($clearcache === TRUE) $is_freeze = array();
111         if (isset($is_freeze[$page])) return $is_freeze[$page];
112
113         if (! $function_freeze || ! is_page($page)) {
114                 $is_freeze[$page] = FALSE;
115                 return FALSE;
116         } else {
117                 $fp = fopen(get_filename($page), 'rb') or
118                         die('is_freeze(): fopen() failed: ' . htmlsc($page));
119                 flock($fp, LOCK_SH) or die('is_freeze(): flock() failed');
120                 rewind($fp);
121                 $buffer = fread($fp, 1000);
122                 flock($fp, LOCK_UN) or die('is_freeze(): flock() failed');
123                 fclose($fp) or die('is_freeze(): fclose() failed: ' . htmlsc($page));
124                 $is_freeze[$page] = (bool) preg_match('/^#freeze$/m', $buffer);
125                 return $is_freeze[$page];
126         }
127 }
128
129 // Handling $non_list
130 // $non_list will be preg_quote($str, '/') later.
131 function check_non_list($page = '')
132 {
133         global $non_list;
134         static $regex;
135
136         if (! isset($regex)) $regex = '/' . $non_list . '/';
137
138         return preg_match($regex, $page);
139 }
140
141 // Auto template
142 function auto_template($page)
143 {
144         global $auto_template_func, $auto_template_rules;
145
146         if (! $auto_template_func) return '';
147
148         $body = '';
149         $matches = array();
150         foreach ($auto_template_rules as $rule => $template) {
151                 $rule_pattrn = '/' . $rule . '/';
152
153                 if (! preg_match($rule_pattrn, $page, $matches)) continue;
154
155                 $template_page = preg_replace($rule_pattrn, $template, $page);
156                 if (! is_page($template_page)) continue;
157
158                 $body = join('', get_source($template_page));
159
160                 // Remove fixed-heading anchors
161                 $body = preg_replace('/^(\*{1,3}.*)\[#[A-Za-z][\w-]+\](.*)$/m', '$1$2', $body);
162
163                 // Remove '#freeze'
164                 $body = preg_replace('/^#freeze\s*$/m', '', $body);
165
166                 $count = count($matches);
167                 for ($i = 0; $i < $count; $i++)
168                         $body = str_replace('$' . $i, $matches[$i], $body);
169
170                 break;
171         }
172         return $body;
173 }
174
175 // Expand all search-words to regexes and push them into an array
176 function get_search_words($words = array(), $do_escape = FALSE)
177 {
178         static $init, $mb_convert_kana, $pre, $post, $quote = '/';
179
180         if (! isset($init)) {
181                 // function: mb_convert_kana() is for Japanese code only
182                 if (LANG == 'ja' && function_exists('mb_convert_kana')) {
183                         $mb_convert_kana = create_function('$str, $option',
184                                 'return mb_convert_kana($str, $option, SOURCE_ENCODING);');
185                 } else {
186                         $mb_convert_kana = create_function('$str, $option',
187                                 'return $str;');
188                 }
189                 if (SOURCE_ENCODING == 'EUC-JP') {
190                         // Perl memo - Correct pattern-matching with EUC-JP
191                         // http://www.din.or.jp/~ohzaki/perl.htm#JP_Match (Japanese)
192                         $pre  = '(?<!\x8F)';
193                         $post = '(?=(?:[\xA1-\xFE][\xA1-\xFE])*' . // JIS X 0208
194                                 '(?:[\x00-\x7F\x8E\x8F]|\z))';     // ASCII, SS2, SS3, or the last
195                 } else {
196                         $pre = $post = '';
197                 }
198                 $init = TRUE;
199         }
200
201         if (! is_array($words)) $words = array($words);
202
203         // Generate regex for the words
204         $regex = array();
205         foreach ($words as $word) {
206                 $word = trim($word);
207                 if ($word == '') continue;
208
209                 // Normalize: ASCII letters = to single-byte. Others = to Zenkaku and Katakana
210                 $word_nm = $mb_convert_kana($word, 'aKCV');
211                 $nmlen   = mb_strlen($word_nm, SOURCE_ENCODING);
212
213                 // Each chars may be served ...
214                 $chars = array();
215                 for ($pos = 0; $pos < $nmlen; $pos++) {
216                         $char = mb_substr($word_nm, $pos, 1, SOURCE_ENCODING);
217
218                         // Just normalized one? (ASCII char or Zenkaku-Katakana?)
219                         $or = array(preg_quote($do_escape ? htmlsc($char) : $char, $quote));
220                         if (strlen($char) == 1) {
221                                 // An ASCII (single-byte) character
222                                 foreach (array(strtoupper($char), strtolower($char)) as $_char) {
223                                         if ($char != '&') $or[] = preg_quote($_char, $quote); // As-is?
224                                         $ascii = ord($_char);
225                                         $or[] = sprintf('&#(?:%d|x%x);', $ascii, $ascii); // As an entity reference?
226                                         $or[] = preg_quote($mb_convert_kana($_char, 'A'), $quote); // As Zenkaku?
227                                 }
228                         } else {
229                                 // NEVER COME HERE with mb_substr(string, start, length, 'ASCII')
230                                 // A multi-byte character
231                                 $or[] = preg_quote($mb_convert_kana($char, 'c'), $quote); // As Hiragana?
232                                 $or[] = preg_quote($mb_convert_kana($char, 'k'), $quote); // As Hankaku-Katakana?
233                         }
234                         $chars[] = '(?:' . join('|', array_unique($or)) . ')'; // Regex for the character
235                 }
236
237                 $regex[$word] = $pre . join('', $chars) . $post; // For the word
238         }
239
240         return $regex; // For all words
241 }
242
243 // 'Search' main function
244 function do_search($word, $type = 'AND', $non_format = FALSE, $base = '')
245 {
246         global $script, $whatsnew, $non_list, $search_non_list;
247         global $_msg_andresult, $_msg_orresult, $_msg_notfoundresult;
248         global $search_auth, $show_passage;
249
250         $retval = array();
251
252         $b_type = ($type == 'AND'); // AND:TRUE OR:FALSE
253         $keys = get_search_words(preg_split('/\s+/', $word, -1, PREG_SPLIT_NO_EMPTY));
254         foreach ($keys as $key=>$value)
255                 $keys[$key] = '/' . $value . '/S';
256
257         $pages = get_existpages();
258
259         // Avoid
260         if ($base != '') {
261                 $pages = preg_grep('/^' . preg_quote($base, '/') . '/S', $pages);
262         }
263         if (! $search_non_list) {
264                 $pages = array_diff($pages, preg_grep('/' . $non_list . '/S', $pages));
265         }
266         $pages = array_flip($pages);
267         unset($pages[$whatsnew]);
268
269         $count = count($pages);
270         foreach (array_keys($pages) as $page) {
271                 $b_match = FALSE;
272
273                 // Search for page name
274                 if (! $non_format) {
275                         foreach ($keys as $key) {
276                                 $b_match = preg_match($key, $page);
277                                 if ($b_type xor $b_match) break; // OR
278                         }
279                         if ($b_match) continue;
280                 }
281
282                 // Search auth for page contents
283                 if ($search_auth && ! check_readable($page, false, false)) {
284                         unset($pages[$page]);
285                         --$count;
286                 }
287
288                 // Search for page contents
289                 foreach ($keys as $key) {
290                         $b_match = preg_match($key, get_source($page, TRUE, TRUE));
291                         if ($b_type xor $b_match) break; // OR
292                 }
293                 if ($b_match) continue;
294
295                 unset($pages[$page]); // Miss
296         }
297         if ($non_format) return array_keys($pages);
298
299         $r_word = rawurlencode($word);
300         $s_word = htmlsc($word);
301         if (empty($pages))
302                 return str_replace('$1', $s_word, $_msg_notfoundresult);
303
304         ksort($pages, SORT_STRING);
305
306         $retval = '<ul>' . "\n";
307         foreach (array_keys($pages) as $page) {
308                 $r_page  = rawurlencode($page);
309                 $s_page  = htmlsc($page);
310                 $passage = $show_passage ? ' ' . get_passage(get_filetime($page)) : '';
311                 $retval .= ' <li><a href="' . $script . '?cmd=read&amp;page=' .
312                         $r_page . '&amp;word=' . $r_word . '">' . $s_page .
313                         '</a>' . $passage . '</li>' . "\n";
314         }
315         $retval .= '</ul>' . "\n";
316
317         $retval .= str_replace('$1', $s_word, str_replace('$2', count($pages),
318                 str_replace('$3', $count, $b_type ? $_msg_andresult : $_msg_orresult)));
319
320         return $retval;
321 }
322
323 // Argument check for program
324 function arg_check($str)
325 {
326         global $vars;
327         return isset($vars['cmd']) && (strpos($vars['cmd'], $str) === 0);
328 }
329
330 function _pagename_urlencode_callback($matches)
331 {
332         return rawurlencode($matches[0]);
333 }
334
335 function pagename_urlencode($page)
336 {
337         return preg_replace_callback('|[^/:]+|', '_pagename_urlencode_callback', $page);
338 }
339
340 // Encode page-name
341 function encode($str)
342 {
343         $str = strval($str);
344         return ($str == '') ? '' : strtoupper(bin2hex($str));
345         // Equal to strtoupper(join('', unpack('H*0', $key)));
346         // But PHP 4.3.10 says 'Warning: unpack(): Type H: outside of string in ...'
347 }
348
349 // Decode page name
350 function decode($str)
351 {
352         return pkwk_hex2bin($str);
353 }
354
355 // Inversion of bin2hex()
356 function pkwk_hex2bin($hex_string)
357 {
358         // preg_match : Avoid warning : pack(): Type H: illegal hex digit ...
359         // (string)   : Always treat as string (not int etc). See BugTrack2/31
360         return preg_match('/^[0-9a-f]+$/i', $hex_string) ?
361                 pack('H*', (string)$hex_string) : $hex_string;
362 }
363
364 // Remove [[ ]] (brackets)
365 function strip_bracket($str)
366 {
367         $match = array();
368         if (preg_match('/^\[\[(.*)\]\]$/', $str, $match)) {
369                 return $match[1];
370         } else {
371                 return $str;
372         }
373 }
374
375 // Create list of pages
376 function page_list($pages, $cmd = 'read', $withfilename = FALSE)
377 {
378         global $script, $list_index;
379         global $_msg_symbol, $_msg_other;
380         global $pagereading_enable;
381
382         // ソートキーを決定する。 ' ' < '[a-zA-Z]' < 'zz'という前提。
383         $symbol = ' ';
384         $other = 'zz';
385
386         $retval = '';
387
388         if($pagereading_enable) {
389                 mb_regex_encoding(SOURCE_ENCODING);
390                 $readings = get_readings($pages);
391         }
392
393         $list = $matches = array();
394
395         // Shrink URI for read
396         if ($cmd == 'read') {
397                 $href = $script . '?';
398         } else {
399                 $href = $script . '?cmd=' . $cmd . '&amp;page=';
400         }
401
402         foreach($pages as $file=>$page) {
403                 $r_page  = pagename_urlencode($page);
404                 $s_page  = htmlsc($page, ENT_QUOTES);
405                 $passage = get_pg_passage($page);
406
407                 $str = '   <li><a href="' . $href . $r_page . '">' .
408                         $s_page . '</a>' . $passage;
409
410                 if ($withfilename) {
411                         $s_file = htmlsc($file);
412                         $str .= "\n" . '    <ul><li>' . $s_file . '</li></ul>' .
413                                 "\n" . '   ';
414                 }
415                 $str .= '</li>';
416
417                 // WARNING: Japanese code hard-wired
418                 if($pagereading_enable) {
419                         if(mb_ereg('^([A-Za-z])', mb_convert_kana($page, 'a'), $matches)) {
420                                 $head = strtoupper($matches[1]);
421                         } elseif (isset($readings[$page]) && mb_ereg('^([ァ-ヶ])', $readings[$page], $matches)) { // here
422                                 $head = $matches[1];
423                         } elseif (mb_ereg('^[ -~]|[^ぁ-ん亜-熙]', $page)) { // and here
424                                 $head = $symbol;
425                         } else {
426                                 $head = $other;
427                         }
428                 } else {
429                         $head = (preg_match('/^([A-Za-z])/', $page, $matches)) ? strtoupper($matches[1]) :
430                                 (preg_match('/^([ -~])/', $page) ? $symbol : $other);
431                 }
432
433                 $list[$head][$page] = $str;
434         }
435         uksort($pages, 'strnatcmp');
436
437         $cnt = 0;
438         $arr_index = array();
439         $retval .= '<ul>' . "\n";
440         foreach ($list as $head=>$pages) {
441                 if ($head === $symbol) {
442                         $head = $_msg_symbol;
443                 } else if ($head === $other) {
444                         $head = $_msg_other;
445                 }
446
447                 if ($list_index) {
448                         ++$cnt;
449                         $arr_index[] = '<a id="top_' . $cnt .
450                                 '" href="#head_' . $cnt . '"><strong>' .
451                                 $head . '</strong></a>';
452                         $retval .= ' <li><a id="head_' . $cnt . '" href="#top_' . $cnt .
453                                 '"><strong>' . $head . '</strong></a>' . "\n" .
454                                 '  <ul>' . "\n";
455                 }
456                 ksort($pages, SORT_STRING);
457                 $retval .= join("\n", $pages);
458                 if ($list_index)
459                         $retval .= "\n  </ul>\n </li>\n";
460         }
461         $retval .= '</ul>' . "\n";
462         if ($list_index && $cnt > 0) {
463                 $top = array();
464                 while (! empty($arr_index))
465                         $top[] = join(' | ' . "\n", array_splice($arr_index, 0, 16)) . "\n";
466
467                 $retval = '<div id="top" style="text-align:center">' . "\n" .
468                         join('<br />', $top) . '</div>' . "\n" . $retval;
469         }
470         return $retval;
471 }
472
473 // Show text formatting rules
474 function catrule()
475 {
476         global $rule_page;
477
478         if (! is_page($rule_page)) {
479                 return '<p>Sorry, page \'' . htmlsc($rule_page) .
480                         '\' unavailable.</p>';
481         } else {
482                 return convert_html(get_source($rule_page));
483         }
484 }
485
486 // Show (critical) error message
487 function die_message($msg)
488 {
489         $title = $page = 'Runtime error';
490         $body = <<<EOD
491 <h3>Runtime error</h3>
492 <strong>Error message : $msg</strong>
493 EOD;
494
495         pkwk_common_headers();
496         if(defined('SKIN_FILE') && file_exists(SKIN_FILE) && is_readable(SKIN_FILE)) {
497                 catbody($title, $page, $body);
498         } else {
499                 $charset = 'utf-8';
500                 if(defined('CONTENT_CHARSET')) {
501                         $charset = CONTENT_CHARSET;
502                 }
503                 header("Content-Type: text/html; charset=$charset");
504                 print <<<EOD
505 <!DOCTYPE html>
506 <html>
507  <head>
508   <meta http-equiv="content-type" content="text/html; charset=$charset">
509   <title>$title</title>
510  </head>
511  <body>
512  $body
513  </body>
514 </html>
515 EOD;
516         }
517         exit;
518 }
519
520 // Have the time (as microtime)
521 function getmicrotime()
522 {
523         list($usec, $sec) = explode(' ', microtime());
524         return ((float)$sec + (float)$usec);
525 }
526
527 // Elapsed time by second
528 //define('MUTIME', getmicrotime());
529 function elapsedtime()
530 {
531         $at_the_microtime = MUTIME;
532         return sprintf('%01.03f', getmicrotime() - $at_the_microtime);
533 }
534
535 // Get the date
536 function get_date($format, $timestamp = NULL)
537 {
538         $format = preg_replace('/(?<!\\\)T/',
539                 preg_replace('/(.)/', '\\\$1', ZONE), $format);
540
541         $time = ZONETIME + (($timestamp !== NULL) ? $timestamp : UTIME);
542
543         return date($format, $time);
544 }
545
546 // Format date string
547 function format_date($val, $paren = FALSE)
548 {
549         global $date_format, $time_format, $weeklabels;
550
551         $val += ZONETIME;
552
553         $date = date($date_format, $val) .
554                 ' (' . $weeklabels[date('w', $val)] . ') ' .
555                 date($time_format, $val);
556
557         return $paren ? '(' . $date . ')' : $date;
558 }
559
560 // Get short string of the passage, 'N seconds/minutes/hours/days/years ago'
561 function get_passage($time, $paren = TRUE)
562 {
563         static $units = array('m'=>60, 'h'=>24, 'd'=>1);
564
565         $time = max(0, (UTIME - $time) / 60); // minutes
566
567         foreach ($units as $unit=>$card) {
568                 if ($time < $card) break;
569                 $time /= $card;
570         }
571         $time = floor($time) . $unit;
572
573         return $paren ? '(' . $time . ')' : $time;
574 }
575
576 // Hide <input type="(submit|button|image)"...>
577 function drop_submit($str)
578 {
579         return preg_replace('/<input([^>]+)type="(submit|button|image)"/i',
580                 '<input$1type="hidden"', $str);
581 }
582
583 // Generate AutoLink patterns (thx to hirofummy)
584 function get_autolink_pattern(& $pages)
585 {
586         global $WikiName, $autolink, $nowikiname;
587
588         $config = new Config('AutoLink');
589         $config->read();
590         $ignorepages      = $config->get('IgnoreList');
591         $forceignorepages = $config->get('ForceIgnoreList');
592         unset($config);
593         $auto_pages = array_merge($ignorepages, $forceignorepages);
594
595         foreach ($pages as $page)
596                 if (preg_match('/^' . $WikiName . '$/', $page) ?
597                     $nowikiname : strlen($page) >= $autolink)
598                         $auto_pages[] = $page;
599
600         if (empty($auto_pages)) {
601                 $result = $result_a = $nowikiname ? '(?!)' : $WikiName;
602         } else {
603                 $auto_pages = array_unique($auto_pages);
604                 sort($auto_pages, SORT_STRING);
605
606                 $auto_pages_a = array_values(preg_grep('/^[A-Z]+$/i', $auto_pages));
607                 $auto_pages   = array_values(array_diff($auto_pages,  $auto_pages_a));
608
609                 $result   = get_autolink_pattern_sub($auto_pages,   0, count($auto_pages),   0);
610                 $result_a = get_autolink_pattern_sub($auto_pages_a, 0, count($auto_pages_a), 0);
611         }
612         return array($result, $result_a, $forceignorepages);
613 }
614
615 function get_autolink_pattern_sub(& $pages, $start, $end, $pos)
616 {
617         if ($end == 0) return '(?!)';
618
619         $result = '';
620         $count = $i = $j = 0;
621         $x = (mb_strlen($pages[$start]) <= $pos);
622         if ($x) ++$start;
623
624         for ($i = $start; $i < $end; $i = $j) {
625                 $char = mb_substr($pages[$i], $pos, 1);
626                 for ($j = $i; $j < $end; $j++)
627                         if (mb_substr($pages[$j], $pos, 1) != $char) break;
628
629                 if ($i != $start) $result .= '|';
630                 if ($i >= ($j - 1)) {
631                         $result .= str_replace(' ', '\\ ', preg_quote(mb_substr($pages[$i], $pos), '/'));
632                 } else {
633                         $result .= str_replace(' ', '\\ ', preg_quote($char, '/')) .
634                                 get_autolink_pattern_sub($pages, $i, $j, $pos + 1);
635                 }
636                 ++$count;
637         }
638         if ($x || $count > 1) $result = '(?:' . $result . ')';
639         if ($x)               $result .= '?';
640
641         return $result;
642 }
643
644 // Get absolute-URI of this script
645 function get_script_uri($init_uri = '')
646 {
647         global $script_directory_index;
648         static $script;
649
650         if ($init_uri == '') {
651                 // Get
652                 if (isset($script)) return $script;
653
654                 // Set automatically
655                 $msg     = 'get_script_uri() failed: Please set $script at INI_FILE manually';
656
657                 $script  = (SERVER_PORT == 443 ? 'https://' : 'http://'); // scheme
658                 $script .= SERVER_NAME; // host
659                 $script .= (SERVER_PORT == 80 ? '' : ':' . SERVER_PORT);  // port
660
661                 // SCRIPT_NAME が'/'で始まっていない場合(cgiなど) REQUEST_URIを使ってみる
662                 $path    = SCRIPT_NAME;
663                 if ($path{0} != '/') {
664                         if (! isset($_SERVER['REQUEST_URI']) || $_SERVER['REQUEST_URI']{0} != '/')
665                                 die_message($msg);
666
667                         // REQUEST_URIをパースし、path部分だけを取り出す
668                         $parse_url = parse_url($script . $_SERVER['REQUEST_URI']);
669                         if (! isset($parse_url['path']) || $parse_url['path']{0} != '/')
670                                 die_message($msg);
671
672                         $path = $parse_url['path'];
673                 }
674                 $script .= $path;
675
676                 if (! is_url($script, TRUE) && php_sapi_name() == 'cgi')
677                         die_message($msg);
678                 unset($msg);
679
680         } else {
681                 // Set manually
682                 if (isset($script)) die_message('$script: Already init');
683                 if (! is_url($init_uri, TRUE)) die_message('$script: Invalid URI');
684                 $script = $init_uri;
685         }
686
687         // Cut filename or not
688         if (isset($script_directory_index)) {
689                 if (! file_exists($script_directory_index))
690                         die_message('Directory index file not found: ' .
691                                 htmlsc($script_directory_index));
692                 $matches = array();
693                 if (preg_match('#^(.+/)' . preg_quote($script_directory_index, '#') . '$#',
694                         $script, $matches)) $script = $matches[1];
695         }
696
697         return $script;
698 }
699
700 // Remove null(\0) bytes from variables
701 //
702 // NOTE: PHP had vulnerabilities that opens "hoge.php" via fopen("hoge.php\0.txt") etc.
703 // [PHP-users 12736] null byte attack
704 // http://ns1.php.gr.jp/pipermail/php-users/2003-January/012742.html
705 //
706 // 2003-05-16: magic quotes gpcの復元処理を統合
707 // 2003-05-21: 連想配列のキーはbinary safe
708 //
709 function input_filter($param)
710 {
711         static $magic_quotes_gpc = NULL;
712         if ($magic_quotes_gpc === NULL)
713             $magic_quotes_gpc = get_magic_quotes_gpc();
714
715         if (is_array($param)) {
716                 return array_map('input_filter', $param);
717         } else {
718                 $result = str_replace("\0", '', $param);
719                 if ($magic_quotes_gpc) $result = stripslashes($result);
720                 return $result;
721         }
722 }
723
724 // Compat for 3rd party plugins. Remove this later
725 function sanitize($param) {
726         return input_filter($param);
727 }
728
729 // Explode Comma-Separated Values to an array
730 function csv_explode($separator, $string)
731 {
732         $retval = $matches = array();
733
734         $_separator = preg_quote($separator, '/');
735         if (! preg_match_all('/("[^"]*(?:""[^"]*)*"|[^' . $_separator . ']*)' .
736             $_separator . '/', $string . $separator, $matches))
737                 return array();
738
739         foreach ($matches[1] as $str) {
740                 $len = strlen($str);
741                 if ($len > 1 && $str{0} == '"' && $str{$len - 1} == '"')
742                         $str = str_replace('""', '"', substr($str, 1, -1));
743                 $retval[] = $str;
744         }
745         return $retval;
746 }
747
748 // Implode an array with CSV data format (escape double quotes)
749 function csv_implode($glue, $pieces)
750 {
751         $_glue = ($glue != '') ? '\\' . $glue{0} : '';
752         $arr = array();
753         foreach ($pieces as $str) {
754                 if (preg_match('/[' . '"' . "\n\r" . $_glue . ']/', $str))
755                         $str = '"' . str_replace('"', '""', $str) . '"';
756                 $arr[] = $str;
757         }
758         return join($glue, $arr);
759 }
760
761 // Sugar with default settings
762 function htmlsc($string = '', $flags = ENT_COMPAT, $charset = CONTENT_CHARSET)
763 {
764         return htmlspecialchars($string, $flags, $charset);     // htmlsc()
765 }
766
767 /**
768  * Get redirect page name on Page Redirect Rules
769  *
770  * This function returns exactly false if it doesn't need redirection.
771  * So callers need check return value is false or not.
772  *
773  * @param $page page name
774  * @return new page name or false
775  */
776 function get_pagename_on_redirect($page) {
777         global $page_redirect_rules;
778         foreach ($page_redirect_rules as $rule=>$replace) {
779                 if (preg_match($rule, $page)) {
780                         if (is_string($replace)) {
781                                 $new_page = preg_replace($rule, $replace, $page);
782                         } elseif (is_object($replace) && is_callable($replace)) {
783                                 $new_page = preg_replace_callback($rule, $replace, $page);
784                         } else {
785                                 die_message('Invalid redirect rule: ' . $rule . '=>' . $replace);
786                         }
787                         if ($page !== $new_page) {
788                                 return $new_page;
789                         }
790                 }
791         }
792         return false;
793 }
794
795 /**
796  * Redirect from an old page to new page
797  *
798  * This function returns true when a redirection occurs.
799  * So callers need check return value is false or true.
800  * And if it is true, then you have to exit PHP script.
801  *
802  * @return bool Inticates a redirection occurred or not
803  */
804 function manage_page_redirect() {
805         global $vars;
806         if (isset($vars['page'])) {
807                 $page = $vars['page'];
808         }
809         $new_page = get_pagename_on_redirect($page);
810         if ($new_page != false) {
811                 header('Location: ' . get_script_uri() . '?' .
812                         pagename_urlencode($new_page));
813                 return TRUE;
814         }
815         return FALSE;
816 }
817
818 //// Compat ////
819
820 // is_a --  Returns TRUE if the object is of this class or has this class as one of its parents
821 // (PHP 4 >= 4.2.0)
822 if (! function_exists('is_a')) {
823
824         function is_a($class, $match)
825         {
826                 if (empty($class)) return FALSE; 
827
828                 $class = is_object($class) ? get_class($class) : $class;
829                 if (strtolower($class) == strtolower($match)) {
830                         return TRUE;
831                 } else {
832                         return is_a(get_parent_class($class), $match);  // Recurse
833                 }
834         }
835 }
836
837 // array_fill -- Fill an array with values
838 // (PHP 4 >= 4.2.0)
839 if (! function_exists('array_fill')) {
840
841         function array_fill($start_index, $num, $value)
842         {
843                 $ret = array();
844                 while ($num-- > 0) $ret[$start_index++] = $value;
845                 return $ret;
846         }
847 }
848
849 // md5_file -- Calculates the md5 hash of a given filename
850 // (PHP 4 >= 4.2.0)
851 if (! function_exists('md5_file')) {
852
853         function md5_file($filename)
854         {
855                 if (! file_exists($filename)) return FALSE;
856
857                 $fd = fopen($filename, 'rb');
858                 if ($fd === FALSE ) return FALSE;
859                 $data = fread($fd, filesize($filename));
860                 fclose($fd);
861                 return md5($data);
862         }
863 }
864
865 // sha1 -- Compute SHA-1 hash
866 // (PHP 4 >= 4.3.0, PHP5)
867 if (! function_exists('sha1')) {
868         if (extension_loaded('mhash')) {
869                 function sha1($str)
870                 {
871                         return bin2hex(mhash(MHASH_SHA1, $str));
872                 }
873         }
874 }