OSDN Git Service

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