2 // PukiWiki - Yet another WikiWikiWeb clone.
5 // 2002-2016 PukiWiki Development Team
6 // 2001-2002 Originally written by yu-ji
7 // License: GPL v2 or (at your option) any later version
11 function pkwk_log($message)
13 $log_filepath = 'log/error.log.php';
14 static $dateTimeExists;
15 if (!isset($dateTimeExists)) {
16 $dateTimeExists = class_exists('DateTime');
17 error_log("<?php\n", 3, $log_filepath);
19 if ($dateTimeExists) {
21 $d = \DateTime::createFromFormat('U.u', sprintf('%6F', microtime(true)));
22 $timestamp = substr($d->format('Y-m-d H:i:s.u'), 0, 23);
24 $timestamp = date('Y-m-d H:i:s');
26 error_log($timestamp . ' ' . $message . "\n", 3, $log_filepath);
29 function is_interwiki($str)
31 global $InterWikiName;
32 return preg_match('/^' . $InterWikiName . '$/', $str);
35 function is_pagename($str)
39 $is_pagename = (! is_interwiki($str) &&
40 preg_match('/^(?!\/)' . $BracketName . '$(?<!\/$)/', $str) &&
41 ! preg_match('#(^|/)\.{1,2}(/|$)#', $str));
43 if (defined('SOURCE_ENCODING')) {
44 switch(SOURCE_ENCODING){
45 case 'UTF-8': $pattern =
46 '/^(?:[\x00-\x7F]|(?:[\xC0-\xDF][\x80-\xBF])|(?:[\xE0-\xEF][\x80-\xBF][\x80-\xBF]))+$/';
48 case 'EUC-JP': $pattern =
49 '/^(?:[\x00-\x7F]|(?:[\x8E\xA1-\xFE][\xA1-\xFE])|(?:\x8F[\xA1-\xFE][\xA1-\xFE]))+$/';
52 if (isset($pattern) && $pattern != '')
53 $is_pagename = ($is_pagename && preg_match($pattern, $str));
59 function is_url($str, $only_http = FALSE)
61 $scheme = $only_http ? 'https?' : 'https?|ftp|news';
62 return preg_match('/^(' . $scheme . ')(:\/\/[-_.!~*\'()a-zA-Z0-9;\/?:\@&=+\$,%#]*)$/', $str);
66 function is_page($page, $clearcache = FALSE)
68 if ($clearcache) clearstatcache();
69 return file_exists(get_filename($page));
72 function is_editable($page)
75 static $is_editable = array();
77 if (! isset($is_editable[$page])) {
78 $is_editable[$page] = (
81 ! in_array($page, $cantedit)
85 return $is_editable[$page];
88 function is_freeze($page, $clearcache = FALSE)
90 global $function_freeze;
91 static $is_freeze = array();
93 if ($clearcache === TRUE) $is_freeze = array();
94 if (isset($is_freeze[$page])) return $is_freeze[$page];
96 if (! $function_freeze || ! is_page($page)) {
97 $is_freeze[$page] = FALSE;
100 $fp = fopen(get_filename($page), 'rb') or
101 die('is_freeze(): fopen() failed: ' . htmlsc($page));
102 flock($fp, LOCK_SH) or die('is_freeze(): flock() failed');
104 $buffer = fgets($fp, 9);
105 flock($fp, LOCK_UN) or die('is_freeze(): flock() failed');
106 fclose($fp) or die('is_freeze(): fclose() failed: ' . htmlsc($page));
108 $is_freeze[$page] = ($buffer != FALSE && rtrim($buffer, "\r\n") == '#freeze');
109 return $is_freeze[$page];
113 // Handling $non_list
114 // $non_list will be preg_quote($str, '/') later.
115 function check_non_list($page = '')
120 if (! isset($regex)) $regex = '/' . $non_list . '/';
122 return preg_match($regex, $page);
126 function auto_template($page)
128 global $auto_template_func, $auto_template_rules;
130 if (! $auto_template_func) return '';
134 foreach ($auto_template_rules as $rule => $template) {
135 $rule_pattrn = '/' . $rule . '/';
137 if (! preg_match($rule_pattrn, $page, $matches)) continue;
139 $template_page = preg_replace($rule_pattrn, $template, $page);
140 if (! is_page($template_page)) continue;
142 $body = join('', get_source($template_page));
144 // Remove fixed-heading anchors
145 $body = preg_replace('/^(\*{1,3}.*)\[#[A-Za-z][\w-]+\](.*)$/m', '$1$2', $body);
148 $body = preg_replace('/^#freeze\s*$/m', '', $body);
150 $count = count($matches);
151 for ($i = 0; $i < $count; $i++)
152 $body = str_replace('$' . $i, $matches[$i], $body);
159 // Expand all search-words to regexes and push them into an array
160 function get_search_words($words = array(), $do_escape = FALSE)
162 static $init, $mb_convert_kana, $pre, $post, $quote = '/';
164 if (! isset($init)) {
165 // function: mb_convert_kana() is for Japanese code only
166 if (LANG == 'ja' && function_exists('mb_convert_kana')) {
167 $mb_convert_kana = create_function('$str, $option',
168 'return mb_convert_kana($str, $option, SOURCE_ENCODING);');
170 $mb_convert_kana = create_function('$str, $option',
173 if (SOURCE_ENCODING == 'EUC-JP') {
174 // Perl memo - Correct pattern-matching with EUC-JP
175 // http://www.din.or.jp/~ohzaki/perl.htm#JP_Match (Japanese)
177 $post = '(?=(?:[\xA1-\xFE][\xA1-\xFE])*' . // JIS X 0208
178 '(?:[\x00-\x7F\x8E\x8F]|\z))'; // ASCII, SS2, SS3, or the last
185 if (! is_array($words)) $words = array($words);
187 // Generate regex for the words
189 foreach ($words as $word) {
191 if ($word == '') continue;
193 // Normalize: ASCII letters = to single-byte. Others = to Zenkaku and Katakana
194 $word_nm = $mb_convert_kana($word, 'aKCV');
195 $nmlen = mb_strlen($word_nm, SOURCE_ENCODING);
197 // Each chars may be served ...
199 for ($pos = 0; $pos < $nmlen; $pos++) {
200 $char = mb_substr($word_nm, $pos, 1, SOURCE_ENCODING);
202 // Just normalized one? (ASCII char or Zenkaku-Katakana?)
203 $or = array(preg_quote($do_escape ? htmlsc($char) : $char, $quote));
204 if (strlen($char) == 1) {
205 // An ASCII (single-byte) character
206 foreach (array(strtoupper($char), strtolower($char)) as $_char) {
207 if ($char != '&') $or[] = preg_quote($_char, $quote); // As-is?
208 $ascii = ord($_char);
209 $or[] = sprintf('&#(?:%d|x%x);', $ascii, $ascii); // As an entity reference?
210 $or[] = preg_quote($mb_convert_kana($_char, 'A'), $quote); // As Zenkaku?
213 // NEVER COME HERE with mb_substr(string, start, length, 'ASCII')
214 // A multi-byte character
215 $or[] = preg_quote($mb_convert_kana($char, 'c'), $quote); // As Hiragana?
216 $or[] = preg_quote($mb_convert_kana($char, 'k'), $quote); // As Hankaku-Katakana?
218 $chars[] = '(?:' . join('|', array_unique($or)) . ')'; // Regex for the character
221 $regex[$word] = $pre . join('', $chars) . $post; // For the word
224 return $regex; // For all words
227 // 'Search' main function
228 function do_search($word, $type = 'AND', $non_format = FALSE, $base = '')
230 global $script, $whatsnew, $non_list, $search_non_list;
231 global $_msg_andresult, $_msg_orresult, $_msg_notfoundresult;
232 global $search_auth, $show_passage;
236 $b_type = ($type == 'AND'); // AND:TRUE OR:FALSE
237 $keys = get_search_words(preg_split('/\s+/', $word, -1, PREG_SPLIT_NO_EMPTY));
238 foreach ($keys as $key=>$value)
239 $keys[$key] = '/' . $value . '/S';
241 $pages = get_existpages();
245 $pages = preg_grep('/^' . preg_quote($base, '/') . '/S', $pages);
247 if (! $search_non_list) {
248 $pages = array_diff($pages, preg_grep('/' . $non_list . '/S', $pages));
250 $pages = array_flip($pages);
251 unset($pages[$whatsnew]);
253 $count = count($pages);
254 foreach (array_keys($pages) as $page) {
257 // Search for page name
259 foreach ($keys as $key) {
260 $b_match = preg_match($key, $page);
261 if ($b_type xor $b_match) break; // OR
263 if ($b_match) continue;
266 // Search auth for page contents
267 if ($search_auth && ! check_readable($page, false, false)) {
268 unset($pages[$page]);
272 // Search for page contents
273 foreach ($keys as $key) {
274 $b_match = preg_match($key, get_source($page, TRUE, TRUE));
275 if ($b_type xor $b_match) break; // OR
277 if ($b_match) continue;
279 unset($pages[$page]); // Miss
281 if ($non_format) return array_keys($pages);
283 $r_word = rawurlencode($word);
284 $s_word = htmlsc($word);
286 return str_replace('$1', $s_word, $_msg_notfoundresult);
288 ksort($pages, SORT_STRING);
290 $retval = '<ul>' . "\n";
291 foreach (array_keys($pages) as $page) {
292 $r_page = rawurlencode($page);
293 $s_page = htmlsc($page);
294 $passage = $show_passage ? ' ' . get_passage(get_filetime($page)) : '';
295 $retval .= ' <li><a href="' . $script . '?cmd=read&page=' .
296 $r_page . '&word=' . $r_word . '">' . $s_page .
297 '</a>' . $passage . '</li>' . "\n";
299 $retval .= '</ul>' . "\n";
301 $retval .= str_replace('$1', $s_word, str_replace('$2', count($pages),
302 str_replace('$3', $count, $b_type ? $_msg_andresult : $_msg_orresult)));
307 // Argument check for program
308 function arg_check($str)
311 return isset($vars['cmd']) && (strpos($vars['cmd'], $str) === 0);
314 function _pagename_urlencode_callback($matches)
316 return rawurlencode($matches[0]);
319 function pagename_urlencode($page)
321 return preg_replace_callback('|[^/:]+|', '_pagename_urlencode_callback', $page);
325 function encode($str)
328 return ($str == '') ? '' : strtoupper(bin2hex($str));
329 // Equal to strtoupper(join('', unpack('H*0', $key)));
330 // But PHP 4.3.10 says 'Warning: unpack(): Type H: outside of string in ...'
334 function decode($str)
336 return pkwk_hex2bin($str);
339 // Inversion of bin2hex()
340 function pkwk_hex2bin($hex_string)
342 // preg_match : Avoid warning : pack(): Type H: illegal hex digit ...
343 // (string) : Always treat as string (not int etc). See BugTrack2/31
344 return preg_match('/^[0-9a-f]+$/i', $hex_string) ?
345 pack('H*', (string)$hex_string) : $hex_string;
348 // Remove [[ ]] (brackets)
349 function strip_bracket($str)
352 if (preg_match('/^\[\[(.*)\]\]$/', $str, $match)) {
359 // Create list of pages
360 function page_list($pages, $cmd = 'read', $withfilename = FALSE)
362 global $script, $list_index;
363 global $_msg_symbol, $_msg_other;
364 global $pagereading_enable;
366 // ソートキーを決定する。 ' ' < '[a-zA-Z]' < 'zz'という前提。
372 if($pagereading_enable) {
373 mb_regex_encoding(SOURCE_ENCODING);
374 $readings = get_readings($pages);
377 $list = $matches = array();
379 // Shrink URI for read
380 if ($cmd == 'read') {
381 $href = $script . '?';
383 $href = $script . '?cmd=' . $cmd . '&page=';
386 foreach($pages as $file=>$page) {
387 $r_page = pagename_urlencode($page);
388 $s_page = htmlsc($page, ENT_QUOTES);
389 $passage = get_pg_passage($page);
391 $str = ' <li><a href="' . $href . $r_page . '">' .
392 $s_page . '</a>' . $passage;
395 $s_file = htmlsc($file);
396 $str .= "\n" . ' <ul><li>' . $s_file . '</li></ul>' .
401 // WARNING: Japanese code hard-wired
402 if($pagereading_enable) {
403 if(mb_ereg('^([A-Za-z])', mb_convert_kana($page, 'a'), $matches)) {
404 $head = strtoupper($matches[1]);
405 } elseif (isset($readings[$page]) && mb_ereg('^([ァ-ヶ])', $readings[$page], $matches)) { // here
407 } elseif (mb_ereg('^[ -~]|[^ぁ-ん亜-熙]', $page)) { // and here
413 $head = (preg_match('/^([A-Za-z])/', $page, $matches)) ? strtoupper($matches[1]) :
414 (preg_match('/^([ -~])/', $page) ? $symbol : $other);
417 $list[$head][$page] = $str;
419 uksort($pages, 'strnatcmp');
422 $arr_index = array();
423 $retval .= '<ul>' . "\n";
424 foreach ($list as $head=>$pages) {
425 if ($head === $symbol) {
426 $head = $_msg_symbol;
427 } else if ($head === $other) {
433 $arr_index[] = '<a id="top_' . $cnt .
434 '" href="#head_' . $cnt . '"><strong>' .
435 $head . '</strong></a>';
436 $retval .= ' <li><a id="head_' . $cnt . '" href="#top_' . $cnt .
437 '"><strong>' . $head . '</strong></a>' . "\n" .
440 ksort($pages, SORT_STRING);
441 $retval .= join("\n", $pages);
443 $retval .= "\n </ul>\n </li>\n";
445 $retval .= '</ul>' . "\n";
446 if ($list_index && $cnt > 0) {
448 while (! empty($arr_index))
449 $top[] = join(' | ' . "\n", array_splice($arr_index, 0, 16)) . "\n";
451 $retval = '<div id="top" style="text-align:center">' . "\n" .
452 join('<br />', $top) . '</div>' . "\n" . $retval;
457 // Show text formatting rules
462 if (! is_page($rule_page)) {
463 return '<p>Sorry, page \'' . htmlsc($rule_page) .
464 '\' unavailable.</p>';
466 return convert_html(get_source($rule_page));
470 // Show (critical) error message
471 function die_message($msg)
473 $title = $page = 'Runtime error';
475 <h3>Runtime error</h3>
476 <strong>Error message : $msg</strong>
479 pkwk_common_headers();
480 if(defined('SKIN_FILE') && file_exists(SKIN_FILE) && is_readable(SKIN_FILE)) {
481 catbody($title, $page, $body);
484 if(defined('CONTENT_CHARSET')) {
485 $charset = CONTENT_CHARSET;
487 header("Content-Type: text/html; charset=$charset");
492 <meta http-equiv="content-type" content="text/html; charset=$charset">
493 <title>$title</title>
504 // Have the time (as microtime)
505 function getmicrotime()
507 list($usec, $sec) = explode(' ', microtime());
508 return ((float)$sec + (float)$usec);
511 // Elapsed time by second
512 //define('MUTIME', getmicrotime());
513 function elapsedtime()
515 $at_the_microtime = MUTIME;
516 return sprintf('%01.03f', getmicrotime() - $at_the_microtime);
520 function get_date($format, $timestamp = NULL)
522 $format = preg_replace('/(?<!\\\)T/',
523 preg_replace('/(.)/', '\\\$1', ZONE), $format);
525 $time = ZONETIME + (($timestamp !== NULL) ? $timestamp : UTIME);
527 return date($format, $time);
530 // Format date string
531 function format_date($val, $paren = FALSE)
533 global $date_format, $time_format, $weeklabels;
537 $date = date($date_format, $val) .
538 ' (' . $weeklabels[date('w', $val)] . ') ' .
539 date($time_format, $val);
541 return $paren ? '(' . $date . ')' : $date;
544 // Get short string of the passage, 'N seconds/minutes/hours/days/years ago'
545 function get_passage($time, $paren = TRUE)
547 static $units = array('m'=>60, 'h'=>24, 'd'=>1);
549 $time = max(0, (UTIME - $time) / 60); // minutes
551 foreach ($units as $unit=>$card) {
552 if ($time < $card) break;
555 $time = floor($time) . $unit;
557 return $paren ? '(' . $time . ')' : $time;
560 // Hide <input type="(submit|button|image)"...>
561 function drop_submit($str)
563 return preg_replace('/<input([^>]+)type="(submit|button|image)"/i',
564 '<input$1type="hidden"', $str);
567 // Generate AutoLink patterns (thx to hirofummy)
568 function get_autolink_pattern(& $pages)
570 global $WikiName, $autolink, $nowikiname;
572 $config = new Config('AutoLink');
574 $ignorepages = $config->get('IgnoreList');
575 $forceignorepages = $config->get('ForceIgnoreList');
577 $auto_pages = array_merge($ignorepages, $forceignorepages);
579 foreach ($pages as $page)
580 if (preg_match('/^' . $WikiName . '$/', $page) ?
581 $nowikiname : strlen($page) >= $autolink)
582 $auto_pages[] = $page;
584 if (empty($auto_pages)) {
585 $result = $result_a = $nowikiname ? '(?!)' : $WikiName;
587 $auto_pages = array_unique($auto_pages);
588 sort($auto_pages, SORT_STRING);
590 $auto_pages_a = array_values(preg_grep('/^[A-Z]+$/i', $auto_pages));
591 $auto_pages = array_values(array_diff($auto_pages, $auto_pages_a));
593 $result = get_autolink_pattern_sub($auto_pages, 0, count($auto_pages), 0);
594 $result_a = get_autolink_pattern_sub($auto_pages_a, 0, count($auto_pages_a), 0);
596 return array($result, $result_a, $forceignorepages);
599 function get_autolink_pattern_sub(& $pages, $start, $end, $pos)
601 if ($end == 0) return '(?!)';
604 $count = $i = $j = 0;
605 $x = (mb_strlen($pages[$start]) <= $pos);
608 for ($i = $start; $i < $end; $i = $j) {
609 $char = mb_substr($pages[$i], $pos, 1);
610 for ($j = $i; $j < $end; $j++)
611 if (mb_substr($pages[$j], $pos, 1) != $char) break;
613 if ($i != $start) $result .= '|';
614 if ($i >= ($j - 1)) {
615 $result .= str_replace(' ', '\\ ', preg_quote(mb_substr($pages[$i], $pos), '/'));
617 $result .= str_replace(' ', '\\ ', preg_quote($char, '/')) .
618 get_autolink_pattern_sub($pages, $i, $j, $pos + 1);
622 if ($x || $count > 1) $result = '(?:' . $result . ')';
623 if ($x) $result .= '?';
628 // Get absolute-URI of this script
629 function get_script_uri($init_uri = '')
631 global $script_directory_index;
634 if ($init_uri == '') {
636 if (isset($script)) return $script;
639 $msg = 'get_script_uri() failed: Please set $script at INI_FILE manually';
641 $script = (SERVER_PORT == 443 ? 'https://' : 'http://'); // scheme
642 $script .= SERVER_NAME; // host
643 $script .= (SERVER_PORT == 80 ? '' : ':' . SERVER_PORT); // port
645 // SCRIPT_NAME が'/'で始まっていない場合(cgiなど) REQUEST_URIを使ってみる
647 if ($path{0} != '/') {
648 if (! isset($_SERVER['REQUEST_URI']) || $_SERVER['REQUEST_URI']{0} != '/')
651 // REQUEST_URIをパースし、path部分だけを取り出す
652 $parse_url = parse_url($script . $_SERVER['REQUEST_URI']);
653 if (! isset($parse_url['path']) || $parse_url['path']{0} != '/')
656 $path = $parse_url['path'];
660 if (! is_url($script, TRUE) && php_sapi_name() == 'cgi')
666 if (isset($script)) die_message('$script: Already init');
667 if (! is_url($init_uri, TRUE)) die_message('$script: Invalid URI');
671 // Cut filename or not
672 if (isset($script_directory_index)) {
673 if (! file_exists($script_directory_index))
674 die_message('Directory index file not found: ' .
675 htmlsc($script_directory_index));
677 if (preg_match('#^(.+/)' . preg_quote($script_directory_index, '#') . '$#',
678 $script, $matches)) $script = $matches[1];
684 // Remove null(\0) bytes from variables
686 // NOTE: PHP had vulnerabilities that opens "hoge.php" via fopen("hoge.php\0.txt") etc.
687 // [PHP-users 12736] null byte attack
688 // http://ns1.php.gr.jp/pipermail/php-users/2003-January/012742.html
690 // 2003-05-16: magic quotes gpcの復元処理を統合
691 // 2003-05-21: 連想配列のキーはbinary safe
693 function input_filter($param)
695 static $magic_quotes_gpc = NULL;
696 if ($magic_quotes_gpc === NULL)
697 $magic_quotes_gpc = get_magic_quotes_gpc();
699 if (is_array($param)) {
700 return array_map('input_filter', $param);
702 $result = str_replace("\0", '', $param);
703 if ($magic_quotes_gpc) $result = stripslashes($result);
708 // Compat for 3rd party plugins. Remove this later
709 function sanitize($param) {
710 return input_filter($param);
713 // Explode Comma-Separated Values to an array
714 function csv_explode($separator, $string)
716 $retval = $matches = array();
718 $_separator = preg_quote($separator, '/');
719 if (! preg_match_all('/("[^"]*(?:""[^"]*)*"|[^' . $_separator . ']*)' .
720 $_separator . '/', $string . $separator, $matches))
723 foreach ($matches[1] as $str) {
725 if ($len > 1 && $str{0} == '"' && $str{$len - 1} == '"')
726 $str = str_replace('""', '"', substr($str, 1, -1));
732 // Implode an array with CSV data format (escape double quotes)
733 function csv_implode($glue, $pieces)
735 $_glue = ($glue != '') ? '\\' . $glue{0} : '';
737 foreach ($pieces as $str) {
738 if (preg_match('/[' . '"' . "\n\r" . $_glue . ']/', $str))
739 $str = '"' . str_replace('"', '""', $str) . '"';
742 return join($glue, $arr);
745 // Sugar with default settings
746 function htmlsc($string = '', $flags = ENT_COMPAT, $charset = CONTENT_CHARSET)
748 return htmlspecialchars($string, $flags, $charset); // htmlsc()
752 * Get redirect page name on Page Redirect Rules
754 * This function returns exactly false if it doesn't need redirection.
755 * So callers need check return value is false or not.
757 * @param $page page name
758 * @return new page name or false
760 function get_pagename_on_redirect($page) {
761 global $page_redirect_rules;
762 foreach ($page_redirect_rules as $rule=>$replace) {
763 if (preg_match($rule, $page)) {
764 if (is_string($replace)) {
765 $new_page = preg_replace($rule, $replace, $page);
766 } elseif (is_object($replace) && is_callable($replace)) {
767 $new_page = preg_replace_callback($rule, $replace, $page);
769 die_message('Invalid redirect rule: ' . $rule . '=>' . $replace);
771 if ($page !== $new_page) {
780 * Redirect from an old page to new page
782 * This function returns true when a redirection occurs.
783 * So callers need check return value is false or true.
784 * And if it is true, then you have to exit PHP script.
786 * @return bool Inticates a redirection occurred or not
788 function manage_page_redirect() {
790 if (isset($vars['page'])) {
791 $page = $vars['page'];
793 $new_page = get_pagename_on_redirect($page);
794 if ($new_page != false) {
795 header('Location: ' . get_script_uri() . '?' .
796 pagename_urlencode($new_page));
804 // is_a -- Returns TRUE if the object is of this class or has this class as one of its parents
806 if (! function_exists('is_a')) {
808 function is_a($class, $match)
810 if (empty($class)) return FALSE;
812 $class = is_object($class) ? get_class($class) : $class;
813 if (strtolower($class) == strtolower($match)) {
816 return is_a(get_parent_class($class), $match); // Recurse
821 // array_fill -- Fill an array with values
823 if (! function_exists('array_fill')) {
825 function array_fill($start_index, $num, $value)
828 while ($num-- > 0) $ret[$start_index++] = $value;
833 // md5_file -- Calculates the md5 hash of a given filename
835 if (! function_exists('md5_file')) {
837 function md5_file($filename)
839 if (! file_exists($filename)) return FALSE;
841 $fd = fopen($filename, 'rb');
842 if ($fd === FALSE ) return FALSE;
843 $data = fread($fd, filesize($filename));
849 // sha1 -- Compute SHA-1 hash
850 // (PHP 4 >= 4.3.0, PHP5)
851 if (! function_exists('sha1')) {
852 if (extension_loaded('mhash')) {
855 return bin2hex(mhash(MHASH_SHA1, $str));