OSDN Git Service

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