2 // PukiWiki - Yet another WikiWikiWeb clone.
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
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);
30 * Get LTSV safe string - Remove tab and newline chars.
32 * @param $s target string
34 function get_ltsv_value($s) {
38 return preg_replace('#[\t\r\n]#', '', $s);
42 * Write update_log on updating contents.
44 * @param $page page name
45 * @param $diff_content diff expression
47 function pkwk_log_updates($page, $diff_content) {
48 global $auth_user, $logging_updates, $logging_updates_log_dir;
49 $log_dir = $logging_updates_log_dir;
51 $ymd = gmdate('Ymd', $timestamp);
52 $difflog_file = $log_dir . '/diff.' . $ymd . '.log';
53 $ltsv_file = $log_dir . '/update.' . $ymd . '.log';
55 'time' => gmdate('Y-m-d H:i:s', $timestamp),
56 'uri' => $_SERVER['REQUEST_URI'],
57 'method' => $_SERVER['REQUEST_METHOD'],
58 'remote_addr' => $_SERVER['REMOTE_ADDR'],
59 'user_agent' => $_SERVER['HTTP_USER_AGENT'],
62 'diff' => $diff_content
64 if (file_exists($log_dir) && defined('JSON_UNESCAPED_UNICODE')) {
66 $line = json_encode($d, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n";
67 file_put_contents($difflog_file, $line, FILE_APPEND | LOCK_EX);
68 $keys = array('time', 'uri', 'method', 'remote_addr', 'user_agent',
71 foreach ($keys as $k) {
72 $ar2[] = $k . ':' . get_ltsv_value($d[$k]);
74 $ltsv = join($ar2, "\t") . "\n";
75 file_put_contents($ltsv_file, $ltsv, FILE_APPEND | LOCK_EX);
80 * ctype_digit that supports PHP4+.
82 * PHP official document says PHP4 has ctype_digit() function.
83 * But sometimes it doen't exists on PHP 4.1.
85 function pkwk_ctype_digit($s) {
86 static $ctype_digit_exists;
87 if (!isset($ctype_digit_exists)) {
88 $ctype_digit_exists = function_exists('ctype_digit');
90 if ($ctype_digit_exists) {
91 return ctype_digit($s);
93 return preg_match('/^[0-9]+$/', $s) ? true : false;
96 function is_interwiki($str)
98 global $InterWikiName;
99 return preg_match('/^' . $InterWikiName . '$/', $str);
102 function is_pagename($str)
106 $is_pagename = (! is_interwiki($str) &&
107 preg_match('/^(?!\/)' . $BracketName . '$(?<!\/$)/', $str) &&
108 ! preg_match('#(^|/)\.{1,2}(/|$)#', $str));
110 if (defined('SOURCE_ENCODING')) {
111 switch(SOURCE_ENCODING){
112 case 'UTF-8': $pattern =
113 '/^(?:[\x00-\x7F]|(?:[\xC0-\xDF][\x80-\xBF])|(?:[\xE0-\xEF][\x80-\xBF][\x80-\xBF]))+$/';
115 case 'EUC-JP': $pattern =
116 '/^(?:[\x00-\x7F]|(?:[\x8E\xA1-\xFE][\xA1-\xFE])|(?:\x8F[\xA1-\xFE][\xA1-\xFE]))+$/';
119 if (isset($pattern) && $pattern != '')
120 $is_pagename = ($is_pagename && preg_match($pattern, $str));
126 function is_url($str, $only_http = FALSE)
128 $scheme = $only_http ? 'https?' : 'https?|ftp|news';
129 return preg_match('/^(' . $scheme . ')(:\/\/[-_.!~*\'()a-zA-Z0-9;\/?:\@&=+\$,%#]*)$/', $str);
132 // If the page exists
133 function is_page($page, $clearcache = FALSE)
135 if ($clearcache) clearstatcache();
136 return file_exists(get_filename($page));
139 function is_editable($page)
142 static $is_editable = array();
144 if (! isset($is_editable[$page])) {
145 $is_editable[$page] = (
146 is_pagename($page) &&
147 ! is_freeze($page) &&
148 ! in_array($page, $cantedit)
152 return $is_editable[$page];
155 function is_freeze($page, $clearcache = FALSE)
157 global $function_freeze;
158 static $is_freeze = array();
160 if ($clearcache === TRUE) $is_freeze = array();
161 if (isset($is_freeze[$page])) return $is_freeze[$page];
163 if (! $function_freeze || ! is_page($page)) {
164 $is_freeze[$page] = FALSE;
167 $fp = fopen(get_filename($page), 'rb') or
168 die('is_freeze(): fopen() failed: ' . htmlsc($page));
169 flock($fp, LOCK_SH) or die('is_freeze(): flock() failed');
171 $buffer = fread($fp, 1000);
172 flock($fp, LOCK_UN) or die('is_freeze(): flock() failed');
173 fclose($fp) or die('is_freeze(): fclose() failed: ' . htmlsc($page));
174 $is_freeze[$page] = (bool) preg_match('/^#freeze$/m', $buffer);
175 return $is_freeze[$page];
179 // Handling $non_list
180 // $non_list will be preg_quote($str, '/') later.
181 function check_non_list($page = '')
186 if (! isset($regex)) $regex = '/' . $non_list . '/';
188 return preg_match($regex, $page);
192 function auto_template($page)
194 global $auto_template_func, $auto_template_rules;
196 if (! $auto_template_func) return '';
200 foreach ($auto_template_rules as $rule => $template) {
201 $rule_pattrn = '/' . $rule . '/';
203 if (! preg_match($rule_pattrn, $page, $matches)) continue;
205 $template_page = preg_replace($rule_pattrn, $template, $page);
206 if (! is_page($template_page)) continue;
208 $body = join('', get_source($template_page));
210 // Remove fixed-heading anchors
211 $body = preg_replace('/^(\*{1,3}.*)\[#[A-Za-z][\w-]+\](.*)$/m', '$1$2', $body);
214 $body = preg_replace('/^#freeze\s*$/m', '', $body);
216 $count = count($matches);
217 for ($i = 0; $i < $count; $i++)
218 $body = str_replace('$' . $i, $matches[$i], $body);
225 // Expand all search-words to regexes and push them into an array
226 function get_search_words($words = array(), $do_escape = FALSE)
228 static $init, $mb_convert_kana, $pre, $post, $quote = '/';
230 if (! isset($init)) {
231 // function: mb_convert_kana() is for Japanese code only
232 if (LANG == 'ja' && function_exists('mb_convert_kana')) {
233 $mb_convert_kana = create_function('$str, $option',
234 'return mb_convert_kana($str, $option, SOURCE_ENCODING);');
236 $mb_convert_kana = create_function('$str, $option',
239 if (SOURCE_ENCODING == 'EUC-JP') {
240 // Perl memo - Correct pattern-matching with EUC-JP
241 // http://www.din.or.jp/~ohzaki/perl.htm#JP_Match (Japanese)
243 $post = '(?=(?:[\xA1-\xFE][\xA1-\xFE])*' . // JIS X 0208
244 '(?:[\x00-\x7F\x8E\x8F]|\z))'; // ASCII, SS2, SS3, or the last
251 if (! is_array($words)) $words = array($words);
253 // Generate regex for the words
255 foreach ($words as $word) {
257 if ($word == '') continue;
259 // Normalize: ASCII letters = to single-byte. Others = to Zenkaku and Katakana
260 $word_nm = $mb_convert_kana($word, 'aKCV');
261 $nmlen = mb_strlen($word_nm, SOURCE_ENCODING);
263 // Each chars may be served ...
265 for ($pos = 0; $pos < $nmlen; $pos++) {
266 $char = mb_substr($word_nm, $pos, 1, SOURCE_ENCODING);
268 // Just normalized one? (ASCII char or Zenkaku-Katakana?)
269 $or = array(preg_quote($do_escape ? htmlsc($char) : $char, $quote));
270 if (strlen($char) == 1) {
271 // An ASCII (single-byte) character
272 foreach (array(strtoupper($char), strtolower($char)) as $_char) {
273 if ($char != '&') $or[] = preg_quote($_char, $quote); // As-is?
274 $ascii = ord($_char);
275 $or[] = sprintf('&#(?:%d|x%x);', $ascii, $ascii); // As an entity reference?
276 $or[] = preg_quote($mb_convert_kana($_char, 'A'), $quote); // As Zenkaku?
279 // NEVER COME HERE with mb_substr(string, start, length, 'ASCII')
280 // A multi-byte character
281 $or[] = preg_quote($mb_convert_kana($char, 'c'), $quote); // As Hiragana?
282 $or[] = preg_quote($mb_convert_kana($char, 'k'), $quote); // As Hankaku-Katakana?
284 $chars[] = '(?:' . join('|', array_unique($or)) . ')'; // Regex for the character
287 $regex[$word] = $pre . join('', $chars) . $post; // For the word
290 return $regex; // For all words
293 // 'Search' main function
294 function do_search($word, $type = 'AND', $non_format = FALSE, $base = '')
296 global $script, $whatsnew, $non_list, $search_non_list;
297 global $_msg_andresult, $_msg_orresult, $_msg_notfoundresult;
298 global $search_auth, $show_passage;
302 $b_type = ($type == 'AND'); // AND:TRUE OR:FALSE
303 $keys = get_search_words(preg_split('/\s+/', $word, -1, PREG_SPLIT_NO_EMPTY));
304 foreach ($keys as $key=>$value)
305 $keys[$key] = '/' . $value . '/S';
307 $pages = get_existpages();
311 $pages = preg_grep('/^' . preg_quote($base, '/') . '/S', $pages);
313 if (! $search_non_list) {
314 $pages = array_diff($pages, preg_grep('/' . $non_list . '/S', $pages));
316 $pages = array_flip($pages);
317 unset($pages[$whatsnew]);
319 $count = count($pages);
320 foreach (array_keys($pages) as $page) {
323 // Search for page name
325 foreach ($keys as $key) {
326 $b_match = preg_match($key, $page);
327 if ($b_type xor $b_match) break; // OR
329 if ($b_match) continue;
332 // Search auth for page contents
333 if ($search_auth && ! check_readable($page, false, false)) {
334 unset($pages[$page]);
338 // Search for page contents
339 foreach ($keys as $key) {
340 $b_match = preg_match($key, get_source($page, TRUE, TRUE));
341 if ($b_type xor $b_match) break; // OR
343 if ($b_match) continue;
345 unset($pages[$page]); // Miss
347 if ($non_format) return array_keys($pages);
349 $r_word = rawurlencode($word);
350 $s_word = htmlsc($word);
352 return str_replace('$1', $s_word, $_msg_notfoundresult);
354 ksort($pages, SORT_STRING);
356 $retval = '<ul>' . "\n";
357 foreach (array_keys($pages) as $page) {
358 $r_page = rawurlencode($page);
359 $s_page = htmlsc($page);
360 $passage = $show_passage ? ' ' . get_passage(get_filetime($page)) : '';
361 $retval .= ' <li><a href="' . $script . '?cmd=read&page=' .
362 $r_page . '&word=' . $r_word . '">' . $s_page .
363 '</a>' . $passage . '</li>' . "\n";
365 $retval .= '</ul>' . "\n";
367 $retval .= str_replace('$1', $s_word, str_replace('$2', count($pages),
368 str_replace('$3', $count, $b_type ? $_msg_andresult : $_msg_orresult)));
373 // Argument check for program
374 function arg_check($str)
377 return isset($vars['cmd']) && (strpos($vars['cmd'], $str) === 0);
380 function _pagename_urlencode_callback($matches)
382 return rawurlencode($matches[0]);
385 function pagename_urlencode($page)
387 return preg_replace_callback('|[^/:]+|', '_pagename_urlencode_callback', $page);
391 function encode($str)
394 return ($str == '') ? '' : strtoupper(bin2hex($str));
395 // Equal to strtoupper(join('', unpack('H*0', $key)));
396 // But PHP 4.3.10 says 'Warning: unpack(): Type H: outside of string in ...'
400 function decode($str)
402 return pkwk_hex2bin($str);
405 // Inversion of bin2hex()
406 function pkwk_hex2bin($hex_string)
408 // preg_match : Avoid warning : pack(): Type H: illegal hex digit ...
409 // (string) : Always treat as string (not int etc). See BugTrack2/31
410 return preg_match('/^[0-9a-f]+$/i', $hex_string) ?
411 pack('H*', (string)$hex_string) : $hex_string;
414 // Remove [[ ]] (brackets)
415 function strip_bracket($str)
418 if (preg_match('/^\[\[(.*)\]\]$/', $str, $match)) {
425 // Create list of pages
426 function page_list($pages, $cmd = 'read', $withfilename = FALSE)
428 global $script, $list_index;
429 global $_msg_symbol, $_msg_other;
430 global $pagereading_enable;
432 // ソートキーを決定する。 ' ' < '[a-zA-Z]' < 'zz'という前提。
438 if($pagereading_enable) {
439 mb_regex_encoding(SOURCE_ENCODING);
440 $readings = get_readings($pages);
443 $list = $matches = array();
445 // Shrink URI for read
446 if ($cmd == 'read') {
447 $href = $script . '?';
449 $href = $script . '?cmd=' . $cmd . '&page=';
452 foreach($pages as $file=>$page) {
453 $r_page = pagename_urlencode($page);
454 $s_page = htmlsc($page, ENT_QUOTES);
455 $passage = get_pg_passage($page);
457 $str = ' <li><a href="' . $href . $r_page . '">' .
458 $s_page . '</a>' . $passage;
461 $s_file = htmlsc($file);
462 $str .= "\n" . ' <ul><li>' . $s_file . '</li></ul>' .
467 // WARNING: Japanese code hard-wired
468 if($pagereading_enable) {
469 if(mb_ereg('^([A-Za-z])', mb_convert_kana($page, 'a'), $matches)) {
470 $head = strtoupper($matches[1]);
471 } elseif (isset($readings[$page]) && mb_ereg('^([ァ-ヶ])', $readings[$page], $matches)) { // here
473 } elseif (mb_ereg('^[ -~]|[^ぁ-ん亜-熙]', $page)) { // and here
479 $head = (preg_match('/^([A-Za-z])/', $page, $matches)) ? strtoupper($matches[1]) :
480 (preg_match('/^([ -~])/', $page) ? $symbol : $other);
483 $list[$head][$page] = $str;
485 uksort($pages, 'strnatcmp');
488 $arr_index = array();
489 $retval .= '<ul>' . "\n";
490 foreach ($list as $head=>$pages) {
491 if ($head === $symbol) {
492 $head = $_msg_symbol;
493 } else if ($head === $other) {
499 $arr_index[] = '<a id="top_' . $cnt .
500 '" href="#head_' . $cnt . '"><strong>' .
501 $head . '</strong></a>';
502 $retval .= ' <li><a id="head_' . $cnt . '" href="#top_' . $cnt .
503 '"><strong>' . $head . '</strong></a>' . "\n" .
506 ksort($pages, SORT_STRING);
507 $retval .= join("\n", $pages);
509 $retval .= "\n </ul>\n </li>\n";
511 $retval .= '</ul>' . "\n";
512 if ($list_index && $cnt > 0) {
514 while (! empty($arr_index))
515 $top[] = join(' | ' . "\n", array_splice($arr_index, 0, 16)) . "\n";
517 $retval = '<div id="top" style="text-align:center">' . "\n" .
518 join('<br />', $top) . '</div>' . "\n" . $retval;
523 // Show text formatting rules
528 if (! is_page($rule_page)) {
529 return '<p>Sorry, page \'' . htmlsc($rule_page) .
530 '\' unavailable.</p>';
532 return convert_html(get_source($rule_page));
536 // Show (critical) error message
537 function die_message($msg)
539 $title = $page = 'Runtime error';
541 <h3>Runtime error</h3>
542 <strong>Error message : $msg</strong>
545 pkwk_common_headers();
546 if(defined('SKIN_FILE') && file_exists(SKIN_FILE) && is_readable(SKIN_FILE)) {
547 catbody($title, $page, $body);
550 if(defined('CONTENT_CHARSET')) {
551 $charset = CONTENT_CHARSET;
553 header("Content-Type: text/html; charset=$charset");
558 <meta http-equiv="content-type" content="text/html; charset=$charset">
559 <title>$title</title>
570 // Have the time (as microtime)
571 function getmicrotime()
573 list($usec, $sec) = explode(' ', microtime());
574 return ((float)$sec + (float)$usec);
577 // Elapsed time by second
578 //define('MUTIME', getmicrotime());
579 function elapsedtime()
581 $at_the_microtime = MUTIME;
582 return sprintf('%01.03f', getmicrotime() - $at_the_microtime);
586 function get_date($format, $timestamp = NULL)
588 $format = preg_replace('/(?<!\\\)T/',
589 preg_replace('/(.)/', '\\\$1', ZONE), $format);
591 $time = ZONETIME + (($timestamp !== NULL) ? $timestamp : UTIME);
593 return date($format, $time);
596 // Format date string
597 function format_date($val, $paren = FALSE)
599 global $date_format, $time_format, $weeklabels;
603 $date = date($date_format, $val) .
604 ' (' . $weeklabels[date('w', $val)] . ') ' .
605 date($time_format, $val);
607 return $paren ? '(' . $date . ')' : $date;
610 // Get short string of the passage, 'N seconds/minutes/hours/days/years ago'
611 function get_passage($time, $paren = TRUE)
613 static $units = array('m'=>60, 'h'=>24, 'd'=>1);
615 $time = max(0, (UTIME - $time) / 60); // minutes
617 foreach ($units as $unit=>$card) {
618 if ($time < $card) break;
621 $time = floor($time) . $unit;
623 return $paren ? '(' . $time . ')' : $time;
626 // Hide <input type="(submit|button|image)"...>
627 function drop_submit($str)
629 return preg_replace('/<input([^>]+)type="(submit|button|image)"/i',
630 '<input$1type="hidden"', $str);
633 // Generate AutoLink patterns (thx to hirofummy)
634 function get_autolink_pattern(& $pages)
636 global $WikiName, $autolink, $nowikiname;
638 $config = new Config('AutoLink');
640 $ignorepages = $config->get('IgnoreList');
641 $forceignorepages = $config->get('ForceIgnoreList');
643 $auto_pages = array_merge($ignorepages, $forceignorepages);
645 foreach ($pages as $page)
646 if (preg_match('/^' . $WikiName . '$/', $page) ?
647 $nowikiname : strlen($page) >= $autolink)
648 $auto_pages[] = $page;
650 if (empty($auto_pages)) {
651 $result = $result_a = $nowikiname ? '(?!)' : $WikiName;
653 $auto_pages = array_unique($auto_pages);
654 sort($auto_pages, SORT_STRING);
656 $auto_pages_a = array_values(preg_grep('/^[A-Z]+$/i', $auto_pages));
657 $auto_pages = array_values(array_diff($auto_pages, $auto_pages_a));
659 $result = get_autolink_pattern_sub($auto_pages, 0, count($auto_pages), 0);
660 $result_a = get_autolink_pattern_sub($auto_pages_a, 0, count($auto_pages_a), 0);
662 return array($result, $result_a, $forceignorepages);
665 function get_autolink_pattern_sub(& $pages, $start, $end, $pos)
667 if ($end == 0) return '(?!)';
670 $count = $i = $j = 0;
671 $x = (mb_strlen($pages[$start]) <= $pos);
674 for ($i = $start; $i < $end; $i = $j) {
675 $char = mb_substr($pages[$i], $pos, 1);
676 for ($j = $i; $j < $end; $j++)
677 if (mb_substr($pages[$j], $pos, 1) != $char) break;
679 if ($i != $start) $result .= '|';
680 if ($i >= ($j - 1)) {
681 $result .= str_replace(' ', '\\ ', preg_quote(mb_substr($pages[$i], $pos), '/'));
683 $result .= str_replace(' ', '\\ ', preg_quote($char, '/')) .
684 get_autolink_pattern_sub($pages, $i, $j, $pos + 1);
688 if ($x || $count > 1) $result = '(?:' . $result . ')';
689 if ($x) $result .= '?';
694 // Get absolute-URI of this script
695 function get_script_uri($init_uri = '')
697 global $script_directory_index;
700 if ($init_uri == '') {
702 if (isset($script)) return $script;
705 $msg = 'get_script_uri() failed: Please set $script at INI_FILE manually';
706 $script = guess_script_absolute_uri();
707 if (! is_url($script, TRUE) && php_sapi_name() == 'cgi')
713 if (isset($script)) die_message('$script: Already init');
714 if (! is_url($init_uri, TRUE)) die_message('$script: Invalid URI');
718 // Cut filename or not
719 if (isset($script_directory_index)) {
720 if (! file_exists($script_directory_index))
721 die_message('Directory index file not found: ' .
722 htmlsc($script_directory_index));
724 if (preg_match('#^(.+/)' . preg_quote($script_directory_index, '#') . '$#',
725 $script, $matches)) $script = $matches[1];
732 * Guess Script Absolute URI.
734 * SERVER_PORT: $_SERVER['SERVER_PORT'] converted in init.php
735 * SERVER_NAME: $_SERVER['SERVER_NAME'] converted in init.php
737 function guess_script_absolute_uri()
740 $is_ssl = (SERVER_PORT == 443) ||
741 (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ||
742 (isset($_SERVER['REQUEST_SCHEME']) && $_SERVER['REQUEST_SCHEME'] === 'https');
744 $host = 'https://' . SERVER_NAME .
745 ($port == 443 ? '' : ':' . $port);
747 $host = 'http://' . SERVER_NAME .
748 ($port == 80 ? '' : ':' . $port);
750 $uri_elements = parse_url($host . $_SERVER['REQUEST_URI']);
751 return $host . $uri_elements['path'];
754 // Remove null(\0) bytes from variables
756 // NOTE: PHP had vulnerabilities that opens "hoge.php" via fopen("hoge.php\0.txt") etc.
757 // [PHP-users 12736] null byte attack
758 // http://ns1.php.gr.jp/pipermail/php-users/2003-January/012742.html
760 // 2003-05-16: magic quotes gpcの復元処理を統合
761 // 2003-05-21: 連想配列のキーはbinary safe
763 function input_filter($param)
765 static $magic_quotes_gpc = NULL;
766 if ($magic_quotes_gpc === NULL)
767 $magic_quotes_gpc = get_magic_quotes_gpc();
769 if (is_array($param)) {
770 return array_map('input_filter', $param);
772 $result = str_replace("\0", '', $param);
773 if ($magic_quotes_gpc) $result = stripslashes($result);
778 // Compat for 3rd party plugins. Remove this later
779 function sanitize($param) {
780 return input_filter($param);
783 // Explode Comma-Separated Values to an array
784 function csv_explode($separator, $string)
786 $retval = $matches = array();
788 $_separator = preg_quote($separator, '/');
789 if (! preg_match_all('/("[^"]*(?:""[^"]*)*"|[^' . $_separator . ']*)' .
790 $_separator . '/', $string . $separator, $matches))
793 foreach ($matches[1] as $str) {
795 if ($len > 1 && $str{0} == '"' && $str{$len - 1} == '"')
796 $str = str_replace('""', '"', substr($str, 1, -1));
802 // Implode an array with CSV data format (escape double quotes)
803 function csv_implode($glue, $pieces)
805 $_glue = ($glue != '') ? '\\' . $glue{0} : '';
807 foreach ($pieces as $str) {
808 if (preg_match('/[' . '"' . "\n\r" . $_glue . ']/', $str))
809 $str = '"' . str_replace('"', '""', $str) . '"';
812 return join($glue, $arr);
815 // Sugar with default settings
816 function htmlsc($string = '', $flags = ENT_COMPAT, $charset = CONTENT_CHARSET)
818 return htmlspecialchars($string, $flags, $charset); // htmlsc()
822 * Get redirect page name on Page Redirect Rules
824 * This function returns exactly false if it doesn't need redirection.
825 * So callers need check return value is false or not.
827 * @param $page page name
828 * @return new page name or false
830 function get_pagename_on_redirect($page) {
831 global $page_redirect_rules;
832 foreach ($page_redirect_rules as $rule=>$replace) {
833 if (preg_match($rule, $page)) {
834 if (is_string($replace)) {
835 $new_page = preg_replace($rule, $replace, $page);
836 } elseif (is_object($replace) && is_callable($replace)) {
837 $new_page = preg_replace_callback($rule, $replace, $page);
839 die_message('Invalid redirect rule: ' . $rule . '=>' . $replace);
841 if ($page !== $new_page) {
850 * Redirect from an old page to new page
852 * This function returns true when a redirection occurs.
853 * So callers need check return value is false or true.
854 * And if it is true, then you have to exit PHP script.
856 * @return bool Inticates a redirection occurred or not
858 function manage_page_redirect() {
860 if (isset($vars['page'])) {
861 $page = $vars['page'];
863 $new_page = get_pagename_on_redirect($page);
864 if ($new_page != false) {
865 header('Location: ' . get_script_uri() . '?' .
866 pagename_urlencode($new_page));
874 // is_a -- Returns TRUE if the object is of this class or has this class as one of its parents
876 if (! function_exists('is_a')) {
878 function is_a($class, $match)
880 if (empty($class)) return FALSE;
882 $class = is_object($class) ? get_class($class) : $class;
883 if (strtolower($class) == strtolower($match)) {
886 return is_a(get_parent_class($class), $match); // Recurse
891 // array_fill -- Fill an array with values
893 if (! function_exists('array_fill')) {
895 function array_fill($start_index, $num, $value)
898 while ($num-- > 0) $ret[$start_index++] = $value;
903 // md5_file -- Calculates the md5 hash of a given filename
905 if (! function_exists('md5_file')) {
907 function md5_file($filename)
909 if (! file_exists($filename)) return FALSE;
911 $fd = fopen($filename, 'rb');
912 if ($fd === FALSE ) return FALSE;
913 $data = fread($fd, filesize($filename));
919 // sha1 -- Compute SHA-1 hash
920 // (PHP 4 >= 4.3.0, PHP5)
921 if (! function_exists('sha1')) {
922 if (extension_loaded('mhash')) {
925 return bin2hex(mhash(MHASH_SHA1, $str));