Merge pull request #4056 from dokuwiki-translate/lang_update_704_1694501527
[dokuwiki.git] / inc / init.php
blob467d4eb7f6101f2fe03e3711dbf029891beea97a
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 // load libraries
206 require_once(DOKU_INC . 'vendor/autoload.php');
207 require_once(DOKU_INC . 'inc/load.php');
209 // from now on everything is an exception
210 ErrorHandler::register();
212 // disable gzip if not available
213 define('DOKU_HAS_BZIP', function_exists('bzopen'));
214 define('DOKU_HAS_GZIP', function_exists('gzopen'));
215 if ($conf['compression'] == 'bz2' && !DOKU_HAS_BZIP) {
216 $conf['compression'] = 'gz';
218 if ($conf['compression'] == 'gz' && !DOKU_HAS_GZIP) {
219 $conf['compression'] = 0;
222 // input handle class
223 global $INPUT;
224 $INPUT = new Input();
226 // initialize plugin controller
227 $plugin_controller = new $plugin_controller_class();
229 // initialize the event handler
230 global $EVENT_HANDLER;
231 $EVENT_HANDLER = new EventHandler();
233 $local = $conf['lang'];
234 Event::createAndTrigger('INIT_LANG_LOAD', $local, 'init_lang', true);
237 // setup authentication system
238 if (!defined('NOSESSION')) {
239 auth_setup();
242 // setup mail system
243 mail_setup();
245 $nil = null;
246 Event::createAndTrigger('DOKUWIKI_INIT_DONE', $nil, null, false);
249 * Initializes the session
251 * Makes sure the passed session cookie is valid, invalid ones are ignored an a new session ID is issued
253 * @link http://stackoverflow.com/a/33024310/172068
254 * @link http://php.net/manual/en/session.configuration.php#ini.session.sid-length
256 function init_session()
258 global $conf;
259 session_name(DOKU_SESSION_NAME);
260 session_set_cookie_params([
261 'lifetime' => DOKU_SESSION_LIFETIME,
262 'path' => DOKU_SESSION_PATH,
263 'domain' => DOKU_SESSION_DOMAIN,
264 'secure' => ($conf['securecookie'] && is_ssl()),
265 'httponly' => true,
266 'samesite' => 'Lax',
269 // make sure the session cookie contains a valid session ID
270 if (isset($_COOKIE[DOKU_SESSION_NAME]) && !preg_match('/^[-,a-zA-Z0-9]{22,256}$/', $_COOKIE[DOKU_SESSION_NAME])) {
271 unset($_COOKIE[DOKU_SESSION_NAME]);
274 session_start();
279 * Checks paths from config file
281 function init_paths()
283 global $conf;
285 $paths = [
286 'datadir' => 'pages',
287 'olddir' => 'attic',
288 'mediadir' => 'media',
289 'mediaolddir' => 'media_attic',
290 'metadir' => 'meta',
291 'mediametadir' => 'media_meta',
292 'cachedir' => 'cache',
293 'indexdir' => 'index',
294 'lockdir' => 'locks',
295 'tmpdir' => 'tmp',
296 'logdir' => 'log',
299 foreach ($paths as $c => $p) {
300 $path = empty($conf[$c]) ? $conf['savedir'] . '/' . $p : $conf[$c];
301 $conf[$c] = init_path($path);
302 if (empty($conf[$c])) {
303 $path = fullpath($path);
304 nice_die("The $c ('$p') at $path is not found, isn't accessible or writable.
305 You should check your config and permission settings.
306 Or maybe you want to <a href=\"install.php\">run the
307 installer</a>?");
311 // path to old changelog only needed for upgrading
312 $conf['changelog_old'] = init_path(
313 $conf['changelog'] ?? $conf['savedir'] . '/changes.log'
315 if ($conf['changelog_old'] == '') {
316 unset($conf['changelog_old']);
318 // hardcoded changelog because it is now a cache that lives in meta
319 $conf['changelog'] = $conf['metadir'] . '/_dokuwiki.changes';
320 $conf['media_changelog'] = $conf['metadir'] . '/_media.changes';
324 * Load the language strings
326 * @param string $langCode language code, as passed by event handler
328 function init_lang($langCode)
330 //prepare language array
331 global $lang, $config_cascade;
332 $lang = [];
334 //load the language files
335 require(DOKU_INC . 'inc/lang/en/lang.php');
336 foreach ($config_cascade['lang']['core'] as $config_file) {
337 if (file_exists($config_file . 'en/lang.php')) {
338 include($config_file . 'en/lang.php');
342 if ($langCode && $langCode != 'en') {
343 if (file_exists(DOKU_INC . "inc/lang/$langCode/lang.php")) {
344 require(DOKU_INC . "inc/lang/$langCode/lang.php");
346 foreach ($config_cascade['lang']['core'] as $config_file) {
347 if (file_exists($config_file . "$langCode/lang.php")) {
348 include($config_file . "$langCode/lang.php");
355 * Checks the existence of certain files and creates them if missing.
357 function init_files()
359 global $conf;
361 $files = [$conf['indexdir'] . '/page.idx'];
363 foreach ($files as $file) {
364 if (!file_exists($file)) {
365 $fh = @fopen($file, 'a');
366 if ($fh) {
367 fclose($fh);
368 if ($conf['fperm']) chmod($file, $conf['fperm']);
369 } else {
370 nice_die("$file is not writable. Check your permissions settings!");
377 * Returns absolute path
379 * This tries the given path first, then checks in DOKU_INC.
380 * Check for accessibility on directories as well.
382 * @author Andreas Gohr <andi@splitbrain.org>
384 * @param string $path
386 * @return bool|string
388 function init_path($path)
390 // check existence
391 $p = fullpath($path);
392 if (!file_exists($p)) {
393 $p = fullpath(DOKU_INC . $path);
394 if (!file_exists($p)) {
395 return '';
399 // check writability
400 if (!@is_writable($p)) {
401 return '';
404 // check accessability (execute bit) for directories
405 if (@is_dir($p) && !file_exists("$p/.")) {
406 return '';
409 return $p;
413 * Sets the internal config values fperm and dperm which, when set,
414 * will be used to change the permission of a newly created dir or
415 * file with chmod. Considers the influence of the system's umask
416 * setting the values only if needed.
418 function init_creationmodes()
420 global $conf;
422 // Legacy support for old umask/dmask scheme
423 unset($conf['dmask']);
424 unset($conf['fmask']);
425 unset($conf['umask']);
427 $conf['fperm'] = false;
428 $conf['dperm'] = false;
430 // get system umask, fallback to 0 if none available
431 $umask = @umask();
432 if (!$umask) $umask = 0000;
434 // check what is set automatically by the system on file creation
435 // and set the fperm param if it's not what we want
436 $auto_fmode = 0666 & ~$umask;
437 if ($auto_fmode != $conf['fmode']) $conf['fperm'] = $conf['fmode'];
439 // check what is set automatically by the system on directory creation
440 // and set the dperm param if it's not what we want.
441 $auto_dmode = 0777 & ~$umask;
442 if ($auto_dmode != $conf['dmode']) $conf['dperm'] = $conf['dmode'];
446 * Returns the full absolute URL to the directory where
447 * DokuWiki is installed in (includes a trailing slash)
449 * !! Can not access $_SERVER values through $INPUT
450 * !! here as this function is called before $INPUT is
451 * !! initialized.
453 * @author Andreas Gohr <andi@splitbrain.org>
455 * @param null|bool $abs Return an absolute URL? (null defaults to $conf['canonical'])
457 * @return string
459 function getBaseURL($abs = null)
461 global $conf;
463 $abs ??= $conf['canonical'];
465 if (!empty($conf['basedir'])) {
466 $dir = $conf['basedir'];
467 } elseif (substr($_SERVER['SCRIPT_NAME'], -4) == '.php') {
468 $dir = dirname($_SERVER['SCRIPT_NAME']);
469 } elseif (substr($_SERVER['PHP_SELF'], -4) == '.php') {
470 $dir = dirname($_SERVER['PHP_SELF']);
471 } elseif ($_SERVER['DOCUMENT_ROOT'] && $_SERVER['SCRIPT_FILENAME']) {
472 $dir = preg_replace(
473 '/^' . preg_quote($_SERVER['DOCUMENT_ROOT'], '/') . '/',
475 $_SERVER['SCRIPT_FILENAME']
477 $dir = dirname('/' . $dir);
478 } else {
479 $dir = '.'; //probably wrong
482 $dir = str_replace('\\', '/', $dir); // bugfix for weird WIN behaviour
483 $dir = preg_replace('#//+#', '/', "/$dir/"); // ensure leading and trailing slashes
485 //handle script in lib/exe dir
486 $dir = preg_replace('!lib/exe/$!', '', $dir);
488 //handle script in lib/plugins dir
489 $dir = preg_replace('!lib/plugins/.*$!', '', $dir);
491 //finish here for relative URLs
492 if (!$abs) return $dir;
494 //use config if available, trim any slash from end of baseurl to avoid multiple consecutive slashes in the path
495 if (!empty($conf['baseurl'])) return rtrim($conf['baseurl'], '/') . $dir;
497 //split hostheader into host and port
498 if (isset($_SERVER['HTTP_HOST'])) {
499 $parsed_host = parse_url('http://' . $_SERVER['HTTP_HOST']);
500 $host = $parsed_host['host'] ?? '';
501 $port = $parsed_host['port'] ?? '';
502 } elseif (isset($_SERVER['SERVER_NAME'])) {
503 $parsed_host = parse_url('http://' . $_SERVER['SERVER_NAME']);
504 $host = $parsed_host['host'] ?? '';
505 $port = $parsed_host['port'] ?? '';
506 } else {
507 $host = php_uname('n');
508 $port = '';
511 if (!is_ssl()) {
512 $proto = 'http://';
513 if ($port == '80') {
514 $port = '';
516 } else {
517 $proto = 'https://';
518 if ($port == '443') {
519 $port = '';
523 if ($port !== '') $port = ':' . $port;
525 return $proto . $host . $port . $dir;
529 * Check if accessed via HTTPS
531 * Apache leaves ,$_SERVER['HTTPS'] empty when not available, IIS sets it to 'off'.
532 * 'false' and 'disabled' are just guessing
534 * @returns bool true when SSL is active
536 function is_ssl()
538 // check if we are behind a reverse proxy
539 if (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') == 'https') {
540 return true;
543 if (preg_match('/^(|off|false|disabled)$/i', $_SERVER['HTTPS'] ?? 'off')) {
544 return false;
547 return true;
551 * checks it is windows OS
552 * @return bool
554 function isWindows()
556 return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
560 * print a nice message even if no styles are loaded yet.
562 * @param integer|string $msg
564 function nice_die($msg)
566 echo<<<EOT
567 <!DOCTYPE html>
568 <html>
569 <head><title>DokuWiki Setup Error</title></head>
570 <body style="font-family: Arial, sans-serif">
571 <div style="width:60%; margin: auto; background-color: #fcc;
572 border: 1px solid #faa; padding: 0.5em 1em;">
573 <h1 style="font-size: 120%">DokuWiki Setup Error</h1>
574 <p>$msg</p>
575 </div>
576 </body>
577 </html>
578 EOT;
579 if (defined('DOKU_UNITTEST')) {
580 throw new RuntimeException('nice_die: ' . $msg);
582 exit(1);
586 * A realpath() replacement
588 * This function behaves similar to PHP's realpath() but does not resolve
589 * symlinks or accesses upper directories
591 * @author Andreas Gohr <andi@splitbrain.org>
592 * @author <richpageau at yahoo dot co dot uk>
593 * @link http://php.net/manual/en/function.realpath.php#75992
595 * @param string $path
596 * @param bool $exists
598 * @return bool|string
600 function fullpath($path, $exists = false)
602 static $run = 0;
603 $root = '';
604 $iswin = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' || !empty($GLOBALS['DOKU_UNITTEST_ASSUME_WINDOWS']));
606 // find the (indestructable) root of the path - keeps windows stuff intact
607 if ($path[0] == '/') {
608 $root = '/';
609 } elseif ($iswin) {
610 // match drive letter and UNC paths
611 if (preg_match('!^([a-zA-z]:)(.*)!', $path, $match)) {
612 $root = $match[1] . '/';
613 $path = $match[2];
614 } elseif (preg_match('!^(\\\\\\\\[^\\\\/]+\\\\[^\\\\/]+[\\\\/])(.*)!', $path, $match)) {
615 $root = $match[1];
616 $path = $match[2];
619 $path = str_replace('\\', '/', $path);
621 // if the given path wasn't absolute already, prepend the script path and retry
622 if (!$root) {
623 $base = dirname($_SERVER['SCRIPT_FILENAME']);
624 $path = $base . '/' . $path;
625 if ($run == 0) { // avoid endless recursion when base isn't absolute for some reason
626 $run++;
627 return fullpath($path, $exists);
630 $run = 0;
632 // canonicalize
633 $path = explode('/', $path);
634 $newpath = [];
635 foreach ($path as $p) {
636 if ($p === '' || $p === '.') continue;
637 if ($p === '..') {
638 array_pop($newpath);
639 continue;
641 $newpath[] = $p;
643 $finalpath = $root . implode('/', $newpath);
645 // check for existence when needed (except when unit testing)
646 if ($exists && !defined('DOKU_UNITTEST') && !file_exists($finalpath)) {
647 return false;
649 return $finalpath;