Merge pull request #4346 from dokuwiki-translate/lang_update_987_1730912283
[dokuwiki.git] / inc / init.php
blob85568894c393b9e3e6bd81a2b69d85bfb0f808a6
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 (
499 (!empty($conf['trustedproxy'])) && isset($_SERVER['HTTP_X_FORWARDED_HOST'])
500 && preg_match('/' . $conf['trustedproxy'] . '/', $_SERVER['REMOTE_ADDR'])
502 $cur_host = $_SERVER['HTTP_X_FORWARDED_HOST'];
503 } else {
504 $cur_host = $_SERVER['HTTP_HOST'];
506 $parsed_host = parse_url('http://' . $cur_host);
507 $host = $parsed_host['host'] ?? '';
508 $port = $parsed_host['port'] ?? '';
509 } elseif (isset($_SERVER['SERVER_NAME'])) {
510 $parsed_host = parse_url('http://' . $_SERVER['SERVER_NAME']);
511 $host = $parsed_host['host'] ?? '';
512 $port = $parsed_host['port'] ?? '';
513 } else {
514 $host = php_uname('n');
515 $port = '';
518 if (!is_ssl()) {
519 $proto = 'http://';
520 if ($port == '80') {
521 $port = '';
523 } else {
524 $proto = 'https://';
525 if ($port == '443') {
526 $port = '';
530 if ($port !== '') $port = ':' . $port;
532 return $proto . $host . $port . $dir;
536 * Check if accessed via HTTPS
538 * Apache leaves ,$_SERVER['HTTPS'] empty when not available, IIS sets it to 'off'.
539 * 'false' and 'disabled' are just guessing
541 * @returns bool true when SSL is active
543 function is_ssl()
545 global $conf;
547 // check if we are behind a reverse proxy
548 if (
549 (!empty($conf['trustedproxy'])) && isset($_SERVER['HTTP_X_FORWARDED_PROTO'])
550 && preg_match('/' . $conf['trustedproxy'] . '/', $_SERVER['REMOTE_ADDR'])
551 && ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')
553 return true;
556 if (preg_match('/^(|off|false|disabled)$/i', $_SERVER['HTTPS'] ?? 'off')) {
557 return false;
560 return true;
564 * checks it is windows OS
565 * @return bool
567 function isWindows()
569 return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
573 * print a nice message even if no styles are loaded yet.
575 * @param integer|string $msg
577 function nice_die($msg)
579 echo<<<EOT
580 <!DOCTYPE html>
581 <html>
582 <head><title>DokuWiki Setup Error</title></head>
583 <body style="font-family: Arial, sans-serif">
584 <div style="width:60%; margin: auto; background-color: #fcc;
585 border: 1px solid #faa; padding: 0.5em 1em;">
586 <h1 style="font-size: 120%">DokuWiki Setup Error</h1>
587 <p>$msg</p>
588 </div>
589 </body>
590 </html>
591 EOT;
592 if (defined('DOKU_UNITTEST')) {
593 throw new RuntimeException('nice_die: ' . $msg);
595 exit(1);
599 * A realpath() replacement
601 * This function behaves similar to PHP's realpath() but does not resolve
602 * symlinks or accesses upper directories
604 * @author Andreas Gohr <andi@splitbrain.org>
605 * @author <richpageau at yahoo dot co dot uk>
606 * @link http://php.net/manual/en/function.realpath.php#75992
608 * @param string $path
609 * @param bool $exists
611 * @return bool|string
613 function fullpath($path, $exists = false)
615 static $run = 0;
616 $root = '';
617 $iswin = (isWindows() || !empty($GLOBALS['DOKU_UNITTEST_ASSUME_WINDOWS']));
619 // find the (indestructable) root of the path - keeps windows stuff intact
620 if ($path[0] == '/') {
621 $root = '/';
622 } elseif ($iswin) {
623 // match drive letter and UNC paths
624 if (preg_match('!^([a-zA-z]:)(.*)!', $path, $match)) {
625 $root = $match[1] . '/';
626 $path = $match[2];
627 } elseif (preg_match('!^(\\\\\\\\[^\\\\/]+\\\\[^\\\\/]+[\\\\/])(.*)!', $path, $match)) {
628 $root = $match[1];
629 $path = $match[2];
632 $path = str_replace('\\', '/', $path);
634 // if the given path wasn't absolute already, prepend the script path and retry
635 if (!$root) {
636 $base = dirname($_SERVER['SCRIPT_FILENAME']);
637 $path = $base . '/' . $path;
638 if ($run == 0) { // avoid endless recursion when base isn't absolute for some reason
639 $run++;
640 return fullpath($path, $exists);
643 $run = 0;
645 // canonicalize
646 $path = explode('/', $path);
647 $newpath = [];
648 foreach ($path as $p) {
649 if ($p === '' || $p === '.') continue;
650 if ($p === '..') {
651 array_pop($newpath);
652 continue;
654 $newpath[] = $p;
656 $finalpath = $root . implode('/', $newpath);
658 // check for existence when needed (except when unit testing)
659 if ($exists && !defined('DOKU_UNITTEST') && !file_exists($finalpath)) {
660 return false;
662 return $finalpath;