OSDN Git Service

2f11e9468749f93b08997c3931c72f8adbcf6a3f
[pukiwiki/pukiwiki.git] / lib / func.php
1 <?php
2 // PukiWiki - Yet another WikiWikiWeb clone.
3 // func.php
4 // Copyright
5 //   2002-2022 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 function get_passage_date_html_span($date_atom)
307 {
308         return '<span class="page_passage" data-mtime="' . $date_atom . '"></span>';
309 }
310
311 function get_passage_mtime_html_span($mtime)
312 {
313         $date_atom = get_date_atom($mtime);
314         return get_passage_date_html_span($date_atom);
315 }
316
317 /**
318  * Get passage span html
319  *
320  * @param $page
321  */
322 function get_passage_html_span($page)
323 {
324         $date_atom = get_page_date_atom($page);
325         return get_passage_date_html_span($date_atom);
326 }
327
328 function get_link_passage_class() {
329         return 'link_page_passage';
330 }
331
332 /**
333  * Get page link general attributes
334  * @param $page
335  * @return array('data_mtime' => page mtime or null, 'class' => additinal classes)
336  */
337 function get_page_link_a_attrs($page)
338 {
339         global $show_passage;
340         if ($show_passage) {
341                 $pagemtime = get_page_date_atom($page);
342                 return array(
343                         'data_mtime' => $pagemtime,
344                         'class' => get_link_passage_class(),
345                 );
346         }
347         return array(
348                 'data_mtime' => '',
349                 'class' => ''
350         );
351 }
352
353 /**
354  * Get page link general attributes from filetime
355  * @param $filetime
356  * @return array('data_mtime' => page mtime or null, 'class' => additinal classes)
357  */
358 function get_filetime_a_attrs($filetime)
359 {
360         global $show_passage;
361         if ($show_passage) {
362                 $pagemtime = get_date_atom($filetime + LOCALZONE);
363                 return array(
364                         'data_mtime' => $pagemtime,
365                         'class' => get_link_passage_class(),
366                 );
367         }
368         return array(
369                 'data_mtime' => '',
370                 'class' => ''
371         );
372 }
373
374 // 'Search' main function
375 function do_search($word, $type = 'AND', $non_format = FALSE, $base = '')
376 {
377         global $whatsnew, $non_list, $search_non_list;
378         global $_msg_andresult, $_msg_orresult, $_msg_notfoundresult;
379         global $search_auth, $show_passage;
380
381         $retval = array();
382
383         $b_type = ($type == 'AND'); // AND:TRUE OR:FALSE
384         $keys = get_search_words(preg_split('/\s+/', $word, -1, PREG_SPLIT_NO_EMPTY));
385         foreach ($keys as $key=>$value)
386                 $keys[$key] = '/' . $value . '/S';
387
388         $pages = get_existpages();
389
390         // Avoid
391         if ($base != '') {
392                 $pages = preg_grep('/^' . preg_quote($base, '/') . '/S', $pages);
393         }
394         if (! $search_non_list) {
395                 $pages = array_diff($pages, preg_grep('/' . $non_list . '/S', $pages));
396         }
397         $pages = array_flip($pages);
398         unset($pages[$whatsnew]);
399
400         $count = count($pages);
401         foreach (array_keys($pages) as $page) {
402                 $b_match = FALSE;
403
404                 // Search for page name
405                 if (! $non_format) {
406                         foreach ($keys as $key) {
407                                 $b_match = preg_match($key, $page);
408                                 if ($b_type xor $b_match) break; // OR
409                         }
410                         if ($b_match) continue;
411                 }
412
413                 // Search auth for page contents
414                 if ($search_auth && ! check_readable($page, false, false)) {
415                         unset($pages[$page]);
416                         --$count;
417                         continue;
418                 }
419
420                 // Search for page contents
421                 foreach ($keys as $key) {
422                         $body = get_source($page, TRUE, TRUE, TRUE);
423                         $b_match = preg_match($key, remove_author_header($body));
424                         if ($b_type xor $b_match) break; // OR
425                 }
426                 if ($b_match) continue;
427
428                 unset($pages[$page]); // Miss
429         }
430         if ($non_format) return array_keys($pages);
431
432         $r_word = rawurlencode($word);
433         $s_word = htmlsc($word);
434         if (empty($pages))
435                 return str_replace('$1', $s_word, str_replace('$3', $count, $_msg_notfoundresult));
436
437         ksort($pages, SORT_STRING);
438
439         $retval = '<ul>' . "\n";
440         foreach (array_keys($pages) as $page) {
441                 $r_page  = rawurlencode($page);
442                 $s_page  = htmlsc($page);
443                 $passage = $show_passage ? ' ' . get_passage_html_span($page) : '';
444                 $retval .= ' <li><a href="' . get_base_uri() . '?cmd=read&amp;page=' .
445                         $r_page . '&amp;word=' . $r_word . '">' . $s_page .
446                         '</a>' . $passage . '</li>' . "\n";
447         }
448         $retval .= '</ul>' . "\n";
449
450         $retval .= str_replace('$1', $s_word, str_replace('$2', count($pages),
451                 str_replace('$3', $count, $b_type ? $_msg_andresult : $_msg_orresult)));
452
453         return $retval;
454 }
455
456 // Argument check for program
457 function arg_check($str)
458 {
459         global $vars;
460         return isset($vars['cmd']) && (strpos($vars['cmd'], $str) === 0);
461 }
462
463 function _pagename_urlencode_callback($matches)
464 {
465         return urlencode($matches[0]);
466 }
467
468 function pagename_urlencode($page)
469 {
470         return preg_replace_callback('|[^/:]+|', '_pagename_urlencode_callback', $page);
471 }
472
473 // Encode page-name
474 function encode($str)
475 {
476         $str = strval($str);
477         return ($str == '') ? '' : strtoupper(bin2hex($str));
478         // Equal to strtoupper(join('', unpack('H*0', $key)));
479         // But PHP 4.3.10 says 'Warning: unpack(): Type H: outside of string in ...'
480 }
481
482 // Decode page name
483 function decode($str)
484 {
485         return pkwk_hex2bin($str);
486 }
487
488 // Inversion of bin2hex()
489 function pkwk_hex2bin($hex_string)
490 {
491         // preg_match : Avoid warning : pack(): Type H: illegal hex digit ...
492         // (string)   : Always treat as string (not int etc). See BugTrack2/31
493         return preg_match('/^[0-9a-f]+$/i', $hex_string) ?
494                 pack('H*', (string)$hex_string) : $hex_string;
495 }
496
497 // Remove [[ ]] (brackets)
498 function strip_bracket($str)
499 {
500         $match = array();
501         if (preg_match('/^\[\[(.*)\]\]$/', $str, $match)) {
502                 return $match[1];
503         } else {
504                 return $str;
505         }
506 }
507
508 // Create list of pages
509 function page_list($pages, $cmd = 'read', $withfilename = FALSE)
510 {
511         global $list_index;
512         global $_msg_symbol, $_msg_other;
513         global $pagereading_enable;
514
515         $script = get_base_uri();
516
517         // ソートキーを決定する。 ' ' < '[a-zA-Z]' < 'zz'という前提。
518         $symbol = ' ';
519         $other = 'zz';
520
521         $retval = '';
522
523         if($pagereading_enable) {
524                 mb_regex_encoding(SOURCE_ENCODING);
525                 $readings = get_readings($pages);
526         }
527         $list = $matches = array();
528         uasort($pages, 'strnatcmp');
529         foreach($pages as $file=>$page) {
530                 $s_page  = htmlsc($page, ENT_QUOTES);
531                 // Shrink URI for read
532                 if ($cmd == 'read') {
533                         $href = get_page_uri($page);
534                 } else {
535                         $href = $script . '?cmd=' . $cmd . '&amp;page=' . rawurlencode($page);
536                 }
537                 $str = '   <li><a href="' . $href . '">' .
538                         $s_page . '</a> ' . get_pg_passage($page);
539                 if ($withfilename) {
540                         $s_file = htmlsc($file);
541                         $str .= "\n" . '    <ul><li>' . $s_file . '</li></ul>' .
542                                 "\n" . '   ';
543                 }
544                 $str .= '</li>';
545
546                 // WARNING: Japanese code hard-wired
547                 if($pagereading_enable) {
548                         if(mb_ereg('^([A-Za-z])', mb_convert_kana($page, 'a'), $matches)) {
549                                 $head = strtoupper($matches[1]);
550                         } elseif (isset($readings[$page]) && mb_ereg('^([ァ-ヶ])', $readings[$page], $matches)) { // here
551                                 $head = $matches[1];
552                         } elseif (mb_ereg('^[ -~]|[^ぁ-ん亜-熙]', $page)) { // and here
553                                 $head = $symbol;
554                         } else {
555                                 $head = $other;
556                         }
557                 } else {
558                         $head = (preg_match('/^([A-Za-z])/', $page, $matches)) ? strtoupper($matches[1]) :
559                                 (preg_match('/^([ -~])/', $page) ? $symbol : $other);
560                 }
561                 $list[$head][$page] = $str;
562         }
563         uksort($list, 'strnatcmp');
564
565         $cnt = 0;
566         $arr_index = array();
567         $retval .= '<ul>' . "\n";
568         foreach ($list as $head=>$sub_pages) {
569                 if ($head === $symbol) {
570                         $head = $_msg_symbol;
571                 } else if ($head === $other) {
572                         $head = $_msg_other;
573                 }
574
575                 if ($list_index) {
576                         ++$cnt;
577                         $arr_index[] = '<a id="top_' . $cnt .
578                                 '" href="#head_' . $cnt . '"><strong>' .
579                                 $head . '</strong></a>';
580                         $retval .= ' <li><a id="head_' . $cnt . '" href="#top_' . $cnt .
581                                 '"><strong>' . $head . '</strong></a>' . "\n" .
582                                 '  <ul>' . "\n";
583                 }
584                 $retval .= join("\n", $sub_pages);
585                 if ($list_index)
586                         $retval .= "\n  </ul>\n </li>\n";
587         }
588         $retval .= '</ul>' . "\n";
589         if ($list_index && $cnt > 0) {
590                 $top = array();
591                 while (! empty($arr_index))
592                         $top[] = join(' | ' . "\n", array_splice($arr_index, 0, 16)) . "\n";
593
594                 $retval = '<div id="top" style="text-align:center">' . "\n" .
595                         join('<br />', $top) . '</div>' . "\n" . $retval;
596         }
597         return $retval;
598 }
599
600 // Show text formatting rules
601 function catrule()
602 {
603         global $rule_page;
604
605         if (! is_page($rule_page)) {
606                 return '<p>Sorry, page \'' . htmlsc($rule_page) .
607                         '\' unavailable.</p>';
608         } else {
609                 return convert_html(get_source($rule_page));
610         }
611 }
612
613 // Show (critical) error message
614 function die_message($msg)
615 {
616         $title = $page = 'Runtime error';
617         $body = <<<EOD
618 <h3>Runtime error</h3>
619 <strong>Error message : $msg</strong>
620 EOD;
621
622         pkwk_common_headers();
623         if(defined('SKIN_FILE') && file_exists(SKIN_FILE) && is_readable(SKIN_FILE)) {
624                 catbody($title, $page, $body);
625         } else {
626                 $charset = 'utf-8';
627                 if(defined('CONTENT_CHARSET')) {
628                         $charset = CONTENT_CHARSET;
629                 }
630                 header("Content-Type: text/html; charset=$charset");
631                 print <<<EOD
632 <!DOCTYPE html>
633 <html>
634  <head>
635   <meta http-equiv="content-type" content="text/html; charset=$charset">
636   <title>$title</title>
637  </head>
638  <body>
639  $body
640  </body>
641 </html>
642 EOD;
643         }
644         exit;
645 }
646
647 function die_invalid_pagename() {
648         $title = 'Error';
649         $page = 'Error: Invlid page name';
650         $body = <<<EOD
651 <h3>Error</h3>
652 <strong>Error message: Invalid page name</strong>
653 EOD;
654
655         pkwk_common_headers();
656         header('HTTP/1.0 400 Bad request');
657         catbody($title, $page, $body);
658         exit;
659 }
660
661
662 // Have the time (as microtime)
663 function getmicrotime()
664 {
665         list($usec, $sec) = explode(' ', microtime());
666         return ((float)$sec + (float)$usec);
667 }
668
669 // Elapsed time by second
670 //define('MUTIME', getmicrotime());
671 function elapsedtime()
672 {
673         $at_the_microtime = MUTIME;
674         return sprintf('%01.03f', getmicrotime() - $at_the_microtime);
675 }
676
677 // Get the date
678 function get_date($format, $timestamp = NULL)
679 {
680         $format = preg_replace('/(?<!\\\)T/',
681                 preg_replace('/(.)/', '\\\$1', ZONE), $format);
682
683         $time = ZONETIME + (($timestamp !== NULL) ? $timestamp : UTIME);
684
685         return date($format, $time);
686 }
687
688 // Format date string
689 function format_date($val, $paren = FALSE)
690 {
691         global $date_format, $time_format, $weeklabels;
692
693         $val += ZONETIME;
694
695         $date = date($date_format, $val) .
696                 ' (' . $weeklabels[date('w', $val)] . ') ' .
697                 date($time_format, $val);
698
699         return $paren ? '(' . $date . ')' : $date;
700 }
701
702 /**
703  * Format date in DATE_ATOM format.
704  */
705 function get_date_atom($timestamp)
706 {
707         // Compatible with DATE_ATOM format
708         // return date(DATE_ATOM, $timestamp);
709         $zmin = abs(LOCALZONE / 60);
710         return date('Y-m-d\TH:i:s', $timestamp) . sprintf('%s%02d:%02d',
711                 (LOCALZONE < 0 ? '-' : '+') , $zmin / 60, $zmin % 60);
712 }
713
714 // Get short string of the passage, 'N seconds/minutes/hours/days/years ago'
715 function get_passage($time, $paren = TRUE)
716 {
717         static $units = array('m'=>60, 'h'=>24, 'd'=>1);
718
719         $time = max(0, (UTIME - $time) / 60); // minutes
720
721         foreach ($units as $unit=>$card) {
722                 if ($time < $card) break;
723                 $time /= $card;
724         }
725         $time = floor($time) . $unit;
726
727         return $paren ? '(' . $time . ')' : $time;
728 }
729
730 // Hide <input type="(submit|button|image)"...>
731 function drop_submit($str)
732 {
733         return preg_replace('/<input([^>]+)type="(submit|button|image)"/i',
734                 '<input$1type="hidden"', $str);
735 }
736
737 // Generate AutoLink patterns (thx to hirofummy)
738 function get_autolink_pattern($pages, $min_length)
739 {
740         global $WikiName, $nowikiname;
741
742         $config = new Config('AutoLink');
743         $config->read();
744         $ignorepages      = $config->get('IgnoreList');
745         $forceignorepages = $config->get('ForceIgnoreList');
746         unset($config);
747         $auto_pages = array_merge($ignorepages, $forceignorepages);
748
749         foreach ($pages as $page) {
750                 if (preg_match('/^' . $WikiName . '$/', $page) ?
751                     $nowikiname : strlen($page) >= $min_length) {
752                         $auto_pages[] = $page;
753                 }
754         }
755         if (empty($auto_pages)) {
756                 $result = $result_a = '(?!)';
757         } else {
758                 $auto_pages = array_unique($auto_pages);
759                 sort($auto_pages, SORT_STRING);
760
761                 $auto_pages_a = array_values(preg_grep('/^[A-Z]+$/i', $auto_pages));
762                 $auto_pages   = array_values(array_diff($auto_pages,  $auto_pages_a));
763
764                 $result   = get_autolink_pattern_sub($auto_pages,   0, count($auto_pages),   0);
765                 $result_a = get_autolink_pattern_sub($auto_pages_a, 0, count($auto_pages_a), 0);
766         }
767         return array($result, $result_a, $forceignorepages);
768 }
769
770 function get_autolink_pattern_sub($pages, $start, $end, $pos)
771 {
772         if ($end == 0) return '(?!)';
773
774         $result = '';
775         $count = $i = $j = 0;
776         $x = (mb_strlen($pages[$start]) <= $pos);
777         if ($x) ++$start;
778
779         for ($i = $start; $i < $end; $i = $j) {
780                 $char = mb_substr($pages[$i], $pos, 1);
781                 for ($j = $i; $j < $end; $j++)
782                         if (mb_substr($pages[$j], $pos, 1) != $char) break;
783
784                 if ($i != $start) $result .= '|';
785                 if ($i >= ($j - 1)) {
786                         $result .= str_replace(' ', '\\ ', preg_quote(mb_substr($pages[$i], $pos), '/'));
787                 } else {
788                         $result .= str_replace(' ', '\\ ', preg_quote($char, '/')) .
789                                 get_autolink_pattern_sub($pages, $i, $j, $pos + 1);
790                 }
791                 ++$count;
792         }
793         if ($x || $count > 1) $result = '(?:' . $result . ')';
794         if ($x)               $result .= '?';
795
796         return $result;
797 }
798
799 // Get AutoAlias value
800 function get_autoalias_right_link($alias_name)
801 {
802         $pairs = get_autoaliases();
803         // A string: Seek the pair
804         if (isset($pairs[$alias_name])) {
805                 return $pairs[$alias_name];
806         }
807         return '';
808 }
809
810 // Load setting pairs from AutoAliasName
811 function get_autoaliases()
812 {
813         global $aliaspage, $autoalias_max_words;
814         static $pairs;
815         $preg_u = get_preg_u();
816
817         if (! isset($pairs)) {
818                 $pairs = array();
819                 $pattern = <<<EOD
820 \[\[                # open bracket
821 ((?:(?!\]\]).)+)>   # (1) alias name
822 ((?:(?!\]\]).)+)    # (2) alias link
823 \]\]                # close bracket
824 EOD;
825                 $postdata = join('', get_source($aliaspage));
826                 $matches  = array();
827                 $count = 0;
828                 $max   = max($autoalias_max_words, 0);
829                 if (preg_match_all('/' . $pattern . '/x' . get_preg_u(), $postdata,
830                         $matches, PREG_SET_ORDER)) {
831                         foreach($matches as $key => $value) {
832                                 if ($count ==  $max) break;
833                                 $name = trim($value[1]);
834                                 if (! isset($pairs[$name])) {
835                                         ++$count;
836                                          $pairs[$name] = trim($value[2]);
837                                 }
838                                 unset($matches[$key]);
839                         }
840                 }
841         }
842         return $pairs;
843 }
844
845 /**
846  * Get propery URI of this script
847  *
848  * @param $uri_type relative or absolute option
849  *        PKWK_URI_RELATIVE, PKWK_URI_ROOT or PKWK_URI_ABSOLUTE
850  */
851 function get_base_uri($uri_type = PKWK_URI_RELATIVE)
852 {
853         $base_type = pkwk_base_uri_type_stack_peek();
854         $type = max($base_type, $uri_type);
855         switch ($type) {
856         case PKWK_URI_RELATIVE:
857                 return pkwk_script_uri_base(PKWK_URI_RELATIVE);
858         case PKWK_URI_ROOT:
859                 return pkwk_script_uri_base(PKWK_URI_ROOT);
860         case PKWK_URI_ABSOLUTE:
861                 return pkwk_script_uri_base(PKWK_URI_ABSOLUTE);
862         default:
863                 die_message('Invalid uri_type in get_base_uri()');
864         }
865 }
866
867 /**
868  * Get URI of the page
869  *
870  * @param page page name
871  * @param $uri_type relative or absolute option
872  *        PKWK_URI_RELATIVE, PKWK_URI_ROOT or PKWK_URI_ABSOLUTE
873  */
874 function get_page_uri($page, $uri_type = PKWK_URI_RELATIVE)
875 {
876         global $page_uri_handler, $defaultpage;
877         if ($page === $defaultpage) {
878                 return get_base_uri($uri_type);
879         }
880         return get_base_uri($uri_type) . $page_uri_handler->get_page_uri_virtual_query($page);
881 }
882
883 // Get absolute-URI of this script
884 function get_script_uri()
885 {
886         return get_base_uri(PKWK_URI_ABSOLUTE);
887 }
888
889 /**
890  * Get or initialize Script URI
891  *
892  * @param $uri_type relative or absolute potion
893  *        PKWK_URI_RELATIVE, PKWK_URI_ROOT or PKWK_URI_ABSOLUTE
894  * @param $initialize true if you initialize URI
895  * @param $uri_set URI set manually
896  */
897 function pkwk_script_uri_base($uri_type, $initialize = null, $uri_set = null)
898 {
899         global $script_directory_index;
900         static $initialized = false;
901         static $uri_absolute, $uri_root, $uri_relative;
902         if (! $initialized) {
903                 if (isset($initialize) && $initialize) {
904                         if (isset($uri_set)) {
905                                 $uri_absolute = $uri_set;
906                         } else {
907                                 $uri_absolute = guess_script_absolute_uri();
908                         }
909                         // Support $script_directory_index (cut 'index.php')
910                         if (isset($script_directory_index)) {
911                                 $slash_index = '/' . $script_directory_index;
912                                 $len = strlen($slash_index);
913                                 if (substr($uri_absolute,  -1 * $len) === $slash_index) {
914                                         $uri_absolute = substr($uri_absolute, 0, strlen($uri_absolute) - $len + 1);
915                                 }
916                         }
917                         $elements = parse_url($uri_absolute);
918                         $uri_root = $elements['path'];
919                         if (substr($uri_root, -1) === '/') {
920                                 $uri_relative = './';
921                         } else {
922                                 $pos = mb_strrpos($uri_root, '/');
923                                 if ($pos >= 0) {
924                                         $uri_relative = substr($uri_root, $pos + 1);
925                                 } else {
926                                         $uri_relative = $uri_root;
927                                 }
928                         }
929                         $initialized = true;
930                 } else {
931                         die_message('Script URI must be initialized in pkwk_script_uri_base()');
932                 }
933         }
934         switch ($uri_type) {
935         case PKWK_URI_RELATIVE:
936                 return $uri_relative;
937         case PKWK_URI_ROOT:
938                 return $uri_root;
939         case PKWK_URI_ABSOLUTE:
940                 return $uri_absolute;
941         default:
942                 die_message('Invalid uri_type in pkwk_script_uri_base()');
943         }
944 }
945
946 /**
947  * Create uri_type context
948  *
949  * @param $uri_type relative or absolute option
950  *        PKWK_URI_RELATIVE, PKWK_URI_ROOT or PKWK_URI_ABSOLUTE
951  */
952 function pkwk_base_uri_type_stack_push($uri_type)
953 {
954         _pkwk_base_uri_type_stack(false, true, $uri_type);
955 }
956
957 /**
958  * Stop current active uri_type context
959  */
960 function pkwk_base_uri_type_stack_pop()
961 {
962         _pkwk_base_uri_type_stack(false, false);
963 }
964
965 /**
966  * Get current active uri_type status
967  */
968 function pkwk_base_uri_type_stack_peek()
969 {
970         $type = _pkwk_base_uri_type_stack(true, false);
971         if (is_null($type)) {
972                 return PKWK_URI_RELATIVE;
973         } elseif ($type === PKWK_URI_ABSOLUTE) {
974                 return PKWK_URI_ABSOLUTE;
975         } elseif ($type === PKWK_URI_ROOT) {
976                 return PKWK_URI_ROOT;
977         } else {
978                 return PKWK_URI_RELATIVE;
979         }
980 }
981
982 /**
983  * uri_type context internal function
984  *
985  * @param $peek is peek action or not
986  * @param $push push(true) or pop(false) on not peeking
987  * @param $uri_type uri_type on push and non-peeking
988  * @return $uri_type uri_type for peeking
989  */
990 function _pkwk_base_uri_type_stack($peek, $push, $uri_type = null)
991 {
992         static $uri_types = array();
993         if ($peek) {
994                 // Peek: get latest value
995                 if (count($uri_types) === 0) {
996                         return null;
997                 } else {
998                         return $uri_types[0];
999                 }
1000         } else {
1001                 if ($push) {
1002                         // Push $uri_type
1003                         if (count($uri_types) === 0) {
1004                                 array_unshift($uri_types, $uri_type);
1005                         } else {
1006                                 $prev_type = $uri_types[0];
1007                                 if ($uri_type >= $prev_type) {
1008                                         array_unshift($uri_types, $uri_type);
1009                                 } else {
1010                                         array_unshift($uri_types, $prev_type);
1011                                 }
1012                         }
1013                 } else {
1014                         // Pop $uri_type
1015                         return array_shift($uri_types);
1016                 }
1017         }
1018 }
1019
1020 /**
1021  * Guess Script Absolute URI.
1022  *
1023  * SERVER_PORT: $_SERVER['SERVER_PORT'] converted in init.php
1024  * SERVER_NAME: $_SERVER['SERVER_NAME'] converted in init.php
1025  */
1026 function guess_script_absolute_uri()
1027 {
1028         $port = SERVER_PORT;
1029         $is_ssl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ||
1030                 (isset($_SERVER['REQUEST_SCHEME']) && $_SERVER['REQUEST_SCHEME'] === 'https');
1031         if ($is_ssl) {
1032                 $host = 'https://' . SERVER_NAME .
1033                         ($port == 443 ? '' : ':' . $port);
1034         } else {
1035                 $host = 'http://' . SERVER_NAME .
1036                         ($port == 80 ? '' : ':' . $port);
1037         }
1038         $uri_elements = parse_url($host . $_SERVER['REQUEST_URI']);
1039         return $host . $uri_elements['path'];
1040 }
1041
1042 // Remove null(\0) bytes from variables
1043 //
1044 // NOTE: PHP had vulnerabilities that opens "hoge.php" via fopen("hoge.php\0.txt") etc.
1045 // [PHP-users 12736] null byte attack
1046 // http://ns1.php.gr.jp/pipermail/php-users/2003-January/012742.html
1047 //
1048 // 2003-05-16: magic quotes gpcの復元処理を統合
1049 // 2003-05-21: 連想配列のキーはbinary safe
1050 //
1051 function input_filter($param)
1052 {
1053         static $magic_quotes_gpc = NULL;
1054         if ($magic_quotes_gpc === NULL) {
1055                 if (function_exists('get_magic_quotes_gpc')) {
1056                         // No 'get_magic_quotes_gpc' function in PHP8
1057                         $magic_quotes_gpc = get_magic_quotes_gpc();
1058                 } else {
1059                         $magic_quotes_gpc = 0;
1060                 }
1061         }
1062         if (is_array($param)) {
1063                 return array_map('input_filter', $param);
1064         } else {
1065                 $result = str_replace("\0", '', $param);
1066                 if ($magic_quotes_gpc) $result = stripslashes($result);
1067                 return $result;
1068         }
1069 }
1070
1071 // Compat for 3rd party plugins. Remove this later
1072 function sanitize($param) {
1073         return input_filter($param);
1074 }
1075
1076 // Explode Comma-Separated Values to an array
1077 function csv_explode($separator, $string)
1078 {
1079         $retval = $matches = array();
1080
1081         $_separator = preg_quote($separator, '/');
1082         if (! preg_match_all('/("[^"]*(?:""[^"]*)*"|[^' . $_separator . ']*)' .
1083             $_separator . '/', $string . $separator, $matches))
1084                 return array();
1085
1086         foreach ($matches[1] as $str) {
1087                 $len = strlen($str);
1088                 if ($len > 1 && $str[0] == '"' && $str[$len - 1] == '"')
1089                         $str = str_replace('""', '"', substr($str, 1, -1));
1090                 $retval[] = $str;
1091         }
1092         return $retval;
1093 }
1094
1095 // Implode an array with CSV data format (escape double quotes)
1096 function csv_implode($glue, $pieces)
1097 {
1098         $_glue = ($glue != '') ? '\\' . $glue[0] : '';
1099         $arr = array();
1100         foreach ($pieces as $str) {
1101                 if (preg_match('/[' . '"' . "\n\r" . $_glue . ']/', $str))
1102                         $str = '"' . str_replace('"', '""', $str) . '"';
1103                 $arr[] = $str;
1104         }
1105         return join($glue, $arr);
1106 }
1107
1108 // Sugar with default settings
1109 function htmlsc($string = '', $flags = ENT_COMPAT, $charset = CONTENT_CHARSET)
1110 {
1111         return htmlspecialchars($string, $flags, $charset);     // htmlsc()
1112 }
1113
1114 /**
1115  * Get JSON string with htmlspecialchars().
1116  */
1117 function htmlsc_json($obj)
1118 {
1119         // json_encode: PHP 5.2+
1120         // JSON_UNESCAPED_UNICODE: PHP 5.4+
1121         // JSON_UNESCAPED_SLASHES: PHP 5.4+
1122         if (defined('JSON_UNESCAPED_UNICODE')) {
1123                 return htmlsc(json_encode($obj,
1124                         JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
1125         }
1126         return '';
1127 }
1128
1129 /**
1130  * Get redirect page name on Page Redirect Rules
1131  *
1132  * This function returns exactly false if it doesn't need redirection.
1133  * So callers need check return value is false or not.
1134  *
1135  * @param $page page name
1136  * @return new page name or false
1137  */
1138 function get_pagename_on_redirect($page) {
1139         global $page_redirect_rules;
1140         foreach ($page_redirect_rules as $rule=>$replace) {
1141                 if (preg_match($rule, $page)) {
1142                         if (is_string($replace)) {
1143                                 $new_page = preg_replace($rule, $replace, $page);
1144                         } elseif (is_object($replace) && is_callable($replace)) {
1145                                 $new_page = preg_replace_callback($rule, $replace, $page);
1146                         } else {
1147                                 die_message('Invalid redirect rule: ' . $rule . '=>' . $replace);
1148                         }
1149                         if ($page !== $new_page) {
1150                                 return $new_page;
1151                         }
1152                 }
1153         }
1154         return false;
1155 }
1156
1157 /**
1158  * Redirect from an old page to new page
1159  *
1160  * This function returns true when a redirection occurs.
1161  * So callers need check return value is false or true.
1162  * And if it is true, then you have to exit PHP script.
1163  *
1164  * @return bool Inticates a redirection occurred or not
1165  */
1166 function manage_page_redirect() {
1167         global $vars;
1168         if (isset($vars['page'])) {
1169                 $page = $vars['page'];
1170         }
1171         $new_page = get_pagename_on_redirect($page);
1172         if ($new_page != false) {
1173                 header('Location: ' . get_page_uri($new_page, PKWK_URI_ROOT));
1174                 return TRUE;
1175         }
1176         return FALSE;
1177 }
1178
1179 /**
1180  * Return 'u' (PCRE_UTF8) if PHP7+ and UTF-8.
1181  */
1182 function get_preg_u() {
1183         static $utf8u; // 'u'(PCRE_UTF8) or ''
1184         if (! isset($utf8u)) {
1185                 if (version_compare('7.0.0', PHP_VERSION, '<=')
1186                         && defined('PKWK_UTF8_ENABLE')) {
1187                         $utf8u = 'u';
1188                 } else {
1189                         $utf8u = '';
1190                 }
1191         }
1192         return $utf8u;
1193 }
1194
1195 // Default Page name - URI mapping handler
1196 class PukiWikiStandardPageURIHandler {
1197         function filter_raw_query_string($query_string) {
1198                 return $query_string;
1199         }
1200
1201         function get_page_uri_virtual_query($page) {
1202                 return '?' . pagename_urlencode($page);
1203         }
1204
1205         function get_page_from_query_string($query_string) {
1206                 $param1st = preg_replace("#^([^&]*)&.*$#", "$1", $query_string);
1207                 if ($param1st == '') {
1208                         return null; // default page
1209                 }
1210                 if (strpos($param1st, '=') !== FALSE) {
1211                         // Found '/?key=value' (Top page with additional query params)
1212                         return null; // default page
1213                 }
1214                 $page = urldecode($param1st);
1215                 $page2 = input_filter($page);
1216                 if ($page !== $page2) {
1217                         return FALSE; // Error page
1218                 }
1219                 return $page2;
1220         }
1221 }
1222
1223 //// Compat ////
1224
1225 // is_a --  Returns TRUE if the object is of this class or has this class as one of its parents
1226 // (PHP 4 >= 4.2.0)
1227 if (! function_exists('is_a')) {
1228
1229         function is_a($class, $match)
1230         {
1231                 if (empty($class)) return FALSE; 
1232
1233                 $class = is_object($class) ? get_class($class) : $class;
1234                 if (strtolower($class) == strtolower($match)) {
1235                         return TRUE;
1236                 } else {
1237                         return is_a(get_parent_class($class), $match);  // Recurse
1238                 }
1239         }
1240 }
1241
1242 // array_fill -- Fill an array with values
1243 // (PHP 4 >= 4.2.0)
1244 if (! function_exists('array_fill')) {
1245
1246         function array_fill($start_index, $num, $value)
1247         {
1248                 $ret = array();
1249                 while ($num-- > 0) $ret[$start_index++] = $value;
1250                 return $ret;
1251         }
1252 }
1253
1254 // md5_file -- Calculates the md5 hash of a given filename
1255 // (PHP 4 >= 4.2.0)
1256 if (! function_exists('md5_file')) {
1257
1258         function md5_file($filename)
1259         {
1260                 if (! file_exists($filename)) return FALSE;
1261
1262                 $fd = fopen($filename, 'rb');
1263                 if ($fd === FALSE ) return FALSE;
1264                 $data = fread($fd, filesize($filename));
1265                 fclose($fd);
1266                 return md5($data);
1267         }
1268 }
1269
1270 // sha1 -- Compute SHA-1 hash
1271 // (PHP 4 >= 4.3.0, PHP5)
1272 if (! function_exists('sha1')) {
1273         if (extension_loaded('mhash')) {
1274                 function sha1($str)
1275                 {
1276                         return bin2hex(mhash(MHASH_SHA1, $str));
1277                 }
1278         }
1279 }