2 // PukiWiki - Yet another WikiWikiWeb clone.
3 // $Id: func.php,v 1.27 2005/01/15 01:56:05 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, 8);
85 $is_freeze[$page] = ($buffer != FALSE && rtrim($buffer) == '#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);
125 function get_search_words($words, $special = FALSE)
129 // Perl¥á¥â - Àµ¤·¤¯¥Ñ¥¿¡¼¥ó¥Þ¥Ã¥Á¤µ¤»¤ë
130 // http://www.din.or.jp/~ohzaki/perl.htm#JP_Match
132 $eucpre = $eucpost = '';
133 if (SOURCE_ENCODING == 'EUC-JP') {
134 $eucpre = '(?<!\x8F)';
135 // # JIS X 0208 ¤¬ 0ʸ»ú°Ê¾å³¤¤¤Æ # ASCII, SS2, SS3 ¤Þ¤¿¤Ï½ªÃ¼
136 $eucpost = '(?=(?:[\xA1-\xFE][\xA1-\xFE])*(?:[\x00-\x7F\x8E\x8F]|\z))';
138 $quote_func = create_function('$str', 'return preg_quote($str, \'/\');');
140 // LANG == 'ja'¤Ç¡¢mb_convert_kana¤¬»È¤¨¤ë¾ì¹ç¤Ïmb_convert_kana¤ò»ÈÍÑ
141 $convert_kana = create_function('$str, $option',
142 (LANG == 'ja' && function_exists('mb_convert_kana')) ?
143 'return mb_convert_kana($str, $option);' : 'return $str;');
145 foreach ($words as $word) {
146 // ±Ñ¿ô»ú¤ÏȾ³Ñ,¥«¥¿¥«¥Ê¤ÏÁ´³Ñ,¤Ò¤é¤¬¤Ê¤Ï¥«¥¿¥«¥Ê¤Ë
147 $word_zk = $convert_kana($word, 'aKCV');
149 for ($pos = 0; $pos < mb_strlen($word_zk); $pos++) {
150 $char = mb_substr($word_zk, $pos, 1);
151 // $special : htmlspecialchars()¤òÄ̤¹¤«
152 $arr = array($quote_func($special ? htmlspecialchars($char) : $char));
153 if (strlen($char) == 1) {
155 foreach (array(strtoupper($char), strtolower($char)) as $_char) {
157 $arr[] = $quote_func($_char);
159 $arr[] = sprintf('&#(?:%d|x%x);', $ord, $ord); // ¼ÂÂλ²¾È
160 $arr[] = $quote_func($convert_kana($_char, 'A')); // Á´³Ñ
164 $arr[] = $quote_func($convert_kana($char, 'c')); // ¤Ò¤é¤¬¤Ê
165 $arr[] = $quote_func($convert_kana($char, 'k')); // Ⱦ³Ñ¥«¥¿¥«¥Ê
167 $chars[] = '(?:' . join('|', array_unique($arr)) . ')';
169 $retval[$word] = $eucpre.join('', $chars) . $eucpost;
174 // 'Search' main function
175 function do_search($word, $type = 'AND', $non_format = FALSE)
177 global $script, $whatsnew, $non_list, $search_non_list;
178 global $_msg_andresult, $_msg_orresult, $_msg_notfoundresult;
183 $b_type = ($type == 'AND'); // AND:TRUE OR:FALSE
184 $keys = get_search_words(preg_split('/\s+/', $word, -1, PREG_SPLIT_NO_EMPTY));
186 $_pages = get_existpages();
189 $non_list_pattern = '/' . $non_list . '/';
190 foreach ($_pages as $page) {
191 if ($page == $whatsnew || (! $search_non_list && preg_match($non_list_pattern, $page)))
194 // ¸¡º÷Âоݥڡ¼¥¸¤ÎÀ©¸Â¤ò¤«¤±¤ë¤«¤É¤¦¤« (¥Ú¡¼¥¸Ì¾¤ÏÀ©¸Â³°)
195 if ($search_auth && ! check_readable($page, false, false)) {
196 $source = get_source(); // ¸¡º÷Âоݥڡ¼¥¸ÆâÍƤò¶õ¤Ë¡£
198 $source = get_source($page);
201 array_unshift($source, $page); // ¥Ú¡¼¥¸Ì¾¤â¸¡º÷ÂоݤË
204 foreach ($keys as $key) {
205 $tmp = preg_grep('/' . $key . '/', $source);
206 $b_match = ! empty($tmp);
207 if ($b_match xor $b_type) break;
209 if ($b_match) $pages[$page] = get_filetime($page);
211 if ($non_format) return array_keys($pages);
213 $r_word = rawurlencode($word);
214 $s_word = htmlspecialchars($word);
216 return str_replace('$1', $s_word, $_msg_notfoundresult);
219 $retval = '<ul>' . "\n";
220 foreach ($pages as $page=>$time) {
221 $r_page = rawurlencode($page);
222 $s_page = htmlspecialchars($page);
223 $passage = get_passage($time);
224 $retval .= ' <li><a href="' . $script . '?cmd=read&page=' .
225 $r_page . '&word=' . $r_word . '">' . $s_page .
226 '</a>' . $passage . '</li>' . "\n";
228 $retval .= '</ul>' . "\n";
230 $retval .= str_replace('$1', $s_word, str_replace('$2', count($pages),
231 str_replace('$3', count($_pages), $b_type ? $_msg_andresult : $_msg_orresult)));
236 // ¥×¥í¥°¥é¥à¤Ø¤Î°ú¿ô¤Î¥Á¥§¥Ã¥¯
237 function arg_check($str)
240 return isset($vars['cmd']) && (strpos($vars['cmd'], $str) === 0);
243 // ¥Ú¡¼¥¸Ì¾¤Î¥¨¥ó¥³¡¼¥É
244 function encode($key)
246 return ($key == '') ? '' : strtoupper(bin2hex($key));
247 // Equal to strtoupper(join('', unpack('H*0', $key)));
248 // But PHP 4.3.10 says 'Warning: unpack(): Type H: outside of string in ...'
251 // ¥Ú¡¼¥¸Ì¾¤Î¥Ç¥³¡¼¥É
252 function decode($key)
254 // Warning: pack(): Type H: illegal hex digit ...
255 return preg_match('/^[0-9a-f]+$/i', $key) ? pack('H*', $key) : $key;
259 function strip_bracket($str)
262 if (preg_match('/^\[\[(.*)\]\]$/', $str, $match)) {
270 function page_list($pages, $cmd = 'read', $withfilename = FALSE)
272 global $script, $list_index;
273 global $_msg_symbol, $_msg_other;
274 global $pagereading_enable;
276 // ¥½¡¼¥È¥¡¼¤ò·èÄꤹ¤ë¡£ ' ' < '[a-zA-Z]' < 'zz'¤È¤¤¤¦Á°Äó¡£
282 if($pagereading_enable) {
283 mb_regex_encoding(SOURCE_ENCODING);
284 $readings = get_readings($pages);
287 $list = $matches = array();
288 foreach($pages as $file=>$page) {
289 $r_page = rawurlencode($page);
290 $s_page = htmlspecialchars($page, ENT_QUOTES);
291 $passage = get_pg_passage($page);
293 $str = ' <li><a href="' .
294 $script . '?cmd=' . $cmd . '&page=' . $r_page .
295 '">' . $s_page . '</a>' . $passage;
298 $s_file = htmlspecialchars($file);
299 $str .= "\n" . ' <ul><li>' . $s_file . '</li></ul>' .
304 // WARNING: Japanese code hard-wired
305 if($pagereading_enable) {
306 if(mb_ereg('^([A-Za-z])', mb_convert_kana($page, 'a'), $matches)) {
308 } elseif(mb_ereg('^([¥¡-¥ö])', $readings[$page], $matches)) { // here
310 } elseif (mb_ereg('^[ -~]|[^¤¡-¤ó°¡-ô¦]', $page)) { // and here
316 $head = (preg_match('/^([A-Za-z])/', $page, $matches)) ? $matches[1] :
317 (preg_match('/^([ -~])/', $page, $matches) ? $symbol : $other);
320 $list[$head][$page] = $str;
325 $arr_index = array();
326 $retval .= '<ul>' . "\n";
327 foreach ($list as $head=>$pages) {
328 if ($head === $symbol) {
329 $head = $_msg_symbol;
330 } else if ($head === $other) {
336 $arr_index[] = '<a id="top_' . $cnt .
337 '" href="#head_' . $cnt . '"><strong>' .
338 $head . '</strong></a>';
339 $retval .= ' <li><a id="head_' . $cnt . '" href="#top_' . $cnt .
340 '"><strong>' . $head . '</strong></a>' . "\n" .
344 $retval .= join("\n", $pages);
346 $retval .= "\n </ul>\n </li>\n";
348 $retval .= '</ul>' . "\n";
349 if ($list_index && $cnt > 0) {
351 while (! empty($arr_index))
352 $top[] = join(' | ' . "\n", array_splice($arr_index, 0, 16)) . "\n";
354 $retval = '<div id="top" style="text-align:center">' . "\n" .
355 join('<br />', $top) . '</div>' . "\n" . $retval;
360 // Show text formatting rules
365 if (! is_page($rule_page)) {
366 return '<p>Sorry, page \'' . htmlspecialchars($rule_page) .
367 '\' unavailable.</p>';
369 return convert_html(get_source($rule_page));
373 // Show (critical) error message
374 function die_message($msg)
376 $title = $page = 'Runtime error';
378 <h3>Runtime error</h3>
379 <strong>Error message : $msg</strong>
382 pkwk_common_headers();
383 if(defined('SKIN_FILE') && file_exists(SKIN_FILE) && is_readable(SKIN_FILE)) {
384 catbody($title, $page, $body);
386 header('Content-Type: text/html; charset=euc-jp');
388 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
391 <title>$title</title>
392 <meta http-equiv="content-type" content="text/html; charset=euc-jp">
403 // ¸½ºß»þ¹ï¤ò¥Þ¥¤¥¯¥íÉäǼèÆÀ
404 function getmicrotime()
406 list($usec, $sec) = explode(' ', microtime());
407 return ((float)$sec + (float)$usec);
411 function get_date($format, $timestamp = NULL)
413 $format = preg_replace('/(?<!\\\)T/',
414 preg_replace('/(.)/', '\\\$1', ZONE), $format);
416 $time = ZONETIME + (($timestamp !== NULL) ? $timestamp : UTIME);
418 return date($format, $time);
422 function format_date($val, $paren = FALSE)
424 global $date_format, $time_format, $weeklabels;
428 $date = date($date_format . ' ' . $time_format, $val) .
429 ' ' . '(' . $weeklabels[date('w', $val)] . ')';
431 return $paren ? '(' . $date . ')' : $date;
434 // ·Ð²á»þ¹ïʸ»úÎó¤òºî¤ë
435 function get_passage($time, $paren = TRUE)
437 static $units = array('m'=>60, 'h'=>24, 'd'=>1);
439 $time = max(0, (UTIME - $time) / 60); // minutes
441 foreach ($units as $unit=>$card) {
442 if ($time < $card) break;
445 $time = floor($time) . $unit;
447 return $paren ? '(' . $time . ')' : $time;
450 // Hide <input type="(submit|button|image)"...>
451 function drop_submit($str)
453 return preg_replace('/<input([^>]+)type="(submit|button|image)"/i',
454 '<input$1type="hidden"', $str);
457 // AutoLink¤Î¥Ñ¥¿¡¼¥ó¤òÀ¸À®¤¹¤ë
459 function get_autolink_pattern(& $pages)
461 global $WikiName, $autolink, $nowikiname;
463 $config = &new Config('AutoLink');
465 $ignorepages = $config->get('IgnoreList');
466 $forceignorepages = $config->get('ForceIgnoreList');
468 $auto_pages = array_merge($ignorepages, $forceignorepages);
470 foreach ($pages as $page) {
471 if (preg_match('/^' . $WikiName . '$/', $page) ?
472 $nowikiname : strlen($page) >= $autolink)
473 $auto_pages[] = $page;
476 if (empty($auto_pages))
477 return $nowikiname ? '(?!)' : $WikiName;
479 $auto_pages = array_unique($auto_pages);
480 sort($auto_pages, SORT_STRING);
482 $auto_pages_a = array_values(preg_grep('/^[A-Z]+$/i', $auto_pages));
483 $auto_pages = array_values(array_diff($auto_pages, $auto_pages_a));
485 $result = get_autolink_pattern_sub($auto_pages, 0, count($auto_pages), 0);
486 $result_a = get_autolink_pattern_sub($auto_pages_a, 0, count($auto_pages_a), 0);
488 return array($result, $result_a, $forceignorepages);
491 function get_autolink_pattern_sub(& $pages, $start, $end, $pos)
493 if ($end == 0) return '(?!)';
496 $count = $i = $j = 0;
497 $x = (mb_strlen($pages[$start]) <= $pos);
500 for ($i = $start; $i < $end; $i = $j)
502 $char = mb_substr($pages[$i], $pos, 1);
503 for ($j = $i; $j < $end; $j++) {
504 if (mb_substr($pages[$j], $pos, 1) != $char) break;
506 if ($i != $start) $result .= '|';
507 if ($i >= ($j - 1)) {
508 $result .= str_replace(' ', '\\ ', preg_quote(mb_substr($pages[$i], $pos), '/'));
510 $result .= str_replace(' ', '\\ ', preg_quote($char, '/')) .
511 get_autolink_pattern_sub($pages, $i, $j, $pos + 1);
515 if ($x || $count > 1) $result = '(?:' . $result . ')';
516 if ($x) $result .= '?';
521 // pukiwiki.php¥¹¥¯¥ê¥×¥È¤Îabsolute-uri¤òÀ¸À®
522 function get_script_uri($init_uri = '')
524 global $script_directory_index;
527 if ($init_uri == '') {
529 if (isset($script)) return $script;
532 $msg = 'get_script_uri() failed: Please set $script at INI_FILE manually';
534 $script = (SERVER_PORT == 443 ? 'https://' : 'http://'); // scheme
535 $script .= SERVER_NAME; // host
536 $script .= (SERVER_PORT == 80 ? '' : ':' . SERVER_PORT); // port
538 // SCRIPT_NAME ¤¬'/'¤Ç»Ï¤Þ¤Ã¤Æ¤¤¤Ê¤¤¾ì¹ç(cgi¤Ê¤É) REQUEST_URI¤ò»È¤Ã¤Æ¤ß¤ë
540 if ($path{0} != '/') {
541 if (! isset($_SERVER['REQUEST_URI']) || $_SERVER['REQUEST_URI']{0} != '/')
544 // REQUEST_URI¤ò¥Ñ¡¼¥¹¤·¡¢pathÉôʬ¤À¤±¤ò¼è¤ê½Ð¤¹
545 $parse_url = parse_url($script . $_SERVER['REQUEST_URI']);
546 if (! isset($parse_url['path']) || $parse_url['path']{0} != '/')
549 $path = $parse_url['path'];
553 if (! is_url($script, TRUE) && php_sapi_name() == 'cgi')
559 if (isset($script)) die_message('$script: Already init');
560 if (! is_url($init_uri, TRUE)) die_message('$script: Invalid URI');
564 // Cut filename or not
565 if (isset($script_directory_index)) {
566 if (! file_exists($script_directory_index))
567 die_message('Directory index file not found: ' .
568 htmlspecialchars($script_directory_index));
570 if (preg_match('#^(.+/)' . preg_quote($script_directory_index, '#') . '$#',
571 $script, $matches)) $script = $matches[1];
578 ÊÑ¿ôÆâ¤Înull(\0)¥Ð¥¤¥È¤òºï½ü¤¹¤ë
579 PHP¤Ïfopen("hoge.php\0.txt")¤Ç"hoge.php"¤ò³«¤¤¤Æ¤·¤Þ¤¦¤Ê¤É¤ÎÌäÂꤢ¤ê
581 http://ns1.php.gr.jp/pipermail/php-users/2003-January/012742.html
582 [PHP-users 12736] null byte attack
584 2003-05-16: magic quotes gpc¤ÎÉü¸µ½èÍý¤òÅý¹ç
585 2003-05-21: Ï¢ÁÛÇÛÎó¤Î¥¡¼¤Ïbinary safe
587 function input_filter($param)
589 static $magic_quotes_gpc = NULL;
590 if ($magic_quotes_gpc === NULL)
591 $magic_quotes_gpc = get_magic_quotes_gpc();
593 if (is_array($param)) {
594 return array_map('input_filter', $param);
596 $result = str_replace("\0", '', $param);
597 if ($magic_quotes_gpc) $result = stripslashes($result);
602 // Compat for 3rd party plugins. Remove this later
603 function sanitize($param) {
604 return input_filter($param);
607 // CSV·Á¼°¤Îʸ»úÎó¤òÇÛÎó¤Ë
608 function csv_explode($separator, $string)
610 $retval = $matches = array();
612 $_separator = preg_quote($separator, '/');
613 if (! preg_match_all('/("[^"]*(?:""[^"]*)*"|[^' . $_separator . ']*)' .
614 $_separator . '/', $string . $separator, $matches))
617 foreach ($matches[1] as $str) {
619 if ($len > 1 && $str{0} == '"' && $str{$len - 1} == '"')
620 $str = str_replace('""', '"', substr($str, 1, -1));
626 // Implode an array with CSV data format (escape double quotes)
627 function csv_implode($glue, $pieces)
629 $_glue = ($glue != '') ? '\\' . $glue{0} : '';
631 foreach ($pieces as $str) {
632 if (ereg('[' . $_glue . '"' . "\n\r" . ']', $str))
633 $str = '"' . str_replace('"', '""', $str) . '"';
636 return join($glue, $arr);
639 function pkwk_login($pass = '')
643 if ($pass != '' && md5($pass) == $adminpass) {
646 sleep(2); // Blocking brute force attack
654 // is_a -- Returns TRUE if the object is of this class or has this class as one of its parents
656 if (! function_exists('is_a')) {
658 function is_a($class, $match)
660 if (empty($class)) return FALSE;
662 $class = is_object($class) ? get_class($class) : $class;
663 if (strtolower($class) == strtolower($match)) {
666 return is_a(get_parent_class($class), $match); // Recurse
671 // array_fill -- Fill an array with values
673 if (! function_exists('array_fill')) {
675 function array_fill($start_index, $num, $value)
678 while ($num-- > 0) $ret[$start_index++] = $value;
683 // md5_file -- Calculates the md5 hash of a given filename
685 if (! function_exists('md5_file')) {
687 function md5_file($filename)
689 if (! file_exists($filename)) return FALSE;
691 $fd = fopen($filename, 'rb');
692 if ($fd === FALSE ) return FALSE;
693 $data = fread($fd, filesize($filename));