OSDN Git Service

BugTrack2/377 Add 'Template pages' label for template page list
[pukiwiki/pukiwiki.git] / lib / init.php
1 <?php
2 // PukiWiki - Yet another WikiWikiWeb clone.
3 // init.php
4 // Copyright
5 //   2002-2016 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.1_beta1');
14 define('S_COPYRIGHT',
15         '<strong>PukiWiki ' . S_VERSION . '</strong>' .
16         ' &copy; 2001-2016' .
17         ' <a href="http://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 ini_set('mbstring.http_input', 'pass');
105 mb_http_output('pass');
106 mb_detect_order('auto');
107
108 /////////////////////////////////////////////////
109 // INI_FILE: Require LANG_FILE
110
111 define('LANG_FILE_HINT', DATA_HOME . LANG . '.lng.php');        // For encoding hint
112 define('LANG_FILE',      DATA_HOME . UI_LANG . '.lng.php');     // For UI resource
113 $die = '';
114 foreach (array('LANG_FILE_HINT', 'LANG_FILE') as $langfile) {
115         if (! file_exists(constant($langfile)) || ! is_readable(constant($langfile))) {
116                 $die .= 'File is not found or not readable. (' . $langfile . ')' . "\n";
117         } else {
118                 require_once(constant($langfile));
119         }
120 }
121 if ($die) die_message(nl2br("\n\n" . $die));
122
123 /////////////////////////////////////////////////
124 // LANG_FILE: Init encoding hint
125
126 define('PKWK_ENCODING_HINT', isset($_LANG['encode_hint'][LANG]) ? $_LANG['encode_hint'][LANG] : '');
127 unset($_LANG['encode_hint']);
128
129 /////////////////////////////////////////////////
130 // LANG_FILE: Init severn days of the week
131
132 $weeklabels = $_msg_week;
133
134 /////////////////////////////////////////////////
135 // INI_FILE: Init $script
136
137 if (isset($script)) {
138         get_script_uri($script); // Init manually
139 } else {
140         $script = get_script_uri(); // Init automatically
141 }
142
143 /////////////////////////////////////////////////
144 // INI_FILE: $agents:  UserAgentの識別
145
146 $ua = 'HTTP_USER_AGENT';
147 $user_agent = $matches = array();
148
149 $user_agent['agent'] = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
150 unset(${$ua}, $_SERVER[$ua], $HTTP_SERVER_VARS[$ua], $ua);      // safety
151
152 foreach ($agents as $agent) {
153         if (preg_match($agent['pattern'], $user_agent['agent'], $matches)) {
154                 $user_agent['profile'] = isset($agent['profile']) ? $agent['profile'] : '';
155                 $user_agent['name']    = isset($matches[1]) ? $matches[1] : ''; // device or browser name
156                 $user_agent['vers']    = isset($matches[2]) ? $matches[2] : ''; // 's version
157                 break;
158         }
159 }
160 unset($agents, $matches);
161
162 // Profile-related init and setting
163 define('UA_PROFILE', isset($user_agent['profile']) ? $user_agent['profile'] : '');
164
165 define('UA_INI_FILE', DATA_HOME . UA_PROFILE . '.ini.php');
166 if (! file_exists(UA_INI_FILE) || ! is_readable(UA_INI_FILE)) {
167         die_message('UA_INI_FILE for "' . UA_PROFILE . '" not found.');
168 } else {
169         require(UA_INI_FILE); // Also manually
170 }
171
172 define('UA_NAME', isset($user_agent['name']) ? $user_agent['name'] : '');
173 define('UA_VERS', isset($user_agent['vers']) ? $user_agent['vers'] : '');
174 unset($user_agent);     // Unset after reading UA_INI_FILE
175
176 /////////////////////////////////////////////////
177 // ディレクトリのチェック
178
179 $die = '';
180 foreach(array('DATA_DIR', 'DIFF_DIR', 'BACKUP_DIR', 'CACHE_DIR') as $dir){
181         if (! is_writable(constant($dir)))
182                 $die .= 'Directory is not found or not writable (' . $dir . ')' . "\n";
183 }
184
185 // 設定ファイルの変数チェック
186 $temp = '';
187 foreach(array('rss_max', 'page_title', 'note_hr', 'related_link', 'show_passage',
188         'rule_related_str', 'load_template_func') as $var){
189         if (! isset(${$var})) $temp .= '$' . $var . "\n";
190 }
191 if ($temp) {
192         if ($die) $die .= "\n"; // A breath
193         $die .= 'Variable(s) not found: (Maybe the old *.ini.php?)' . "\n" . $temp;
194 }
195
196 $temp = '';
197 foreach(array('LANG', 'PLUGIN_DIR') as $def){
198         if (! defined($def)) $temp .= $def . "\n";
199 }
200 if ($temp) {
201         if ($die) $die .= "\n"; // A breath
202         $die .= 'Define(s) not found: (Maybe the old *.ini.php?)' . "\n" . $temp;
203 }
204
205 if($die) die_message(nl2br("\n\n" . $die));
206 unset($die, $temp);
207
208 /////////////////////////////////////////////////
209 // 必須のページが存在しなければ、空のファイルを作成する
210
211 foreach(array($defaultpage, $whatsnew, $interwiki) as $page){
212         if (! is_page($page)) pkwk_touch_file(get_filename($page));
213 }
214
215 /////////////////////////////////////////////////
216 // 外部からくる変数のチェック
217
218 // Prohibit $_GET attack
219 foreach (array('msg', 'pass') as $key) {
220         if (isset($_GET[$key])) die_message('Sorry, already reserved: ' . $key . '=');
221 }
222
223 // Expire risk
224 unset($HTTP_GET_VARS, $HTTP_POST_VARS); //, 'SERVER', 'ENV', 'SESSION', ...
225 unset($_REQUEST);       // Considered harmful
226
227 // Remove null character etc.
228 $_GET    = input_filter($_GET);
229 $_POST   = input_filter($_POST);
230 $_COOKIE = input_filter($_COOKIE);
231
232 // 文字コード変換 ($_POST)
233 // <form> で送信された文字 (ブラウザがエンコードしたデータ) のコードを変換
234 // POST method は常に form 経由なので、必ず変換する
235 //
236 if (isset($_POST['encode_hint']) && $_POST['encode_hint'] != '') {
237         // do_plugin_xxx() の中で、<form> に encode_hint を仕込んでいるので、
238         // encode_hint を用いてコード検出する。
239         // 全体を見てコード検出すると、機種依存文字や、妙なバイナリ
240         // コードが混入した場合に、コード検出に失敗する恐れがある。
241         $encode = mb_detect_encoding($_POST['encode_hint']);
242         mb_convert_variables(SOURCE_ENCODING, $encode, $_POST);
243
244 } else if (isset($_POST['charset']) && $_POST['charset'] != '') {
245         // TrackBack Ping で指定されていることがある
246         // うまくいかない場合は自動検出に切り替え
247         if (mb_convert_variables(SOURCE_ENCODING,
248             $_POST['charset'], $_POST) !== $_POST['charset']) {
249                 mb_convert_variables(SOURCE_ENCODING, 'auto', $_POST);
250         }
251
252 } else if (! empty($_POST)) {
253         // 全部まとめて、自動検出/変換
254         mb_convert_variables(SOURCE_ENCODING, 'auto', $_POST);
255 }
256
257 // 文字コード変換 ($_GET)
258 // GET method は form からの場合と、<a href="http://script/?key=value> の場合がある
259 // <a href...> の場合は、サーバーが rawurlencode しているので、コード変換は不要
260 if (isset($_GET['encode_hint']) && $_GET['encode_hint'] != '')
261 {
262         // form 経由の場合は、ブラウザがエンコードしているので、コード検出・変換が必要。
263         // encode_hint が含まれているはずなので、それを見て、コード検出した後、変換する。
264         // 理由は、post と同様
265         $encode = mb_detect_encoding($_GET['encode_hint']);
266         mb_convert_variables(SOURCE_ENCODING, $encode, $_GET);
267 }
268
269
270 /////////////////////////////////////////////////
271 // QUERY_STRINGを取得
272
273 // cmdもpluginも指定されていない場合は、QUERY_STRINGを
274 // ページ名かInterWikiNameであるとみなす
275 $arg = '';
276 if (isset($_SERVER['QUERY_STRING']) && $_SERVER['QUERY_STRING'] != '') {
277         global $g_query_string;
278         $g_query_string = $_SERVER['QUERY_STRING'];
279         $arg = & $_SERVER['QUERY_STRING'];
280 } else if (isset($_SERVER['argv']) && ! empty($_SERVER['argv'])) {
281         $arg = & $_SERVER['argv'][0];
282 }
283 if (PKWK_QUERY_STRING_MAX && strlen($arg) > PKWK_QUERY_STRING_MAX) {
284         // Something nasty attack?
285         pkwk_common_headers();
286         sleep(1);       // Fake processing, and/or process other threads
287         echo('Query string too long');
288         exit;
289 }
290 $arg = input_filter($arg); // \0 除去
291
292 // unset QUERY_STRINGs
293 foreach (array('QUERY_STRING', 'argv', 'argc') as $key) {
294         unset(${$key}, $_SERVER[$key], $HTTP_SERVER_VARS[$key]);
295 }
296 // $_SERVER['REQUEST_URI'] is used at func.php NOW
297 unset($REQUEST_URI, $HTTP_SERVER_VARS['REQUEST_URI']);
298
299 // mb_convert_variablesのバグ(?)対策: 配列で渡さないと落ちる
300 $arg = array($arg);
301 mb_convert_variables(SOURCE_ENCODING, 'auto', $arg);
302 $arg = $arg[0];
303
304 /////////////////////////////////////////////////
305 // QUERY_STRINGを分解してコード変換し、$_GET に上書き
306
307 // URI を urlencode せずに入力した場合に対処する
308 $matches = array();
309 foreach (explode('&', $arg) as $key_and_value) {
310         if (preg_match('/^([^=]+)=(.+)/', $key_and_value, $matches) &&
311             mb_detect_encoding($matches[2]) != 'ASCII') {
312                 $_GET[$matches[1]] = $matches[2];
313         }
314 }
315 unset($matches);
316
317 /////////////////////////////////////////////////
318 // GET, POST, COOKIE
319
320 $get    = & $_GET;
321 $post   = & $_POST;
322 $cookie = & $_COOKIE;
323
324 // GET + POST = $vars
325 if (empty($_POST)) {
326         $vars = & $_GET;  // Major pattern: Read-only access via GET
327 } else if (empty($_GET)) {
328         $vars = & $_POST; // Minor pattern: Write access via POST etc.
329 } else {
330         $vars = array_merge($_GET, $_POST); // Considered reliable than $_REQUEST
331 }
332
333 // 入力チェック: 'cmd=' and 'plugin=' can't live together
334 if (isset($vars['cmd']) && isset($vars['plugin']))
335         die('Using both cmd= and plugin= is not allowed');
336
337 // 入力チェック: cmd, plugin の文字列は英数字以外ありえない
338 foreach(array('cmd', 'plugin') as $var) {
339         if (isset($vars[$var]) && ! preg_match('/^[a-zA-Z][a-zA-Z0-9_]*$/', $vars[$var]))
340                 unset($get[$var], $post[$var], $vars[$var]);
341 }
342
343 // 整形: page, strip_bracket()
344 if (isset($vars['page'])) {
345         $get['page'] = $post['page'] = $vars['page']  = strip_bracket($vars['page']);
346 } else {
347         $get['page'] = $post['page'] = $vars['page'] = '';
348 }
349
350 // 整形: msg, 改行を取り除く
351 if (isset($vars['msg'])) {
352         $get['msg'] = $post['msg'] = $vars['msg'] = str_replace("\r", '', $vars['msg']);
353 }
354
355 // 後方互換性 (?md5=...)
356 if (isset($get['md5']) && $get['md5'] != '' &&
357     ! isset($vars['cmd']) && ! isset($vars['plugin'])) {
358         $get['cmd'] = $post['cmd'] = $vars['cmd'] = 'md5';
359 }
360
361 // cmdもpluginも指定されていない場合は、QUERY_STRINGをページ名かInterWikiNameであるとみなす
362 if (! isset($vars['cmd']) && ! isset($vars['plugin'])) {
363
364         $get['cmd']  = $post['cmd']  = $vars['cmd']  = 'read';
365
366         $arg = preg_replace("#^([^&]*)&.*$#", "$1", $arg);
367         if ($arg == '') $arg = $defaultpage;
368         $arg = rawurldecode($arg);
369         $arg = strip_bracket($arg);
370         $arg = input_filter($arg);
371         $get['page'] = $post['page'] = $vars['page'] = $arg;
372 }
373
374 /////////////////////////////////////////////////
375 // 初期設定($WikiName,$BracketNameなど)
376 // $WikiName = '[A-Z][a-z]+(?:[A-Z][a-z]+)+';
377 // $WikiName = '\b[A-Z][a-z]+(?:[A-Z][a-z]+)+\b';
378 // $WikiName = '(?<![[:alnum:]])(?:[[:upper:]][[:lower:]]+){2,}(?![[:alnum:]])';
379 // $WikiName = '(?<!\w)(?:[A-Z][a-z]+){2,}(?!\w)';
380
381 // BugTrack/304暫定対処
382 $WikiName = '(?:[A-Z][a-z]+){2,}(?!\w)';
383
384 // $BracketName = ':?[^\s\]#&<>":]+:?';
385 $BracketName = '(?!\s):?[^\r\n\t\f\[\]<>#&":]+:?(?<!\s)';
386
387 // InterWiki
388 $InterWikiName = '(\[\[)?((?:(?!\s|:|\]\]).)+):(.+)(?(1)\]\])';
389
390 // 注釈
391 $NotePattern = '/\(\(((?:(?>(?:(?!\(\()(?!\)\)(?:[^\)]|$)).)+)|(?R))*)\)\)/x';
392
393 /////////////////////////////////////////////////
394 // 初期設定(ユーザ定義ルール読み込み)
395 require(DATA_HOME . 'rules.ini.php');
396
397 /////////////////////////////////////////////////
398 // 初期設定(その他のグローバル変数)
399
400 // 現在時刻
401 $now = format_date(UTIME);
402
403 // 日時置換ルールを$line_rulesに加える
404 if ($usedatetime) $line_rules += $datetime_rules;
405 unset($datetime_rules);
406
407 // フェイスマークを$line_rulesに加える
408 if ($usefacemark) $line_rules += $facemark_rules;
409 unset($facemark_rules);
410
411 // 実体参照パターンおよびシステムで使用するパターンを$line_rulesに加える
412 //$entity_pattern = '[a-zA-Z0-9]{2,8}';
413 $entity_pattern = trim(join('', file(CACHE_DIR . 'entities.dat')));
414
415 $line_rules = array_merge(array(
416         '&amp;(#[0-9]+|#x[0-9a-f]+|' . $entity_pattern . ');' => '&$1;',
417         "\r"          => '<br />' . "\n",       /* 行末にチルダは改行 */
418 ), $line_rules);