OSDN Git Service

2dedd736dc12db4ba22250c193143d50591c7736
[pukiwiki/pukiwiki.git] / lib / init.php
1 <?php
2 // PukiWiki - Yet another WikiWikiWeb clone.
3 // init.php
4 // Copyright
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
8 //
9 // Init PukiWiki here
10
11 // PukiWiki version / Copyright / Licence
12
13 define('S_VERSION', '1.5.4');
14 define('S_COPYRIGHT',
15         '<strong>PukiWiki ' . S_VERSION . '</strong>' .
16         ' &copy; 2001-2021' .
17         ' <a href="https://pukiwiki.osdn.jp/">PukiWiki Development Team</a>'
18 );
19
20 /////////////////////////////////////////////////
21 // Session security options
22
23 ini_set('session.use_strict_mode', 1);
24 ini_set('session.use_cookies', 1);
25 ini_set('session.use_only_cookies', 1);
26
27 /////////////////////////////////////////////////
28 // Init server variables
29
30 // Comapat and suppress notices
31 if (!isset($HTTP_SERVER_VARS)) $HTTP_SERVER_VARS = array();
32
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]);
37 }
38
39 /////////////////////////////////////////////////
40 // Init grobal variables
41
42 $foot_explain = array();        // Footnotes
43 $related      = array();        // Related pages
44 $head_tags    = array();        // XHTML tags in <head></head>
45
46 /////////////////////////////////////////////////
47 // Time settings
48
49 define('LOCALZONE', date('Z'));
50 define('UTIME', time() - LOCALZONE);
51 define('MUTIME', getmicrotime());
52
53 /////////////////////////////////////////////////
54 // Require INI_FILE
55
56 define('INI_FILE',  DATA_HOME . 'pukiwiki.ini.php');
57 $die = '';
58 if (! file_exists(INI_FILE) || ! is_readable(INI_FILE)) {
59         $die .= 'File is not found. (INI_FILE)' . "\n";
60 } else {
61         require(INI_FILE);
62 }
63 if ($die) die_message(nl2br("\n\n" . $die));
64
65 /////////////////////////////////////////////////
66 // INI_FILE: LANG に基づくエンコーディング設定
67
68 // MB_LANGUAGE: mb_language (for mbstring extension)
69 //   'uni'(means UTF-8), 'English', or 'Japanese'
70 // SOURCE_ENCODING: Internal content encoding (for mbstring extension)
71 //   'UTF-8', 'ASCII', or 'EUC-JP'
72 // CONTENT_CHARSET: Internal content encoding = Output content charset
73 //    (for DTD, htmlsc())
74 //   'UTF-8', 'iso-8859-1', 'EUC-JP' or ...
75
76 switch (LANG){
77 case 'en': define('MB_LANGUAGE', 'English' ); break;
78 case 'ja': define('MB_LANGUAGE', 'Japanese'); break;
79 case 'ko': define('MB_LANGUAGE', 'Korean'  ); break; //UTF-8 only
80         // See BugTrack2/13 for all hack about Korean support, //UTF-8 only
81         // and give us your report!                            //UTF-8 only
82 default: die_message('No such language "' . LANG . '"'); break;
83 }
84
85 define('PKWK_UTF8_ENABLE', 1); //UTF-8 only
86 if (defined('PKWK_UTF8_ENABLE')) {
87         define('SOURCE_ENCODING', 'UTF-8');
88         define('CONTENT_CHARSET', 'UTF-8');
89 } else {
90         switch (LANG){
91         case 'en':
92                 define('SOURCE_ENCODING', 'ASCII');
93                 define('CONTENT_CHARSET', 'iso-8859-1');
94                 break;
95         case 'ja':
96                 define('SOURCE_ENCODING', 'EUC-JP');
97                 define('CONTENT_CHARSET', 'EUC-JP');
98                 break;
99         }
100 }
101
102 mb_language(MB_LANGUAGE);
103 mb_internal_encoding(SOURCE_ENCODING);
104 mb_http_output('pass');
105 mb_detect_order('auto');
106
107 /////////////////////////////////////////////////
108 // INI_FILE: Require LANG_FILE
109
110 define('LANG_FILE_HINT', DATA_HOME . LANG . '.lng.php');        // For encoding hint
111 define('LANG_FILE',      DATA_HOME . UI_LANG . '.lng.php');     // For UI resource
112 $die = '';
113 foreach (array('LANG_FILE_HINT', 'LANG_FILE') as $langfile) {
114         if (! file_exists(constant($langfile)) || ! is_readable(constant($langfile))) {
115                 $die .= 'File is not found or not readable. (' . $langfile . ')' . "\n";
116         } else {
117                 require_once(constant($langfile));
118         }
119 }
120 if ($die) die_message(nl2br("\n\n" . $die));
121
122 /////////////////////////////////////////////////
123 // LANG_FILE: Init encoding hint
124
125 define('PKWK_ENCODING_HINT', isset($_LANG['encode_hint'][LANG]) ? $_LANG['encode_hint'][LANG] : '');
126 unset($_LANG['encode_hint']);
127
128 /////////////////////////////////////////////////
129 // LANG_FILE: Init severn days of the week
130
131 $weeklabels = $_msg_week;
132
133 /////////////////////////////////////////////////
134 // INI_FILE: Init $script
135
136 if (isset($script)) {
137         // Init manually
138         pkwk_script_uri_base(PKWK_URI_ABSOLUTE, true, $script);
139 } else {
140         // Init automatically
141         $script = pkwk_script_uri_base(PKWK_URI_ABSOLUTE, true);
142 }
143
144 // INI_FILE: Auth settings
145 if (isset($auth_type) && $auth_type === AUTH_TYPE_SAML) {
146         $auth_external_login_url_base = get_base_uri() . '?//cmd.saml//sso';
147 }
148
149
150 /////////////////////////////////////////////////
151 // INI_FILE: $agents:  UserAgentの識別
152
153 $ua = 'HTTP_USER_AGENT';
154 $user_agent = $matches = array();
155
156 $user_agent['agent'] = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
157
158 foreach ($agents as $agent) {
159         if (preg_match($agent['pattern'], $user_agent['agent'], $matches)) {
160                 $user_agent['profile'] = isset($agent['profile']) ? $agent['profile'] : '';
161                 $user_agent['name']    = isset($matches[1]) ? $matches[1] : ''; // device or browser name
162                 $user_agent['vers']    = isset($matches[2]) ? $matches[2] : ''; // 's version
163                 break;
164         }
165 }
166 unset($agents, $matches);
167
168 // Profile-related init and setting
169 define('UA_PROFILE', isset($user_agent['profile']) ? $user_agent['profile'] : '');
170
171 define('UA_INI_FILE', DATA_HOME . UA_PROFILE . '.ini.php');
172 if (! file_exists(UA_INI_FILE) || ! is_readable(UA_INI_FILE)) {
173         die_message('UA_INI_FILE for "' . UA_PROFILE . '" not found.');
174 } else {
175         require(UA_INI_FILE); // Also manually
176 }
177
178 define('UA_NAME', isset($user_agent['name']) ? $user_agent['name'] : '');
179 define('UA_VERS', isset($user_agent['vers']) ? $user_agent['vers'] : '');
180 unset($user_agent);     // Unset after reading UA_INI_FILE
181
182 /////////////////////////////////////////////////
183 // ディレクトリのチェック
184
185 $die = '';
186 foreach(array('DATA_DIR', 'DIFF_DIR', 'BACKUP_DIR', 'CACHE_DIR') as $dir){
187         if (! is_writable(constant($dir)))
188                 $die .= 'Directory is not found or not writable (' . $dir . ')' . "\n";
189 }
190
191 // 設定ファイルの変数チェック
192 $temp = '';
193 foreach(array('rss_max', 'page_title', 'note_hr', 'related_link', 'show_passage',
194         'rule_related_str', 'load_template_func') as $var){
195         if (! isset(${$var})) $temp .= '$' . $var . "\n";
196 }
197 if ($temp) {
198         if ($die) $die .= "\n"; // A breath
199         $die .= 'Variable(s) not found: (Maybe the old *.ini.php?)' . "\n" . $temp;
200 }
201
202 $temp = '';
203 foreach(array('LANG', 'PLUGIN_DIR') as $def){
204         if (! defined($def)) $temp .= $def . "\n";
205 }
206 if ($temp) {
207         if ($die) $die .= "\n"; // A breath
208         $die .= 'Define(s) not found: (Maybe the old *.ini.php?)' . "\n" . $temp;
209 }
210
211 if($die) die_message(nl2br("\n\n" . $die));
212 unset($die, $temp);
213
214 /////////////////////////////////////////////////
215 // 必須のページが存在しなければ、空のファイルを作成する
216
217 foreach(array($defaultpage, $whatsnew, $interwiki) as $page){
218         if (! is_page($page)) pkwk_touch_file(get_filename($page));
219 }
220
221 /////////////////////////////////////////////////
222 // 外部からくる変数のチェック
223
224 // Prohibit $_GET attack
225 foreach (array('msg', 'pass') as $key) {
226         if (isset($_GET[$key])) die_message('Sorry, already reserved: ' . $key . '=');
227 }
228
229 // Expire risk
230 unset($HTTP_GET_VARS, $HTTP_POST_VARS); //, 'SERVER', 'ENV', 'SESSION', ...
231 unset($_REQUEST);       // Considered harmful
232
233 // Remove null character etc.
234 $_GET    = input_filter($_GET);
235 $_POST   = input_filter($_POST);
236 $_COOKIE = input_filter($_COOKIE);
237
238 // 文字コード変換 ($_POST)
239 // <form> で送信された文字 (ブラウザがエンコードしたデータ) のコードを変換
240 // POST method は常に form 経由なので、必ず変換する
241 //
242 if (isset($_POST['encode_hint']) && $_POST['encode_hint'] != '') {
243         // do_plugin_xxx() の中で、<form> に encode_hint を仕込んでいるので、
244         // encode_hint を用いてコード検出する。
245         // 全体を見てコード検出すると、機種依存文字や、妙なバイナリ
246         // コードが混入した場合に、コード検出に失敗する恐れがある。
247         $encode = mb_detect_encoding($_POST['encode_hint']);
248         mb_convert_variables(SOURCE_ENCODING, $encode, $_POST);
249
250 } else if (isset($_POST['charset']) && $_POST['charset'] != '') {
251         // TrackBack Ping で指定されていることがある
252         // うまくいかない場合は自動検出に切り替え
253         if (mb_convert_variables(SOURCE_ENCODING,
254             $_POST['charset'], $_POST) !== $_POST['charset']) {
255                 mb_convert_variables(SOURCE_ENCODING, 'auto', $_POST);
256         }
257
258 } else if (! empty($_POST)) {
259         // 全部まとめて、自動検出/変換
260         mb_convert_variables(SOURCE_ENCODING, 'auto', $_POST);
261 }
262
263 // 文字コード変換 ($_GET)
264 // GET method は form からの場合と、<a href="http://script/?key=value> の場合がある
265 // <a href...> の場合は、サーバーが rawurlencode しているので、コード変換は不要
266 if (isset($_GET['encode_hint']) && $_GET['encode_hint'] != '')
267 {
268         // form 経由の場合は、ブラウザがエンコードしているので、コード検出・変換が必要。
269         // encode_hint が含まれているはずなので、それを見て、コード検出した後、変換する。
270         // 理由は、post と同様
271         $encode = mb_detect_encoding($_GET['encode_hint']);
272         mb_convert_variables(SOURCE_ENCODING, $encode, $_GET);
273 }
274
275
276 /////////////////////////////////////////////////
277 // QUERY_STRINGを取得
278
279 // cmdもpluginも指定されていない場合は、QUERY_STRINGを
280 // ページ名かInterWikiNameであるとみなす
281 $arg = '';
282 if (isset($_SERVER['QUERY_STRING']) && $_SERVER['QUERY_STRING'] != '') {
283         global $g_query_string;
284         $g_query_string = $_SERVER['QUERY_STRING'];
285         $arg = & $_SERVER['QUERY_STRING'];
286 } else if (isset($_SERVER['argv']) && ! empty($_SERVER['argv'])) {
287         $arg = & $_SERVER['argv'][0];
288 }
289 if (PKWK_QUERY_STRING_MAX && strlen($arg) > PKWK_QUERY_STRING_MAX) {
290         // Something nasty attack?
291         pkwk_common_headers();
292         sleep(1);       // Fake processing, and/or process other threads
293         echo('Query string too long');
294         exit;
295 }
296 $arg = input_filter($arg); // \0 除去
297
298 // Convert QueryString by PageURIHandler
299 $arg_replaced = $pkwk_page_uri_handler->filter_raw_query_string($arg);
300 if ($arg_replaced !== $arg) {
301         $_GET = array();
302         $m = array();
303         foreach (explode('&', $arg_replaced) as $kv) {
304                 if (preg_match('/^([^=]+)(=(.+))?/', $kv, $matches)) {
305                         $_GET[$m[1]] = is_null($m[3]) ? '' : $m[3];
306                 }
307         }
308         unset($m);
309         $arg = $arg_replaced;
310 }
311 unset($arg_replaced);
312
313 // unset QUERY_STRINGs
314 foreach (array('QUERY_STRING', 'argv', 'argc') as $key) {
315         unset(${$key}, $_SERVER[$key], $HTTP_SERVER_VARS[$key]);
316 }
317 // $_SERVER['REQUEST_URI'] is used at func.php NOW
318 unset($REQUEST_URI, $HTTP_SERVER_VARS['REQUEST_URI']);
319
320 // mb_convert_variablesのバグ(?)対策: 配列で渡さないと落ちる
321 $arg = array($arg);
322 mb_convert_variables(SOURCE_ENCODING, 'auto', $arg);
323 $arg = $arg[0];
324
325 /////////////////////////////////////////////////
326 // QUERY_STRINGを分解してコード変換し、$_GET に上書き
327
328 // URI を urlencode せずに入力した場合に対処する
329 $matches = array();
330 foreach (explode('&', $arg) as $key_and_value) {
331         if (preg_match('/^([^=]+)=(.+)/', $key_and_value, $matches) &&
332             mb_detect_encoding($matches[2]) != 'ASCII') {
333                 $_GET[$matches[1]] = $matches[2];
334         }
335 }
336 unset($matches);
337
338 /////////////////////////////////////////////////
339 // GET, POST, COOKIE
340
341 $get    = & $_GET;
342 $post   = & $_POST;
343 $cookie = & $_COOKIE;
344
345 // GET + POST = $vars
346 if (empty($_POST)) {
347         $vars = & $_GET;  // Major pattern: Read-only access via GET
348 } else if (empty($_GET)) {
349         $vars = & $_POST; // Minor pattern: Write access via POST etc.
350 } else {
351         $vars = array_merge($_GET, $_POST); // Considered reliable than $_REQUEST
352 }
353
354 /**
355  * Parse specified format query_string as params.
356  *
357  * For example: ?//key1.value2//key2.value2
358  */
359 function parse_query_string_ext($query_string) {
360         $vars = array();
361         $m = null;
362         if (preg_match('#^//[^&]*#', $query_string, $m)) {
363                 foreach (explode('//', $m[0]) as $item) {
364                         $sp = explode('.', $item, 2);
365                         if (isset($sp[0])) {
366                                 if (isset($sp[1])) {
367                                         $vars[$sp[0]] = $sp[1];
368                                 } else {
369                                         $vars[$sp[0]] = '';
370                                 }
371                         }
372                 }
373         }
374         return $vars;
375 }
376 if (isset($g_query_string) && $g_query_string) {
377         if (substr($g_query_string, 0, 2) === '//') {
378                 // Parse ?//key.value//key.value format query string
379                 $vars = array_merge($vars, parse_query_string_ext($g_query_string));
380         }
381 }
382
383
384 // 入力チェック: 'cmd=' and 'plugin=' can't live together
385 if (isset($vars['cmd']) && isset($vars['plugin']))
386         die('Using both cmd= and plugin= is not allowed');
387
388 // 入力チェック: cmd, plugin の文字列は英数字以外ありえない
389 foreach(array('cmd', 'plugin') as $var) {
390         if (isset($vars[$var]) && ! preg_match('/^[a-zA-Z][a-zA-Z0-9_]*$/', $vars[$var]))
391                 unset($get[$var], $post[$var], $vars[$var]);
392 }
393
394 // 整形: page, strip_bracket()
395 if (isset($vars['page'])) {
396         $get['page'] = $post['page'] = $vars['page']  = strip_bracket($vars['page']);
397 } else {
398         $get['page'] = $post['page'] = $vars['page'] = '';
399 }
400
401 // 整形: msg, 改行を取り除く
402 if (isset($vars['msg'])) {
403         $get['msg'] = $post['msg'] = $vars['msg'] = str_replace("\r", '', $vars['msg']);
404 }
405
406 // 後方互換性 (?md5=...)
407 if (isset($get['md5']) && $get['md5'] != '' &&
408     ! isset($vars['cmd']) && ! isset($vars['plugin'])) {
409         $get['cmd'] = $post['cmd'] = $vars['cmd'] = 'md5';
410 }
411
412 // cmdもpluginも指定されていない場合は、QUERY_STRINGをページ名かInterWikiNameであるとみなす
413 if (! isset($vars['cmd']) && ! isset($vars['plugin'])) {
414
415         $get['cmd']  = $post['cmd']  = $vars['cmd']  = 'read';
416         $arg = $pkwk_page_uri_handler->get_page_from_query_string($arg);
417         if (!$arg) {
418                 $arg = $defaultpage;
419         }
420         $get['page'] = $post['page'] = $vars['page'] = $arg;
421 }
422
423 /////////////////////////////////////////////////
424 // 初期設定($WikiName,$BracketNameなど)
425 // $WikiName = '[A-Z][a-z]+(?:[A-Z][a-z]+)+';
426 // $WikiName = '\b[A-Z][a-z]+(?:[A-Z][a-z]+)+\b';
427 // $WikiName = '(?<![[:alnum:]])(?:[[:upper:]][[:lower:]]+){2,}(?![[:alnum:]])';
428 // $WikiName = '(?<!\w)(?:[A-Z][a-z]+){2,}(?!\w)';
429
430 // BugTrack/304暫定対処
431 $WikiName = '(?:[A-Z][a-z]+){2,}(?!\w)';
432
433 // $BracketName = ':?[^\s\]#&<>":]+:?';
434 $BracketName = '(?!\s):?[^\r\n\t\f\[\]<>#&":]+:?(?<!\s)';
435
436 // InterWiki
437 $InterWikiName = '(\[\[)?((?:(?!\s|:|\]\]).)+):(.+)(?(1)\]\])';
438
439 // 注釈
440 $NotePattern = '/\(\(((?:(?>(?:(?!\(\()(?!\)\)(?:[^\)]|$)).)+)|(?R))*)\)\)/x'
441         . get_preg_u();
442
443 /////////////////////////////////////////////////
444 // 初期設定(ユーザ定義ルール読み込み)
445 require(DATA_HOME . 'rules.ini.php');
446
447 /////////////////////////////////////////////////
448 // Load HTML Entity pattern
449 // This pattern is created by 'plugin/update_entities.inc.php'
450 require(LIB_DIR . 'html_entities.php');
451
452 /////////////////////////////////////////////////
453 // 初期設定(その他のグローバル変数)
454
455 // 現在時刻
456 $now = format_date(UTIME);
457
458 // 日時置換ルールを$line_rulesに加える
459 if ($usedatetime) $line_rules += $datetime_rules;
460 unset($datetime_rules);
461
462 // フェイスマークを$line_rulesに加える
463 if ($usefacemark) $line_rules += $facemark_rules;
464 unset($facemark_rules);
465
466 // 実体参照パターンおよびシステムで使用するパターンを$line_rulesに加える
467 $line_rules = array_merge(array(
468         '&amp;(#[0-9]+|#x[0-9a-f]+|' . get_html_entity_pattern() . ');' => '&$1;',
469         "\r"          => '<br />' . "\n",       /* 行末にチルダは改行 */
470 ), $line_rules);