OSDN Git Service

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