2 // PukiWiki - Yet another WikiWikiWeb clone.
3 // $Id: func.php,v 1.35 2005/03/27 10:23:06 henoheno Exp $
7 function is_interwiki($str)
10 return preg_match('/^' . $InterWikiName . '$/', $str);
13 function is_pagename($str)
17 $is_pagename = (! is_interwiki($str) &&
18 preg_match('/^(?!\/)' . $BracketName . '$(?<!\/$)/', $str) &&
19 ! preg_match('#(^|/)\.{1,2}(/|$)#', $str));
21 if (defined('SOURCE_ENCODING')) {
22 switch(SOURCE_ENCODING){
23 case 'UTF-8': $pattern =
24 '/^(?:[\x00-\x7F]|(?:[\xC0-\xDF][\x80-\xBF])|(?:[\xE0-\xEF][\x80-\xBF][\x80-\xBF]))+$/';
26 case 'EUC-JP': $pattern =
27 '/^(?:[\x00-\x7F]|(?:[\x8E\xA1-\xFE][\xA1-\xFE])|(?:\x8F[\xA1-\xFE][\xA1-\xFE]))+$/';
30 if (isset($pattern) && $pattern != '')
31 $is_pagename = ($is_pagename && preg_match($pattern, $str));
37 function is_url($str, $only_http = FALSE)
39 $scheme = $only_http ? 'https?' : 'https?|ftp|news';
40 return preg_match('/^(' . $scheme . ')(:\/\/[-_.!~*\'()a-zA-Z0-9;\/?:\@&=+\$,%#]*)$/', $str);
44 function is_page($page, $clearcache = FALSE)
46 if ($clearcache) clearstatcache();
47 return file_exists(get_filename($page));
50 function is_editable($page)
53 static $is_editable = array();
55 if (! isset($is_editable[$page])) {
56 $is_editable[$page] = (
59 ! in_array($page, $cantedit)
63 return $is_editable[$page];
66 function is_freeze($page, $clearcache = FALSE)
68 global $function_freeze;
69 static $is_freeze = array();
71 if ($clearcache === TRUE) $is_freeze = array();
72 if (isset($is_freeze[$page])) return $is_freeze[$page];
74 if (! $function_freeze || ! is_page($page)) {
75 $is_freeze[$page] = FALSE;
78 $fp = fopen(get_filename($page), 'rb');
81 $buffer = fgets($fp, 9);
85 $is_freeze[$page] = ($buffer != FALSE && rtrim($buffer, "\r\n") == '#freeze');
86 return $is_freeze[$page];
91 function auto_template($page)
93 global $auto_template_func, $auto_template_rules;
95 if (! $auto_template_func) return '';
99 foreach ($auto_template_rules as $rule => $template) {
100 $rule_pattrn = '/' . $rule . '/';
102 if (! preg_match($rule_pattrn, $page, $matches)) continue;
104 $template_page = preg_replace($rule_pattrn, $template, $page);
105 if (! is_page($template_page)) continue;
107 $body = join('', get_source($template_page));
109 // Remove fixed-heading anchors
110 $body = preg_replace('/^(\*{1,3}.*)\[#[A-Za-z][\w-]+\](.*)$/m', '$1$2', $body);
113 $body = preg_replace('/^#freeze\s*$/m', '', $body);
115 $count = count($matches);
116 for ($i = 0; $i < $count; $i++)
117 $body = str_replace('$' . $i, $matches[$i], $body);
124 // Expand search words
125 function get_search_words($words, $do_escape = FALSE)
130 if (SOURCE_ENCODING == 'EUC-JP') {
131 // Perl memo - Correct pattern-matching with EUC-JP
132 // http://www.din.or.jp/~ohzaki/perl.htm#JP_Match (Japanese)
134 $post = '(?=(?:[\xA1-\xFE][\xA1-\xFE])*' . // JIS X 0208
135 '(?:[\x00-\x7F\x8E\x8F]|\z))'; // ASCII, SS2, SS3, or the last
138 // function: just preg_quote()
139 $quote_func = create_function('$str', 'return preg_quote($str, \'/\');');
141 // function: mb_convert_kana() or nothing
142 $convert_kana = create_function('$str, $option',
143 (LANG == 'ja' && function_exists('mb_convert_kana')) ?
144 'return mb_convert_kana($str, $option);' : 'return $str;');
146 foreach ($words as $word) {
147 // 'a': Zenkaku-Alphabet to Hankaku-Alphabet
148 // 'K': Hankaku-Katakana to Zenkaku-Katakana
149 // 'C': Zenkaku-Hiragana to Zenkaku-Katakana
150 // 'V': Merge 'A character and A voiced sound symbol' to 'A character with the symbol'
151 $word_zk = $convert_kana($word, 'aKCV');
152 $len = mb_strlen($word_zk);
154 for ($pos = 0; $pos < $len; $pos++) {
155 $char = mb_substr($word_zk, $pos, 1);
156 $arr = array($quote_func($do_escape ? htmlspecialchars($char) : $char));
157 if (strlen($char) == 1) {
158 // Single-byte characters
159 foreach (array(strtoupper($char), strtolower($char)) as $_char) {
160 if ($char != '&') $arr[] = $quote_func($_char);
162 $arr[] = sprintf('&#(?:%d|x%x);', $ord, $ord); // Entity references
163 $arr[] = $quote_func($convert_kana($_char, 'A')); // Zenkaku-Alphabet
166 // Multi-byte characters
167 $arr[] = $quote_func($convert_kana($char, 'c')); // Zenkaku-Katakana to Zenkaku-Hiragana
168 $arr[] = $quote_func($convert_kana($char, 'k')); // Zenkaku-Katakana to Hankaku-Katakana
170 $chars[] = '(?:' . join('|', array_unique($arr)) . ')';
172 $retval[$word] = $pre . join('', $chars) . $post;
178 // 'Search' main function
179 function do_search($word, $type = 'AND', $non_format = FALSE)
181 global $script, $whatsnew, $non_list, $search_non_list;
182 global $_msg_andresult, $_msg_orresult, $_msg_notfoundresult;
187 $b_type = ($type == 'AND'); // AND:TRUE OR:FALSE
188 $keys = get_search_words(preg_split('/\s+/', $word, -1, PREG_SPLIT_NO_EMPTY));
190 $_pages = get_existpages();
193 $non_list_pattern = '/' . $non_list . '/';
194 foreach ($_pages as $page) {
195 if ($page == $whatsnew || (! $search_non_list && preg_match($non_list_pattern, $page)))
198 // ¸¡º÷Âоݥڡ¼¥¸¤ÎÀ©¸Â¤ò¤«¤±¤ë¤«¤É¤¦¤« (¥Ú¡¼¥¸Ì¾¤ÏÀ©¸Â³°)
199 if ($search_auth && ! check_readable($page, false, false)) {
200 $source = get_source(); // Empty
202 $source = get_source($page);
205 array_unshift($source, $page); // ¥Ú¡¼¥¸Ì¾¤â¸¡º÷ÂоݤË
208 foreach ($keys as $key) {
209 $tmp = preg_grep('/' . $key . '/', $source);
210 $b_match = ! empty($tmp);
211 if ($b_match xor $b_type) break;
213 if ($b_match) $pages[$page] = get_filetime($page);
215 if ($non_format) return array_keys($pages);
217 $r_word = rawurlencode($word);
218 $s_word = htmlspecialchars($word);
220 return str_replace('$1', $s_word, $_msg_notfoundresult);
223 $retval = '<ul>' . "\n";
224 foreach ($pages as $page=>$time) {
225 $r_page = rawurlencode($page);
226 $s_page = htmlspecialchars($page);
227 $passage = get_passage($time);
228 $retval .= ' <li><a href="' . $script . '?cmd=read&page=' .
229 $r_page . '&word=' . $r_word . '">' . $s_page .
230 '</a>' . $passage . '</li>' . "\n";
232 $retval .= '</ul>' . "\n";
234 $retval .= str_replace('$1', $s_word, str_replace('$2', count($pages),
235 str_replace('$3', count($_pages), $b_type ? $_msg_andresult : $_msg_orresult)));
240 // Argument check for program
241 function arg_check($str)
244 return isset($vars['cmd']) && (strpos($vars['cmd'], $str) === 0);
248 function encode($key)
250 return ($key == '') ? '' : strtoupper(bin2hex($key));
251 // Equal to strtoupper(join('', unpack('H*0', $key)));
252 // But PHP 4.3.10 says 'Warning: unpack(): Type H: outside of string in ...'
256 function decode($key)
258 // preg_match() = Warning: pack(): Type H: illegal hex digit ...
259 // substr('20202020') = Avoid pack() bug
260 return preg_match('/^[0-9a-f]+$/i', $key) ?
261 substr(pack('H*', '20202020' . $key), 4) : $key;
264 // Remove [[ ]] (brackets)
265 function strip_bracket($str)
268 if (preg_match('/^\[\[(.*)\]\]$/', $str, $match)) {
275 // Create list of pages
276 function page_list($pages, $cmd = 'read', $withfilename = FALSE)
278 global $script, $list_index;
279 global $_msg_symbol, $_msg_other;
280 global $pagereading_enable;
282 // ¥½¡¼¥È¥¡¼¤ò·èÄꤹ¤ë¡£ ' ' < '[a-zA-Z]' < 'zz'¤È¤¤¤¦Á°Äó¡£
288 if($pagereading_enable) {
289 mb_regex_encoding(SOURCE_ENCODING);
290 $readings = get_readings($pages);
293 $list = $matches = array();
294 foreach($pages as $file=>$page) {
295 $r_page = rawurlencode($page);
296 $s_page = htmlspecialchars($page, ENT_QUOTES);
297 $passage = get_pg_passage($page);
299 $str = ' <li><a href="' .
300 $script . '?cmd=' . $cmd . '&page=' . $r_page .
301 '">' . $s_page . '</a>' . $passage;
304 $s_file = htmlspecialchars($file);
305 $str .= "\n" . ' <ul><li>' . $s_file . '</li></ul>' .
310 // WARNING: Japanese code hard-wired
311 if($pagereading_enable) {
312 if(mb_ereg('^([A-Za-z])', mb_convert_kana($page, 'a'), $matches)) {
314 } elseif (isset($readings[$page]) && mb_ereg('^([¥¡-¥ö])', $readings[$page], $matches)) { // here
316 } elseif (mb_ereg('^[ -~]|[^¤¡-¤ó°¡-ô¦]', $page)) { // and here
322 $head = (preg_match('/^([A-Za-z])/', $page, $matches)) ? $matches[1] :
323 (preg_match('/^([ -~])/', $page, $matches) ? $symbol : $other);
326 $list[$head][$page] = $str;
331 $arr_index = array();
332 $retval .= '<ul>' . "\n";
333 foreach ($list as $head=>$pages) {
334 if ($head === $symbol) {
335 $head = $_msg_symbol;
336 } else if ($head === $other) {
342 $arr_index[] = '<a id="top_' . $cnt .
343 '" href="#head_' . $cnt . '"><strong>' .
344 $head . '</strong></a>';
345 $retval .= ' <li><a id="head_' . $cnt . '" href="#top_' . $cnt .
346 '"><strong>' . $head . '</strong></a>' . "\n" .
350 $retval .= join("\n", $pages);
352 $retval .= "\n </ul>\n </li>\n";
354 $retval .= '</ul>' . "\n";
355 if ($list_index && $cnt > 0) {
357 while (! empty($arr_index))
358 $top[] = join(' | ' . "\n", array_splice($arr_index, 0, 16)) . "\n";
360 $retval = '<div id="top" style="text-align:center">' . "\n" .
361 join('<br />', $top) . '</div>' . "\n" . $retval;
366 // Show text formatting rules
371 if (! is_page($rule_page)) {
372 return '<p>Sorry, page \'' . htmlspecialchars($rule_page) .
373 '\' unavailable.</p>';
375 return convert_html(get_source($rule_page));
379 // Show (critical) error message
380 function die_message($msg)
382 $title = $page = 'Runtime error';
384 <h3>Runtime error</h3>
385 <strong>Error message : $msg</strong>
388 pkwk_common_headers();
389 if(defined('SKIN_FILE') && file_exists(SKIN_FILE) && is_readable(SKIN_FILE)) {
390 catbody($title, $page, $body);
392 header('Content-Type: text/html; charset=euc-jp');
394 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
397 <title>$title</title>
398 <meta http-equiv="content-type" content="text/html; charset=euc-jp">
409 // Have the time (as microtime)
410 function getmicrotime()
412 list($usec, $sec) = explode(' ', microtime());
413 return ((float)$sec + (float)$usec);
417 function get_date($format, $timestamp = NULL)
419 $format = preg_replace('/(?<!\\\)T/',
420 preg_replace('/(.)/', '\\\$1', ZONE), $format);
422 $time = ZONETIME + (($timestamp !== NULL) ? $timestamp : UTIME);
424 return date($format, $time);
427 // Format date string
428 function format_date($val, $paren = FALSE)
430 global $date_format, $time_format, $weeklabels;
434 $date = date($date_format, $val) .
435 ' (' . $weeklabels[date('w', $val)] . ') ' .
436 date($time_format, $val);
438 return $paren ? '(' . $date . ')' : $date;
441 // Get short string of the passage, 'N seconds/minutes/hours/days/years ago'
442 function get_passage($time, $paren = TRUE)
444 static $units = array('m'=>60, 'h'=>24, 'd'=>1);
446 $time = max(0, (UTIME - $time) / 60); // minutes
448 foreach ($units as $unit=>$card) {
449 if ($time < $card) break;
452 $time = floor($time) . $unit;
454 return $paren ? '(' . $time . ')' : $time;
457 // Hide <input type="(submit|button|image)"...>
458 function drop_submit($str)
460 return preg_replace('/<input([^>]+)type="(submit|button|image)"/i',
461 '<input$1type="hidden"', $str);
464 // Generate AutoLink patterns (thx to hirofummy)
465 function get_autolink_pattern(& $pages)
467 global $WikiName, $autolink, $nowikiname;
469 $config = &new Config('AutoLink');
471 $ignorepages = $config->get('IgnoreList');
472 $forceignorepages = $config->get('ForceIgnoreList');
474 $auto_pages = array_merge($ignorepages, $forceignorepages);
476 foreach ($pages as $page)
477 if (preg_match('/^' . $WikiName . '$/', $page) ?
478 $nowikiname : strlen($page) >= $autolink)
479 $auto_pages[] = $page;
481 if (empty($auto_pages)) {
482 $result = $result_a = $nowikiname ? '(?!)' : $WikiName;
484 $auto_pages = array_unique($auto_pages);
485 sort($auto_pages, SORT_STRING);
487 $auto_pages_a = array_values(preg_grep('/^[A-Z]+$/i', $auto_pages));
488 $auto_pages = array_values(array_diff($auto_pages, $auto_pages_a));
490 $result = get_autolink_pattern_sub($auto_pages, 0, count($auto_pages), 0);
491 $result_a = get_autolink_pattern_sub($auto_pages_a, 0, count($auto_pages_a), 0);
493 return array($result, $result_a, $forceignorepages);
496 function get_autolink_pattern_sub(& $pages, $start, $end, $pos)
498 if ($end == 0) return '(?!)';
501 $count = $i = $j = 0;
502 $x = (mb_strlen($pages[$start]) <= $pos);
505 for ($i = $start; $i < $end; $i = $j) {
506 $char = mb_substr($pages[$i], $pos, 1);
507 for ($j = $i; $j < $end; $j++)
508 if (mb_substr($pages[$j], $pos, 1) != $char) break;
510 if ($i != $start) $result .= '|';
511 if ($i >= ($j - 1)) {
512 $result .= str_replace(' ', '\\ ', preg_quote(mb_substr($pages[$i], $pos), '/'));
514 $result .= str_replace(' ', '\\ ', preg_quote($char, '/')) .
515 get_autolink_pattern_sub($pages, $i, $j, $pos + 1);
519 if ($x || $count > 1) $result = '(?:' . $result . ')';
520 if ($x) $result .= '?';
525 // Get absolute-URI of this script
526 function get_script_uri($init_uri = '')
528 global $script_directory_index;
531 if ($init_uri == '') {
533 if (isset($script)) return $script;
536 $msg = 'get_script_uri() failed: Please set $script at INI_FILE manually';
538 $script = (SERVER_PORT == 443 ? 'https://' : 'http://'); // scheme
539 $script .= SERVER_NAME; // host
540 $script .= (SERVER_PORT == 80 ? '' : ':' . SERVER_PORT); // port
542 // SCRIPT_NAME ¤¬'/'¤Ç»Ï¤Þ¤Ã¤Æ¤¤¤Ê¤¤¾ì¹ç(cgi¤Ê¤É) REQUEST_URI¤ò»È¤Ã¤Æ¤ß¤ë
544 if ($path{0} != '/') {
545 if (! isset($_SERVER['REQUEST_URI']) || $_SERVER['REQUEST_URI']{0} != '/')
548 // REQUEST_URI¤ò¥Ñ¡¼¥¹¤·¡¢pathÉôʬ¤À¤±¤ò¼è¤ê½Ð¤¹
549 $parse_url = parse_url($script . $_SERVER['REQUEST_URI']);
550 if (! isset($parse_url['path']) || $parse_url['path']{0} != '/')
553 $path = $parse_url['path'];
557 if (! is_url($script, TRUE) && php_sapi_name() == 'cgi')
563 if (isset($script)) die_message('$script: Already init');
564 if (! is_url($init_uri, TRUE)) die_message('$script: Invalid URI');
568 // Cut filename or not
569 if (isset($script_directory_index)) {
570 if (! file_exists($script_directory_index))
571 die_message('Directory index file not found: ' .
572 htmlspecialchars($script_directory_index));
574 if (preg_match('#^(.+/)' . preg_quote($script_directory_index, '#') . '$#',
575 $script, $matches)) $script = $matches[1];
581 // Remove null(\0) bytes from variables
583 // NOTE: PHP had vulnerabilities that opens "hoge.php" via fopen("hoge.php\0.txt") etc.
584 // [PHP-users 12736] null byte attack
585 // http://ns1.php.gr.jp/pipermail/php-users/2003-January/012742.html
587 // 2003-05-16: magic quotes gpc¤ÎÉü¸µ½èÍý¤òÅý¹ç
588 // 2003-05-21: Ï¢ÁÛÇÛÎó¤Î¥¡¼¤Ïbinary safe
590 function input_filter($param)
592 static $magic_quotes_gpc = NULL;
593 if ($magic_quotes_gpc === NULL)
594 $magic_quotes_gpc = get_magic_quotes_gpc();
596 if (is_array($param)) {
597 return array_map('input_filter', $param);
599 $result = str_replace("\0", '', $param);
600 if ($magic_quotes_gpc) $result = stripslashes($result);
605 // Compat for 3rd party plugins. Remove this later
606 function sanitize($param) {
607 return input_filter($param);
610 // Explode Comma-Separated Values to an array
611 function csv_explode($separator, $string)
613 $retval = $matches = array();
615 $_separator = preg_quote($separator, '/');
616 if (! preg_match_all('/("[^"]*(?:""[^"]*)*"|[^' . $_separator . ']*)' .
617 $_separator . '/', $string . $separator, $matches))
620 foreach ($matches[1] as $str) {
622 if ($len > 1 && $str{0} == '"' && $str{$len - 1} == '"')
623 $str = str_replace('""', '"', substr($str, 1, -1));
629 // Implode an array with CSV data format (escape double quotes)
630 function csv_implode($glue, $pieces)
632 $_glue = ($glue != '') ? '\\' . $glue{0} : '';
634 foreach ($pieces as $str) {
635 if (ereg('[' . $_glue . '"' . "\n\r" . ']', $str))
636 $str = '"' . str_replace('"', '""', $str) . '"';
639 return join($glue, $arr);
642 function pkwk_login($pass = '')
646 if (! PKWK_READONLY && $pass != '' && md5($pass) == $adminpass) {
649 sleep(2); // Blocking brute force attack
657 // is_a -- Returns TRUE if the object is of this class or has this class as one of its parents
659 if (! function_exists('is_a')) {
661 function is_a($class, $match)
663 if (empty($class)) return FALSE;
665 $class = is_object($class) ? get_class($class) : $class;
666 if (strtolower($class) == strtolower($match)) {
669 return is_a(get_parent_class($class), $match); // Recurse
674 // array_fill -- Fill an array with values
676 if (! function_exists('array_fill')) {
678 function array_fill($start_index, $num, $value)
681 while ($num-- > 0) $ret[$start_index++] = $value;
686 // md5_file -- Calculates the md5 hash of a given filename
688 if (! function_exists('md5_file')) {
690 function md5_file($filename)
692 if (! file_exists($filename)) return FALSE;
694 $fd = fopen($filename, 'rb');
695 if ($fd === FALSE ) return FALSE;
696 $data = fread($fd, filesize($filename));