format('Y-m-d H:i:s.u'), 0, 23); } else { $timestamp = date('Y-m-d H:i:s'); } error_log($timestamp . ' ' . $message . "\n", 3, $log_filepath); } /* * Get LTSV safe string - Remove tab and newline chars. * * @param $s target string */ function get_ltsv_value($s) { if (!$s) { return ''; } return preg_replace('#[\t\r\n]#', '', $s); } /** * Write update_log on updating contents. * * @param $page page name * @param $diff_content diff expression */ function pkwk_log_updates($page, $diff_content) { global $auth_user, $logging_updates, $logging_updates_log_dir; $log_dir = $logging_updates_log_dir; $timestamp = time(); $ymd = gmdate('Ymd', $timestamp); $difflog_file = $log_dir . '/diff.' . $ymd . '.log'; $ltsv_file = $log_dir . '/update.' . $ymd . '.log'; $d = array( 'time' => gmdate('Y-m-d H:i:s', $timestamp), 'uri' => $_SERVER['REQUEST_URI'], 'method' => $_SERVER['REQUEST_METHOD'], 'remote_addr' => $_SERVER['REMOTE_ADDR'], 'user_agent' => $_SERVER['HTTP_USER_AGENT'], 'page' => $page, 'user' => $auth_user, 'diff' => $diff_content ); if (file_exists($log_dir) && defined('JSON_UNESCAPED_UNICODE')) { // require: PHP5.4+ $line = json_encode($d, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n"; file_put_contents($difflog_file, $line, FILE_APPEND | LOCK_EX); $keys = array('time', 'uri', 'method', 'remote_addr', 'user_agent', 'page', 'user'); $ar2 = array(); foreach ($keys as $k) { $ar2[] = $k . ':' . get_ltsv_value($d[$k]); } $ltsv = join($ar2, "\t") . "\n"; file_put_contents($ltsv_file, $ltsv, FILE_APPEND | LOCK_EX); } } /** * ctype_digit that supports PHP4+. * * PHP official document says PHP4 has ctype_digit() function. * But sometimes it doen't exists on PHP 4.1. */ function pkwk_ctype_digit($s) { static $ctype_digit_exists; if (!isset($ctype_digit_exists)) { $ctype_digit_exists = function_exists('ctype_digit'); } if ($ctype_digit_exists) { return ctype_digit($s); } return preg_match('/^[0-9]+$/', $s) ? true : false; } function is_interwiki($str) { global $InterWikiName; return preg_match('/^' . $InterWikiName . '$/', $str); } function is_pagename($str) { global $BracketName; $is_pagename = (! is_interwiki($str) && preg_match('/^(?!\/)' . $BracketName . '$(? $template) { $rule_pattrn = '/' . $rule . '/'; if (! preg_match($rule_pattrn, $page, $matches)) continue; $template_page = preg_replace($rule_pattrn, $template, $page); if (! is_page($template_page)) continue; $body = join('', get_source($template_page)); // Remove fixed-heading anchors $body = preg_replace('/^(\*{1,3}.*)\[#[A-Za-z][\w-]+\](.*)$/m', '$1$2', $body); // Remove '#freeze' $body = preg_replace('/^#freeze\s*$/m', '', $body); $count = count($matches); for ($i = 0; $i < $count; $i++) $body = str_replace('$' . $i, $matches[$i], $body); break; } return $body; } // Expand all search-words to regexes and push them into an array function get_search_words($words = array(), $do_escape = FALSE) { static $init, $mb_convert_kana, $pre, $post, $quote = '/'; if (! isset($init)) { // function: mb_convert_kana() is for Japanese code only if (LANG == 'ja' && function_exists('mb_convert_kana')) { $mb_convert_kana = create_function('$str, $option', 'return mb_convert_kana($str, $option, SOURCE_ENCODING);'); } else { $mb_convert_kana = create_function('$str, $option', 'return $str;'); } if (SOURCE_ENCODING == 'EUC-JP') { // Perl memo - Correct pattern-matching with EUC-JP // http://www.din.or.jp/~ohzaki/perl.htm#JP_Match (Japanese) $pre = '(?$value) $keys[$key] = '/' . $value . '/S'; $pages = get_existpages(); // Avoid if ($base != '') { $pages = preg_grep('/^' . preg_quote($base, '/') . '/S', $pages); } if (! $search_non_list) { $pages = array_diff($pages, preg_grep('/' . $non_list . '/S', $pages)); } $pages = array_flip($pages); unset($pages[$whatsnew]); $count = count($pages); foreach (array_keys($pages) as $page) { $b_match = FALSE; // Search for page name if (! $non_format) { foreach ($keys as $key) { $b_match = preg_match($key, $page); if ($b_type xor $b_match) break; // OR } if ($b_match) continue; } // Search auth for page contents if ($search_auth && ! check_readable($page, false, false)) { unset($pages[$page]); --$count; } // Search for page contents foreach ($keys as $key) { $b_match = preg_match($key, get_source($page, TRUE, TRUE)); if ($b_type xor $b_match) break; // OR } if ($b_match) continue; unset($pages[$page]); // Miss } if ($non_format) return array_keys($pages); $r_word = rawurlencode($word); $s_word = htmlsc($word); if (empty($pages)) return str_replace('$1', $s_word, $_msg_notfoundresult); ksort($pages, SORT_STRING); $retval = '' . "\n"; $retval .= str_replace('$1', $s_word, str_replace('$2', count($pages), str_replace('$3', $count, $b_type ? $_msg_andresult : $_msg_orresult))); return $retval; } // Argument check for program function arg_check($str) { global $vars; return isset($vars['cmd']) && (strpos($vars['cmd'], $str) === 0); } function _pagename_urlencode_callback($matches) { return rawurlencode($matches[0]); } function pagename_urlencode($page) { return preg_replace_callback('|[^/:]+|', '_pagename_urlencode_callback', $page); } // Encode page-name function encode($str) { $str = strval($str); return ($str == '') ? '' : strtoupper(bin2hex($str)); // Equal to strtoupper(join('', unpack('H*0', $key))); // But PHP 4.3.10 says 'Warning: unpack(): Type H: outside of string in ...' } // Decode page name function decode($str) { return pkwk_hex2bin($str); } // Inversion of bin2hex() function pkwk_hex2bin($hex_string) { // preg_match : Avoid warning : pack(): Type H: illegal hex digit ... // (string) : Always treat as string (not int etc). See BugTrack2/31 return preg_match('/^[0-9a-f]+$/i', $hex_string) ? pack('H*', (string)$hex_string) : $hex_string; } // Remove [[ ]] (brackets) function strip_bracket($str) { $match = array(); if (preg_match('/^\[\[(.*)\]\]$/', $str, $match)) { return $match[1]; } else { return $str; } } // Create list of pages function page_list($pages, $cmd = 'read', $withfilename = FALSE) { global $script, $list_index; global $_msg_symbol, $_msg_other; global $pagereading_enable; // ソートキーを決定する。 ' ' < '[a-zA-Z]' < 'zz'という前提。 $symbol = ' '; $other = 'zz'; $retval = ''; if($pagereading_enable) { mb_regex_encoding(SOURCE_ENCODING); $readings = get_readings($pages); } $list = $matches = array(); // Shrink URI for read if ($cmd == 'read') { $href = $script . '?'; } else { $href = $script . '?cmd=' . $cmd . '&page='; } foreach($pages as $file=>$page) { $r_page = pagename_urlencode($page); $s_page = htmlsc($page, ENT_QUOTES); $passage = get_pg_passage($page); $str = '
  • ' . $s_page . '' . $passage; if ($withfilename) { $s_file = htmlsc($file); $str .= "\n" . ' ' . "\n" . ' '; } $str .= '
  • '; // WARNING: Japanese code hard-wired if($pagereading_enable) { if(mb_ereg('^([A-Za-z])', mb_convert_kana($page, 'a'), $matches)) { $head = strtoupper($matches[1]); } elseif (isset($readings[$page]) && mb_ereg('^([ァ-ヶ])', $readings[$page], $matches)) { // here $head = $matches[1]; } elseif (mb_ereg('^[ -~]|[^ぁ-ん亜-熙]', $page)) { // and here $head = $symbol; } else { $head = $other; } } else { $head = (preg_match('/^([A-Za-z])/', $page, $matches)) ? strtoupper($matches[1]) : (preg_match('/^([ -~])/', $page) ? $symbol : $other); } $list[$head][$page] = $str; } uksort($pages, 'strnatcmp'); $cnt = 0; $arr_index = array(); $retval .= '' . "\n"; if ($list_index && $cnt > 0) { $top = array(); while (! empty($arr_index)) $top[] = join(' | ' . "\n", array_splice($arr_index, 0, 16)) . "\n"; $retval = '
    ' . "\n" . join('
    ', $top) . '
    ' . "\n" . $retval; } return $retval; } // Show text formatting rules function catrule() { global $rule_page; if (! is_page($rule_page)) { return '

    Sorry, page \'' . htmlsc($rule_page) . '\' unavailable.

    '; } else { return convert_html(get_source($rule_page)); } } // Show (critical) error message function die_message($msg) { $title = $page = 'Runtime error'; $body = <<Runtime error Error message : $msg EOD; pkwk_common_headers(); if(defined('SKIN_FILE') && file_exists(SKIN_FILE) && is_readable(SKIN_FILE)) { catbody($title, $page, $body); } else { $charset = 'utf-8'; if(defined('CONTENT_CHARSET')) { $charset = CONTENT_CHARSET; } header("Content-Type: text/html; charset=$charset"); print << $title $body EOD; } exit; } // Have the time (as microtime) function getmicrotime() { list($usec, $sec) = explode(' ', microtime()); return ((float)$sec + (float)$usec); } // Elapsed time by second //define('MUTIME', getmicrotime()); function elapsedtime() { $at_the_microtime = MUTIME; return sprintf('%01.03f', getmicrotime() - $at_the_microtime); } // Get the date function get_date($format, $timestamp = NULL) { $format = preg_replace('/(?60, 'h'=>24, 'd'=>1); $time = max(0, (UTIME - $time) / 60); // minutes foreach ($units as $unit=>$card) { if ($time < $card) break; $time /= $card; } $time = floor($time) . $unit; return $paren ? '(' . $time . ')' : $time; } // Hide function drop_submit($str) { return preg_replace('/]+)type="(submit|button|image)"/i', 'read(); $ignorepages = $config->get('IgnoreList'); $forceignorepages = $config->get('ForceIgnoreList'); unset($config); $auto_pages = array_merge($ignorepages, $forceignorepages); foreach ($pages as $page) if (preg_match('/^' . $WikiName . '$/', $page) ? $nowikiname : strlen($page) >= $autolink) $auto_pages[] = $page; if (empty($auto_pages)) { $result = $result_a = $nowikiname ? '(?!)' : $WikiName; } else { $auto_pages = array_unique($auto_pages); sort($auto_pages, SORT_STRING); $auto_pages_a = array_values(preg_grep('/^[A-Z]+$/i', $auto_pages)); $auto_pages = array_values(array_diff($auto_pages, $auto_pages_a)); $result = get_autolink_pattern_sub($auto_pages, 0, count($auto_pages), 0); $result_a = get_autolink_pattern_sub($auto_pages_a, 0, count($auto_pages_a), 0); } return array($result, $result_a, $forceignorepages); } function get_autolink_pattern_sub(& $pages, $start, $end, $pos) { if ($end == 0) return '(?!)'; $result = ''; $count = $i = $j = 0; $x = (mb_strlen($pages[$start]) <= $pos); if ($x) ++$start; for ($i = $start; $i < $end; $i = $j) { $char = mb_substr($pages[$i], $pos, 1); for ($j = $i; $j < $end; $j++) if (mb_substr($pages[$j], $pos, 1) != $char) break; if ($i != $start) $result .= '|'; if ($i >= ($j - 1)) { $result .= str_replace(' ', '\\ ', preg_quote(mb_substr($pages[$i], $pos), '/')); } else { $result .= str_replace(' ', '\\ ', preg_quote($char, '/')) . get_autolink_pattern_sub($pages, $i, $j, $pos + 1); } ++$count; } if ($x || $count > 1) $result = '(?:' . $result . ')'; if ($x) $result .= '?'; return $result; } // Get absolute-URI of this script function get_script_uri($init_uri = '') { global $script_directory_index; static $script; if ($init_uri == '') { // Get if (isset($script)) return $script; // Set automatically $msg = 'get_script_uri() failed: Please set $script at INI_FILE manually'; $script = (SERVER_PORT == 443 ? 'https://' : 'http://'); // scheme $script .= SERVER_NAME; // host $script .= (SERVER_PORT == 80 ? '' : ':' . SERVER_PORT); // port // SCRIPT_NAME が'/'で始まっていない場合(cgiなど) REQUEST_URIを使ってみる $path = SCRIPT_NAME; if ($path{0} != '/') { if (! isset($_SERVER['REQUEST_URI']) || $_SERVER['REQUEST_URI']{0} != '/') die_message($msg); // REQUEST_URIをパースし、path部分だけを取り出す $parse_url = parse_url($script . $_SERVER['REQUEST_URI']); if (! isset($parse_url['path']) || $parse_url['path']{0} != '/') die_message($msg); $path = $parse_url['path']; } $script .= $path; if (! is_url($script, TRUE) && php_sapi_name() == 'cgi') die_message($msg); unset($msg); } else { // Set manually if (isset($script)) die_message('$script: Already init'); if (! is_url($init_uri, TRUE)) die_message('$script: Invalid URI'); $script = $init_uri; } // Cut filename or not if (isset($script_directory_index)) { if (! file_exists($script_directory_index)) die_message('Directory index file not found: ' . htmlsc($script_directory_index)); $matches = array(); if (preg_match('#^(.+/)' . preg_quote($script_directory_index, '#') . '$#', $script, $matches)) $script = $matches[1]; } return $script; } // Remove null(\0) bytes from variables // // NOTE: PHP had vulnerabilities that opens "hoge.php" via fopen("hoge.php\0.txt") etc. // [PHP-users 12736] null byte attack // http://ns1.php.gr.jp/pipermail/php-users/2003-January/012742.html // // 2003-05-16: magic quotes gpcの復元処理を統合 // 2003-05-21: 連想配列のキーはbinary safe // function input_filter($param) { static $magic_quotes_gpc = NULL; if ($magic_quotes_gpc === NULL) $magic_quotes_gpc = get_magic_quotes_gpc(); if (is_array($param)) { return array_map('input_filter', $param); } else { $result = str_replace("\0", '', $param); if ($magic_quotes_gpc) $result = stripslashes($result); return $result; } } // Compat for 3rd party plugins. Remove this later function sanitize($param) { return input_filter($param); } // Explode Comma-Separated Values to an array function csv_explode($separator, $string) { $retval = $matches = array(); $_separator = preg_quote($separator, '/'); if (! preg_match_all('/("[^"]*(?:""[^"]*)*"|[^' . $_separator . ']*)' . $_separator . '/', $string . $separator, $matches)) return array(); foreach ($matches[1] as $str) { $len = strlen($str); if ($len > 1 && $str{0} == '"' && $str{$len - 1} == '"') $str = str_replace('""', '"', substr($str, 1, -1)); $retval[] = $str; } return $retval; } // Implode an array with CSV data format (escape double quotes) function csv_implode($glue, $pieces) { $_glue = ($glue != '') ? '\\' . $glue{0} : ''; $arr = array(); foreach ($pieces as $str) { if (preg_match('/[' . '"' . "\n\r" . $_glue . ']/', $str)) $str = '"' . str_replace('"', '""', $str) . '"'; $arr[] = $str; } return join($glue, $arr); } // Sugar with default settings function htmlsc($string = '', $flags = ENT_COMPAT, $charset = CONTENT_CHARSET) { return htmlspecialchars($string, $flags, $charset); // htmlsc() } /** * Get redirect page name on Page Redirect Rules * * This function returns exactly false if it doesn't need redirection. * So callers need check return value is false or not. * * @param $page page name * @return new page name or false */ function get_pagename_on_redirect($page) { global $page_redirect_rules; foreach ($page_redirect_rules as $rule=>$replace) { if (preg_match($rule, $page)) { if (is_string($replace)) { $new_page = preg_replace($rule, $replace, $page); } elseif (is_object($replace) && is_callable($replace)) { $new_page = preg_replace_callback($rule, $replace, $page); } else { die_message('Invalid redirect rule: ' . $rule . '=>' . $replace); } if ($page !== $new_page) { return $new_page; } } } return false; } /** * Redirect from an old page to new page * * This function returns true when a redirection occurs. * So callers need check return value is false or true. * And if it is true, then you have to exit PHP script. * * @return bool Inticates a redirection occurred or not */ function manage_page_redirect() { global $vars; if (isset($vars['page'])) { $page = $vars['page']; } $new_page = get_pagename_on_redirect($page); if ($new_page != false) { header('Location: ' . get_script_uri() . '?' . pagename_urlencode($new_page)); return TRUE; } return FALSE; } //// Compat //// // is_a -- Returns TRUE if the object is of this class or has this class as one of its parents // (PHP 4 >= 4.2.0) if (! function_exists('is_a')) { function is_a($class, $match) { if (empty($class)) return FALSE; $class = is_object($class) ? get_class($class) : $class; if (strtolower($class) == strtolower($match)) { return TRUE; } else { return is_a(get_parent_class($class), $match); // Recurse } } } // array_fill -- Fill an array with values // (PHP 4 >= 4.2.0) if (! function_exists('array_fill')) { function array_fill($start_index, $num, $value) { $ret = array(); while ($num-- > 0) $ret[$start_index++] = $value; return $ret; } } // md5_file -- Calculates the md5 hash of a given filename // (PHP 4 >= 4.2.0) if (! function_exists('md5_file')) { function md5_file($filename) { if (! file_exists($filename)) return FALSE; $fd = fopen($filename, 'rb'); if ($fd === FALSE ) return FALSE; $data = fread($fd, filesize($filename)); fclose($fd); return md5($data); } } // sha1 -- Compute SHA-1 hash // (PHP 4 >= 4.3.0, PHP5) if (! function_exists('sha1')) { if (extension_loaded('mhash')) { function sha1($str) { return bin2hex(mhash(MHASH_SHA1, $str)); } } }