OSDN Git Service

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