2 // PukiWiki - Yet another WikiWikiWeb clone.
3 // $Id: func.php,v 1.40 2005/04/16 05:37:13 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') or
79 die('is_freeze(): fopen() failed: ' . htmlspecialchars($page));
80 flock($fp, LOCK_SH) or die('is_freeze(): flock() failed');
82 $buffer = fgets($fp, 9);
83 flock($fp, LOCK_UN) or die('is_freeze(): flock() failed');
84 fclose($fp) or die('is_freeze(): fclose() failed: ' . htmlspecialchars($page));
86 $is_freeze[$page] = ($buffer != FALSE && rtrim($buffer, "\r\n") == '#freeze');
87 return $is_freeze[$page];
92 function auto_template($page)
94 global $auto_template_func, $auto_template_rules;
96 if (! $auto_template_func) return '';
100 foreach ($auto_template_rules as $rule => $template) {
101 $rule_pattrn = '/' . $rule . '/';
103 if (! preg_match($rule_pattrn, $page, $matches)) continue;
105 $template_page = preg_replace($rule_pattrn, $template, $page);
106 if (! is_page($template_page)) continue;
108 $body = join('', get_source($template_page));
110 // Remove fixed-heading anchors
111 $body = preg_replace('/^(\*{1,3}.*)\[#[A-Za-z][\w-]+\](.*)$/m', '$1$2', $body);
114 $body = preg_replace('/^#freeze\s*$/m', '', $body);
116 $count = count($matches);
117 for ($i = 0; $i < $count; $i++)
118 $body = str_replace('$' . $i, $matches[$i], $body);
125 // Expand search words
126 function get_search_words($words, $do_escape = FALSE)
131 if (SOURCE_ENCODING == 'EUC-JP') {
132 // Perl memo - Correct pattern-matching with EUC-JP
133 // http://www.din.or.jp/~ohzaki/perl.htm#JP_Match (Japanese)
135 $post = '(?=(?:[\xA1-\xFE][\xA1-\xFE])*' . // JIS X 0208
136 '(?:[\x00-\x7F\x8E\x8F]|\z))'; // ASCII, SS2, SS3, or the last
139 // function: just preg_quote()
140 $quote_func = create_function('$str', 'return preg_quote($str, \'/\');');
142 // function: mb_convert_kana() or nothing
143 $convert_kana = create_function('$str, $option',
144 (LANG == 'ja' && function_exists('mb_convert_kana')) ?
145 'return mb_convert_kana($str, $option);' : 'return $str;');
147 foreach ($words as $word) {
148 // 'a': Zenkaku-Alphabet to Hankaku-Alphabet
149 // 'K': Hankaku-Katakana to Zenkaku-Katakana
150 // 'C': Zenkaku-Hiragana to Zenkaku-Katakana
151 // 'V': Merge 'A character and A voiced sound symbol' to 'A character with the symbol'
152 $word_zk = $convert_kana($word, 'aKCV');
153 $len = mb_strlen($word_zk);
155 for ($pos = 0; $pos < $len; $pos++) {
156 $char = mb_substr($word_zk, $pos, 1);
157 $arr = array($quote_func($do_escape ? htmlspecialchars($char) : $char));
158 if (strlen($char) == 1) {
159 // Single-byte characters
160 foreach (array(strtoupper($char), strtolower($char)) as $_char) {
161 if ($char != '&') $arr[] = $quote_func($_char);
163 $arr[] = sprintf('&#(?:%d|x%x);', $ord, $ord); // Entity references
164 $arr[] = $quote_func($convert_kana($_char, 'A')); // Zenkaku-Alphabet
167 // Multi-byte characters
168 $arr[] = $quote_func($convert_kana($char, 'c')); // Zenkaku-Katakana to Zenkaku-Hiragana
169 $arr[] = $quote_func($convert_kana($char, 'k')); // Zenkaku-Katakana to Hankaku-Katakana
171 $chars[] = '(?:' . join('|', array_unique($arr)) . ')';
173 $retval[$word] = $pre . join('', $chars) . $post;
179 // 'Search' main function
180 function do_search($word, $type = 'AND', $non_format = FALSE)
182 global $script, $whatsnew, $non_list, $search_non_list;
183 global $_msg_andresult, $_msg_orresult, $_msg_notfoundresult;
188 $b_type = ($type == 'AND'); // AND:TRUE OR:FALSE
189 $keys = get_search_words(preg_split('/\s+/', $word, -1, PREG_SPLIT_NO_EMPTY));
191 $_pages = get_existpages();
194 $non_list_pattern = '/' . $non_list . '/';
195 foreach ($_pages as $page) {
196 if ($page == $whatsnew || (! $search_non_list && preg_match($non_list_pattern, $page)))
199 // ¸¡º÷Âоݥڡ¼¥¸¤ÎÀ©¸Â¤ò¤«¤±¤ë¤«¤É¤¦¤« (¥Ú¡¼¥¸Ì¾¤ÏÀ©¸Â³°)
200 if ($search_auth && ! check_readable($page, false, false)) {
201 $source = get_source(); // Empty
203 $source = get_source($page);
206 array_unshift($source, $page); // ¥Ú¡¼¥¸Ì¾¤â¸¡º÷ÂоݤË
209 foreach ($keys as $key) {
210 $tmp = preg_grep('/' . $key . '/', $source);
211 $b_match = ! empty($tmp);
212 if ($b_match xor $b_type) break;
214 if ($b_match) $pages[$page] = get_filetime($page);
216 if ($non_format) return array_keys($pages);
218 $r_word = rawurlencode($word);
219 $s_word = htmlspecialchars($word);
221 return str_replace('$1', $s_word, $_msg_notfoundresult);
224 $retval = '<ul>' . "\n";
225 foreach ($pages as $page=>$time) {
226 $r_page = rawurlencode($page);
227 $s_page = htmlspecialchars($page);
228 $passage = get_passage($time);
229 $retval .= ' <li><a href="' . $script . '?cmd=read&page=' .
230 $r_page . '&word=' . $r_word . '">' . $s_page .
231 '</a>' . $passage . '</li>' . "\n";
233 $retval .= '</ul>' . "\n";
235 $retval .= str_replace('$1', $s_word, str_replace('$2', count($pages),
236 str_replace('$3', count($_pages), $b_type ? $_msg_andresult : $_msg_orresult)));
241 // Argument check for program
242 function arg_check($str)
245 return isset($vars['cmd']) && (strpos($vars['cmd'], $str) === 0);
249 function encode($key)
251 return ($key == '') ? '' : strtoupper(bin2hex($key));
252 // Equal to strtoupper(join('', unpack('H*0', $key)));
253 // But PHP 4.3.10 says 'Warning: unpack(): Type H: outside of string in ...'
257 function decode($key)
259 return hex2bin($key);
262 // Inversion of bin2hex()
263 function hex2bin($hex_string)
265 // preg_match : Avoid warning : pack(): Type H: illegal hex digit ...
266 // (string) : Always treat as string (not int etc). See BugTrack2/31
267 return preg_match('/^[0-9a-f]+$/i', $hex_string) ?
268 pack('H*', (string)$hex_string) : $hex_string;
271 // Remove [[ ]] (brackets)
272 function strip_bracket($str)
275 if (preg_match('/^\[\[(.*)\]\]$/', $str, $match)) {
282 // Create list of pages
283 function page_list($pages, $cmd = 'read', $withfilename = FALSE)
285 global $script, $list_index;
286 global $_msg_symbol, $_msg_other;
287 global $pagereading_enable;
289 // ¥½¡¼¥È¥¡¼¤ò·èÄꤹ¤ë¡£ ' ' < '[a-zA-Z]' < 'zz'¤È¤¤¤¦Á°Äó¡£
295 if($pagereading_enable) {
296 mb_regex_encoding(SOURCE_ENCODING);
297 $readings = get_readings($pages);
300 $list = $matches = array();
301 foreach($pages as $file=>$page) {
302 $r_page = rawurlencode($page);
303 $s_page = htmlspecialchars($page, ENT_QUOTES);
304 $passage = get_pg_passage($page);
306 $str = ' <li><a href="' .
307 $script . '?cmd=' . $cmd . '&page=' . $r_page .
308 '">' . $s_page . '</a>' . $passage;
311 $s_file = htmlspecialchars($file);
312 $str .= "\n" . ' <ul><li>' . $s_file . '</li></ul>' .
317 // WARNING: Japanese code hard-wired
318 if($pagereading_enable) {
319 if(mb_ereg('^([A-Za-z])', mb_convert_kana($page, 'a'), $matches)) {
321 } elseif (isset($readings[$page]) && mb_ereg('^([¥¡-¥ö])', $readings[$page], $matches)) { // here
323 } elseif (mb_ereg('^[ -~]|[^¤¡-¤ó°¡-ô¦]', $page)) { // and here
329 $head = (preg_match('/^([A-Za-z])/', $page, $matches)) ? $matches[1] :
330 (preg_match('/^([ -~])/', $page, $matches) ? $symbol : $other);
333 $list[$head][$page] = $str;
338 $arr_index = array();
339 $retval .= '<ul>' . "\n";
340 foreach ($list as $head=>$pages) {
341 if ($head === $symbol) {
342 $head = $_msg_symbol;
343 } else if ($head === $other) {
349 $arr_index[] = '<a id="top_' . $cnt .
350 '" href="#head_' . $cnt . '"><strong>' .
351 $head . '</strong></a>';
352 $retval .= ' <li><a id="head_' . $cnt . '" href="#top_' . $cnt .
353 '"><strong>' . $head . '</strong></a>' . "\n" .
357 $retval .= join("\n", $pages);
359 $retval .= "\n </ul>\n </li>\n";
361 $retval .= '</ul>' . "\n";
362 if ($list_index && $cnt > 0) {
364 while (! empty($arr_index))
365 $top[] = join(' | ' . "\n", array_splice($arr_index, 0, 16)) . "\n";
367 $retval = '<div id="top" style="text-align:center">' . "\n" .
368 join('<br />', $top) . '</div>' . "\n" . $retval;
373 // Show text formatting rules
378 if (! is_page($rule_page)) {
379 return '<p>Sorry, page \'' . htmlspecialchars($rule_page) .
380 '\' unavailable.</p>';
382 return convert_html(get_source($rule_page));
386 // Show (critical) error message
387 function die_message($msg)
389 $title = $page = 'Runtime error';
391 <h3>Runtime error</h3>
392 <strong>Error message : $msg</strong>
395 pkwk_common_headers();
396 if(defined('SKIN_FILE') && file_exists(SKIN_FILE) && is_readable(SKIN_FILE)) {
397 catbody($title, $page, $body);
399 header('Content-Type: text/html; charset=euc-jp');
401 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
404 <title>$title</title>
405 <meta http-equiv="content-type" content="text/html; charset=euc-jp">
416 // Have the time (as microtime)
417 function getmicrotime()
419 list($usec, $sec) = explode(' ', microtime());
420 return ((float)$sec + (float)$usec);
424 function get_date($format, $timestamp = NULL)
426 $format = preg_replace('/(?<!\\\)T/',
427 preg_replace('/(.)/', '\\\$1', ZONE), $format);
429 $time = ZONETIME + (($timestamp !== NULL) ? $timestamp : UTIME);
431 return date($format, $time);
434 // Format date string
435 function format_date($val, $paren = FALSE)
437 global $date_format, $time_format, $weeklabels;
441 $date = date($date_format, $val) .
442 ' (' . $weeklabels[date('w', $val)] . ') ' .
443 date($time_format, $val);
445 return $paren ? '(' . $date . ')' : $date;
448 // Get short string of the passage, 'N seconds/minutes/hours/days/years ago'
449 function get_passage($time, $paren = TRUE)
451 static $units = array('m'=>60, 'h'=>24, 'd'=>1);
453 $time = max(0, (UTIME - $time) / 60); // minutes
455 foreach ($units as $unit=>$card) {
456 if ($time < $card) break;
459 $time = floor($time) . $unit;
461 return $paren ? '(' . $time . ')' : $time;
464 // Hide <input type="(submit|button|image)"...>
465 function drop_submit($str)
467 return preg_replace('/<input([^>]+)type="(submit|button|image)"/i',
468 '<input$1type="hidden"', $str);
471 // Generate AutoLink patterns (thx to hirofummy)
472 function get_autolink_pattern(& $pages)
474 global $WikiName, $autolink, $nowikiname;
476 $config = &new Config('AutoLink');
478 $ignorepages = $config->get('IgnoreList');
479 $forceignorepages = $config->get('ForceIgnoreList');
481 $auto_pages = array_merge($ignorepages, $forceignorepages);
483 foreach ($pages as $page)
484 if (preg_match('/^' . $WikiName . '$/', $page) ?
485 $nowikiname : strlen($page) >= $autolink)
486 $auto_pages[] = $page;
488 if (empty($auto_pages)) {
489 $result = $result_a = $nowikiname ? '(?!)' : $WikiName;
491 $auto_pages = array_unique($auto_pages);
492 sort($auto_pages, SORT_STRING);
494 $auto_pages_a = array_values(preg_grep('/^[A-Z]+$/i', $auto_pages));
495 $auto_pages = array_values(array_diff($auto_pages, $auto_pages_a));
497 $result = get_autolink_pattern_sub($auto_pages, 0, count($auto_pages), 0);
498 $result_a = get_autolink_pattern_sub($auto_pages_a, 0, count($auto_pages_a), 0);
500 return array($result, $result_a, $forceignorepages);
503 function get_autolink_pattern_sub(& $pages, $start, $end, $pos)
505 if ($end == 0) return '(?!)';
508 $count = $i = $j = 0;
509 $x = (mb_strlen($pages[$start]) <= $pos);
512 for ($i = $start; $i < $end; $i = $j) {
513 $char = mb_substr($pages[$i], $pos, 1);
514 for ($j = $i; $j < $end; $j++)
515 if (mb_substr($pages[$j], $pos, 1) != $char) break;
517 if ($i != $start) $result .= '|';
518 if ($i >= ($j - 1)) {
519 $result .= str_replace(' ', '\\ ', preg_quote(mb_substr($pages[$i], $pos), '/'));
521 $result .= str_replace(' ', '\\ ', preg_quote($char, '/')) .
522 get_autolink_pattern_sub($pages, $i, $j, $pos + 1);
526 if ($x || $count > 1) $result = '(?:' . $result . ')';
527 if ($x) $result .= '?';
532 // Get absolute-URI of this script
533 function get_script_uri($init_uri = '')
535 global $script_directory_index;
538 if ($init_uri == '') {
540 if (isset($script)) return $script;
543 $msg = 'get_script_uri() failed: Please set $script at INI_FILE manually';
545 $script = (SERVER_PORT == 443 ? 'https://' : 'http://'); // scheme
546 $script .= SERVER_NAME; // host
547 $script .= (SERVER_PORT == 80 ? '' : ':' . SERVER_PORT); // port
549 // SCRIPT_NAME ¤¬'/'¤Ç»Ï¤Þ¤Ã¤Æ¤¤¤Ê¤¤¾ì¹ç(cgi¤Ê¤É) REQUEST_URI¤ò»È¤Ã¤Æ¤ß¤ë
551 if ($path{0} != '/') {
552 if (! isset($_SERVER['REQUEST_URI']) || $_SERVER['REQUEST_URI']{0} != '/')
555 // REQUEST_URI¤ò¥Ñ¡¼¥¹¤·¡¢pathÉôʬ¤À¤±¤ò¼è¤ê½Ð¤¹
556 $parse_url = parse_url($script . $_SERVER['REQUEST_URI']);
557 if (! isset($parse_url['path']) || $parse_url['path']{0} != '/')
560 $path = $parse_url['path'];
564 if (! is_url($script, TRUE) && php_sapi_name() == 'cgi')
570 if (isset($script)) die_message('$script: Already init');
571 if (! is_url($init_uri, TRUE)) die_message('$script: Invalid URI');
575 // Cut filename or not
576 if (isset($script_directory_index)) {
577 if (! file_exists($script_directory_index))
578 die_message('Directory index file not found: ' .
579 htmlspecialchars($script_directory_index));
581 if (preg_match('#^(.+/)' . preg_quote($script_directory_index, '#') . '$#',
582 $script, $matches)) $script = $matches[1];
588 // Remove null(\0) bytes from variables
590 // NOTE: PHP had vulnerabilities that opens "hoge.php" via fopen("hoge.php\0.txt") etc.
591 // [PHP-users 12736] null byte attack
592 // http://ns1.php.gr.jp/pipermail/php-users/2003-January/012742.html
594 // 2003-05-16: magic quotes gpc¤ÎÉü¸µ½èÍý¤òÅý¹ç
595 // 2003-05-21: Ï¢ÁÛÇÛÎó¤Î¥¡¼¤Ïbinary safe
597 function input_filter($param)
599 static $magic_quotes_gpc = NULL;
600 if ($magic_quotes_gpc === NULL)
601 $magic_quotes_gpc = get_magic_quotes_gpc();
603 if (is_array($param)) {
604 return array_map('input_filter', $param);
606 $result = str_replace("\0", '', $param);
607 if ($magic_quotes_gpc) $result = stripslashes($result);
612 // Compat for 3rd party plugins. Remove this later
613 function sanitize($param) {
614 return input_filter($param);
617 // Explode Comma-Separated Values to an array
618 function csv_explode($separator, $string)
620 $retval = $matches = array();
622 $_separator = preg_quote($separator, '/');
623 if (! preg_match_all('/("[^"]*(?:""[^"]*)*"|[^' . $_separator . ']*)' .
624 $_separator . '/', $string . $separator, $matches))
627 foreach ($matches[1] as $str) {
629 if ($len > 1 && $str{0} == '"' && $str{$len - 1} == '"')
630 $str = str_replace('""', '"', substr($str, 1, -1));
636 // Implode an array with CSV data format (escape double quotes)
637 function csv_implode($glue, $pieces)
639 $_glue = ($glue != '') ? '\\' . $glue{0} : '';
641 foreach ($pieces as $str) {
642 if (ereg('[' . $_glue . '"' . "\n\r" . ']', $str))
643 $str = '"' . str_replace('"', '""', $str) . '"';
646 return join($glue, $arr);
651 // is_a -- Returns TRUE if the object is of this class or has this class as one of its parents
653 if (! function_exists('is_a')) {
655 function is_a($class, $match)
657 if (empty($class)) return FALSE;
659 $class = is_object($class) ? get_class($class) : $class;
660 if (strtolower($class) == strtolower($match)) {
663 return is_a(get_parent_class($class), $match); // Recurse
668 // array_fill -- Fill an array with values
670 if (! function_exists('array_fill')) {
672 function array_fill($start_index, $num, $value)
675 while ($num-- > 0) $ret[$start_index++] = $value;
680 // md5_file -- Calculates the md5 hash of a given filename
682 if (! function_exists('md5_file')) {
684 function md5_file($filename)
686 if (! file_exists($filename)) return FALSE;
688 $fd = fopen($filename, 'rb');
689 if ($fd === FALSE ) return FALSE;
690 $data = fread($fd, filesize($filename));
696 // sha1 -- Compute SHA-1 hash
697 // (PHP 4 >= 4.3.0, PHP5)
698 if (! function_exists('sha1')) {
699 if (extension_loaded('mhash')) {
700 function sha1($str, $raw_output = FALSE)
703 // PHP 5.0.0 or lator only :)
704 return mhash(MHASH_SHA1, $str);
706 return bin2hex(mhash(MHASH_SHA1, $str));