OSDN Git Service

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