2 // PukiWiki - Yet another WikiWikiWeb clone.
5 // 2002-2021 PukiWiki Development Team
6 // 2001-2002 Originally written by yu-ji
7 // License: GPL v2 or (at your option) any later version
11 // PukiWiki version / Copyright / Licence
13 define('S_VERSION', '1.5.4');
15 '<strong>PukiWiki ' . S_VERSION . '</strong>' .
17 ' <a href="https://pukiwiki.osdn.jp/">PukiWiki Development Team</a>'
20 /////////////////////////////////////////////////
21 // Session security options
23 ini_set('session.use_strict_mode', 1);
24 ini_set('session.use_cookies', 1);
25 ini_set('session.use_only_cookies', 1);
27 /////////////////////////////////////////////////
28 // Init server variables
30 // Comapat and suppress notices
31 if (!isset($HTTP_SERVER_VARS)) $HTTP_SERVER_VARS = array();
33 foreach (array('SCRIPT_NAME', 'SERVER_ADMIN', 'SERVER_NAME',
34 'SERVER_PORT', 'SERVER_SOFTWARE') as $key) {
35 define($key, isset($_SERVER[$key]) ? $_SERVER[$key] : '');
36 unset(${$key}, $_SERVER[$key], $HTTP_SERVER_VARS[$key]);
39 /////////////////////////////////////////////////
40 // Init grobal variables
42 $foot_explain = array(); // Footnotes
43 $related = array(); // Related pages
44 $head_tags = array(); // XHTML tags in <head></head>
46 /////////////////////////////////////////////////
49 define('LOCALZONE', date('Z'));
50 define('UTIME', time() - LOCALZONE);
51 define('MUTIME', getmicrotime());
53 /////////////////////////////////////////////////
56 define('INI_FILE', DATA_HOME . 'pukiwiki.ini.php');
58 if (! file_exists(INI_FILE) || ! is_readable(INI_FILE)) {
59 $die .= 'File is not found. (INI_FILE)' . "\n";
63 if ($die) die_message(nl2br("\n\n" . $die));
65 /////////////////////////////////////////////////
66 // Page-URI mapping handler (default)
67 if (! $page_uri_handler) {
68 $page_uri_handler = new PukiWikiStandardPageURIHandler();
71 /////////////////////////////////////////////////
72 // INI_FILE: LANG に基づくエンコーディング設定
74 // MB_LANGUAGE: mb_language (for mbstring extension)
75 // 'uni'(means UTF-8), 'English', or 'Japanese'
76 // SOURCE_ENCODING: Internal content encoding (for mbstring extension)
77 // 'UTF-8', 'ASCII', or 'EUC-JP'
78 // CONTENT_CHARSET: Internal content encoding = Output content charset
79 // (for DTD, htmlsc())
80 // 'UTF-8', 'iso-8859-1', 'EUC-JP' or ...
83 case 'en': define('MB_LANGUAGE', 'English' ); break;
84 case 'ja': define('MB_LANGUAGE', 'Japanese'); break;
85 case 'ko': define('MB_LANGUAGE', 'Korean' ); break; //UTF-8 only
86 // See BugTrack2/13 for all hack about Korean support, //UTF-8 only
87 // and give us your report! //UTF-8 only
88 default: die_message('No such language "' . LANG . '"'); break;
91 define('PKWK_UTF8_ENABLE', 1); //UTF-8 only
92 if (defined('PKWK_UTF8_ENABLE')) {
93 define('SOURCE_ENCODING', 'UTF-8');
94 define('CONTENT_CHARSET', 'UTF-8');
98 define('SOURCE_ENCODING', 'ASCII');
99 define('CONTENT_CHARSET', 'iso-8859-1');
102 define('SOURCE_ENCODING', 'EUC-JP');
103 define('CONTENT_CHARSET', 'EUC-JP');
108 mb_language(MB_LANGUAGE);
109 mb_internal_encoding(SOURCE_ENCODING);
110 mb_http_output('pass');
111 mb_detect_order('auto');
113 /////////////////////////////////////////////////
114 // INI_FILE: Require LANG_FILE
116 define('LANG_FILE_HINT', DATA_HOME . LANG . '.lng.php'); // For encoding hint
117 define('LANG_FILE', DATA_HOME . UI_LANG . '.lng.php'); // For UI resource
119 foreach (array('LANG_FILE_HINT', 'LANG_FILE') as $langfile) {
120 if (! file_exists(constant($langfile)) || ! is_readable(constant($langfile))) {
121 $die .= 'File is not found or not readable. (' . $langfile . ')' . "\n";
123 require_once(constant($langfile));
126 if ($die) die_message(nl2br("\n\n" . $die));
128 /////////////////////////////////////////////////
129 // LANG_FILE: Init encoding hint
131 define('PKWK_ENCODING_HINT', isset($_LANG['encode_hint'][LANG]) ? $_LANG['encode_hint'][LANG] : '');
132 unset($_LANG['encode_hint']);
134 /////////////////////////////////////////////////
135 // LANG_FILE: Init severn days of the week
137 $weeklabels = $_msg_week;
139 /////////////////////////////////////////////////
140 // INI_FILE: Init $script
142 if (isset($script)) {
144 pkwk_script_uri_base(PKWK_URI_ABSOLUTE, true, $script);
146 // Init automatically
147 $script = pkwk_script_uri_base(PKWK_URI_ABSOLUTE, true);
150 // INI_FILE: Auth settings
151 if (isset($auth_type) && $auth_type === AUTH_TYPE_SAML) {
152 $auth_external_login_url_base = get_base_uri() . '?//cmd.saml//sso';
156 /////////////////////////////////////////////////
157 // INI_FILE: $agents: UserAgentの識別
159 $ua = 'HTTP_USER_AGENT';
160 $user_agent = $matches = array();
162 $user_agent['agent'] = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
164 foreach ($agents as $agent) {
165 if (preg_match($agent['pattern'], $user_agent['agent'], $matches)) {
166 $user_agent['profile'] = isset($agent['profile']) ? $agent['profile'] : '';
167 $user_agent['name'] = isset($matches[1]) ? $matches[1] : ''; // device or browser name
168 $user_agent['vers'] = isset($matches[2]) ? $matches[2] : ''; // 's version
172 unset($agents, $matches);
174 // Profile-related init and setting
175 define('UA_PROFILE', isset($user_agent['profile']) ? $user_agent['profile'] : '');
177 define('UA_INI_FILE', DATA_HOME . UA_PROFILE . '.ini.php');
178 if (! file_exists(UA_INI_FILE) || ! is_readable(UA_INI_FILE)) {
179 die_message('UA_INI_FILE for "' . UA_PROFILE . '" not found.');
181 require(UA_INI_FILE); // Also manually
184 define('UA_NAME', isset($user_agent['name']) ? $user_agent['name'] : '');
185 define('UA_VERS', isset($user_agent['vers']) ? $user_agent['vers'] : '');
186 unset($user_agent); // Unset after reading UA_INI_FILE
188 /////////////////////////////////////////////////
192 foreach(array('DATA_DIR', 'DIFF_DIR', 'BACKUP_DIR', 'CACHE_DIR') as $dir){
193 if (! is_writable(constant($dir)))
194 $die .= 'Directory is not found or not writable (' . $dir . ')' . "\n";
199 foreach(array('rss_max', 'page_title', 'note_hr', 'related_link', 'show_passage',
200 'rule_related_str', 'load_template_func') as $var){
201 if (! isset(${$var})) $temp .= '$' . $var . "\n";
204 if ($die) $die .= "\n"; // A breath
205 $die .= 'Variable(s) not found: (Maybe the old *.ini.php?)' . "\n" . $temp;
209 foreach(array('LANG', 'PLUGIN_DIR') as $def){
210 if (! defined($def)) $temp .= $def . "\n";
213 if ($die) $die .= "\n"; // A breath
214 $die .= 'Define(s) not found: (Maybe the old *.ini.php?)' . "\n" . $temp;
217 if($die) die_message(nl2br("\n\n" . $die));
220 /////////////////////////////////////////////////
221 // 必須のページが存在しなければ、空のファイルを作成する
223 foreach(array($defaultpage, $whatsnew, $interwiki) as $page){
224 if (! is_page($page)) pkwk_touch_file(get_filename($page));
227 /////////////////////////////////////////////////
230 // Prohibit $_GET attack
231 foreach (array('msg', 'pass') as $key) {
232 if (isset($_GET[$key])) die_message('Sorry, already reserved: ' . $key . '=');
236 unset($HTTP_GET_VARS, $HTTP_POST_VARS); //, 'SERVER', 'ENV', 'SESSION', ...
237 unset($_REQUEST); // Considered harmful
239 // Remove null character etc.
240 $_GET = input_filter($_GET);
241 $_POST = input_filter($_POST);
242 $_COOKIE = input_filter($_COOKIE);
245 // <form> で送信された文字 (ブラウザがエンコードしたデータ) のコードを変換
246 // POST method は常に form 経由なので、必ず変換する
248 if (isset($_POST['encode_hint']) && $_POST['encode_hint'] != '') {
249 // do_plugin_xxx() の中で、<form> に encode_hint を仕込んでいるので、
250 // encode_hint を用いてコード検出する。
251 // 全体を見てコード検出すると、機種依存文字や、妙なバイナリ
252 // コードが混入した場合に、コード検出に失敗する恐れがある。
253 $encode = mb_detect_encoding($_POST['encode_hint']);
254 mb_convert_variables(SOURCE_ENCODING, $encode, $_POST);
256 } else if (isset($_POST['charset']) && $_POST['charset'] != '') {
257 // TrackBack Ping で指定されていることがある
258 // うまくいかない場合は自動検出に切り替え
259 if (mb_convert_variables(SOURCE_ENCODING,
260 $_POST['charset'], $_POST) !== $_POST['charset']) {
261 mb_convert_variables(SOURCE_ENCODING, 'auto', $_POST);
264 } else if (! empty($_POST)) {
266 mb_convert_variables(SOURCE_ENCODING, 'auto', $_POST);
270 // GET method は form からの場合と、<a href="http://script/?key=value> の場合がある
271 // <a href...> の場合は、サーバーが rawurlencode しているので、コード変換は不要
272 if (isset($_GET['encode_hint']) && $_GET['encode_hint'] != '')
274 // form 経由の場合は、ブラウザがエンコードしているので、コード検出・変換が必要。
275 // encode_hint が含まれているはずなので、それを見て、コード検出した後、変換する。
277 $encode = mb_detect_encoding($_GET['encode_hint']);
278 mb_convert_variables(SOURCE_ENCODING, $encode, $_GET);
282 /////////////////////////////////////////////////
285 // cmdもpluginも指定されていない場合は、QUERY_STRINGを
286 // ページ名かInterWikiNameであるとみなす
288 if (isset($_SERVER['QUERY_STRING']) && $_SERVER['QUERY_STRING'] != '') {
289 global $g_query_string;
290 $g_query_string = $_SERVER['QUERY_STRING'];
291 $arg = & $_SERVER['QUERY_STRING'];
292 } else if (isset($_SERVER['argv']) && ! empty($_SERVER['argv'])) {
293 $arg = & $_SERVER['argv'][0];
295 if (PKWK_QUERY_STRING_MAX && strlen($arg) > PKWK_QUERY_STRING_MAX) {
296 // Something nasty attack?
297 pkwk_common_headers();
298 sleep(1); // Fake processing, and/or process other threads
299 echo('Query string too long');
302 $arg = input_filter($arg); // \0 除去
304 // Convert QueryString by PageURIHandler
305 $arg_replaced = $page_uri_handler->filter_raw_query_string($arg);
306 if ($arg_replaced !== $arg) {
309 foreach (explode('&', $arg_replaced) as $kv) {
310 if (preg_match('/^([^=]+)(=(.+))?/', $kv, $m)) {
311 $_GET[$m[1]] = is_null($m[3]) ? '' : $m[3];
315 $arg = $arg_replaced;
317 unset($arg_replaced);
319 // unset QUERY_STRINGs
320 foreach (array('QUERY_STRING', 'argv', 'argc') as $key) {
321 unset(${$key}, $_SERVER[$key], $HTTP_SERVER_VARS[$key]);
323 // $_SERVER['REQUEST_URI'] is used at func.php NOW
324 unset($REQUEST_URI, $HTTP_SERVER_VARS['REQUEST_URI']);
326 // mb_convert_variablesのバグ(?)対策: 配列で渡さないと落ちる
328 mb_convert_variables(SOURCE_ENCODING, 'auto', $arg);
331 /////////////////////////////////////////////////
332 // QUERY_STRINGを分解してコード変換し、$_GET に上書き
334 // URI を urlencode せずに入力した場合に対処する
336 foreach (explode('&', $arg) as $key_and_value) {
337 if (preg_match('/^([^=]+)=(.+)/', $key_and_value, $matches) &&
338 mb_detect_encoding($matches[2]) != 'ASCII') {
339 $_GET[$matches[1]] = $matches[2];
344 /////////////////////////////////////////////////
349 $cookie = & $_COOKIE;
351 // GET + POST = $vars
353 $vars = & $_GET; // Major pattern: Read-only access via GET
354 } else if (empty($_GET)) {
355 $vars = & $_POST; // Minor pattern: Write access via POST etc.
357 $vars = array_merge($_GET, $_POST); // Considered reliable than $_REQUEST
361 * Parse specified format query_string as params.
363 * For example: ?//key1.value2//key2.value2
365 function parse_query_string_ext($query_string) {
368 if (preg_match('#^//[^&]*#', $query_string, $m)) {
369 foreach (explode('//', $m[0]) as $item) {
370 $sp = explode('.', $item, 2);
373 $vars[$sp[0]] = $sp[1];
382 if (isset($g_query_string) && $g_query_string) {
383 if (substr($g_query_string, 0, 2) === '//') {
384 // Parse ?//key.value//key.value format query string
385 $vars = array_merge($vars, parse_query_string_ext($g_query_string));
390 // 入力チェック: 'cmd=' and 'plugin=' can't live together
391 if (isset($vars['cmd']) && isset($vars['plugin']))
392 die('Using both cmd= and plugin= is not allowed');
394 // 入力チェック: cmd, plugin の文字列は英数字以外ありえない
395 foreach(array('cmd', 'plugin') as $var) {
396 if (isset($vars[$var]) && ! preg_match('/^[a-zA-Z][a-zA-Z0-9_]*$/', $vars[$var]))
397 unset($get[$var], $post[$var], $vars[$var]);
400 // 整形: page, strip_bracket()
401 if (isset($vars['page'])) {
402 $get['page'] = $post['page'] = $vars['page'] = strip_bracket($vars['page']);
404 $get['page'] = $post['page'] = $vars['page'] = '';
408 if (isset($vars['msg'])) {
409 $get['msg'] = $post['msg'] = $vars['msg'] = str_replace("\r", '', $vars['msg']);
413 if (isset($get['md5']) && $get['md5'] != '' &&
414 ! isset($vars['cmd']) && ! isset($vars['plugin'])) {
415 $get['cmd'] = $post['cmd'] = $vars['cmd'] = 'md5';
418 // cmdもpluginも指定されていない場合は、QUERY_STRINGをページ名かInterWikiNameであるとみなす
419 if (! isset($vars['cmd']) && ! isset($vars['plugin'])) {
421 $get['cmd'] = $post['cmd'] = $vars['cmd'] = 'read';
422 $arg = $page_uri_handler->get_page_from_query_string($arg);
423 if ($arg === FALSE) {
424 // page is FALSE if page name is not valid
425 // Keep $arg is FALSE
427 // if $arg is null or '' ($arg is NOT FALSE)
430 $get['page'] = $post['page'] = $vars['page'] = $arg;
433 /////////////////////////////////////////////////
434 // 初期設定($WikiName,$BracketNameなど)
435 // $WikiName = '[A-Z][a-z]+(?:[A-Z][a-z]+)+';
436 // $WikiName = '\b[A-Z][a-z]+(?:[A-Z][a-z]+)+\b';
437 // $WikiName = '(?<![[:alnum:]])(?:[[:upper:]][[:lower:]]+){2,}(?![[:alnum:]])';
438 // $WikiName = '(?<!\w)(?:[A-Z][a-z]+){2,}(?!\w)';
441 $WikiName = '(?:[A-Z][a-z]+){2,}(?!\w)';
443 // $BracketName = ':?[^\s\]#&<>":]+:?';
444 $BracketName = '(?!\s):?[^\r\n\t\f\[\]<>#&":]+:?(?<!\s)';
447 $InterWikiName = '(\[\[)?((?:(?!\s|:|\]\]).)+):(.+)(?(1)\]\])';
450 $NotePattern = '/\(\(((?:(?>(?:(?!\(\()(?!\)\)(?:[^\)]|$)).)+)|(?R))*)\)\)/x'
453 /////////////////////////////////////////////////
454 // 初期設定(ユーザ定義ルール読み込み)
455 require(DATA_HOME . 'rules.ini.php');
457 /////////////////////////////////////////////////
458 // Load HTML Entity pattern
459 // This pattern is created by 'plugin/update_entities.inc.php'
460 require(LIB_DIR . 'html_entities.php');
462 /////////////////////////////////////////////////
466 $now = format_date(UTIME);
468 // 日時置換ルールを$line_rulesに加える
469 if ($usedatetime) $line_rules += $datetime_rules;
470 unset($datetime_rules);
472 // フェイスマークを$line_rulesに加える
473 if ($usefacemark) $line_rules += $facemark_rules;
474 unset($facemark_rules);
476 // 実体参照パターンおよびシステムで使用するパターンを$line_rulesに加える
477 $line_rules = array_merge(array(
478 '&(#[0-9]+|#x[0-9a-f]+|' . get_html_entity_pattern() . ');' => '&$1;',
479 "\r" => '<br />' . "\n", /* 行末にチルダは改行 */