OSDN Git Service

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