2 /////////////////////////////////////////////////
3 // PukiWiki - Yet another WikiWikiWeb clone.
5 // $Id: func.php,v 1.21 2004/12/30 07:30:55 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, $force = FALSE)
75 global $function_freeze;
76 static $is_freeze = array();
78 if ($force === TRUE) $is_freeze = array();
80 if (isset($is_freeze[$page])) return $is_freeze[$page];
81 if (! $function_freeze || ! is_page($page)) {
82 $is_freeze[$page] = FALSE;
86 list($lines) = get_source($page);
87 $is_freeze[$page] = (rtrim($lines) == '#freeze');
89 return $is_freeze[$page];
93 function auto_template($page)
95 global $auto_template_func, $auto_template_rules;
97 if (! $auto_template_func) return '';
101 foreach ($auto_template_rules as $rule => $template) {
103 if (! preg_match("/$rule/", $page, $matches)) continue;
105 $template_page = preg_replace("/$rule/", $template, $page);
106 if (! is_page($template_page)) continue;
108 $body = join('', get_source($template_page));
110 // ¸«½Ð¤·¤Î¸ÇÍIDÉô¤òºï½ü
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);
126 function get_search_words($words, $special = FALSE)
129 // Perl¥á¥â - Àµ¤·¤¯¥Ñ¥¿¡¼¥ó¥Þ¥Ã¥Á¤µ¤»¤ë
130 // http://www.din.or.jp/~ohzaki/perl.htm#JP_Match
131 $eucpre = $eucpost = '';
132 if (SOURCE_ENCODING == 'EUC-JP') {
133 $eucpre = '(?<!\x8F)';
134 // # JIS X 0208 ¤¬ 0ʸ»ú°Ê¾å³¤¤¤Æ # ASCII, SS2, SS3 ¤Þ¤¿¤Ï½ªÃ¼
135 $eucpost = '(?=(?:[\xA1-\xFE][\xA1-\xFE])*(?:[\x00-\x7F\x8E\x8F]|\z))';
137 $quote_func = create_function('$str', 'return preg_quote($str, "/");');
139 // LANG=='ja'¤Ç¡¢mb_convert_kana¤¬»È¤¨¤ë¾ì¹ç¤Ïmb_convert_kana¤ò»ÈÍÑ
140 $convert_kana = create_function('$str, $option',
141 (LANG == 'ja' && function_exists('mb_convert_kana')) ?
142 '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;
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 foreach ($_pages as $page) {
190 if ($page == $whatsnew || (! $search_non_list && preg_match("/$non_list/", $page)))
193 // ¸¡º÷Âоݥڡ¼¥¸¤ÎÀ©¸Â¤ò¤«¤±¤ë¤«¤É¤¦¤« (¥Ú¡¼¥¸Ì¾¤ÏÀ©¸Â³°)
194 if ($search_auth && ! check_readable($page, false, false)) {
195 $source = get_source(); // ¸¡º÷Âоݥڡ¼¥¸ÆâÍƤò¶õ¤Ë¡£
197 $source = get_source($page);
200 array_unshift($source, $page); // ¥Ú¡¼¥¸Ì¾¤â¸¡º÷ÂоݤË
203 foreach ($keys as $key) {
204 $tmp = preg_grep("/$key/", $source);
205 $b_match = (! empty($tmp));
206 if ($b_match xor $b_type) break;
208 if ($b_match) $pages[$page] = get_filetime($page);
210 if ($non_format) return array_keys($pages);
212 $r_word = rawurlencode($word);
213 $s_word = htmlspecialchars($word);
215 return str_replace('$1', $s_word, $_msg_notfoundresult);
219 foreach ($pages as $page=>$time) {
220 $r_page = rawurlencode($page);
221 $s_page = htmlspecialchars($page);
222 $passage = get_passage($time);
223 $retval .= ' <li><a href="' . $script . '?cmd=read&page=' .
224 $r_page . '&word=' . $r_word . '">' . $s_page .
225 '</a>' . $passage . '</li>' . "\n";
227 $retval .= '</ul>' . "\n";
229 $retval .= str_replace('$1', $s_word, str_replace('$2', count($pages),
230 str_replace('$3', count($_pages), $b_type ? $_msg_andresult : $_msg_orresult)));
235 // ¥×¥í¥°¥é¥à¤Ø¤Î°ú¿ô¤Î¥Á¥§¥Ã¥¯
236 function arg_check($str)
239 return isset($vars['cmd']) && (strpos($vars['cmd'], $str) === 0);
242 // ¥Ú¡¼¥¸Ì¾¤Î¥¨¥ó¥³¡¼¥É
243 function encode($key)
245 return ($key == '') ? '' : strtoupper(bin2hex($key));
246 // Equal to strtoupper(join('', unpack('H*0', $key)));
247 // But PHP 4.3.10 says 'Warning: unpack(): Type H: outside of string in ...'
250 // ¥Ú¡¼¥¸Ì¾¤Î¥Ç¥³¡¼¥É
251 function decode($key)
253 return ($key == '') ? '' : substr(pack('H*', '20202020' . $key), 4);
257 function strip_bracket($str)
260 if (preg_match('/^\[\[(.*)\]\]$/', $str, $match)) {
268 function page_list($pages, $cmd = 'read', $withfilename = FALSE)
270 global $script, $list_index;
271 global $_msg_symbol, $_msg_other;
272 global $pagereading_enable;
274 // ¥½¡¼¥È¥¡¼¤ò·èÄꤹ¤ë¡£ ' ' < '[a-zA-Z]' < 'zz'¤È¤¤¤¦Á°Äó¡£
280 if($pagereading_enable) {
281 mb_regex_encoding(SOURCE_ENCODING);
282 $readings = get_readings($pages);
285 $list = $matches = array();
286 foreach($pages as $file=>$page) {
287 $r_page = rawurlencode($page);
288 $s_page = htmlspecialchars($page, ENT_QUOTES);
289 $passage = get_pg_passage($page);
291 $str = ' <li><a href="' .
292 $script . '?cmd=' . $cmd . '&page=' . $r_page .
293 '">' . $s_page . '</a>' . $passage;
296 $s_file = htmlspecialchars($file);
297 $str .= "\n" . ' <ul><li>' . $s_file . '</li></ul>' .
302 // WARNING: Japanese code hard-wired
303 if($pagereading_enable) {
304 if(mb_ereg('^([A-Za-z])', mb_convert_kana($page, 'a'), $matches)) {
306 } elseif(mb_ereg('^([¥¡-¥ö])', $readings[$page], $matches)) { // here
308 } elseif (mb_ereg('^[ -~]|[^¤¡-¤ó°¡-ô¦]', $page)) { // and here
314 $head = (preg_match('/^([A-Za-z])/', $page, $matches)) ? $matches[1] :
315 (preg_match('/^([ -~])/', $page, $matches) ? $symbol : $other);
318 $list[$head][$page] = $str;
323 $arr_index = array();
324 $retval .= '<ul>' . "\n";
325 foreach ($list as $head=>$pages) {
326 if ($head === $symbol) {
327 $head = $_msg_symbol;
328 } else if ($head === $other) {
334 $arr_index[] = '<a id="top_' . $cnt .
335 '" href="#head_' . $cnt . '"><strong>' .
336 $head . '</strong></a>';
337 $retval .= ' <li><a id="head_' . $cnt . '" href="#top_' . $cnt .
338 '"><strong>' . $head . '</strong></a>' . "\n" .
342 $retval .= join("\n", $pages);
344 $retval .= "\n </ul>\n </li>\n";
346 $retval .= '</ul>' . "\n";
347 if ($list_index && $cnt > 0) {
349 while (! empty($arr_index))
350 $top[] = join(' | ' . "\n", array_splice($arr_index, 0, 16)) . "\n";
352 $retval = '<div id="top" style="text-align:center">' . "\n" .
353 join('<br />', $top) . '</div>' . "\n" . $retval;
358 // Show text formatting rules
363 if (! is_page($rule_page)) {
364 return '<p>Sorry, page \'' . htmlspecialchars($rule_page) .
365 '\' unavailable.</p>';
367 return convert_html(get_source($rule_page));
371 // Show (critical) error message
372 function die_message($msg)
374 $title = $page = 'Runtime error';
376 <h3>Runtime error</h3>
377 <strong>Error message : $msg</strong>
380 pkwk_common_headers();
381 if(defined('SKIN_FILE') && file_exists(SKIN_FILE) && is_readable(SKIN_FILE)) {
382 catbody($title, $page, $body);
384 header('Content-Type: text/html; charset=euc-jp');
386 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
389 <title>$title</title>
390 <meta http-equiv="content-type" content="text/html; charset=euc-jp">
401 // ¸½ºß»þ¹ï¤ò¥Þ¥¤¥¯¥íÉäǼèÆÀ
402 function getmicrotime()
404 list($usec, $sec) = explode(' ', microtime());
405 return ((float)$sec + (float)$usec);
409 function get_date($format, $timestamp = NULL)
411 $format = preg_replace('/(?<!\\\)T/',
412 preg_replace('/(.)/', '\\\$1', ZONE), $format);
414 $time = ZONETIME + (($timestamp !== NULL) ? $timestamp : UTIME);
416 return date($format, $time);
420 function format_date($val, $paren = FALSE)
422 global $date_format, $time_format, $weeklabels;
426 $date = date($date_format . ' ' . $time_format, $val) .
427 ' ' . '(' . $weeklabels[date('w', $val)] . ')';
429 return $paren ? '(' . $date . ')' : $date;
432 // ·Ð²á»þ¹ïʸ»úÎó¤òºî¤ë
433 function get_passage($time, $paren = TRUE)
435 static $units = array('m'=>60, 'h'=>24, 'd'=>1);
437 $time = max(0, (UTIME - $time) / 60); // minutes
439 foreach ($units as $unit=>$card) {
440 if ($time < $card) break;
443 $time = floor($time) . $unit;
445 return $paren ? '(' . $time . ')' : $time;
448 // Hide <input type="(submit|button|image)"...>
449 function drop_submit($str)
451 return preg_replace('/<input([^>]+)type="(submit|button|image)"/i',
452 '<input$1type="hidden"', $str);
455 // AutoLink¤Î¥Ñ¥¿¡¼¥ó¤òÀ¸À®¤¹¤ë
457 function get_autolink_pattern(& $pages)
459 global $WikiName, $autolink, $nowikiname;
461 $config = &new Config('AutoLink');
463 $ignorepages = $config->get('IgnoreList');
464 $forceignorepages = $config->get('ForceIgnoreList');
466 $auto_pages = array_merge($ignorepages, $forceignorepages);
468 foreach ($pages as $page) {
469 if (preg_match("/^$WikiName$/", $page) ?
470 $nowikiname : strlen($page) >= $autolink)
471 $auto_pages[] = $page;
474 if (empty($auto_pages))
475 return $nowikiname ? '(?!)' : $WikiName;
477 $auto_pages = array_unique($auto_pages);
478 sort($auto_pages, SORT_STRING);
480 $auto_pages_a = array_values(preg_grep('/^[A-Z]+$/i', $auto_pages));
481 $auto_pages = array_values(array_diff($auto_pages, $auto_pages_a));
483 $result = get_autolink_pattern_sub($auto_pages, 0, count($auto_pages), 0);
484 $result_a = get_autolink_pattern_sub($auto_pages_a, 0, count($auto_pages_a), 0);
486 return array($result, $result_a, $forceignorepages);
489 function get_autolink_pattern_sub(& $pages, $start, $end, $pos)
491 if ($end == 0) return '(?!)';
494 $count = $i = $j = 0;
495 $x = (mb_strlen($pages[$start]) <= $pos);
498 for ($i = $start; $i < $end; $i = $j)
500 $char = mb_substr($pages[$i], $pos, 1);
501 for ($j = $i; $j < $end; $j++) {
502 if (mb_substr($pages[$j], $pos, 1) != $char) break;
504 if ($i != $start) $result .= '|';
505 if ($i >= ($j - 1)) {
506 $result .= str_replace(' ', '\\ ', preg_quote(mb_substr($pages[$i], $pos), '/'));
508 $result .= str_replace(' ', '\\ ', preg_quote($char, '/')) .
509 get_autolink_pattern_sub($pages, $i, $j, $pos + 1);
513 if ($x || $count > 1) $result = '(?:' . $result . ')';
514 if ($x) $result .= '?';
519 // pukiwiki.php¥¹¥¯¥ê¥×¥È¤Îabsolute-uri¤òÀ¸À®
520 function get_script_uri($init_uri = '')
522 global $script_directory_index;
525 if ($init_uri == '') {
527 if (isset($script)) return $script;
530 $msg = 'get_script_uri() failed: Please set $script at INI_FILE manually';
532 $script = (SERVER_PORT == 443 ? 'https://' : 'http://'); // scheme
533 $script .= SERVER_NAME; // host
534 $script .= (SERVER_PORT == 80 ? '' : ':' . SERVER_PORT); // port
536 // SCRIPT_NAME ¤¬'/'¤Ç»Ï¤Þ¤Ã¤Æ¤¤¤Ê¤¤¾ì¹ç(cgi¤Ê¤É) REQUEST_URI¤ò»È¤Ã¤Æ¤ß¤ë
538 if ($path{0} != '/') {
539 if (! isset($_SERVER['REQUEST_URI']) || $_SERVER['REQUEST_URI']{0} != '/')
542 // REQUEST_URI¤ò¥Ñ¡¼¥¹¤·¡¢pathÉôʬ¤À¤±¤ò¼è¤ê½Ð¤¹
543 $parse_url = parse_url($script . $_SERVER['REQUEST_URI']);
544 if (! isset($parse_url['path']) || $parse_url['path']{0} != '/')
547 $path = $parse_url['path'];
551 if (! is_url($script, TRUE) && php_sapi_name() == 'cgi')
557 if (isset($script)) die_message('$script: Already init');
558 if (! is_url($init_uri, TRUE)) die_message('$script: Invalid URI');
562 // Cut filename or not
563 if (isset($script_directory_index)) {
564 if (! file_exists($script_directory_index))
565 die_message('Directory index file not found: ' .
566 htmlspecialchars($script_directory_index));
568 if (preg_match('#^(.+/)' . preg_quote($script_directory_index, '#') . '$#',
569 $script, $matches)) $script = $matches[1];
576 ÊÑ¿ôÆâ¤Înull(\0)¥Ð¥¤¥È¤òºï½ü¤¹¤ë
577 PHP¤Ïfopen("hoge.php\0.txt")¤Ç"hoge.php"¤ò³«¤¤¤Æ¤·¤Þ¤¦¤Ê¤É¤ÎÌäÂꤢ¤ê
579 http://ns1.php.gr.jp/pipermail/php-users/2003-January/012742.html
580 [PHP-users 12736] null byte attack
582 2003-05-16: magic quotes gpc¤ÎÉü¸µ½èÍý¤òÅý¹ç
583 2003-05-21: Ï¢ÁÛÇÛÎó¤Î¥¡¼¤Ïbinary safe
585 function input_filter($param)
587 static $magic_quotes_gpc = NULL;
588 if ($magic_quotes_gpc === NULL)
589 $magic_quotes_gpc = get_magic_quotes_gpc();
591 if (is_array($param)) {
592 return array_map('input_filter', $param);
594 $result = str_replace("\0", '', $param);
595 if ($magic_quotes_gpc) $result = stripslashes($result);
600 // Compat for 3rd party plugins. Remove this later
601 function sanitize($param) {
602 return input_filter($param);
605 // CSV·Á¼°¤Îʸ»úÎó¤òÇÛÎó¤Ë
606 function csv_explode($separator, $string)
608 $retval = $matches = array();
610 $_separator = preg_quote($separator, '/');
611 if (! preg_match_all('/("[^"]*(?:""[^"]*)*"|[^' . $_separator . ']*)' .
612 $_separator . '/', $string . $separator, $matches))
615 foreach ($matches[1] as $str) {
617 if ($len > 1 && $str{0} == '"' && $str{$len - 1} == '"')
618 $str = str_replace('""', '"', substr($str, 1, -1));
624 // ÇÛÎó¤òCSV·Á¼°¤Îʸ»úÎó¤Ë
625 function csv_implode($glue, $pieces)
627 $_glue = ($glue != '') ? '\\' . $glue{0} : '';
629 foreach ($pieces as $str) {
630 if (ereg("[$_glue\"\n\r]", $str))
631 $str = '"' . str_replace('"', '""', $str) . '"';
634 return join($glue, $arr);
637 function pkwk_login($pass = '')
641 if ($pass != '' && md5($pass) == $adminpass) {
644 sleep(2); // Blocking brute force attack
652 // is_a -- Returns TRUE if the object is of this class or has this class as one of its parents
654 if (! function_exists('is_a'))
656 function is_a($class, $match)
658 if (empty($class)) return FALSE;
660 $class = is_object($class) ? get_class($class) : $class;
661 if (strtolower($class) == strtolower($match)) {
664 return is_a(get_parent_class($class), $match); // Recurse
669 // array_fill -- Fill an array with values
671 if (! function_exists('array_fill'))
673 function array_fill($start_index, $num, $value)
676 while ($num-- > 0) $ret[$start_index++] = $value;
681 // md5_file -- Calculates the md5 hash of a given filename
683 if (! function_exists('md5_file'))
685 function md5_file($filename)
687 if (! file_exists($filename)) return FALSE;
689 $fd = fopen($filename, 'rb');
690 if ($fd === FALSE ) return FALSE;
691 $data = fread($fd, filesize($filename));