2 /////////////////////////////////////////////////
3 // PukiWiki - Yet another WikiWikiWeb clone.
5 // $Id: func.php,v 1.18 2004/12/11 12:03:06 henoheno Exp $
8 // ʸ»úÎó¤¬InterWikiName¤«¤É¤¦¤«
9 function is_interwiki($str)
11 global $InterWikiName;
13 return preg_match("/^$InterWikiName$/", $str);
16 // ʸ»úÎ󤬥ڡ¼¥¸Ì¾¤«¤É¤¦¤«
17 function is_pagename($str)
21 $is_pagename = (! is_interwiki($str) &&
22 preg_match("/^(?!\/)$BracketName$(?<!\/$)/", $str) &&
23 ! preg_match('/(^|\/)\.{1,2}(\/|$)/', $str));
26 if (defined('SOURCE_ENCODING')) {
27 switch(SOURCE_ENCODING){
29 $pattern = '/^(?:[\x00-\x7F]|(?:[\xC0-\xDF][\x80-\xBF])|(?:[\xE0-\xEF][\x80-\xBF][\x80-\xBF]))+$/';
32 $pattern = '/^(?:[\x00-\x7F]|(?:[\x8E\xA1-\xFE][\xA1-\xFE])|(?:\x8F[\xA1-\xFE][\xA1-\xFE]))+$/';
36 if($pattern !== '') $is_pagename = ($is_pagename && preg_match($pattern, $str));
41 // ʸ»úÎó¤¬URL¤«¤É¤¦¤«
42 function is_url($str, $only_http = FALSE)
44 $scheme = $only_http ? 'https?' : 'https?|ftp|news';
45 return preg_match('/^(' . $scheme . ')(:\/\/[-_.!~*\'()a-zA-Z0-9;\/?:\@&=+\$,%#]*)$/', $str);
49 function is_page($page, $reload = FALSE)
51 if ($reload) clearstatcache();
52 return file_exists(get_filename($page));
56 function is_editable($page)
59 static $is_editable = array();
61 if (! isset($is_editable[$page])) {
62 $is_editable[$page] = (
65 ! in_array($page, $cantedit)
69 return $is_editable[$page];
72 // ¥Ú¡¼¥¸¤¬Åà·ë¤µ¤ì¤Æ¤¤¤ë¤«
73 function is_freeze($page)
75 global $function_freeze;
76 static $is_freeze = array();
78 if (isset($is_freeze[$page])) return $is_freeze[$page];
79 if (! $function_freeze || ! is_page($page)) return FALSE;
81 list($lines) = get_source($page);
82 $is_freeze[$page] = (rtrim($lines) == '#freeze');
84 return $is_freeze[$page];
88 function auto_template($page)
90 global $auto_template_func, $auto_template_rules;
92 if (! $auto_template_func) return '';
96 foreach ($auto_template_rules as $rule => $template) {
98 if (! preg_match("/$rule/", $page, $matches)) continue;
100 $template_page = preg_replace("/$rule/", $template, $page);
101 if (! is_page($template_page)) continue;
103 $body = join('', get_source($template_page));
105 // ¸«½Ð¤·¤Î¸ÇÍIDÉô¤òºï½ü
106 $body = preg_replace('/^(\*{1,3}.*)\[#[A-Za-z][\w-]+\](.*)$/m', '$1$2', $body);
109 $body = preg_replace('/^#freeze\s*$/m', '', $body);
111 $count = count($matches);
112 for ($i = 0; $i < $count; $i++)
113 $body = str_replace("\$$i", $matches[$i], $body);
121 function get_search_words($words, $special = FALSE)
124 // Perl¥á¥â - Àµ¤·¤¯¥Ñ¥¿¡¼¥ó¥Þ¥Ã¥Á¤µ¤»¤ë
125 // http://www.din.or.jp/~ohzaki/perl.htm#JP_Match
126 $eucpre = $eucpost = '';
127 if (SOURCE_ENCODING == 'EUC-JP') {
128 $eucpre = '(?<!\x8F)';
129 // # JIS X 0208 ¤¬ 0ʸ»ú°Ê¾å³¤¤¤Æ # ASCII, SS2, SS3 ¤Þ¤¿¤Ï½ªÃ¼
130 $eucpost = '(?=(?:[\xA1-\xFE][\xA1-\xFE])*(?:[\x00-\x7F\x8E\x8F]|\z))';
132 $quote_func = create_function('$str', 'return preg_quote($str, "/");');
134 // LANG=='ja'¤Ç¡¢mb_convert_kana¤¬»È¤¨¤ë¾ì¹ç¤Ïmb_convert_kana¤ò»ÈÍÑ
135 $convert_kana = create_function('$str, $option',
136 (LANG == 'ja' && function_exists('mb_convert_kana')) ?
137 'return mb_convert_kana($str, $option);' : 'return $str;'
140 foreach ($words as $word) {
141 // ±Ñ¿ô»ú¤ÏȾ³Ñ,¥«¥¿¥«¥Ê¤ÏÁ´³Ñ,¤Ò¤é¤¬¤Ê¤Ï¥«¥¿¥«¥Ê¤Ë
142 $word_zk = $convert_kana($word, 'aKCV');
144 for ($pos = 0; $pos < mb_strlen($word_zk); $pos++) {
145 $char = mb_substr($word_zk, $pos, 1);
146 // $special : htmlspecialchars()¤òÄ̤¹¤«
147 $arr = array($quote_func($special ? htmlspecialchars($char) : $char));
148 if (strlen($char) == 1) {
150 foreach (array(strtoupper($char), strtolower($char)) as $_char) {
152 $arr[] = $quote_func($_char);
154 $arr[] = sprintf('&#(?:%d|x%x);', $ord, $ord); // ¼ÂÂλ²¾È
155 $arr[] = $quote_func($convert_kana($_char, 'A')); // Á´³Ñ
159 $arr[] = $quote_func($convert_kana($char, 'c')); // ¤Ò¤é¤¬¤Ê
160 $arr[] = $quote_func($convert_kana($char, 'k')); // Ⱦ³Ñ¥«¥¿¥«¥Ê
162 $chars[] = '(?:' . join('|', array_unique($arr)) . ')';
164 $retval[$word] = $eucpre.join('', $chars) . $eucpost;
170 function do_search($word, $type = 'AND', $non_format = FALSE)
172 global $script, $whatsnew, $non_list, $search_non_list;
173 global $_msg_andresult, $_msg_orresult, $_msg_notfoundresult;
178 $b_type = ($type == 'AND'); // AND:TRUE OR:FALSE
179 $keys = get_search_words(preg_split('/\s+/', $word, -1, PREG_SPLIT_NO_EMPTY));
181 $_pages = get_existpages();
184 foreach ($_pages as $page) {
185 if ($page == $whatsnew || (! $search_non_list && preg_match("/$non_list/", $page)))
188 // ¸¡º÷Âоݥڡ¼¥¸¤ÎÀ©¸Â¤ò¤«¤±¤ë¤«¤É¤¦¤« (¥Ú¡¼¥¸Ì¾¤ÏÀ©¸Â³°)
189 if ($search_auth && ! check_readable($page, false, false)) {
190 $source = get_source(); // ¸¡º÷Âоݥڡ¼¥¸ÆâÍƤò¶õ¤Ë¡£
192 $source = get_source($page);
195 array_unshift($source, $page); // ¥Ú¡¼¥¸Ì¾¤â¸¡º÷ÂоݤË
198 foreach ($keys as $key) {
199 $tmp = preg_grep("/$key/", $source);
200 $b_match = (! empty($tmp));
201 if ($b_match xor $b_type) break;
203 if ($b_match) $pages[$page] = get_filetime($page);
205 if ($non_format) return array_keys($pages);
207 $r_word = rawurlencode($word);
208 $s_word = htmlspecialchars($word);
210 return str_replace('$1', $s_word, $_msg_notfoundresult);
214 foreach ($pages as $page=>$time) {
215 $r_page = rawurlencode($page);
216 $s_page = htmlspecialchars($page);
217 $passage = get_passage($time);
218 $retval .= ' <li><a href="' . $script . '?cmd=read&page=' .
219 $r_page . '&word=' . $r_word . '">' . $s_page .
220 '</a>' . $passage . '</li>' . "\n";
222 $retval .= '</ul>' . "\n";
224 $retval .= str_replace('$1', $s_word, str_replace('$2', count($pages),
225 str_replace('$3', count($_pages), $b_type ? $_msg_andresult : $_msg_orresult)));
230 // ¥×¥í¥°¥é¥à¤Ø¤Î°ú¿ô¤Î¥Á¥§¥Ã¥¯
231 function arg_check($str)
234 return isset($vars['cmd']) && (strpos($vars['cmd'], $str) === 0);
237 // ¥Ú¡¼¥¸Ì¾¤Î¥¨¥ó¥³¡¼¥É
238 function encode($key)
240 return ($key == '') ? '' : strtoupper(join('', unpack('H*0', $key)));
243 // ¥Ú¡¼¥¸Ì¾¤Î¥Ç¥³¡¼¥É
244 function decode($key)
246 return ($key == '') ? '' : substr(pack('H*', '20202020' . $key), 4);
250 function strip_bracket($str)
253 if (preg_match('/^\[\[(.*)\]\]$/', $str, $match)) {
261 function page_list($pages, $cmd = 'read', $withfilename = FALSE)
263 global $script, $list_index;
264 global $_msg_symbol, $_msg_other;
265 global $pagereading_enable;
267 // ¥½¡¼¥È¥¡¼¤ò·èÄꤹ¤ë¡£ ' ' < '[a-zA-Z]' < 'zz'¤È¤¤¤¦Á°Äó¡£
273 if($pagereading_enable) {
274 mb_regex_encoding(SOURCE_ENCODING);
275 $readings = get_readings($pages);
278 $list = $matches = array();
279 foreach($pages as $file=>$page) {
280 $r_page = rawurlencode($page);
281 $s_page = htmlspecialchars($page, ENT_QUOTES);
282 $passage = get_pg_passage($page);
284 $str = ' <li><a href="' .
285 $script . '?cmd=' . $cmd . '&page=' . $r_page .
286 '">' . $s_page . '</a>' . $passage;
289 $s_file = htmlspecialchars($file);
290 $str .= "\n" . ' <ul><li>' . $s_file . '</li></ul>' .
295 // WARNING: Japanese code hard-wired
296 if($pagereading_enable) {
297 if(mb_ereg('^([A-Za-z])', mb_convert_kana($page, 'a'), $matches)) {
299 } elseif(mb_ereg('^([¥¡-¥ö])', $readings[$page], $matches)) { // here
301 } elseif (mb_ereg('^[ -~]|[^¤¡-¤ó°¡-ô¦]', $page)) { // and here
307 $head = (preg_match('/^([A-Za-z])/', $page, $matches)) ? $matches[1] :
308 (preg_match('/^([ -~])/', $page, $matches) ? $symbol : $other);
311 $list[$head][$page] = $str;
316 $arr_index = array();
317 $retval .= '<ul>' . "\n";
318 foreach ($list as $head=>$pages) {
319 if ($head === $symbol) {
320 $head = $_msg_symbol;
321 } else if ($head === $other) {
327 $arr_index[] = '<a id="top_' . $cnt .
328 '" href="#head_' . $cnt . '"><strong>' .
329 $head . '</strong></a>';
330 $retval .= ' <li><a id="head_' . $cnt . '" href="#top_' . $cnt .
331 '"><strong>' . $head . '</strong></a>' . "\n" .
335 $retval .= join("\n", $pages);
337 $retval .= "\n </ul>\n </li>\n";
339 $retval .= '</ul>' . "\n";
340 if ($list_index && $cnt > 0) {
342 while (! empty($arr_index))
343 $top[] = join(' | ' . "\n", array_splice($arr_index, 0, 16)) . "\n";
345 $retval = '<div id="top" style="text-align:center">' . "\n" .
346 join('<br />', $top) . '</div>' . "\n" . $retval;
351 // Show text formatting rules
356 if (! is_page($rule_page)) {
357 return '<p>Sorry, page \'' . htmlspecialchars($rule_page) .
358 '\' unavailable.</p>';
360 return convert_html(get_source($rule_page));
364 // Show (critical) error message
365 function die_message($msg)
367 $title = $page = 'Runtime error';
370 <h3>Runtime error</h3>
371 <strong>Error message : $msg</strong>
374 if(defined('SKIN_FILE') && file_exists(SKIN_FILE) && is_readable(SKIN_FILE)) {
375 catbody($title, $page, $body);
378 header('Content-Type: text/html; charset=euc-jp');
380 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
383 <title>$title</title>
384 <meta http-equiv="content-type" content="text/html; charset=euc-jp">
395 // ¸½ºß»þ¹ï¤ò¥Þ¥¤¥¯¥íÉäǼèÆÀ
396 function getmicrotime()
398 list($usec, $sec) = explode(' ', microtime());
399 return ((float)$sec + (float)$usec);
403 function get_date($format, $timestamp = NULL)
405 $format = preg_replace('/(?<!\\\)T/',
406 preg_replace('/(.)/', '\\\$1', ZONE), $format);
408 $time = ZONETIME + (($timestamp !== NULL) ? $timestamp : UTIME);
410 return date($format, $time);
414 function format_date($val, $paren = FALSE)
416 global $date_format, $time_format, $weeklabels;
420 $date = date($date_format . ' ' . $time_format, $val) .
421 ' ' . '(' . $weeklabels[date('w', $val)] . ')';
423 return $paren ? '(' . $date . ')' : $date;
426 // ·Ð²á»þ¹ïʸ»úÎó¤òºî¤ë
427 function get_passage($time, $paren = TRUE)
429 static $units = array('m'=>60, 'h'=>24, 'd'=>1);
431 $time = max(0, (UTIME - $time) / 60); // minutes
433 foreach ($units as $unit=>$card) {
434 if ($time < $card) break;
437 $time = floor($time) . $unit;
439 return $paren ? '(' . $time . ')' : $time;
442 // Hide <input type="(submit|button|image)"...>
443 function drop_submit($str)
445 return preg_replace('/<input([^>]+)type="(submit|button|image)"/i',
446 '<input$1type="hidden"', $str);
449 // AutoLink¤Î¥Ñ¥¿¡¼¥ó¤òÀ¸À®¤¹¤ë
451 function get_autolink_pattern(& $pages)
453 global $WikiName, $autolink, $nowikiname;
455 $config = &new Config('AutoLink');
457 $ignorepages = $config->get('IgnoreList');
458 $forceignorepages = $config->get('ForceIgnoreList');
460 $auto_pages = array_merge($ignorepages, $forceignorepages);
462 foreach ($pages as $page) {
463 if (preg_match("/^$WikiName$/", $page) ?
464 $nowikiname : strlen($page) >= $autolink)
465 $auto_pages[] = $page;
468 if (empty($auto_pages))
469 return $nowikiname ? '(?!)' : $WikiName;
471 $auto_pages = array_unique($auto_pages);
472 sort($auto_pages, SORT_STRING);
474 $auto_pages_a = array_values(preg_grep('/^[A-Z]+$/i', $auto_pages));
475 $auto_pages = array_values(array_diff($auto_pages, $auto_pages_a));
477 $result = get_autolink_pattern_sub($auto_pages, 0, count($auto_pages), 0);
478 $result_a = get_autolink_pattern_sub($auto_pages_a, 0, count($auto_pages_a), 0);
480 return array($result, $result_a, $forceignorepages);
483 function get_autolink_pattern_sub(& $pages, $start, $end, $pos)
485 if ($end == 0) return '(?!)';
488 $count = $i = $j = 0;
489 $x = (mb_strlen($pages[$start]) <= $pos);
492 for ($i = $start; $i < $end; $i = $j)
494 $char = mb_substr($pages[$i], $pos, 1);
495 for ($j = $i; $j < $end; $j++) {
496 if (mb_substr($pages[$j], $pos, 1) != $char) break;
498 if ($i != $start) $result .= '|';
499 if ($i >= ($j - 1)) {
500 $result .= str_replace(' ', '\\ ', preg_quote(mb_substr($pages[$i], $pos), '/'));
502 $result .= str_replace(' ', '\\ ', preg_quote($char, '/')) .
503 get_autolink_pattern_sub($pages, $i, $j, $pos + 1);
507 if ($x || $count > 1) $result = '(?:' . $result . ')';
508 if ($x) $result .= '?';
513 // pukiwiki.php¥¹¥¯¥ê¥×¥È¤Îabsolute-uri¤òÀ¸À®
514 function get_script_uri($init_uri = '')
516 global $script_directory_index;
519 if ($init_uri == '') {
521 if (isset($script)) return $script;
524 $msg = 'get_script_uri() failed: Please set $script at INI_FILE manually';
526 $script = (SERVER_PORT == 443 ? 'https://' : 'http://'); // scheme
527 $script .= SERVER_NAME; // host
528 $script .= (SERVER_PORT == 80 ? '' : ':' . SERVER_PORT); // port
530 // SCRIPT_NAME ¤¬'/'¤Ç»Ï¤Þ¤Ã¤Æ¤¤¤Ê¤¤¾ì¹ç(cgi¤Ê¤É) REQUEST_URI¤ò»È¤Ã¤Æ¤ß¤ë
532 if ($path{0} != '/') {
533 if (! isset($_SERVER['REQUEST_URI']) || $_SERVER['REQUEST_URI']{0} != '/')
536 // REQUEST_URI¤ò¥Ñ¡¼¥¹¤·¡¢pathÉôʬ¤À¤±¤ò¼è¤ê½Ð¤¹
537 $parse_url = parse_url($script . $_SERVER['REQUEST_URI']);
538 if (! isset($parse_url['path']) || $parse_url['path']{0} != '/')
541 $path = $parse_url['path'];
545 if (! is_url($script, TRUE) && php_sapi_name() == 'cgi')
551 if (isset($script)) die_message('$script: Already init');
552 if (! is_url($init_uri, TRUE)) die_message('$script: Invalid URI');
556 // Cut filename or not
557 if (isset($script_directory_index)) {
558 if (! file_exists($script_directory_index))
559 die_message('Directory index file not found: ' .
560 htmlspecialchars($script_directory_index));
562 if (preg_match('#^(.+/)' . preg_quote($script_directory_index, '#') . '$#',
563 $script, $matches)) $script = $matches[1];
570 ÊÑ¿ôÆâ¤Înull(\0)¥Ð¥¤¥È¤òºï½ü¤¹¤ë
571 PHP¤Ïfopen("hoge.php\0.txt")¤Ç"hoge.php"¤ò³«¤¤¤Æ¤·¤Þ¤¦¤Ê¤É¤ÎÌäÂꤢ¤ê
573 http://ns1.php.gr.jp/pipermail/php-users/2003-January/012742.html
574 [PHP-users 12736] null byte attack
576 2003-05-16: magic quotes gpc¤ÎÉü¸µ½èÍý¤òÅý¹ç
577 2003-05-21: Ï¢ÁÛÇÛÎó¤Î¥¡¼¤Ïbinary safe
579 function input_filter($param)
581 static $magic_quotes_gpc = NULL;
582 if ($magic_quotes_gpc === NULL)
583 $magic_quotes_gpc = get_magic_quotes_gpc();
585 if (is_array($param)) {
586 return array_map('input_filter', $param);
588 $result = str_replace("\0", '', $param);
589 if ($magic_quotes_gpc) $result = stripslashes($result);
594 // Compat for 3rd party plugins. Remove this later
595 function sanitize($param) {
596 return input_filter($param);
599 // CSV·Á¼°¤Îʸ»úÎó¤òÇÛÎó¤Ë
600 function csv_explode($separator, $string)
602 $retval = $matches = array();
604 $_separator = preg_quote($separator, '/');
605 if (! preg_match_all('/("[^"]*(?:""[^"]*)*"|[^' . $_separator . ']*)' .
606 $_separator . '/', $string . $separator, $matches))
609 foreach ($matches[1] as $str) {
611 if ($len > 1 && $str{0} == '"' && $str{$len - 1} == '"')
612 $str = str_replace('""', '"', substr($str, 1, -1));
618 // ÇÛÎó¤òCSV·Á¼°¤Îʸ»úÎó¤Ë
619 function csv_implode($glue, $pieces)
621 $_glue = ($glue != '') ? '\\' . $glue{0} : '';
623 foreach ($pieces as $str) {
624 if (ereg("[$_glue\"\n\r]", $str))
625 $str = '"' . str_replace('"', '""', $str) . '"';
628 return join($glue, $arr);
631 function pkwk_login($pass = '')
635 if ($pass != '' && md5($pass) == $adminpass) {
638 sleep(2); // Blocking brute force attack
646 // is_a -- Returns TRUE if the object is of this class or has this class as one of its parents
648 if (! function_exists('is_a'))
650 function is_a($class, $match)
652 if (empty($class)) return FALSE;
654 $class = is_object($class) ? get_class($class) : $class;
655 if (strtolower($class) == strtolower($match)) {
658 return is_a(get_parent_class($class), $match); // Recurse
663 // array_fill -- Fill an array with values
665 if (! function_exists('array_fill'))
667 function array_fill($start_index, $num, $value)
670 while ($num-- > 0) $ret[$start_index++] = $value;
675 // md5_file -- Calculates the md5 hash of a given filename
677 if (! function_exists('md5_file'))
679 function md5_file($filename)
681 if (! file_exists($filename)) return FALSE;
683 $fd = fopen($filename, 'rb');
684 if ($fd === FALSE ) return FALSE;
685 $data = fread($fd, filesize($filename));