2 // PukiWiki - Yet another WikiWikiWeb clone.
5 // 2002-2020 PukiWiki Development Team
6 // 2001-2002 Originally written by yu-ji
7 // License: GPL v2 or (at your option) any later version
13 define('PKWK_URI_RELATIVE', 0);
14 /** Root relative URI. */
15 define('PKWK_URI_ROOT', 1);
17 define('PKWK_URI_ABSOLUTE', 2);
19 function pkwk_log($message)
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);
27 if ($dateTimeExists) {
29 $d = \DateTime::createFromFormat('U.u', sprintf('%6F', microtime(true)));
30 $timestamp = substr($d->format('Y-m-d H:i:s.u'), 0, 23);
32 $timestamp = date('Y-m-d H:i:s');
34 error_log($timestamp . ' ' . $message . "\n", 3, $log_filepath);
38 * Get LTSV safe string - Remove tab and newline chars.
40 * @param $s target string
42 function get_ltsv_value($s) {
46 return preg_replace('#[\t\r\n]#', '', $s);
50 * Write update_log on updating contents.
52 * @param $page page name
53 * @param $diff_content diff expression
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;
59 $ymd = gmdate('Ymd', $timestamp);
60 $difflog_file = $log_dir . '/diff.' . $ymd . '.log';
61 $ltsv_file = $log_dir . '/update.' . $ymd . '.log';
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'],
70 'diff' => $diff_content
72 if (file_exists($log_dir) && defined('JSON_UNESCAPED_UNICODE')) {
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',
79 foreach ($keys as $k) {
80 $ar2[] = $k . ':' . get_ltsv_value($d[$k]);
82 $ltsv = join($ar2, "\t") . "\n";
83 file_put_contents($ltsv_file, $ltsv, FILE_APPEND | LOCK_EX);
88 * ctype_digit that supports PHP4+.
90 * PHP official document says PHP4 has ctype_digit() function.
91 * But sometimes it doen't exists on PHP 4.1.
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');
98 if ($ctype_digit_exists) {
99 return ctype_digit($s);
101 return preg_match('/^[0-9]+$/', $s) ? true : false;
104 function is_interwiki($str)
106 global $InterWikiName;
107 return preg_match('/^' . $InterWikiName . '$/', $str);
110 function is_pagename($str)
114 $is_pagename = (! is_interwiki($str) &&
115 preg_match('/^(?!\/)' . $BracketName . '$(?<!\/$)/', $str) &&
116 ! preg_match('#(^|/)\.{1,2}(/|$)#', $str));
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]))+$/';
123 case 'EUC-JP': $pattern =
124 '/^(?:[\x00-\x7F]|(?:[\x8E\xA1-\xFE][\xA1-\xFE])|(?:\x8F[\xA1-\xFE][\xA1-\xFE]))+$/';
127 if (isset($pattern) && $pattern != '')
128 $is_pagename = ($is_pagename && preg_match($pattern, $str));
134 function is_url($str, $only_http = FALSE)
136 $scheme = $only_http ? 'https?' : 'https?|ftp|news';
137 return preg_match('/^(' . $scheme . ')(:\/\/[-_.!~*\'()a-zA-Z0-9;\/?:\@&=+\$,%#]*)$/', $str);
140 // If the page exists
141 function is_page($page, $clearcache = FALSE)
143 if ($clearcache) clearstatcache();
144 return file_exists(get_filename($page));
147 function is_editable($page)
150 static $is_editable = array();
152 if (! isset($is_editable[$page])) {
153 $is_editable[$page] = (
154 is_pagename($page) &&
155 ! is_freeze($page) &&
156 ! in_array($page, $cantedit)
160 return $is_editable[$page];
163 function is_freeze($page, $clearcache = FALSE)
165 global $function_freeze;
166 static $is_freeze = array();
168 if ($clearcache === TRUE) $is_freeze = array();
169 if (isset($is_freeze[$page])) return $is_freeze[$page];
171 if (! $function_freeze || ! is_page($page)) {
172 $is_freeze[$page] = FALSE;
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');
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];
187 // Handling $non_list
188 // $non_list will be preg_quote($str, '/') later.
189 function check_non_list($page = '')
194 if (! isset($regex)) $regex = '/' . $non_list . '/';
196 return preg_match($regex, $page);
200 function auto_template($page)
202 global $auto_template_func, $auto_template_rules;
204 if (! $auto_template_func) return '';
208 foreach ($auto_template_rules as $rule => $template) {
209 $rule_pattrn = '/' . $rule . '/';
211 if (! preg_match($rule_pattrn, $page, $matches)) continue;
213 $template_page = preg_replace($rule_pattrn, $template, $page);
214 if (! is_page($template_page)) continue;
216 $body = join('', get_source($template_page));
218 // Remove fixed-heading anchors
219 $body = preg_replace('/^(\*{1,3}.*)\[#[A-Za-z][\w-]+\](.*)$/m', '$1$2', $body);
222 $body = preg_replace('/^#freeze\s*$/m', '', $body);
224 $count = count($matches);
225 for ($i = 0; $i < $count; $i++)
226 $body = str_replace('$' . $i, $matches[$i], $body);
233 function _mb_convert_kana__enable($str, $option) {
234 return mb_convert_kana($str, $option, SOURCE_ENCODING);
236 function _mb_convert_kana__none($str, $option) {
240 // Expand all search-words to regexes and push them into an array
241 function get_search_words($words = array(), $do_escape = FALSE)
243 static $init, $mb_convert_kana, $pre, $post, $quote = '/';
245 if (! isset($init)) {
246 // function: mb_convert_kana() is for Japanese code only
247 if (LANG == 'ja' && function_exists('mb_convert_kana')) {
248 $mb_convert_kana = '_mb_convert_kana__enable';
250 $mb_convert_kana = '_mb_convert_kana__none';
252 if (SOURCE_ENCODING == 'EUC-JP') {
253 // Perl memo - Correct pattern-matching with EUC-JP
254 // http://www.din.or.jp/~ohzaki/perl.htm#JP_Match (Japanese)
256 $post = '(?=(?:[\xA1-\xFE][\xA1-\xFE])*' . // JIS X 0208
257 '(?:[\x00-\x7F\x8E\x8F]|\z))'; // ASCII, SS2, SS3, or the last
264 if (! is_array($words)) $words = array($words);
266 // Generate regex for the words
268 foreach ($words as $word) {
270 if ($word == '') continue;
272 // Normalize: ASCII letters = to single-byte. Others = to Zenkaku and Katakana
273 $word_nm = $mb_convert_kana($word, 'aKCV');
274 $nmlen = mb_strlen($word_nm, SOURCE_ENCODING);
276 // Each chars may be served ...
278 for ($pos = 0; $pos < $nmlen; $pos++) {
279 $char = mb_substr($word_nm, $pos, 1, SOURCE_ENCODING);
281 // Just normalized one? (ASCII char or Zenkaku-Katakana?)
282 $or = array(preg_quote($do_escape ? htmlsc($char) : $char, $quote));
283 if (strlen($char) == 1) {
284 // An ASCII (single-byte) character
285 foreach (array(strtoupper($char), strtolower($char)) as $_char) {
286 if ($char != '&') $or[] = preg_quote($_char, $quote); // As-is?
287 $ascii = ord($_char);
288 $or[] = sprintf('&#(?:%d|x%x);', $ascii, $ascii); // As an entity reference?
289 $or[] = preg_quote($mb_convert_kana($_char, 'A'), $quote); // As Zenkaku?
292 // NEVER COME HERE with mb_substr(string, start, length, 'ASCII')
293 // A multi-byte character
294 $or[] = preg_quote($mb_convert_kana($char, 'c'), $quote); // As Hiragana?
295 $or[] = preg_quote($mb_convert_kana($char, 'k'), $quote); // As Hankaku-Katakana?
297 $chars[] = '(?:' . join('|', array_unique($or)) . ')'; // Regex for the character
300 $regex[$word] = $pre . join('', $chars) . $post; // For the word
303 return $regex; // For all words
306 function get_passage_date_html_span($date_atom)
308 return '<span class="page_passage" data-mtime="' . $date_atom . '"></span>';
311 function get_passage_mtime_html_span($mtime)
313 $date_atom = get_date_atom($mtime);
314 return get_passage_date_html_span($date_atom);
318 * Get passage span html
322 function get_passage_html_span($page)
324 $date_atom = get_page_date_atom($page);
325 return get_passage_date_html_span($date_atom);
328 function get_link_passage_class() {
329 return 'link_page_passage';
333 * Get page link general attributes
335 * @return array('data_mtime' => page mtime or null, 'class' => additinal classes)
337 function get_page_link_a_attrs($page)
339 global $show_passage;
341 $pagemtime = get_page_date_atom($page);
343 'data_mtime' => $pagemtime,
344 'class' => get_link_passage_class(),
354 * Get page link general attributes from filetime
356 * @return array('data_mtime' => page mtime or null, 'class' => additinal classes)
358 function get_filetime_a_attrs($filetime)
360 global $show_passage;
362 $pagemtime = get_date_atom($filetime + LOCALZONE);
364 'data_mtime' => $pagemtime,
365 'class' => get_link_passage_class(),
374 // 'Search' main function
375 function do_search($word, $type = 'AND', $non_format = FALSE, $base = '')
377 global $whatsnew, $non_list, $search_non_list;
378 global $_msg_andresult, $_msg_orresult, $_msg_notfoundresult;
379 global $search_auth, $show_passage;
383 $b_type = ($type == 'AND'); // AND:TRUE OR:FALSE
384 $keys = get_search_words(preg_split('/\s+/', $word, -1, PREG_SPLIT_NO_EMPTY));
385 foreach ($keys as $key=>$value)
386 $keys[$key] = '/' . $value . '/S';
388 $pages = get_existpages();
392 $pages = preg_grep('/^' . preg_quote($base, '/') . '/S', $pages);
394 if (! $search_non_list) {
395 $pages = array_diff($pages, preg_grep('/' . $non_list . '/S', $pages));
397 $pages = array_flip($pages);
398 unset($pages[$whatsnew]);
400 $count = count($pages);
401 foreach (array_keys($pages) as $page) {
404 // Search for page name
406 foreach ($keys as $key) {
407 $b_match = preg_match($key, $page);
408 if ($b_type xor $b_match) break; // OR
410 if ($b_match) continue;
413 // Search auth for page contents
414 if ($search_auth && ! check_readable($page, false, false)) {
415 unset($pages[$page]);
420 // Search for page contents
421 foreach ($keys as $key) {
422 $body = get_source($page, TRUE, TRUE, TRUE);
423 $b_match = preg_match($key, remove_author_header($body));
424 if ($b_type xor $b_match) break; // OR
426 if ($b_match) continue;
428 unset($pages[$page]); // Miss
430 if ($non_format) return array_keys($pages);
432 $r_word = rawurlencode($word);
433 $s_word = htmlsc($word);
435 return str_replace('$1', $s_word, str_replace('$3', $count, $_msg_notfoundresult));
437 ksort($pages, SORT_STRING);
439 $retval = '<ul>' . "\n";
440 foreach (array_keys($pages) as $page) {
441 $r_page = rawurlencode($page);
442 $s_page = htmlsc($page);
443 $passage = $show_passage ? ' ' . get_passage_html_span($page) : '';
444 $retval .= ' <li><a href="' . get_base_uri() . '?cmd=read&page=' .
445 $r_page . '&word=' . $r_word . '">' . $s_page .
446 '</a>' . $passage . '</li>' . "\n";
448 $retval .= '</ul>' . "\n";
450 $retval .= str_replace('$1', $s_word, str_replace('$2', count($pages),
451 str_replace('$3', $count, $b_type ? $_msg_andresult : $_msg_orresult)));
456 // Argument check for program
457 function arg_check($str)
460 return isset($vars['cmd']) && (strpos($vars['cmd'], $str) === 0);
463 function _pagename_urlencode_callback($matches)
465 return urlencode($matches[0]);
468 function pagename_urlencode($page)
470 return preg_replace_callback('|[^/:]+|', '_pagename_urlencode_callback', $page);
474 function encode($str)
477 return ($str == '') ? '' : strtoupper(bin2hex($str));
478 // Equal to strtoupper(join('', unpack('H*0', $key)));
479 // But PHP 4.3.10 says 'Warning: unpack(): Type H: outside of string in ...'
483 function decode($str)
485 return pkwk_hex2bin($str);
488 // Inversion of bin2hex()
489 function pkwk_hex2bin($hex_string)
491 // preg_match : Avoid warning : pack(): Type H: illegal hex digit ...
492 // (string) : Always treat as string (not int etc). See BugTrack2/31
493 return preg_match('/^[0-9a-f]+$/i', $hex_string) ?
494 pack('H*', (string)$hex_string) : $hex_string;
497 // Remove [[ ]] (brackets)
498 function strip_bracket($str)
501 if (preg_match('/^\[\[(.*)\]\]$/', $str, $match)) {
508 // Create list of pages
509 function page_list($pages, $cmd = 'read', $withfilename = FALSE)
512 global $_msg_symbol, $_msg_other;
513 global $pagereading_enable;
515 $script = get_base_uri();
517 // ソートキーを決定する。 ' ' < '[a-zA-Z]' < 'zz'という前提。
523 if($pagereading_enable) {
524 mb_regex_encoding(SOURCE_ENCODING);
525 $readings = get_readings($pages);
528 $list = $matches = array();
530 // Shrink URI for read
531 if ($cmd == 'read') {
532 $href = $script . '?';
534 $href = $script . '?cmd=' . $cmd . '&page=';
536 uasort($pages, 'strnatcmp');
537 foreach($pages as $file=>$page) {
538 $r_page = pagename_urlencode($page);
539 $s_page = htmlsc($page, ENT_QUOTES);
540 $str = ' <li><a href="' . $href . $r_page . '">' .
541 $s_page . '</a> ' . get_pg_passage($page);
543 $s_file = htmlsc($file);
544 $str .= "\n" . ' <ul><li>' . $s_file . '</li></ul>' .
549 // WARNING: Japanese code hard-wired
550 if($pagereading_enable) {
551 if(mb_ereg('^([A-Za-z])', mb_convert_kana($page, 'a'), $matches)) {
552 $head = strtoupper($matches[1]);
553 } elseif (isset($readings[$page]) && mb_ereg('^([ァ-ヶ])', $readings[$page], $matches)) { // here
555 } elseif (mb_ereg('^[ -~]|[^ぁ-ん亜-熙]', $page)) { // and here
561 $head = (preg_match('/^([A-Za-z])/', $page, $matches)) ? strtoupper($matches[1]) :
562 (preg_match('/^([ -~])/', $page) ? $symbol : $other);
564 $list[$head][$page] = $str;
566 uksort($list, 'strnatcmp');
569 $arr_index = array();
570 $retval .= '<ul>' . "\n";
571 foreach ($list as $head=>$sub_pages) {
572 if ($head === $symbol) {
573 $head = $_msg_symbol;
574 } else if ($head === $other) {
580 $arr_index[] = '<a id="top_' . $cnt .
581 '" href="#head_' . $cnt . '"><strong>' .
582 $head . '</strong></a>';
583 $retval .= ' <li><a id="head_' . $cnt . '" href="#top_' . $cnt .
584 '"><strong>' . $head . '</strong></a>' . "\n" .
587 $retval .= join("\n", $sub_pages);
589 $retval .= "\n </ul>\n </li>\n";
591 $retval .= '</ul>' . "\n";
592 if ($list_index && $cnt > 0) {
594 while (! empty($arr_index))
595 $top[] = join(' | ' . "\n", array_splice($arr_index, 0, 16)) . "\n";
597 $retval = '<div id="top" style="text-align:center">' . "\n" .
598 join('<br />', $top) . '</div>' . "\n" . $retval;
603 // Show text formatting rules
608 if (! is_page($rule_page)) {
609 return '<p>Sorry, page \'' . htmlsc($rule_page) .
610 '\' unavailable.</p>';
612 return convert_html(get_source($rule_page));
616 // Show (critical) error message
617 function die_message($msg)
619 $title = $page = 'Runtime error';
621 <h3>Runtime error</h3>
622 <strong>Error message : $msg</strong>
625 pkwk_common_headers();
626 if(defined('SKIN_FILE') && file_exists(SKIN_FILE) && is_readable(SKIN_FILE)) {
627 catbody($title, $page, $body);
630 if(defined('CONTENT_CHARSET')) {
631 $charset = CONTENT_CHARSET;
633 header("Content-Type: text/html; charset=$charset");
638 <meta http-equiv="content-type" content="text/html; charset=$charset">
639 <title>$title</title>
650 // Have the time (as microtime)
651 function getmicrotime()
653 list($usec, $sec) = explode(' ', microtime());
654 return ((float)$sec + (float)$usec);
657 // Elapsed time by second
658 //define('MUTIME', getmicrotime());
659 function elapsedtime()
661 $at_the_microtime = MUTIME;
662 return sprintf('%01.03f', getmicrotime() - $at_the_microtime);
666 function get_date($format, $timestamp = NULL)
668 $format = preg_replace('/(?<!\\\)T/',
669 preg_replace('/(.)/', '\\\$1', ZONE), $format);
671 $time = ZONETIME + (($timestamp !== NULL) ? $timestamp : UTIME);
673 return date($format, $time);
676 // Format date string
677 function format_date($val, $paren = FALSE)
679 global $date_format, $time_format, $weeklabels;
683 $date = date($date_format, $val) .
684 ' (' . $weeklabels[date('w', $val)] . ') ' .
685 date($time_format, $val);
687 return $paren ? '(' . $date . ')' : $date;
691 * Format date in DATE_ATOM format.
693 function get_date_atom($timestamp)
695 // Compatible with DATE_ATOM format
696 // return date(DATE_ATOM, $timestamp);
697 $zmin = abs(LOCALZONE / 60);
698 return date('Y-m-d\TH:i:s', $timestamp) . sprintf('%s%02d:%02d',
699 (LOCALZONE < 0 ? '-' : '+') , $zmin / 60, $zmin % 60);
702 // Get short string of the passage, 'N seconds/minutes/hours/days/years ago'
703 function get_passage($time, $paren = TRUE)
705 static $units = array('m'=>60, 'h'=>24, 'd'=>1);
707 $time = max(0, (UTIME - $time) / 60); // minutes
709 foreach ($units as $unit=>$card) {
710 if ($time < $card) break;
713 $time = floor($time) . $unit;
715 return $paren ? '(' . $time . ')' : $time;
718 // Hide <input type="(submit|button|image)"...>
719 function drop_submit($str)
721 return preg_replace('/<input([^>]+)type="(submit|button|image)"/i',
722 '<input$1type="hidden"', $str);
725 // Generate AutoLink patterns (thx to hirofummy)
726 function get_autolink_pattern($pages, $min_length)
728 global $WikiName, $nowikiname;
730 $config = new Config('AutoLink');
732 $ignorepages = $config->get('IgnoreList');
733 $forceignorepages = $config->get('ForceIgnoreList');
735 $auto_pages = array_merge($ignorepages, $forceignorepages);
737 foreach ($pages as $page) {
738 if (preg_match('/^' . $WikiName . '$/', $page) ?
739 $nowikiname : strlen($page) >= $min_length) {
740 $auto_pages[] = $page;
743 if (empty($auto_pages)) {
744 $result = $result_a = '(?!)';
746 $auto_pages = array_unique($auto_pages);
747 sort($auto_pages, SORT_STRING);
749 $auto_pages_a = array_values(preg_grep('/^[A-Z]+$/i', $auto_pages));
750 $auto_pages = array_values(array_diff($auto_pages, $auto_pages_a));
752 $result = get_autolink_pattern_sub($auto_pages, 0, count($auto_pages), 0);
753 $result_a = get_autolink_pattern_sub($auto_pages_a, 0, count($auto_pages_a), 0);
755 return array($result, $result_a, $forceignorepages);
758 function get_autolink_pattern_sub($pages, $start, $end, $pos)
760 if ($end == 0) return '(?!)';
763 $count = $i = $j = 0;
764 $x = (mb_strlen($pages[$start]) <= $pos);
767 for ($i = $start; $i < $end; $i = $j) {
768 $char = mb_substr($pages[$i], $pos, 1);
769 for ($j = $i; $j < $end; $j++)
770 if (mb_substr($pages[$j], $pos, 1) != $char) break;
772 if ($i != $start) $result .= '|';
773 if ($i >= ($j - 1)) {
774 $result .= str_replace(' ', '\\ ', preg_quote(mb_substr($pages[$i], $pos), '/'));
776 $result .= str_replace(' ', '\\ ', preg_quote($char, '/')) .
777 get_autolink_pattern_sub($pages, $i, $j, $pos + 1);
781 if ($x || $count > 1) $result = '(?:' . $result . ')';
782 if ($x) $result .= '?';
787 // Get AutoAlias value
788 function get_autoalias_right_link($alias_name)
790 $pairs = get_autoaliases();
791 // A string: Seek the pair
792 if (isset($pairs[$alias_name])) {
793 return $pairs[$alias_name];
798 // Load setting pairs from AutoAliasName
799 function get_autoaliases()
801 global $aliaspage, $autoalias_max_words;
804 if (! isset($pairs)) {
808 ((?:(?!\]\]).)+)> # (1) alias name
809 ((?:(?!\]\]).)+) # (2) alias link
812 $postdata = join('', get_source($aliaspage));
815 $max = max($autoalias_max_words, 0);
816 if (preg_match_all('/' . $pattern . '/x', $postdata, $matches, PREG_SET_ORDER)) {
817 foreach($matches as $key => $value) {
818 if ($count == $max) break;
819 $name = trim($value[1]);
820 if (! isset($pairs[$name])) {
822 $pairs[$name] = trim($value[2]);
824 unset($matches[$key]);
832 * Get propery URI of this script
834 * @param $uri_type relative or absolute option
835 * PKWK_URI_RELATIVE, PKWK_URI_ROOT or PKWK_URI_ABSOLUTE
837 function get_base_uri($uri_type = PKWK_URI_RELATIVE)
839 $base_type = pkwk_base_uri_type_stack_peek();
840 $type = max($base_type, $uri_type);
842 case PKWK_URI_RELATIVE:
843 return pkwk_script_uri_base(PKWK_URI_RELATIVE);
845 return pkwk_script_uri_base(PKWK_URI_ROOT);
846 case PKWK_URI_ABSOLUTE:
847 return pkwk_script_uri_base(PKWK_URI_ABSOLUTE);
849 die_message('Invalid uri_type in get_base_uri()');
854 * Get URI of the page
856 * @param page page name
857 * @param $uri_type relative or absolute option
858 * PKWK_URI_RELATIVE, PKWK_URI_ROOT or PKWK_URI_ABSOLUTE
860 function get_page_uri($page, $uri_type = PKWK_URI_RELATIVE)
863 if ($page === $defaultpage) {
864 return get_base_uri($uri_type);
866 return get_base_uri($uri_type) . '?' . pagename_urlencode($page);
869 // Get absolute-URI of this script
870 function get_script_uri()
872 return get_base_uri(PKWK_URI_ABSOLUTE);
876 * Get or initialize Script URI
878 * @param $uri_type relative or absolute potion
879 * PKWK_URI_RELATIVE, PKWK_URI_ROOT or PKWK_URI_ABSOLUTE
880 * @param $initialize true if you initialize URI
881 * @param $uri_set URI set manually
883 function pkwk_script_uri_base($uri_type, $initialize = null, $uri_set = null)
885 global $script_directory_index;
886 static $initialized = false;
887 static $uri_absolute, $uri_root, $uri_relative;
888 if (! $initialized) {
889 if (isset($initialize) && $initialize) {
890 if (isset($uri_set)) {
891 $uri_absolute = $uri_set;
893 $uri_absolute = guess_script_absolute_uri();
895 // Support $script_directory_index (cut 'index.php')
896 if (isset($script_directory_index)) {
897 $slash_index = '/' . $script_directory_index;
898 $len = strlen($slash_index);
899 if (substr($uri_absolute, -1 * $len) === $slash_index) {
900 $uri_absolute = substr($uri_absolute, 0, strlen($uri_absolute) - $len + 1);
903 $elements = parse_url($uri_absolute);
904 $uri_root = $elements['path'];
905 if (substr($uri_root, -1) === '/') {
906 $uri_relative = './';
908 $pos = mb_strrpos($uri_root, '/');
910 $uri_relative = substr($uri_root, $pos + 1);
912 $uri_relative = $uri_root;
917 die_message('Script URI must be initialized in pkwk_script_uri_base()');
921 case PKWK_URI_RELATIVE:
922 return $uri_relative;
925 case PKWK_URI_ABSOLUTE:
926 return $uri_absolute;
928 die_message('Invalid uri_type in pkwk_script_uri_base()');
933 * Create uri_type context
935 * @param $uri_type relative or absolute option
936 * PKWK_URI_RELATIVE, PKWK_URI_ROOT or PKWK_URI_ABSOLUTE
938 function pkwk_base_uri_type_stack_push($uri_type)
940 _pkwk_base_uri_type_stack(false, true, $uri_type);
944 * Stop current active uri_type context
946 function pkwk_base_uri_type_stack_pop()
948 _pkwk_base_uri_type_stack(false, false);
952 * Get current active uri_type status
954 function pkwk_base_uri_type_stack_peek()
956 $type = _pkwk_base_uri_type_stack(true, false);
957 if (is_null($type)) {
958 return PKWK_URI_RELATIVE;
959 } elseif ($type === PKWK_URI_ABSOLUTE) {
960 return PKWK_URI_ABSOLUTE;
961 } elseif ($type === PKWK_URI_ROOT) {
962 return PKWK_URI_ROOT;
964 return PKWK_URI_RELATIVE;
969 * uri_type context internal function
971 * @param $peek is peek action or not
972 * @param $push push(true) or pop(false) on not peeking
973 * @param $uri_type uri_type on push and non-peeking
974 * @return $uri_type uri_type for peeking
976 function _pkwk_base_uri_type_stack($peek, $push, $uri_type = null)
978 static $uri_types = array();
980 // Peek: get latest value
981 if (count($uri_types) === 0) {
984 return $uri_types[0];
989 if (count($uri_types) === 0) {
990 array_unshift($uri_types, $uri_type);
992 $prev_type = $uri_types[0];
993 if ($uri_type >= $prev_type) {
994 array_unshift($uri_types, $uri_type);
996 array_unshift($uri_types, $prev_type);
1001 return array_shift($uri_types);
1007 * Guess Script Absolute URI.
1009 * SERVER_PORT: $_SERVER['SERVER_PORT'] converted in init.php
1010 * SERVER_NAME: $_SERVER['SERVER_NAME'] converted in init.php
1012 function guess_script_absolute_uri()
1014 $port = SERVER_PORT;
1015 $is_ssl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ||
1016 (isset($_SERVER['REQUEST_SCHEME']) && $_SERVER['REQUEST_SCHEME'] === 'https');
1018 $host = 'https://' . SERVER_NAME .
1019 ($port == 443 ? '' : ':' . $port);
1021 $host = 'http://' . SERVER_NAME .
1022 ($port == 80 ? '' : ':' . $port);
1024 $uri_elements = parse_url($host . $_SERVER['REQUEST_URI']);
1025 return $host . $uri_elements['path'];
1028 // Remove null(\0) bytes from variables
1030 // NOTE: PHP had vulnerabilities that opens "hoge.php" via fopen("hoge.php\0.txt") etc.
1031 // [PHP-users 12736] null byte attack
1032 // http://ns1.php.gr.jp/pipermail/php-users/2003-January/012742.html
1034 // 2003-05-16: magic quotes gpcの復元処理を統合
1035 // 2003-05-21: 連想配列のキーはbinary safe
1037 function input_filter($param)
1039 static $magic_quotes_gpc = NULL;
1040 if ($magic_quotes_gpc === NULL)
1041 $magic_quotes_gpc = get_magic_quotes_gpc();
1043 if (is_array($param)) {
1044 return array_map('input_filter', $param);
1046 $result = str_replace("\0", '', $param);
1047 if ($magic_quotes_gpc) $result = stripslashes($result);
1052 // Compat for 3rd party plugins. Remove this later
1053 function sanitize($param) {
1054 return input_filter($param);
1057 // Explode Comma-Separated Values to an array
1058 function csv_explode($separator, $string)
1060 $retval = $matches = array();
1062 $_separator = preg_quote($separator, '/');
1063 if (! preg_match_all('/("[^"]*(?:""[^"]*)*"|[^' . $_separator . ']*)' .
1064 $_separator . '/', $string . $separator, $matches))
1067 foreach ($matches[1] as $str) {
1068 $len = strlen($str);
1069 if ($len > 1 && $str{0} == '"' && $str{$len - 1} == '"')
1070 $str = str_replace('""', '"', substr($str, 1, -1));
1076 // Implode an array with CSV data format (escape double quotes)
1077 function csv_implode($glue, $pieces)
1079 $_glue = ($glue != '') ? '\\' . $glue{0} : '';
1081 foreach ($pieces as $str) {
1082 if (preg_match('/[' . '"' . "\n\r" . $_glue . ']/', $str))
1083 $str = '"' . str_replace('"', '""', $str) . '"';
1086 return join($glue, $arr);
1089 // Sugar with default settings
1090 function htmlsc($string = '', $flags = ENT_COMPAT, $charset = CONTENT_CHARSET)
1092 return htmlspecialchars($string, $flags, $charset); // htmlsc()
1096 * Get JSON string with htmlspecialchars().
1098 function htmlsc_json($obj)
1100 // json_encode: PHP 5.2+
1101 // JSON_UNESCAPED_UNICODE: PHP 5.4+
1102 // JSON_UNESCAPED_SLASHES: PHP 5.4+
1103 if (defined('JSON_UNESCAPED_UNICODE')) {
1104 return htmlsc(json_encode($obj,
1105 JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
1111 * Get redirect page name on Page Redirect Rules
1113 * This function returns exactly false if it doesn't need redirection.
1114 * So callers need check return value is false or not.
1116 * @param $page page name
1117 * @return new page name or false
1119 function get_pagename_on_redirect($page) {
1120 global $page_redirect_rules;
1121 foreach ($page_redirect_rules as $rule=>$replace) {
1122 if (preg_match($rule, $page)) {
1123 if (is_string($replace)) {
1124 $new_page = preg_replace($rule, $replace, $page);
1125 } elseif (is_object($replace) && is_callable($replace)) {
1126 $new_page = preg_replace_callback($rule, $replace, $page);
1128 die_message('Invalid redirect rule: ' . $rule . '=>' . $replace);
1130 if ($page !== $new_page) {
1139 * Redirect from an old page to new page
1141 * This function returns true when a redirection occurs.
1142 * So callers need check return value is false or true.
1143 * And if it is true, then you have to exit PHP script.
1145 * @return bool Inticates a redirection occurred or not
1147 function manage_page_redirect() {
1149 if (isset($vars['page'])) {
1150 $page = $vars['page'];
1152 $new_page = get_pagename_on_redirect($page);
1153 if ($new_page != false) {
1154 header('Location: ' . get_page_uri($new_page, PKWK_URI_ROOT));
1162 // is_a -- Returns TRUE if the object is of this class or has this class as one of its parents
1164 if (! function_exists('is_a')) {
1166 function is_a($class, $match)
1168 if (empty($class)) return FALSE;
1170 $class = is_object($class) ? get_class($class) : $class;
1171 if (strtolower($class) == strtolower($match)) {
1174 return is_a(get_parent_class($class), $match); // Recurse
1179 // array_fill -- Fill an array with values
1181 if (! function_exists('array_fill')) {
1183 function array_fill($start_index, $num, $value)
1186 while ($num-- > 0) $ret[$start_index++] = $value;
1191 // md5_file -- Calculates the md5 hash of a given filename
1193 if (! function_exists('md5_file')) {
1195 function md5_file($filename)
1197 if (! file_exists($filename)) return FALSE;
1199 $fd = fopen($filename, 'rb');
1200 if ($fd === FALSE ) return FALSE;
1201 $data = fread($fd, filesize($filename));
1207 // sha1 -- Compute SHA-1 hash
1208 // (PHP 4 >= 4.3.0, PHP5)
1209 if (! function_exists('sha1')) {
1210 if (extension_loaded('mhash')) {
1213 return bin2hex(mhash(MHASH_SHA1, $str));