2 // PukiWiki - Yet another WikiWikiWeb clone.
3 // $Id: func.php,v 1.26 2005/01/10 04:18:46 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 return ($key == '') ? '' : substr(pack('H*', '20202020' . $key), 4);
258 function strip_bracket($str)
261 if (preg_match('/^\[\[(.*)\]\]$/', $str, $match)) {
269 function page_list($pages, $cmd = 'read', $withfilename = FALSE)
271 global $script, $list_index;
272 global $_msg_symbol, $_msg_other;
273 global $pagereading_enable;
275 // ¥½¡¼¥È¥¡¼¤ò·èÄꤹ¤ë¡£ ' ' < '[a-zA-Z]' < 'zz'¤È¤¤¤¦Á°Äó¡£
281 if($pagereading_enable) {
282 mb_regex_encoding(SOURCE_ENCODING);
283 $readings = get_readings($pages);
286 $list = $matches = array();
287 foreach($pages as $file=>$page) {
288 $r_page = rawurlencode($page);
289 $s_page = htmlspecialchars($page, ENT_QUOTES);
290 $passage = get_pg_passage($page);
292 $str = ' <li><a href="' .
293 $script . '?cmd=' . $cmd . '&page=' . $r_page .
294 '">' . $s_page . '</a>' . $passage;
297 $s_file = htmlspecialchars($file);
298 $str .= "\n" . ' <ul><li>' . $s_file . '</li></ul>' .
303 // WARNING: Japanese code hard-wired
304 if($pagereading_enable) {
305 if(mb_ereg('^([A-Za-z])', mb_convert_kana($page, 'a'), $matches)) {
307 } elseif(mb_ereg('^([¥¡-¥ö])', $readings[$page], $matches)) { // here
309 } elseif (mb_ereg('^[ -~]|[^¤¡-¤ó°¡-ô¦]', $page)) { // and here
315 $head = (preg_match('/^([A-Za-z])/', $page, $matches)) ? $matches[1] :
316 (preg_match('/^([ -~])/', $page, $matches) ? $symbol : $other);
319 $list[$head][$page] = $str;
324 $arr_index = array();
325 $retval .= '<ul>' . "\n";
326 foreach ($list as $head=>$pages) {
327 if ($head === $symbol) {
328 $head = $_msg_symbol;
329 } else if ($head === $other) {
335 $arr_index[] = '<a id="top_' . $cnt .
336 '" href="#head_' . $cnt . '"><strong>' .
337 $head . '</strong></a>';
338 $retval .= ' <li><a id="head_' . $cnt . '" href="#top_' . $cnt .
339 '"><strong>' . $head . '</strong></a>' . "\n" .
343 $retval .= join("\n", $pages);
345 $retval .= "\n </ul>\n </li>\n";
347 $retval .= '</ul>' . "\n";
348 if ($list_index && $cnt > 0) {
350 while (! empty($arr_index))
351 $top[] = join(' | ' . "\n", array_splice($arr_index, 0, 16)) . "\n";
353 $retval = '<div id="top" style="text-align:center">' . "\n" .
354 join('<br />', $top) . '</div>' . "\n" . $retval;
359 // Show text formatting rules
364 if (! is_page($rule_page)) {
365 return '<p>Sorry, page \'' . htmlspecialchars($rule_page) .
366 '\' unavailable.</p>';
368 return convert_html(get_source($rule_page));
372 // Show (critical) error message
373 function die_message($msg)
375 $title = $page = 'Runtime error';
377 <h3>Runtime error</h3>
378 <strong>Error message : $msg</strong>
381 pkwk_common_headers();
382 if(defined('SKIN_FILE') && file_exists(SKIN_FILE) && is_readable(SKIN_FILE)) {
383 catbody($title, $page, $body);
385 header('Content-Type: text/html; charset=euc-jp');
387 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
390 <title>$title</title>
391 <meta http-equiv="content-type" content="text/html; charset=euc-jp">
402 // ¸½ºß»þ¹ï¤ò¥Þ¥¤¥¯¥íÉäǼèÆÀ
403 function getmicrotime()
405 list($usec, $sec) = explode(' ', microtime());
406 return ((float)$sec + (float)$usec);
410 function get_date($format, $timestamp = NULL)
412 $format = preg_replace('/(?<!\\\)T/',
413 preg_replace('/(.)/', '\\\$1', ZONE), $format);
415 $time = ZONETIME + (($timestamp !== NULL) ? $timestamp : UTIME);
417 return date($format, $time);
421 function format_date($val, $paren = FALSE)
423 global $date_format, $time_format, $weeklabels;
427 $date = date($date_format . ' ' . $time_format, $val) .
428 ' ' . '(' . $weeklabels[date('w', $val)] . ')';
430 return $paren ? '(' . $date . ')' : $date;
433 // ·Ð²á»þ¹ïʸ»úÎó¤òºî¤ë
434 function get_passage($time, $paren = TRUE)
436 static $units = array('m'=>60, 'h'=>24, 'd'=>1);
438 $time = max(0, (UTIME - $time) / 60); // minutes
440 foreach ($units as $unit=>$card) {
441 if ($time < $card) break;
444 $time = floor($time) . $unit;
446 return $paren ? '(' . $time . ')' : $time;
449 // Hide <input type="(submit|button|image)"...>
450 function drop_submit($str)
452 return preg_replace('/<input([^>]+)type="(submit|button|image)"/i',
453 '<input$1type="hidden"', $str);
456 // AutoLink¤Î¥Ñ¥¿¡¼¥ó¤òÀ¸À®¤¹¤ë
458 function get_autolink_pattern(& $pages)
460 global $WikiName, $autolink, $nowikiname;
462 $config = &new Config('AutoLink');
464 $ignorepages = $config->get('IgnoreList');
465 $forceignorepages = $config->get('ForceIgnoreList');
467 $auto_pages = array_merge($ignorepages, $forceignorepages);
469 foreach ($pages as $page) {
470 if (preg_match('/^' . $WikiName . '$/', $page) ?
471 $nowikiname : strlen($page) >= $autolink)
472 $auto_pages[] = $page;
475 if (empty($auto_pages))
476 return $nowikiname ? '(?!)' : $WikiName;
478 $auto_pages = array_unique($auto_pages);
479 sort($auto_pages, SORT_STRING);
481 $auto_pages_a = array_values(preg_grep('/^[A-Z]+$/i', $auto_pages));
482 $auto_pages = array_values(array_diff($auto_pages, $auto_pages_a));
484 $result = get_autolink_pattern_sub($auto_pages, 0, count($auto_pages), 0);
485 $result_a = get_autolink_pattern_sub($auto_pages_a, 0, count($auto_pages_a), 0);
487 return array($result, $result_a, $forceignorepages);
490 function get_autolink_pattern_sub(& $pages, $start, $end, $pos)
492 if ($end == 0) return '(?!)';
495 $count = $i = $j = 0;
496 $x = (mb_strlen($pages[$start]) <= $pos);
499 for ($i = $start; $i < $end; $i = $j)
501 $char = mb_substr($pages[$i], $pos, 1);
502 for ($j = $i; $j < $end; $j++) {
503 if (mb_substr($pages[$j], $pos, 1) != $char) break;
505 if ($i != $start) $result .= '|';
506 if ($i >= ($j - 1)) {
507 $result .= str_replace(' ', '\\ ', preg_quote(mb_substr($pages[$i], $pos), '/'));
509 $result .= str_replace(' ', '\\ ', preg_quote($char, '/')) .
510 get_autolink_pattern_sub($pages, $i, $j, $pos + 1);
514 if ($x || $count > 1) $result = '(?:' . $result . ')';
515 if ($x) $result .= '?';
520 // pukiwiki.php¥¹¥¯¥ê¥×¥È¤Îabsolute-uri¤òÀ¸À®
521 function get_script_uri($init_uri = '')
523 global $script_directory_index;
526 if ($init_uri == '') {
528 if (isset($script)) return $script;
531 $msg = 'get_script_uri() failed: Please set $script at INI_FILE manually';
533 $script = (SERVER_PORT == 443 ? 'https://' : 'http://'); // scheme
534 $script .= SERVER_NAME; // host
535 $script .= (SERVER_PORT == 80 ? '' : ':' . SERVER_PORT); // port
537 // SCRIPT_NAME ¤¬'/'¤Ç»Ï¤Þ¤Ã¤Æ¤¤¤Ê¤¤¾ì¹ç(cgi¤Ê¤É) REQUEST_URI¤ò»È¤Ã¤Æ¤ß¤ë
539 if ($path{0} != '/') {
540 if (! isset($_SERVER['REQUEST_URI']) || $_SERVER['REQUEST_URI']{0} != '/')
543 // REQUEST_URI¤ò¥Ñ¡¼¥¹¤·¡¢pathÉôʬ¤À¤±¤ò¼è¤ê½Ð¤¹
544 $parse_url = parse_url($script . $_SERVER['REQUEST_URI']);
545 if (! isset($parse_url['path']) || $parse_url['path']{0} != '/')
548 $path = $parse_url['path'];
552 if (! is_url($script, TRUE) && php_sapi_name() == 'cgi')
558 if (isset($script)) die_message('$script: Already init');
559 if (! is_url($init_uri, TRUE)) die_message('$script: Invalid URI');
563 // Cut filename or not
564 if (isset($script_directory_index)) {
565 if (! file_exists($script_directory_index))
566 die_message('Directory index file not found: ' .
567 htmlspecialchars($script_directory_index));
569 if (preg_match('#^(.+/)' . preg_quote($script_directory_index, '#') . '$#',
570 $script, $matches)) $script = $matches[1];
577 ÊÑ¿ôÆâ¤Înull(\0)¥Ð¥¤¥È¤òºï½ü¤¹¤ë
578 PHP¤Ïfopen("hoge.php\0.txt")¤Ç"hoge.php"¤ò³«¤¤¤Æ¤·¤Þ¤¦¤Ê¤É¤ÎÌäÂꤢ¤ê
580 http://ns1.php.gr.jp/pipermail/php-users/2003-January/012742.html
581 [PHP-users 12736] null byte attack
583 2003-05-16: magic quotes gpc¤ÎÉü¸µ½èÍý¤òÅý¹ç
584 2003-05-21: Ï¢ÁÛÇÛÎó¤Î¥¡¼¤Ïbinary safe
586 function input_filter($param)
588 static $magic_quotes_gpc = NULL;
589 if ($magic_quotes_gpc === NULL)
590 $magic_quotes_gpc = get_magic_quotes_gpc();
592 if (is_array($param)) {
593 return array_map('input_filter', $param);
595 $result = str_replace("\0", '', $param);
596 if ($magic_quotes_gpc) $result = stripslashes($result);
601 // Compat for 3rd party plugins. Remove this later
602 function sanitize($param) {
603 return input_filter($param);
606 // CSV·Á¼°¤Îʸ»úÎó¤òÇÛÎó¤Ë
607 function csv_explode($separator, $string)
609 $retval = $matches = array();
611 $_separator = preg_quote($separator, '/');
612 if (! preg_match_all('/("[^"]*(?:""[^"]*)*"|[^' . $_separator . ']*)' .
613 $_separator . '/', $string . $separator, $matches))
616 foreach ($matches[1] as $str) {
618 if ($len > 1 && $str{0} == '"' && $str{$len - 1} == '"')
619 $str = str_replace('""', '"', substr($str, 1, -1));
625 // Implode an array with CSV data format (escape double quotes)
626 function csv_implode($glue, $pieces)
628 $_glue = ($glue != '') ? '\\' . $glue{0} : '';
630 foreach ($pieces as $str) {
631 if (ereg('[' . $_glue . '"' . "\n\r" . ']', $str))
632 $str = '"' . str_replace('"', '""', $str) . '"';
635 return join($glue, $arr);
638 function pkwk_login($pass = '')
642 if ($pass != '' && md5($pass) == $adminpass) {
645 sleep(2); // Blocking brute force attack
653 // is_a -- Returns TRUE if the object is of this class or has this class as one of its parents
655 if (! function_exists('is_a')) {
657 function is_a($class, $match)
659 if (empty($class)) return FALSE;
661 $class = is_object($class) ? get_class($class) : $class;
662 if (strtolower($class) == strtolower($match)) {
665 return is_a(get_parent_class($class), $match); // Recurse
670 // array_fill -- Fill an array with values
672 if (! function_exists('array_fill')) {
674 function array_fill($start_index, $num, $value)
677 while ($num-- > 0) $ret[$start_index++] = $value;
682 // md5_file -- Calculates the md5 hash of a given filename
684 if (! function_exists('md5_file')) {
686 function md5_file($filename)
688 if (! file_exists($filename)) return FALSE;
690 $fd = fopen($filename, 'rb');
691 if ($fd === FALSE ) return FALSE;
692 $data = fread($fd, filesize($filename));