2 // PukiWiki - Yet another WikiWikiWeb clone.
3 // $Id: func.php,v 1.65 2006/04/16 11:20:52 henoheno Exp $
5 // 2002-2006 PukiWiki Developers Team
6 // 2001-2002 Originally written by yu-ji
7 // License: GPL v2 or (at your option) any later version
11 function is_interwiki($str)
13 global $InterWikiName;
14 return preg_match('/^' . $InterWikiName . '$/', $str);
17 function is_pagename($str)
21 $is_pagename = (! is_interwiki($str) &&
22 preg_match('/^(?!\/)' . $BracketName . '$(?<!\/$)/', $str) &&
23 ! preg_match('#(^|/)\.{1,2}(/|$)#', $str));
25 if (defined('SOURCE_ENCODING')) {
26 switch(SOURCE_ENCODING){
27 case 'UTF-8': $pattern =
28 '/^(?:[\x00-\x7F]|(?:[\xC0-\xDF][\x80-\xBF])|(?:[\xE0-\xEF][\x80-\xBF][\x80-\xBF]))+$/';
30 case 'EUC-JP': $pattern =
31 '/^(?:[\x00-\x7F]|(?:[\x8E\xA1-\xFE][\xA1-\xFE])|(?:\x8F[\xA1-\xFE][\xA1-\xFE]))+$/';
34 if (isset($pattern) && $pattern != '')
35 $is_pagename = ($is_pagename && preg_match($pattern, $str));
41 function is_url($str, $only_http = FALSE)
43 $scheme = $only_http ? 'https?' : 'https?|ftp|news';
44 return preg_match('/^(' . $scheme . ')(:\/\/[-_.!~*\'()a-zA-Z0-9;\/?:\@&=+\$,%#]*)$/', $str);
48 function is_page($page, $clearcache = FALSE)
50 if ($clearcache) clearstatcache();
51 return file_exists(get_filename($page));
54 function is_editable($page)
57 static $is_editable = array();
59 if (! isset($is_editable[$page])) {
60 $is_editable[$page] = (
63 ! in_array($page, $cantedit)
67 return $is_editable[$page];
70 function is_freeze($page, $clearcache = FALSE)
72 global $function_freeze;
73 static $is_freeze = array();
75 if ($clearcache === TRUE) $is_freeze = array();
76 if (isset($is_freeze[$page])) return $is_freeze[$page];
78 if (! $function_freeze || ! is_page($page)) {
79 $is_freeze[$page] = FALSE;
82 $fp = fopen(get_filename($page), 'rb') or
83 die('is_freeze(): fopen() failed: ' . htmlspecialchars($page));
84 flock($fp, LOCK_SH) or die('is_freeze(): flock() failed');
86 $buffer = fgets($fp, 9);
87 flock($fp, LOCK_UN) or die('is_freeze(): flock() failed');
88 fclose($fp) or die('is_freeze(): fclose() failed: ' . htmlspecialchars($page));
90 $is_freeze[$page] = ($buffer != FALSE && rtrim($buffer, "\r\n") == '#freeze');
91 return $is_freeze[$page];
96 // $non_list will be preg_quote($str, '/') later.
97 function check_non_list($page = '')
102 if (! isset($regex)) $regex = '/' . $non_list . '/';
104 return preg_match($regex, $page);
108 function auto_template($page)
110 global $auto_template_func, $auto_template_rules;
112 if (! $auto_template_func) return '';
116 foreach ($auto_template_rules as $rule => $template) {
117 $rule_pattrn = '/' . $rule . '/';
119 if (! preg_match($rule_pattrn, $page, $matches)) continue;
121 $template_page = preg_replace($rule_pattrn, $template, $page);
122 if (! is_page($template_page)) continue;
124 $body = join('', get_source($template_page));
126 // Remove fixed-heading anchors
127 $body = preg_replace('/^(\*{1,3}.*)\[#[A-Za-z][\w-]+\](.*)$/m', '$1$2', $body);
130 $body = preg_replace('/^#freeze\s*$/m', '', $body);
132 $count = count($matches);
133 for ($i = 0; $i < $count; $i++)
134 $body = str_replace('$' . $i, $matches[$i], $body);
141 // Expand all search-words to regexes and push them into an array
142 function get_search_words($words = array(), $do_escape = FALSE)
144 static $init, $mb_convert_kana, $pre, $post, $quote = '/';
146 if (! isset($init)) {
147 // function: mb_convert_kana() is for Japanese code only
148 if (LANG == 'ja' && function_exists('mb_convert_kana')) {
149 $mb_convert_kana = create_function('$str, $option',
150 'return mb_convert_kana($str, $option, SOURCE_ENCODING);');
152 $mb_convert_kana = create_function('$str, $option',
155 if (SOURCE_ENCODING == 'EUC-JP') {
156 // Perl memo - Correct pattern-matching with EUC-JP
157 // http://www.din.or.jp/~ohzaki/perl.htm#JP_Match (Japanese)
159 $post = '(?=(?:[\xA1-\xFE][\xA1-\xFE])*' . // JIS X 0208
160 '(?:[\x00-\x7F\x8E\x8F]|\z))'; // ASCII, SS2, SS3, or the last
167 if (! is_array($words)) $words = array($words);
169 // Generate regex for the words
171 foreach ($words as $word) {
173 if ($word == '') continue;
175 // Normalize: ASCII letters = to single-byte. Others = to Zenkaku and Katakana
176 $word_nm = $mb_convert_kana($word, 'aKCV');
177 $nmlen = mb_strlen($word_nm, SOURCE_ENCODING);
179 // Each chars may be served ...
181 for ($pos = 0; $pos < $nmlen; $pos++) {
182 $char = mb_substr($word_nm, $pos, 1, SOURCE_ENCODING);
184 // Just normalized one? (ASCII char or Zenkaku-Katakana?)
185 $or = array(preg_quote($do_escape ? htmlspecialchars($char) : $char, $quote));
186 if (strlen($char) == 1) {
187 // An ASCII (single-byte) character
188 foreach (array(strtoupper($char), strtolower($char)) as $_char) {
189 if ($char != '&') $or[] = preg_quote($_char, $quote); // As-is?
190 $ascii = ord($_char);
191 $or[] = sprintf('&#(?:%d|x%x);', $ascii, $ascii); // As an entity reference?
192 $or[] = preg_quote($mb_convert_kana($_char, 'A'), $quote); // As Zenkaku?
195 // NEVER COME HERE with mb_substr(string, start, length, 'ASCII')
196 // A multi-byte character
197 $or[] = preg_quote($mb_convert_kana($char, 'c'), $quote); // As Hiragana?
198 $or[] = preg_quote($mb_convert_kana($char, 'k'), $quote); // As Hankaku-Katakana?
200 $chars[] = '(?:' . join('|', array_unique($or)) . ')'; // Regex for the character
203 $regex[$word] = $pre . join('', $chars) . $post; // For the word
206 return $regex; // For all words
209 // 'Search' main function
210 function do_search($word, $type = 'AND', $non_format = FALSE, $base = '')
212 global $script, $whatsnew, $search_non_list;
213 global $_msg_andresult, $_msg_orresult, $_msg_notfoundresult;
218 $b_type = ($type == 'AND'); // AND:TRUE OR:FALSE
219 $keys = get_search_words(preg_split('/\s+/', $word, -1, PREG_SPLIT_NO_EMPTY));
220 foreach ($keys as $key=>$value) {
221 $keys[$key] = '/' . $value . '/S';
224 $_pages = get_existpages();
227 unset($_pages[encode($whatsnew) . '.txt']);
229 $_pages = preg_grep('/^' . preg_quote('/', $base) . '/S', $_pages);
233 foreach ($_pages as $page) {
234 if (! $search_non_list && check_non_list($page)) continue;
238 // Search for page name
240 foreach ($keys as $key) {
241 $b_match = preg_match($key, $page);
242 if ($b_type xor $b_match) break; // OR
245 $pages[$page] = TRUE;
250 // Search auth for page contents
251 if ($search_auth && ! check_readable($page, false, false))
254 // Search for page contents
255 foreach ($keys as $key) {
256 $b_match = preg_match($key, get_source($page, TRUE, TRUE));
257 if ($b_type xor $b_match) break; // OR
259 if ($b_match) $pages[$page] = TRUE;
261 if ($non_format) return array_keys($pages);
263 foreach ($pages as $page)
264 $pages[$page] = get_filetime($page);
266 $r_word = rawurlencode($word);
267 $s_word = htmlspecialchars($word);
269 return str_replace('$1', $s_word, $_msg_notfoundresult);
272 $retval = '<ul>' . "\n";
273 foreach ($pages as $page=>$time) {
274 $r_page = rawurlencode($page);
275 $s_page = htmlspecialchars($page);
276 $passage = get_passage($time);
277 $retval .= ' <li><a href="' . $script . '?cmd=read&page=' .
278 $r_page . '&word=' . $r_word . '">' . $s_page .
279 '</a>' . $passage . '</li>' . "\n";
281 $retval .= '</ul>' . "\n";
283 $retval .= str_replace('$1', $s_word, str_replace('$2', count($pages),
284 str_replace('$3', count($_pages), $b_type ? $_msg_andresult : $_msg_orresult)));
289 // Argument check for program
290 function arg_check($str)
293 return isset($vars['cmd']) && (strpos($vars['cmd'], $str) === 0);
297 function encode($key)
299 return ($key == '') ? '' : strtoupper(bin2hex($key));
300 // Equal to strtoupper(join('', unpack('H*0', $key)));
301 // But PHP 4.3.10 says 'Warning: unpack(): Type H: outside of string in ...'
305 function decode($key)
307 return hex2bin($key);
310 // Inversion of bin2hex()
311 function hex2bin($hex_string)
313 // preg_match : Avoid warning : pack(): Type H: illegal hex digit ...
314 // (string) : Always treat as string (not int etc). See BugTrack2/31
315 return preg_match('/^[0-9a-f]+$/i', $hex_string) ?
316 pack('H*', (string)$hex_string) : $hex_string;
319 // Remove [[ ]] (brackets)
320 function strip_bracket($str)
323 if (preg_match('/^\[\[(.*)\]\]$/', $str, $match)) {
330 // Create list of pages
331 function page_list($pages, $cmd = 'read', $withfilename = FALSE)
333 global $script, $list_index;
334 global $_msg_symbol, $_msg_other;
335 global $pagereading_enable;
337 // ¥½¡¼¥È¥¡¼¤ò·èÄꤹ¤ë¡£ ' ' < '[a-zA-Z]' < 'zz'¤È¤¤¤¦Á°Äó¡£
343 if($pagereading_enable) {
344 mb_regex_encoding(SOURCE_ENCODING);
345 $readings = get_readings($pages);
348 $list = $matches = array();
350 // Shrink URI for read
351 if ($cmd == 'read') {
352 $href = $script . '?';
354 $href = $script . '?cmd=' . $cmd . '&page=';
357 foreach($pages as $file=>$page) {
358 $r_page = rawurlencode($page);
359 $s_page = htmlspecialchars($page, ENT_QUOTES);
360 $passage = get_pg_passage($page);
362 $str = ' <li><a href="' . $href . $r_page . '">' .
363 $s_page . '</a>' . $passage;
366 $s_file = htmlspecialchars($file);
367 $str .= "\n" . ' <ul><li>' . $s_file . '</li></ul>' .
372 // WARNING: Japanese code hard-wired
373 if($pagereading_enable) {
374 if(mb_ereg('^([A-Za-z])', mb_convert_kana($page, 'a'), $matches)) {
376 } elseif (isset($readings[$page]) && mb_ereg('^([¥¡-¥ö])', $readings[$page], $matches)) { // here
378 } elseif (mb_ereg('^[ -~]|[^¤¡-¤ó°¡-ô¦]', $page)) { // and here
384 $head = (preg_match('/^([A-Za-z])/', $page, $matches)) ? $matches[1] :
385 (preg_match('/^([ -~])/', $page, $matches) ? $symbol : $other);
388 $list[$head][$page] = $str;
393 $arr_index = array();
394 $retval .= '<ul>' . "\n";
395 foreach ($list as $head=>$pages) {
396 if ($head === $symbol) {
397 $head = $_msg_symbol;
398 } else if ($head === $other) {
404 $arr_index[] = '<a id="top_' . $cnt .
405 '" href="#head_' . $cnt . '"><strong>' .
406 $head . '</strong></a>';
407 $retval .= ' <li><a id="head_' . $cnt . '" href="#top_' . $cnt .
408 '"><strong>' . $head . '</strong></a>' . "\n" .
412 $retval .= join("\n", $pages);
414 $retval .= "\n </ul>\n </li>\n";
416 $retval .= '</ul>' . "\n";
417 if ($list_index && $cnt > 0) {
419 while (! empty($arr_index))
420 $top[] = join(' | ' . "\n", array_splice($arr_index, 0, 16)) . "\n";
422 $retval = '<div id="top" style="text-align:center">' . "\n" .
423 join('<br />', $top) . '</div>' . "\n" . $retval;
428 // Show text formatting rules
433 if (! is_page($rule_page)) {
434 return '<p>Sorry, page \'' . htmlspecialchars($rule_page) .
435 '\' unavailable.</p>';
437 return convert_html(get_source($rule_page));
441 // Show (critical) error message
442 function die_message($msg)
444 $title = $page = 'Runtime error';
446 <h3>Runtime error</h3>
447 <strong>Error message : $msg</strong>
450 pkwk_common_headers();
451 if(defined('SKIN_FILE') && file_exists(SKIN_FILE) && is_readable(SKIN_FILE)) {
452 catbody($title, $page, $body);
454 header('Content-Type: text/html; charset=euc-jp');
456 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
459 <title>$title</title>
460 <meta http-equiv="content-type" content="text/html; charset=euc-jp">
471 // Have the time (as microtime)
472 function getmicrotime()
474 list($usec, $sec) = explode(' ', microtime());
475 return ((float)$sec + (float)$usec);
479 function get_date($format, $timestamp = NULL)
481 $format = preg_replace('/(?<!\\\)T/',
482 preg_replace('/(.)/', '\\\$1', ZONE), $format);
484 $time = ZONETIME + (($timestamp !== NULL) ? $timestamp : UTIME);
486 return date($format, $time);
489 // Format date string
490 function format_date($val, $paren = FALSE)
492 global $date_format, $time_format, $weeklabels;
496 $date = date($date_format, $val) .
497 ' (' . $weeklabels[date('w', $val)] . ') ' .
498 date($time_format, $val);
500 return $paren ? '(' . $date . ')' : $date;
503 // Get short string of the passage, 'N seconds/minutes/hours/days/years ago'
504 function get_passage($time, $paren = TRUE)
506 static $units = array('m'=>60, 'h'=>24, 'd'=>1);
508 $time = max(0, (UTIME - $time) / 60); // minutes
510 foreach ($units as $unit=>$card) {
511 if ($time < $card) break;
514 $time = floor($time) . $unit;
516 return $paren ? '(' . $time . ')' : $time;
519 // Hide <input type="(submit|button|image)"...>
520 function drop_submit($str)
522 return preg_replace('/<input([^>]+)type="(submit|button|image)"/i',
523 '<input$1type="hidden"', $str);
526 // Generate AutoLink patterns (thx to hirofummy)
527 function get_autolink_pattern(& $pages)
529 global $WikiName, $autolink, $nowikiname;
531 $config = &new Config('AutoLink');
533 $ignorepages = $config->get('IgnoreList');
534 $forceignorepages = $config->get('ForceIgnoreList');
536 $auto_pages = array_merge($ignorepages, $forceignorepages);
538 foreach ($pages as $page)
539 if (preg_match('/^' . $WikiName . '$/', $page) ?
540 $nowikiname : strlen($page) >= $autolink)
541 $auto_pages[] = $page;
543 if (empty($auto_pages)) {
544 $result = $result_a = $nowikiname ? '(?!)' : $WikiName;
546 $auto_pages = array_unique($auto_pages);
547 sort($auto_pages, SORT_STRING);
549 $auto_pages_a = array_values(preg_grep('/^[A-Z]+$/i', $auto_pages));
550 $auto_pages = array_values(array_diff($auto_pages, $auto_pages_a));
552 $result = get_autolink_pattern_sub($auto_pages, 0, count($auto_pages), 0);
553 $result_a = get_autolink_pattern_sub($auto_pages_a, 0, count($auto_pages_a), 0);
555 return array($result, $result_a, $forceignorepages);
558 function get_autolink_pattern_sub(& $pages, $start, $end, $pos)
560 if ($end == 0) return '(?!)';
563 $count = $i = $j = 0;
564 $x = (mb_strlen($pages[$start]) <= $pos);
567 for ($i = $start; $i < $end; $i = $j) {
568 $char = mb_substr($pages[$i], $pos, 1);
569 for ($j = $i; $j < $end; $j++)
570 if (mb_substr($pages[$j], $pos, 1) != $char) break;
572 if ($i != $start) $result .= '|';
573 if ($i >= ($j - 1)) {
574 $result .= str_replace(' ', '\\ ', preg_quote(mb_substr($pages[$i], $pos), '/'));
576 $result .= str_replace(' ', '\\ ', preg_quote($char, '/')) .
577 get_autolink_pattern_sub($pages, $i, $j, $pos + 1);
581 if ($x || $count > 1) $result = '(?:' . $result . ')';
582 if ($x) $result .= '?';
587 // Get absolute-URI of this script
588 function get_script_uri($init_uri = '')
590 global $script_directory_index;
593 if ($init_uri == '') {
595 if (isset($script)) return $script;
598 $msg = 'get_script_uri() failed: Please set $script at INI_FILE manually';
600 $script = (SERVER_PORT == 443 ? 'https://' : 'http://'); // scheme
601 $script .= SERVER_NAME; // host
602 $script .= (SERVER_PORT == 80 ? '' : ':' . SERVER_PORT); // port
604 // SCRIPT_NAME ¤¬'/'¤Ç»Ï¤Þ¤Ã¤Æ¤¤¤Ê¤¤¾ì¹ç(cgi¤Ê¤É) REQUEST_URI¤ò»È¤Ã¤Æ¤ß¤ë
606 if ($path{0} != '/') {
607 if (! isset($_SERVER['REQUEST_URI']) || $_SERVER['REQUEST_URI']{0} != '/')
610 // REQUEST_URI¤ò¥Ñ¡¼¥¹¤·¡¢pathÉôʬ¤À¤±¤ò¼è¤ê½Ð¤¹
611 $parse_url = parse_url($script . $_SERVER['REQUEST_URI']);
612 if (! isset($parse_url['path']) || $parse_url['path']{0} != '/')
615 $path = $parse_url['path'];
619 if (! is_url($script, TRUE) && php_sapi_name() == 'cgi')
625 if (isset($script)) die_message('$script: Already init');
626 if (! is_url($init_uri, TRUE)) die_message('$script: Invalid URI');
630 // Cut filename or not
631 if (isset($script_directory_index)) {
632 if (! file_exists($script_directory_index))
633 die_message('Directory index file not found: ' .
634 htmlspecialchars($script_directory_index));
636 if (preg_match('#^(.+/)' . preg_quote($script_directory_index, '#') . '$#',
637 $script, $matches)) $script = $matches[1];
643 // Remove null(\0) bytes from variables
645 // NOTE: PHP had vulnerabilities that opens "hoge.php" via fopen("hoge.php\0.txt") etc.
646 // [PHP-users 12736] null byte attack
647 // http://ns1.php.gr.jp/pipermail/php-users/2003-January/012742.html
649 // 2003-05-16: magic quotes gpc¤ÎÉü¸µ½èÍý¤òÅý¹ç
650 // 2003-05-21: Ï¢ÁÛÇÛÎó¤Î¥¡¼¤Ïbinary safe
652 function input_filter($param)
654 static $magic_quotes_gpc = NULL;
655 if ($magic_quotes_gpc === NULL)
656 $magic_quotes_gpc = get_magic_quotes_gpc();
658 if (is_array($param)) {
659 return array_map('input_filter', $param);
661 $result = str_replace("\0", '', $param);
662 if ($magic_quotes_gpc) $result = stripslashes($result);
667 // Compat for 3rd party plugins. Remove this later
668 function sanitize($param) {
669 return input_filter($param);
672 // Explode Comma-Separated Values to an array
673 function csv_explode($separator, $string)
675 $retval = $matches = array();
677 $_separator = preg_quote($separator, '/');
678 if (! preg_match_all('/("[^"]*(?:""[^"]*)*"|[^' . $_separator . ']*)' .
679 $_separator . '/', $string . $separator, $matches))
682 foreach ($matches[1] as $str) {
684 if ($len > 1 && $str{0} == '"' && $str{$len - 1} == '"')
685 $str = str_replace('""', '"', substr($str, 1, -1));
691 // Implode an array with CSV data format (escape double quotes)
692 function csv_implode($glue, $pieces)
694 $_glue = ($glue != '') ? '\\' . $glue{0} : '';
696 foreach ($pieces as $str) {
697 if (ereg('[' . $_glue . '"' . "\n\r" . ']', $str))
698 $str = '"' . str_replace('"', '""', $str) . '"';
701 return join($glue, $arr);
706 // is_a -- Returns TRUE if the object is of this class or has this class as one of its parents
708 if (! function_exists('is_a')) {
710 function is_a($class, $match)
712 if (empty($class)) return FALSE;
714 $class = is_object($class) ? get_class($class) : $class;
715 if (strtolower($class) == strtolower($match)) {
718 return is_a(get_parent_class($class), $match); // Recurse
723 // array_fill -- Fill an array with values
725 if (! function_exists('array_fill')) {
727 function array_fill($start_index, $num, $value)
730 while ($num-- > 0) $ret[$start_index++] = $value;
735 // md5_file -- Calculates the md5 hash of a given filename
737 if (! function_exists('md5_file')) {
739 function md5_file($filename)
741 if (! file_exists($filename)) return FALSE;
743 $fd = fopen($filename, 'rb');
744 if ($fd === FALSE ) return FALSE;
745 $data = fread($fd, filesize($filename));
751 // sha1 -- Compute SHA-1 hash
752 // (PHP 4 >= 4.3.0, PHP5)
753 if (! function_exists('sha1')) {
754 if (extension_loaded('mhash')) {
757 return bin2hex(mhash(MHASH_SHA1, $str));
760 function sha1($str, $raw_output = FALSE)
762 die('Function sha1() not found and extension \'mhash\' not exists');