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
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 // Expand all search-words to regexes and push them into an array
234 function get_search_words($words = array(), $do_escape = FALSE)
236 static $init, $mb_convert_kana, $pre, $post, $quote = '/';
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);');
244 $mb_convert_kana = create_function('$str, $option',
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)
251 $post = '(?=(?:[\xA1-\xFE][\xA1-\xFE])*' . // JIS X 0208
252 '(?:[\x00-\x7F\x8E\x8F]|\z))'; // ASCII, SS2, SS3, or the last
259 if (! is_array($words)) $words = array($words);
261 // Generate regex for the words
263 foreach ($words as $word) {
265 if ($word == '') continue;
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);
271 // Each chars may be served ...
273 for ($pos = 0; $pos < $nmlen; $pos++) {
274 $char = mb_substr($word_nm, $pos, 1, SOURCE_ENCODING);
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?
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?
292 $chars[] = '(?:' . join('|', array_unique($or)) . ')'; // Regex for the character
295 $regex[$word] = $pre . join('', $chars) . $post; // For the word
298 return $regex; // For all words
301 // 'Search' main function
302 function do_search($word, $type = 'AND', $non_format = FALSE, $base = '')
304 global $script, $whatsnew, $non_list, $search_non_list;
305 global $_msg_andresult, $_msg_orresult, $_msg_notfoundresult;
306 global $search_auth, $show_passage;
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';
315 $pages = get_existpages();
319 $pages = preg_grep('/^' . preg_quote($base, '/') . '/S', $pages);
321 if (! $search_non_list) {
322 $pages = array_diff($pages, preg_grep('/' . $non_list . '/S', $pages));
324 $pages = array_flip($pages);
325 unset($pages[$whatsnew]);
327 $count = count($pages);
328 foreach (array_keys($pages) as $page) {
331 // Search for page name
333 foreach ($keys as $key) {
334 $b_match = preg_match($key, $page);
335 if ($b_type xor $b_match) break; // OR
337 if ($b_match) continue;
340 // Search auth for page contents
341 if ($search_auth && ! check_readable($page, false, false)) {
342 unset($pages[$page]);
346 // Search for page contents
347 foreach ($keys as $key) {
348 $b_match = preg_match($key, get_source($page, TRUE, TRUE));
349 if ($b_type xor $b_match) break; // OR
351 if ($b_match) continue;
353 unset($pages[$page]); // Miss
355 if ($non_format) return array_keys($pages);
357 $r_word = rawurlencode($word);
358 $s_word = htmlsc($word);
360 return str_replace('$1', $s_word, $_msg_notfoundresult);
362 ksort($pages, SORT_STRING);
364 $retval = '<ul>' . "\n";
365 foreach (array_keys($pages) as $page) {
366 $r_page = rawurlencode($page);
367 $s_page = htmlsc($page);
368 $passage = $show_passage ? ' ' . get_passage(get_filetime($page)) : '';
369 $retval .= ' <li><a href="' . $script . '?cmd=read&page=' .
370 $r_page . '&word=' . $r_word . '">' . $s_page .
371 '</a>' . $passage . '</li>' . "\n";
373 $retval .= '</ul>' . "\n";
375 $retval .= str_replace('$1', $s_word, str_replace('$2', count($pages),
376 str_replace('$3', $count, $b_type ? $_msg_andresult : $_msg_orresult)));
381 // Argument check for program
382 function arg_check($str)
385 return isset($vars['cmd']) && (strpos($vars['cmd'], $str) === 0);
388 function _pagename_urlencode_callback($matches)
390 return rawurlencode($matches[0]);
393 function pagename_urlencode($page)
395 return preg_replace_callback('|[^/:]+|', '_pagename_urlencode_callback', $page);
399 function encode($str)
402 return ($str == '') ? '' : strtoupper(bin2hex($str));
403 // Equal to strtoupper(join('', unpack('H*0', $key)));
404 // But PHP 4.3.10 says 'Warning: unpack(): Type H: outside of string in ...'
408 function decode($str)
410 return pkwk_hex2bin($str);
413 // Inversion of bin2hex()
414 function pkwk_hex2bin($hex_string)
416 // preg_match : Avoid warning : pack(): Type H: illegal hex digit ...
417 // (string) : Always treat as string (not int etc). See BugTrack2/31
418 return preg_match('/^[0-9a-f]+$/i', $hex_string) ?
419 pack('H*', (string)$hex_string) : $hex_string;
422 // Remove [[ ]] (brackets)
423 function strip_bracket($str)
426 if (preg_match('/^\[\[(.*)\]\]$/', $str, $match)) {
433 // Create list of pages
434 function page_list($pages, $cmd = 'read', $withfilename = FALSE)
436 global $script, $list_index;
437 global $_msg_symbol, $_msg_other;
438 global $pagereading_enable;
440 // ソートキーを決定する。 ' ' < '[a-zA-Z]' < 'zz'という前提。
446 if($pagereading_enable) {
447 mb_regex_encoding(SOURCE_ENCODING);
448 $readings = get_readings($pages);
451 $list = $matches = array();
453 // Shrink URI for read
454 if ($cmd == 'read') {
455 $href = $script . '?';
457 $href = $script . '?cmd=' . $cmd . '&page=';
460 foreach($pages as $file=>$page) {
461 $r_page = pagename_urlencode($page);
462 $s_page = htmlsc($page, ENT_QUOTES);
463 $passage = get_pg_passage($page);
465 $str = ' <li><a href="' . $href . $r_page . '">' .
466 $s_page . '</a>' . $passage;
469 $s_file = htmlsc($file);
470 $str .= "\n" . ' <ul><li>' . $s_file . '</li></ul>' .
475 // WARNING: Japanese code hard-wired
476 if($pagereading_enable) {
477 if(mb_ereg('^([A-Za-z])', mb_convert_kana($page, 'a'), $matches)) {
478 $head = strtoupper($matches[1]);
479 } elseif (isset($readings[$page]) && mb_ereg('^([ァ-ヶ])', $readings[$page], $matches)) { // here
481 } elseif (mb_ereg('^[ -~]|[^ぁ-ん亜-熙]', $page)) { // and here
487 $head = (preg_match('/^([A-Za-z])/', $page, $matches)) ? strtoupper($matches[1]) :
488 (preg_match('/^([ -~])/', $page) ? $symbol : $other);
491 $list[$head][$page] = $str;
493 uksort($pages, 'strnatcmp');
496 $arr_index = array();
497 $retval .= '<ul>' . "\n";
498 foreach ($list as $head=>$pages) {
499 if ($head === $symbol) {
500 $head = $_msg_symbol;
501 } else if ($head === $other) {
507 $arr_index[] = '<a id="top_' . $cnt .
508 '" href="#head_' . $cnt . '"><strong>' .
509 $head . '</strong></a>';
510 $retval .= ' <li><a id="head_' . $cnt . '" href="#top_' . $cnt .
511 '"><strong>' . $head . '</strong></a>' . "\n" .
514 ksort($pages, SORT_STRING);
515 $retval .= join("\n", $pages);
517 $retval .= "\n </ul>\n </li>\n";
519 $retval .= '</ul>' . "\n";
520 if ($list_index && $cnt > 0) {
522 while (! empty($arr_index))
523 $top[] = join(' | ' . "\n", array_splice($arr_index, 0, 16)) . "\n";
525 $retval = '<div id="top" style="text-align:center">' . "\n" .
526 join('<br />', $top) . '</div>' . "\n" . $retval;
531 // Show text formatting rules
536 if (! is_page($rule_page)) {
537 return '<p>Sorry, page \'' . htmlsc($rule_page) .
538 '\' unavailable.</p>';
540 return convert_html(get_source($rule_page));
544 // Show (critical) error message
545 function die_message($msg)
547 $title = $page = 'Runtime error';
549 <h3>Runtime error</h3>
550 <strong>Error message : $msg</strong>
553 pkwk_common_headers();
554 if(defined('SKIN_FILE') && file_exists(SKIN_FILE) && is_readable(SKIN_FILE)) {
555 catbody($title, $page, $body);
558 if(defined('CONTENT_CHARSET')) {
559 $charset = CONTENT_CHARSET;
561 header("Content-Type: text/html; charset=$charset");
566 <meta http-equiv="content-type" content="text/html; charset=$charset">
567 <title>$title</title>
578 // Have the time (as microtime)
579 function getmicrotime()
581 list($usec, $sec) = explode(' ', microtime());
582 return ((float)$sec + (float)$usec);
585 // Elapsed time by second
586 //define('MUTIME', getmicrotime());
587 function elapsedtime()
589 $at_the_microtime = MUTIME;
590 return sprintf('%01.03f', getmicrotime() - $at_the_microtime);
594 function get_date($format, $timestamp = NULL)
596 $format = preg_replace('/(?<!\\\)T/',
597 preg_replace('/(.)/', '\\\$1', ZONE), $format);
599 $time = ZONETIME + (($timestamp !== NULL) ? $timestamp : UTIME);
601 return date($format, $time);
604 // Format date string
605 function format_date($val, $paren = FALSE)
607 global $date_format, $time_format, $weeklabels;
611 $date = date($date_format, $val) .
612 ' (' . $weeklabels[date('w', $val)] . ') ' .
613 date($time_format, $val);
615 return $paren ? '(' . $date . ')' : $date;
618 // Get short string of the passage, 'N seconds/minutes/hours/days/years ago'
619 function get_passage($time, $paren = TRUE)
621 static $units = array('m'=>60, 'h'=>24, 'd'=>1);
623 $time = max(0, (UTIME - $time) / 60); // minutes
625 foreach ($units as $unit=>$card) {
626 if ($time < $card) break;
629 $time = floor($time) . $unit;
631 return $paren ? '(' . $time . ')' : $time;
634 // Hide <input type="(submit|button|image)"...>
635 function drop_submit($str)
637 return preg_replace('/<input([^>]+)type="(submit|button|image)"/i',
638 '<input$1type="hidden"', $str);
641 // Generate AutoLink patterns (thx to hirofummy)
642 function get_autolink_pattern(& $pages)
644 global $WikiName, $autolink, $nowikiname;
646 $config = new Config('AutoLink');
648 $ignorepages = $config->get('IgnoreList');
649 $forceignorepages = $config->get('ForceIgnoreList');
651 $auto_pages = array_merge($ignorepages, $forceignorepages);
653 foreach ($pages as $page)
654 if (preg_match('/^' . $WikiName . '$/', $page) ?
655 $nowikiname : strlen($page) >= $autolink)
656 $auto_pages[] = $page;
658 if (empty($auto_pages)) {
659 $result = $result_a = $nowikiname ? '(?!)' : $WikiName;
661 $auto_pages = array_unique($auto_pages);
662 sort($auto_pages, SORT_STRING);
664 $auto_pages_a = array_values(preg_grep('/^[A-Z]+$/i', $auto_pages));
665 $auto_pages = array_values(array_diff($auto_pages, $auto_pages_a));
667 $result = get_autolink_pattern_sub($auto_pages, 0, count($auto_pages), 0);
668 $result_a = get_autolink_pattern_sub($auto_pages_a, 0, count($auto_pages_a), 0);
670 return array($result, $result_a, $forceignorepages);
673 function get_autolink_pattern_sub(& $pages, $start, $end, $pos)
675 if ($end == 0) return '(?!)';
678 $count = $i = $j = 0;
679 $x = (mb_strlen($pages[$start]) <= $pos);
682 for ($i = $start; $i < $end; $i = $j) {
683 $char = mb_substr($pages[$i], $pos, 1);
684 for ($j = $i; $j < $end; $j++)
685 if (mb_substr($pages[$j], $pos, 1) != $char) break;
687 if ($i != $start) $result .= '|';
688 if ($i >= ($j - 1)) {
689 $result .= str_replace(' ', '\\ ', preg_quote(mb_substr($pages[$i], $pos), '/'));
691 $result .= str_replace(' ', '\\ ', preg_quote($char, '/')) .
692 get_autolink_pattern_sub($pages, $i, $j, $pos + 1);
696 if ($x || $count > 1) $result = '(?:' . $result . ')';
697 if ($x) $result .= '?';
703 * Get propery URI of this script
705 * @param $uri_type relative or absolute option
706 * PKWK_URI_RELATIVE, PKWK_URI_ROOT or PKWK_URI_ABSOLUTE
708 function get_base_uri($uri_type = PKWK_URI_RELATIVE)
711 case PKWK_URI_RELATIVE:
712 return pkwk_script_uri_base(PKWK_URI_RELATIVE);
714 return pkwk_script_uri_base(PKWK_URI_ROOT);
715 case PKWK_URI_ABSOLUTE:
716 return pkwk_script_uri_base(PKWK_URI_ABSOLUTE);
718 die_message('Invalid uri_type in get_base_uri()');
723 * Get URI of the page
725 * @param page page name
726 * @param $uri_type relative or absolute option
727 * PKWK_URI_RELATIVE, PKWK_URI_ROOT or PKWK_URI_ABSOLUTE
729 function get_page_uri($page, $uri_type = PKWK_URI_RELATIVE)
731 return get_base_uri($uri_type) . '?' . pagename_urlencode($page);
734 // Get absolute-URI of this script
735 function get_script_uri()
737 return get_base_uri(PKWK_URI_ABSOLUTE);
741 * Get or initialize Script URI
743 * @param $uri_type relative or absolute potion
744 * PKWK_URI_RELATIVE, PKWK_URI_ROOT or PKWK_URI_ABSOLUTE
745 * @param $initialize true if you initialize URI
746 * @param $uri_set URI set manually
748 function pkwk_script_uri_base($uri_type, $initialize, $uri_set)
750 global $script_directory_index;
751 static $initialized = false;
752 static $uri_absolute, $uri_root, $uri_relative;
753 if (! $initialized) {
754 if (isset($initialize) && $initialize) {
755 if (isset($uri_set)) {
756 $uri_absolute = $uri_set;
758 $uri_absolute = guess_script_absolute_uri();
760 // Support $script_directory_index (cut 'index.php')
761 if (isset($script_directory_index)) {
762 $slash_index = '/' . $script_directory_index;
763 $len = strlen($slash_index);
764 if (substr($uri_absolute, -1 * $len) === $slash_index) {
765 $uri_absolute = substr($uri_absolute, 0, strlen($uri_absolute) - $len + 1);
768 $elements = parse_url($uri_absolute);
769 $uri_root = $elements['path'];
770 if (substr($uri_root, -1) === '/') {
771 $uri_relative = './';
773 $pos = mb_strrpos($uri_root, '/');
775 $uri_relative = substr($uri_root, $pos + 1);
777 $uri_relative = $uri_root;
782 die_message('Script URI must be initialized in pkwk_script_uri_base()');
786 case PKWK_URI_RELATIVE:
787 return $uri_relative;
790 case PKWK_URI_ABSOLUTE:
791 return $uri_absolute;
793 die_message('Invalid uri_type in pkwk_script_uri_base()');
798 * Guess Script Absolute URI.
800 * SERVER_PORT: $_SERVER['SERVER_PORT'] converted in init.php
801 * SERVER_NAME: $_SERVER['SERVER_NAME'] converted in init.php
803 function guess_script_absolute_uri()
806 $is_ssl = (SERVER_PORT == 443) ||
807 (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ||
808 (isset($_SERVER['REQUEST_SCHEME']) && $_SERVER['REQUEST_SCHEME'] === 'https');
810 $host = 'https://' . SERVER_NAME .
811 ($port == 443 ? '' : ':' . $port);
813 $host = 'http://' . SERVER_NAME .
814 ($port == 80 ? '' : ':' . $port);
816 $uri_elements = parse_url($host . $_SERVER['REQUEST_URI']);
817 return $host . $uri_elements['path'];
820 // Remove null(\0) bytes from variables
822 // NOTE: PHP had vulnerabilities that opens "hoge.php" via fopen("hoge.php\0.txt") etc.
823 // [PHP-users 12736] null byte attack
824 // http://ns1.php.gr.jp/pipermail/php-users/2003-January/012742.html
826 // 2003-05-16: magic quotes gpcの復元処理を統合
827 // 2003-05-21: 連想配列のキーはbinary safe
829 function input_filter($param)
831 static $magic_quotes_gpc = NULL;
832 if ($magic_quotes_gpc === NULL)
833 $magic_quotes_gpc = get_magic_quotes_gpc();
835 if (is_array($param)) {
836 return array_map('input_filter', $param);
838 $result = str_replace("\0", '', $param);
839 if ($magic_quotes_gpc) $result = stripslashes($result);
844 // Compat for 3rd party plugins. Remove this later
845 function sanitize($param) {
846 return input_filter($param);
849 // Explode Comma-Separated Values to an array
850 function csv_explode($separator, $string)
852 $retval = $matches = array();
854 $_separator = preg_quote($separator, '/');
855 if (! preg_match_all('/("[^"]*(?:""[^"]*)*"|[^' . $_separator . ']*)' .
856 $_separator . '/', $string . $separator, $matches))
859 foreach ($matches[1] as $str) {
861 if ($len > 1 && $str{0} == '"' && $str{$len - 1} == '"')
862 $str = str_replace('""', '"', substr($str, 1, -1));
868 // Implode an array with CSV data format (escape double quotes)
869 function csv_implode($glue, $pieces)
871 $_glue = ($glue != '') ? '\\' . $glue{0} : '';
873 foreach ($pieces as $str) {
874 if (preg_match('/[' . '"' . "\n\r" . $_glue . ']/', $str))
875 $str = '"' . str_replace('"', '""', $str) . '"';
878 return join($glue, $arr);
881 // Sugar with default settings
882 function htmlsc($string = '', $flags = ENT_COMPAT, $charset = CONTENT_CHARSET)
884 return htmlspecialchars($string, $flags, $charset); // htmlsc()
888 * Get redirect page name on Page Redirect Rules
890 * This function returns exactly false if it doesn't need redirection.
891 * So callers need check return value is false or not.
893 * @param $page page name
894 * @return new page name or false
896 function get_pagename_on_redirect($page) {
897 global $page_redirect_rules;
898 foreach ($page_redirect_rules as $rule=>$replace) {
899 if (preg_match($rule, $page)) {
900 if (is_string($replace)) {
901 $new_page = preg_replace($rule, $replace, $page);
902 } elseif (is_object($replace) && is_callable($replace)) {
903 $new_page = preg_replace_callback($rule, $replace, $page);
905 die_message('Invalid redirect rule: ' . $rule . '=>' . $replace);
907 if ($page !== $new_page) {
916 * Redirect from an old page to new page
918 * This function returns true when a redirection occurs.
919 * So callers need check return value is false or true.
920 * And if it is true, then you have to exit PHP script.
922 * @return bool Inticates a redirection occurred or not
924 function manage_page_redirect() {
926 if (isset($vars['page'])) {
927 $page = $vars['page'];
929 $new_page = get_pagename_on_redirect($page);
930 if ($new_page != false) {
931 header('Location: ' . get_script_uri() . '?' .
932 pagename_urlencode($new_page));
940 // is_a -- Returns TRUE if the object is of this class or has this class as one of its parents
942 if (! function_exists('is_a')) {
944 function is_a($class, $match)
946 if (empty($class)) return FALSE;
948 $class = is_object($class) ? get_class($class) : $class;
949 if (strtolower($class) == strtolower($match)) {
952 return is_a(get_parent_class($class), $match); // Recurse
957 // array_fill -- Fill an array with values
959 if (! function_exists('array_fill')) {
961 function array_fill($start_index, $num, $value)
964 while ($num-- > 0) $ret[$start_index++] = $value;
969 // md5_file -- Calculates the md5 hash of a given filename
971 if (! function_exists('md5_file')) {
973 function md5_file($filename)
975 if (! file_exists($filename)) return FALSE;
977 $fd = fopen($filename, 'rb');
978 if ($fd === FALSE ) return FALSE;
979 $data = fread($fd, filesize($filename));
985 // sha1 -- Compute SHA-1 hash
986 // (PHP 4 >= 4.3.0, PHP5)
987 if (! function_exists('sha1')) {
988 if (extension_loaded('mhash')) {
991 return bin2hex(mhash(MHASH_SHA1, $str));