OSDN Git Service

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