Merge pull request #4104 from m-martin-78/xfhsupport
[dokuwiki.git] / inc / init.php
blob12048af49220b05c93e5b5e388ca2bbd95523501
1 <?php
3 /**
4 * Initialize some defaults needed for DokuWiki
5 */
7 use dokuwiki\Extension\PluginController;
8 use dokuwiki\ErrorHandler;
9 use dokuwiki\Input\Input;
10 use dokuwiki\Extension\Event;
11 use dokuwiki\Extension\EventHandler;
13 /**
14 * timing Dokuwiki execution
16 * @param integer $start
18 * @return mixed
20 function delta_time($start = 0)
22 return microtime(true) - ((float)$start);
24 define('DOKU_START_TIME', delta_time());
26 global $config_cascade;
27 $config_cascade = [];
29 // if available load a preload config file
30 $preload = fullpath(__DIR__) . '/preload.php';
31 if (file_exists($preload)) include($preload);
33 // define the include path
34 if (!defined('DOKU_INC')) define('DOKU_INC', fullpath(__DIR__ . '/../') . '/');
36 // define Plugin dir
37 if (!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN', DOKU_INC . 'lib/plugins/');
39 // define config path (packagers may want to change this to /etc/dokuwiki/)
40 if (!defined('DOKU_CONF')) define('DOKU_CONF', DOKU_INC . 'conf/');
42 // check for error reporting override or set error reporting to sane values
43 if (!defined('DOKU_E_LEVEL') && file_exists(DOKU_CONF . 'report_e_all')) {
44 define('DOKU_E_LEVEL', E_ALL);
46 if (!defined('DOKU_E_LEVEL')) {
47 error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT);
48 } else {
49 error_reporting(DOKU_E_LEVEL);
52 // avoid caching issues #1594
53 header('Vary: Cookie');
55 // init memory caches
56 global $cache_revinfo;
57 $cache_revinfo = [];
58 global $cache_wikifn;
59 $cache_wikifn = [];
60 global $cache_cleanid;
61 $cache_cleanid = [];
62 global $cache_authname;
63 $cache_authname = [];
64 global $cache_metadata;
65 $cache_metadata = [];
67 // always include 'inc/config_cascade.php'
68 // previously in preload.php set fields of $config_cascade will be merged with the defaults
69 include(DOKU_INC . 'inc/config_cascade.php');
71 //prepare config array()
72 global $conf;
73 $conf = [];
75 // load the global config file(s)
76 foreach (['default', 'local', 'protected'] as $config_group) {
77 if (empty($config_cascade['main'][$config_group])) continue;
78 foreach ($config_cascade['main'][$config_group] as $config_file) {
79 if (file_exists($config_file)) {
80 include($config_file);
85 //prepare license array()
86 global $license;
87 $license = [];
89 // load the license file(s)
90 foreach (['default', 'local'] as $config_group) {
91 if (empty($config_cascade['license'][$config_group])) continue;
92 foreach ($config_cascade['license'][$config_group] as $config_file) {
93 if (file_exists($config_file)) {
94 include($config_file);
99 // set timezone (as in pre 5.3.0 days)
100 date_default_timezone_set(@date_default_timezone_get());
102 // define baseURL
103 if (!defined('DOKU_REL')) define('DOKU_REL', getBaseURL(false));
104 if (!defined('DOKU_URL')) define('DOKU_URL', getBaseURL(true));
105 if (!defined('DOKU_BASE')) {
106 if ($conf['canonical']) {
107 define('DOKU_BASE', DOKU_URL);
108 } else {
109 define('DOKU_BASE', DOKU_REL);
113 // define whitespace
114 if (!defined('NL')) define('NL', "\n");
115 if (!defined('DOKU_LF')) define('DOKU_LF', "\n");
116 if (!defined('DOKU_TAB')) define('DOKU_TAB', "\t");
118 // define cookie and session id, append server port when securecookie is configured FS#1664
119 if (!defined('DOKU_COOKIE')) {
120 $serverPort = $_SERVER['SERVER_PORT'] ?? '';
121 define('DOKU_COOKIE', 'DW' . md5(DOKU_REL . (($conf['securecookie']) ? $serverPort : '')));
122 unset($serverPort);
125 // define main script
126 if (!defined('DOKU_SCRIPT')) define('DOKU_SCRIPT', 'doku.php');
128 if (!defined('DOKU_TPL')) {
130 * @deprecated 2012-10-13 replaced by more dynamic method
131 * @see tpl_basedir()
133 define('DOKU_TPL', DOKU_BASE . 'lib/tpl/' . $conf['template'] . '/');
136 if (!defined('DOKU_TPLINC')) {
138 * @deprecated 2012-10-13 replaced by more dynamic method
139 * @see tpl_incdir()
141 define('DOKU_TPLINC', DOKU_INC . 'lib/tpl/' . $conf['template'] . '/');
144 // make session rewrites XHTML compliant
145 @ini_set('arg_separator.output', '&amp;');
147 // make sure global zlib does not interfere FS#1132
148 @ini_set('zlib.output_compression', 'off');
150 // increase PCRE backtrack limit
151 @ini_set('pcre.backtrack_limit', '20971520');
153 // enable gzip compression if supported
154 $httpAcceptEncoding = $_SERVER['HTTP_ACCEPT_ENCODING'] ?? '';
155 $conf['gzip_output'] &= (strpos($httpAcceptEncoding, 'gzip') !== false);
156 global $ACT;
157 if (
158 $conf['gzip_output'] &&
159 !defined('DOKU_DISABLE_GZIP_OUTPUT') &&
160 function_exists('ob_gzhandler') &&
161 // Disable compression when a (compressed) sitemap might be delivered
162 // See https://bugs.dokuwiki.org/index.php?do=details&task_id=2576
163 $ACT != 'sitemap'
165 ob_start('ob_gzhandler');
168 // init session
169 if (!headers_sent() && !defined('NOSESSION')) {
170 if (!defined('DOKU_SESSION_NAME')) define('DOKU_SESSION_NAME', "DokuWiki");
171 if (!defined('DOKU_SESSION_LIFETIME')) define('DOKU_SESSION_LIFETIME', 0);
172 if (!defined('DOKU_SESSION_PATH')) {
173 $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
174 define('DOKU_SESSION_PATH', $cookieDir);
176 if (!defined('DOKU_SESSION_DOMAIN')) define('DOKU_SESSION_DOMAIN', '');
178 // start the session
179 init_session();
181 // load left over messages
182 if (isset($_SESSION[DOKU_COOKIE]['msg'])) {
183 $MSG = $_SESSION[DOKU_COOKIE]['msg'];
184 unset($_SESSION[DOKU_COOKIE]['msg']);
188 // don't let cookies ever interfere with request vars
189 $_REQUEST = array_merge($_GET, $_POST);
191 // we don't want a purge URL to be digged
192 if (isset($_REQUEST['purge']) && !empty($_SERVER['HTTP_REFERER'])) unset($_REQUEST['purge']);
194 // precalculate file creation modes
195 init_creationmodes();
197 // make real paths and check them
198 init_paths();
199 init_files();
201 // setup plugin controller class (can be overwritten in preload.php)
202 global $plugin_controller_class, $plugin_controller;
203 if (empty($plugin_controller_class)) $plugin_controller_class = PluginController::class;
205 // autoloader
206 require_once(DOKU_INC . 'inc/load.php');
208 // from now on everything is an exception
209 ErrorHandler::register();
211 // disable gzip if not available
212 define('DOKU_HAS_BZIP', function_exists('bzopen'));
213 define('DOKU_HAS_GZIP', function_exists('gzopen'));
214 if ($conf['compression'] == 'bz2' && !DOKU_HAS_BZIP) {
215 $conf['compression'] = 'gz';
217 if ($conf['compression'] == 'gz' && !DOKU_HAS_GZIP) {
218 $conf['compression'] = 0;
221 // input handle class
222 global $INPUT;
223 $INPUT = new Input();
225 // initialize plugin controller
226 $plugin_controller = new $plugin_controller_class();
228 // initialize the event handler
229 global $EVENT_HANDLER;
230 $EVENT_HANDLER = new EventHandler();
232 $local = $conf['lang'];
233 Event::createAndTrigger('INIT_LANG_LOAD', $local, 'init_lang', true);
236 // setup authentication system
237 if (!defined('NOSESSION')) {
238 auth_setup();
241 // setup mail system
242 mail_setup();
244 $nil = null;
245 Event::createAndTrigger('DOKUWIKI_INIT_DONE', $nil, null, false);
248 * Initializes the session
250 * Makes sure the passed session cookie is valid, invalid ones are ignored an a new session ID is issued
252 * @link http://stackoverflow.com/a/33024310/172068
253 * @link http://php.net/manual/en/session.configuration.php#ini.session.sid-length
255 function init_session()
257 global $conf;
258 session_name(DOKU_SESSION_NAME);
259 session_set_cookie_params([
260 'lifetime' => DOKU_SESSION_LIFETIME,
261 'path' => DOKU_SESSION_PATH,
262 'domain' => DOKU_SESSION_DOMAIN,
263 'secure' => ($conf['securecookie'] && is_ssl()),
264 'httponly' => true,
265 'samesite' => 'Lax',
268 // make sure the session cookie contains a valid session ID
269 if (isset($_COOKIE[DOKU_SESSION_NAME]) && !preg_match('/^[-,a-zA-Z0-9]{22,256}$/', $_COOKIE[DOKU_SESSION_NAME])) {
270 unset($_COOKIE[DOKU_SESSION_NAME]);
273 session_start();
278 * Checks paths from config file
280 function init_paths()
282 global $conf;
284 $paths = [
285 'datadir' => 'pages',
286 'olddir' => 'attic',
287 'mediadir' => 'media',
288 'mediaolddir' => 'media_attic',
289 'metadir' => 'meta',
290 'mediametadir' => 'media_meta',
291 'cachedir' => 'cache',
292 'indexdir' => 'index',
293 'lockdir' => 'locks',
294 'tmpdir' => 'tmp',
295 'logdir' => 'log',
298 foreach ($paths as $c => $p) {
299 $path = empty($conf[$c]) ? $conf['savedir'] . '/' . $p : $conf[$c];
300 $conf[$c] = init_path($path);
301 if (empty($conf[$c])) {
302 $path = fullpath($path);
303 nice_die("The $c ('$p') at $path is not found, isn't accessible or writable.
304 You should check your config and permission settings.
305 Or maybe you want to <a href=\"install.php\">run the
306 installer</a>?");
310 // path to old changelog only needed for upgrading
311 $conf['changelog_old'] = init_path(
312 $conf['changelog'] ?? $conf['savedir'] . '/changes.log'
314 if ($conf['changelog_old'] == '') {
315 unset($conf['changelog_old']);
317 // hardcoded changelog because it is now a cache that lives in meta
318 $conf['changelog'] = $conf['metadir'] . '/_dokuwiki.changes';
319 $conf['media_changelog'] = $conf['metadir'] . '/_media.changes';
323 * Load the language strings
325 * @param string $langCode language code, as passed by event handler
327 function init_lang($langCode)
329 //prepare language array
330 global $lang, $config_cascade;
331 $lang = [];
333 //load the language files
334 require(DOKU_INC . 'inc/lang/en/lang.php');
335 foreach ($config_cascade['lang']['core'] as $config_file) {
336 if (file_exists($config_file . 'en/lang.php')) {
337 include($config_file . 'en/lang.php');
341 if ($langCode && $langCode != 'en') {
342 if (file_exists(DOKU_INC . "inc/lang/$langCode/lang.php")) {
343 require(DOKU_INC . "inc/lang/$langCode/lang.php");
345 foreach ($config_cascade['lang']['core'] as $config_file) {
346 if (file_exists($config_file . "$langCode/lang.php")) {
347 include($config_file . "$langCode/lang.php");
354 * Checks the existence of certain files and creates them if missing.
356 function init_files()
358 global $conf;
360 $files = [$conf['indexdir'] . '/page.idx'];
362 foreach ($files as $file) {
363 if (!file_exists($file)) {
364 $fh = @fopen($file, 'a');
365 if ($fh) {
366 fclose($fh);
367 if ($conf['fperm']) chmod($file, $conf['fperm']);
368 } else {
369 nice_die("$file is not writable. Check your permissions settings!");
376 * Returns absolute path
378 * This tries the given path first, then checks in DOKU_INC.
379 * Check for accessibility on directories as well.
381 * @author Andreas Gohr <andi@splitbrain.org>
383 * @param string $path
385 * @return bool|string
387 function init_path($path)
389 // check existence
390 $p = fullpath($path);
391 if (!file_exists($p)) {
392 $p = fullpath(DOKU_INC . $path);
393 if (!file_exists($p)) {
394 return '';
398 // check writability
399 if (!@is_writable($p)) {
400 return '';
403 // check accessability (execute bit) for directories
404 if (@is_dir($p) && !file_exists("$p/.")) {
405 return '';
408 return $p;
412 * Sets the internal config values fperm and dperm which, when set,
413 * will be used to change the permission of a newly created dir or
414 * file with chmod. Considers the influence of the system's umask
415 * setting the values only if needed.
417 function init_creationmodes()
419 global $conf;
421 // Legacy support for old umask/dmask scheme
422 unset($conf['dmask']);
423 unset($conf['fmask']);
424 unset($conf['umask']);
426 $conf['fperm'] = false;
427 $conf['dperm'] = false;
429 // get system umask, fallback to 0 if none available
430 $umask = @umask();
431 if (!$umask) $umask = 0000;
433 // check what is set automatically by the system on file creation
434 // and set the fperm param if it's not what we want
435 $auto_fmode = 0666 & ~$umask;
436 if ($auto_fmode != $conf['fmode']) $conf['fperm'] = $conf['fmode'];
438 // check what is set automatically by the system on directory creation
439 // and set the dperm param if it's not what we want.
440 $auto_dmode = 0777 & ~$umask;
441 if ($auto_dmode != $conf['dmode']) $conf['dperm'] = $conf['dmode'];
445 * Returns the full absolute URL to the directory where
446 * DokuWiki is installed in (includes a trailing slash)
448 * !! Can not access $_SERVER values through $INPUT
449 * !! here as this function is called before $INPUT is
450 * !! initialized.
452 * @author Andreas Gohr <andi@splitbrain.org>
454 * @param null|bool $abs Return an absolute URL? (null defaults to $conf['canonical'])
456 * @return string
458 function getBaseURL($abs = null)
460 global $conf;
462 $abs ??= $conf['canonical'];
464 if (!empty($conf['basedir'])) {
465 $dir = $conf['basedir'];
466 } elseif (substr($_SERVER['SCRIPT_NAME'], -4) == '.php') {
467 $dir = dirname($_SERVER['SCRIPT_NAME']);
468 } elseif (substr($_SERVER['PHP_SELF'], -4) == '.php') {
469 $dir = dirname($_SERVER['PHP_SELF']);
470 } elseif ($_SERVER['DOCUMENT_ROOT'] && $_SERVER['SCRIPT_FILENAME']) {
471 $dir = preg_replace(
472 '/^' . preg_quote($_SERVER['DOCUMENT_ROOT'], '/') . '/',
474 $_SERVER['SCRIPT_FILENAME']
476 $dir = dirname('/' . $dir);
477 } else {
478 $dir = ''; //probably wrong, but we assume it's in the root
481 $dir = str_replace('\\', '/', $dir); // bugfix for weird WIN behaviour
482 $dir = preg_replace('#//+#', '/', "/$dir/"); // ensure leading and trailing slashes
484 //handle script in lib/exe dir
485 $dir = preg_replace('!lib/exe/$!', '', $dir);
487 //handle script in lib/plugins dir
488 $dir = preg_replace('!lib/plugins/.*$!', '', $dir);
490 //finish here for relative URLs
491 if (!$abs) return $dir;
493 //use config if available, trim any slash from end of baseurl to avoid multiple consecutive slashes in the path
494 if (!empty($conf['baseurl'])) return rtrim($conf['baseurl'], '/') . $dir;
496 //split hostheader into host and port
497 if (isset($_SERVER['HTTP_HOST'])) {
498 if ((!empty($conf['trustedproxy'])) && isset($_SERVER['HTTP_X_FORWARDED_HOST'])
499 && preg_match('/' . $conf['trustedproxy'] . '/', $_SERVER['REMOTE_ADDR'])) {
500 $cur_host = $_SERVER['HTTP_X_FORWARDED_HOST'];
501 } else {
502 $cur_host = $_SERVER['HTTP_HOST'];
504 $parsed_host = parse_url('http://' . $cur_host);
505 $host = $parsed_host['host'] ?? '';
506 $port = $parsed_host['port'] ?? '';
507 } elseif (isset($_SERVER['SERVER_NAME'])) {
508 $parsed_host = parse_url('http://' . $_SERVER['SERVER_NAME']);
509 $host = $parsed_host['host'] ?? '';
510 $port = $parsed_host['port'] ?? '';
511 } else {
512 $host = php_uname('n');
513 $port = '';
516 if (!is_ssl()) {
517 $proto = 'http://';
518 if ($port == '80') {
519 $port = '';
521 } else {
522 $proto = 'https://';
523 if ($port == '443') {
524 $port = '';
528 if ($port !== '') $port = ':' . $port;
530 return $proto . $host . $port . $dir;
534 * Check if accessed via HTTPS
536 * Apache leaves ,$_SERVER['HTTPS'] empty when not available, IIS sets it to 'off'.
537 * 'false' and 'disabled' are just guessing
539 * @returns bool true when SSL is active
541 function is_ssl()
543 // check if we are behind a reverse proxy
544 if ((!empty($conf['trustedproxy'])) && isset($_SERVER['HTTP_X_FORWARDED_PROTO'])
545 && preg_match('/' . $conf['trustedproxy'] . '/', $_SERVER['REMOTE_ADDR'])
546 && ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) {
547 return true;
550 if (preg_match('/^(|off|false|disabled)$/i', $_SERVER['HTTPS'] ?? 'off')) {
551 return false;
554 return true;
558 * checks it is windows OS
559 * @return bool
561 function isWindows()
563 return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
567 * print a nice message even if no styles are loaded yet.
569 * @param integer|string $msg
571 function nice_die($msg)
573 echo<<<EOT
574 <!DOCTYPE html>
575 <html>
576 <head><title>DokuWiki Setup Error</title></head>
577 <body style="font-family: Arial, sans-serif">
578 <div style="width:60%; margin: auto; background-color: #fcc;
579 border: 1px solid #faa; padding: 0.5em 1em;">
580 <h1 style="font-size: 120%">DokuWiki Setup Error</h1>
581 <p>$msg</p>
582 </div>
583 </body>
584 </html>
585 EOT;
586 if (defined('DOKU_UNITTEST')) {
587 throw new RuntimeException('nice_die: ' . $msg);
589 exit(1);
593 * A realpath() replacement
595 * This function behaves similar to PHP's realpath() but does not resolve
596 * symlinks or accesses upper directories
598 * @author Andreas Gohr <andi@splitbrain.org>
599 * @author <richpageau at yahoo dot co dot uk>
600 * @link http://php.net/manual/en/function.realpath.php#75992
602 * @param string $path
603 * @param bool $exists
605 * @return bool|string
607 function fullpath($path, $exists = false)
609 static $run = 0;
610 $root = '';
611 $iswin = (isWindows() || !empty($GLOBALS['DOKU_UNITTEST_ASSUME_WINDOWS']));
613 // find the (indestructable) root of the path - keeps windows stuff intact
614 if ($path[0] == '/') {
615 $root = '/';
616 } elseif ($iswin) {
617 // match drive letter and UNC paths
618 if (preg_match('!^([a-zA-z]:)(.*)!', $path, $match)) {
619 $root = $match[1] . '/';
620 $path = $match[2];
621 } elseif (preg_match('!^(\\\\\\\\[^\\\\/]+\\\\[^\\\\/]+[\\\\/])(.*)!', $path, $match)) {
622 $root = $match[1];
623 $path = $match[2];
626 $path = str_replace('\\', '/', $path);
628 // if the given path wasn't absolute already, prepend the script path and retry
629 if (!$root) {
630 $base = dirname($_SERVER['SCRIPT_FILENAME']);
631 $path = $base . '/' . $path;
632 if ($run == 0) { // avoid endless recursion when base isn't absolute for some reason
633 $run++;
634 return fullpath($path, $exists);
637 $run = 0;
639 // canonicalize
640 $path = explode('/', $path);
641 $newpath = [];
642 foreach ($path as $p) {
643 if ($p === '' || $p === '.') continue;
644 if ($p === '..') {
645 array_pop($newpath);
646 continue;
648 $newpath[] = $p;
650 $finalpath = $root . implode('/', $newpath);
652 // check for existence when needed (except when unit testing)
653 if ($exists && !defined('DOKU_UNITTEST') && !file_exists($finalpath)) {
654 return false;
656 return $finalpath;