xref: /dokuwiki/inc/init.php (revision 9399c87e10527bd9270ac34f45432bcff3a2b473)
1<?php
2
3/**
4 * Initialize some defaults needed for DokuWiki
5 */
6
7use dokuwiki\Ip;
8use dokuwiki\Extension\PluginController;
9use dokuwiki\ErrorHandler;
10use dokuwiki\Input\Input;
11use dokuwiki\Extension\Event;
12use dokuwiki\Extension\EventHandler;
13
14/**
15 * timing Dokuwiki execution
16 *
17 * @param integer $start
18 *
19 * @return mixed
20 */
21function delta_time($start = 0)
22{
23    return microtime(true) - ((float)$start);
24}
25define('DOKU_START_TIME', delta_time());
26
27global $config_cascade;
28$config_cascade = [];
29
30// if available load a preload config file
31$preload = fullpath(__DIR__) . '/preload.php';
32if (file_exists($preload)) include($preload);
33
34// define the include path
35if (!defined('DOKU_INC')) define('DOKU_INC', fullpath(__DIR__ . '/../') . '/');
36
37// define Plugin dir
38if (!defined('DOKU_PLUGIN'))  define('DOKU_PLUGIN', DOKU_INC . 'lib/plugins/');
39
40// define config path (packagers may want to change this to /etc/dokuwiki/)
41if (!defined('DOKU_CONF')) define('DOKU_CONF', DOKU_INC . 'conf/');
42
43// check for error reporting override or set error reporting to sane values
44if (!defined('DOKU_E_LEVEL') && file_exists(DOKU_CONF . 'report_e_all')) {
45    define('DOKU_E_LEVEL', E_ALL);
46}
47if (!defined('DOKU_E_LEVEL')) {
48    error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
49} else {
50    error_reporting(DOKU_E_LEVEL);
51}
52
53// autoloader
54require_once(DOKU_INC . 'inc/load.php');
55
56// avoid caching issues #1594
57header('Vary: Cookie');
58
59// init memory caches
60global $cache_revinfo;
61       $cache_revinfo = [];
62global $cache_wikifn;
63       $cache_wikifn = [];
64global $cache_cleanid;
65       $cache_cleanid = [];
66global $cache_authname;
67       $cache_authname = [];
68global $cache_metadata;
69       $cache_metadata = [];
70
71// always include 'inc/config_cascade.php'
72// previously in preload.php set fields of $config_cascade will be merged with the defaults
73include(DOKU_INC . 'inc/config_cascade.php');
74
75//prepare config array()
76global $conf;
77$conf = [];
78
79// load the global config file(s)
80foreach (['default', 'local', 'protected'] as $config_group) {
81    if (empty($config_cascade['main'][$config_group])) continue;
82    foreach ($config_cascade['main'][$config_group] as $config_file) {
83        if (file_exists($config_file)) {
84            include($config_file);
85        }
86    }
87}
88
89// precalculate file creation modes
90init_creationmodes();
91
92// make real paths and check them
93init_paths();
94init_files();
95
96//prepare license array()
97global $license;
98$license = [];
99
100// load the license file(s)
101foreach (['default', 'local'] as $config_group) {
102    if (empty($config_cascade['license'][$config_group])) continue;
103    foreach ($config_cascade['license'][$config_group] as $config_file) {
104        if (file_exists($config_file)) {
105            include($config_file);
106        }
107    }
108}
109
110if ($conf === []) {
111    nice_die("No configuration found in " . DOKU_CONF . ".");
112}
113
114// set timezone (as in pre 5.3.0 days)
115date_default_timezone_set(@date_default_timezone_get());
116
117
118// don't let cookies ever interfere with request vars
119$_REQUEST = array_merge($_GET, $_POST);
120// input handle class
121global $INPUT;
122$INPUT = new Input();
123
124
125// define baseURL
126if (!defined('DOKU_REL')) define('DOKU_REL', getBaseURL(false));
127if (!defined('DOKU_URL')) define('DOKU_URL', getBaseURL(true));
128if (!defined('DOKU_BASE')) {
129    if ($conf['canonical']) {
130        define('DOKU_BASE', DOKU_URL);
131    } else {
132        define('DOKU_BASE', DOKU_REL);
133    }
134}
135
136// define whitespace
137if (!defined('NL')) define('NL', "\n");
138if (!defined('DOKU_LF')) define('DOKU_LF', "\n");
139if (!defined('DOKU_TAB')) define('DOKU_TAB', "\t");
140
141// define cookie and session id, append server port when securecookie is configured FS#1664
142if (!defined('DOKU_COOKIE')) {
143    $serverPort = $_SERVER['SERVER_PORT'] ?? '';
144    define('DOKU_COOKIE', 'DW' . md5(DOKU_REL . (($conf['securecookie']) ? $serverPort : '')));
145    unset($serverPort);
146}
147
148// define main script
149if (!defined('DOKU_SCRIPT')) define('DOKU_SCRIPT', 'doku.php');
150
151if (!defined('DOKU_TPL')) {
152    /**
153     * @deprecated 2012-10-13 replaced by more dynamic method
154     * @see tpl_basedir()
155     */
156    define('DOKU_TPL', DOKU_BASE . 'lib/tpl/' . $conf['template'] . '/');
157}
158
159if (!defined('DOKU_TPLINC')) {
160    /**
161     * @deprecated 2012-10-13 replaced by more dynamic method
162     * @see tpl_incdir()
163     */
164    define('DOKU_TPLINC', DOKU_INC . 'lib/tpl/' . $conf['template'] . '/');
165}
166
167// make session rewrites XHTML compliant
168@ini_set('arg_separator.output', '&amp;');
169
170// make sure global zlib does not interfere FS#1132
171@ini_set('zlib.output_compression', 'off');
172
173// increase PCRE backtrack limit
174@ini_set('pcre.backtrack_limit', '20971520');
175
176// enable gzip compression if supported
177$httpAcceptEncoding = $_SERVER['HTTP_ACCEPT_ENCODING'] ?? '';
178$conf['gzip_output'] &= (strpos($httpAcceptEncoding, 'gzip') !== false);
179global $ACT;
180if (
181    $conf['gzip_output'] &&
182        !defined('DOKU_DISABLE_GZIP_OUTPUT') &&
183        function_exists('ob_gzhandler') &&
184        // Disable compression when a (compressed) sitemap might be delivered
185        // See https://bugs.dokuwiki.org/index.php?do=details&task_id=2576
186        $ACT != 'sitemap'
187) {
188    ob_start('ob_gzhandler');
189}
190
191// init session
192if (!headers_sent() && !defined('NOSESSION')) {
193    if (!defined('DOKU_SESSION_NAME'))     define('DOKU_SESSION_NAME', "DokuWiki");
194    if (!defined('DOKU_SESSION_LIFETIME')) define('DOKU_SESSION_LIFETIME', 0);
195    if (!defined('DOKU_SESSION_PATH')) {
196        $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
197        define('DOKU_SESSION_PATH', $cookieDir);
198    }
199    if (!defined('DOKU_SESSION_DOMAIN'))   define('DOKU_SESSION_DOMAIN', '');
200
201    // start the session
202    init_session();
203
204    // load left over messages
205    if (isset($_SESSION[DOKU_COOKIE]['msg'])) {
206        $MSG = $_SESSION[DOKU_COOKIE]['msg'];
207        unset($_SESSION[DOKU_COOKIE]['msg']);
208    }
209}
210
211
212// we don't want a purge URL to be digged
213if (isset($_REQUEST['purge']) && !empty($_SERVER['HTTP_REFERER'])) unset($_REQUEST['purge']);
214
215
216// setup plugin controller class (can be overwritten in preload.php)
217global $plugin_controller_class, $plugin_controller;
218if (empty($plugin_controller_class)) $plugin_controller_class = PluginController::class;
219
220// from now on everything is an exception
221ErrorHandler::register();
222
223// disable gzip if not available
224define('DOKU_HAS_BZIP', function_exists('bzopen'));
225define('DOKU_HAS_GZIP', function_exists('gzopen'));
226if ($conf['compression'] == 'bz2' && !DOKU_HAS_BZIP) {
227    $conf['compression'] = 'gz';
228}
229if ($conf['compression'] == 'gz' && !DOKU_HAS_GZIP) {
230    $conf['compression'] = 0;
231}
232
233// initialize plugin controller
234$plugin_controller = new $plugin_controller_class();
235
236// initialize the event handler
237global $EVENT_HANDLER;
238$EVENT_HANDLER = new EventHandler();
239
240$local = $conf['lang'];
241Event::createAndTrigger('INIT_LANG_LOAD', $local, 'init_lang', true);
242
243
244// setup authentication system
245if (!defined('NOSESSION')) {
246    auth_setup();
247}
248
249// setup mail system
250mail_setup();
251
252$nil = null;
253Event::createAndTrigger('DOKUWIKI_INIT_DONE', $nil, null, false);
254
255/**
256 * Initializes the session
257 *
258 * Makes sure the passed session cookie is valid, invalid ones are ignored an a new session ID is issued
259 *
260 * @link http://stackoverflow.com/a/33024310/172068
261 * @link http://php.net/manual/en/session.configuration.php#ini.session.sid-length
262 */
263function init_session()
264{
265    global $conf;
266    session_name(DOKU_SESSION_NAME);
267    session_set_cookie_params([
268        'lifetime' => DOKU_SESSION_LIFETIME,
269        'path' => DOKU_SESSION_PATH,
270        'domain' => DOKU_SESSION_DOMAIN,
271        'secure' => ($conf['securecookie'] && Ip::isSsl()),
272        'httponly' => true,
273        'samesite' => 'Lax',
274    ]);
275
276    // make sure the session cookie contains a valid session ID
277    if (isset($_COOKIE[DOKU_SESSION_NAME]) && !preg_match('/^[-,a-zA-Z0-9]{22,256}$/', $_COOKIE[DOKU_SESSION_NAME])) {
278        unset($_COOKIE[DOKU_SESSION_NAME]);
279    }
280
281    session_start();
282}
283
284
285/**
286 * Checks paths from config file
287 */
288function init_paths()
289{
290    global $conf;
291
292    $paths = [
293        'datadir'   => 'pages',
294        'olddir'    => 'attic',
295        'mediadir'  => 'media',
296        'mediaolddir' => 'media_attic',
297        'metadir'   => 'meta',
298        'mediametadir' => 'media_meta',
299        'cachedir'  => 'cache',
300        'indexdir'  => 'index',
301        'lockdir'   => 'locks',
302        'tmpdir'    => 'tmp',
303        'logdir'    => 'log',
304    ];
305
306    foreach ($paths as $c => $p) {
307        $path = empty($conf[$c]) ? $conf['savedir'] . '/' . $p : $conf[$c];
308        $conf[$c] = init_path($path);
309        if (empty($conf[$c])) {
310            $path = fullpath($path);
311            nice_die("The $c ('$p') at $path is not found, isn't accessible or writable.
312                You should check your config and permission settings.
313                Or maybe you want to <a href=\"install.php\">run the
314                installer</a>?");
315        }
316    }
317
318    // path to old changelog only needed for upgrading
319    $conf['changelog_old'] = init_path(
320        $conf['changelog'] ?? $conf['savedir'] . '/changes.log'
321    );
322    if ($conf['changelog_old'] == '') {
323        unset($conf['changelog_old']);
324    }
325    // hardcoded changelog because it is now a cache that lives in meta
326    $conf['changelog'] = $conf['metadir'] . '/_dokuwiki.changes';
327    $conf['media_changelog'] = $conf['metadir'] . '/_media.changes';
328}
329
330/**
331 * Load the language strings
332 *
333 * @param string $langCode language code, as passed by event handler
334 */
335function init_lang($langCode)
336{
337    //prepare language array
338    global $lang, $config_cascade;
339    $lang = [];
340
341    //load the language files
342    require(DOKU_INC . 'inc/lang/en/lang.php');
343    foreach ($config_cascade['lang']['core'] as $config_file) {
344        if (file_exists($config_file . 'en/lang.php')) {
345            include($config_file . 'en/lang.php');
346        }
347    }
348
349    if ($langCode && $langCode != 'en') {
350        if (file_exists(DOKU_INC . "inc/lang/$langCode/lang.php")) {
351            require(DOKU_INC . "inc/lang/$langCode/lang.php");
352        }
353        foreach ($config_cascade['lang']['core'] as $config_file) {
354            if (file_exists($config_file . "$langCode/lang.php")) {
355                include($config_file . "$langCode/lang.php");
356            }
357        }
358    }
359}
360
361/**
362 * Checks the existence of certain files and creates them if missing.
363 */
364function init_files()
365{
366    global $conf;
367
368    $files = [$conf['indexdir'] . '/page.idx'];
369
370    foreach ($files as $file) {
371        if (!file_exists($file)) {
372            $fh = @fopen($file, 'a');
373            if ($fh) {
374                fclose($fh);
375                if ($conf['fperm']) chmod($file, $conf['fperm']);
376            } else {
377                nice_die("$file is not writable. Check your permissions settings!");
378            }
379        }
380    }
381}
382
383/**
384 * Returns absolute path
385 *
386 * This tries the given path first, then checks in DOKU_INC.
387 * Check for accessibility on directories as well.
388 *
389 * @author Andreas Gohr <andi@splitbrain.org>
390 *
391 * @param string $path
392 *
393 * @return bool|string
394 */
395function init_path($path)
396{
397    // check existence
398    $p = fullpath($path);
399    if (!file_exists($p)) {
400        $p = fullpath(DOKU_INC . $path);
401        if (!file_exists($p)) {
402            return '';
403        }
404    }
405
406    // check writability
407    if (!@is_writable($p)) {
408        return '';
409    }
410
411    // check accessability (execute bit) for directories
412    if (@is_dir($p) && !file_exists("$p/.")) {
413        return '';
414    }
415
416    return $p;
417}
418
419/**
420 * Sets the internal config values fperm and dperm which, when set,
421 * will be used to change the permission of a newly created dir or
422 * file with chmod. Considers the influence of the system's umask
423 * setting the values only if needed.
424 */
425function init_creationmodes()
426{
427    global $conf;
428
429    // Legacy support for old umask/dmask scheme
430    unset($conf['dmask']);
431    unset($conf['fmask']);
432    unset($conf['umask']);
433
434    $conf['fperm'] = false;
435    $conf['dperm'] = false;
436
437    // get system umask, fallback to 0 if none available
438    $umask = @umask();
439    if (!$umask) $umask = 0000;
440
441    // check what is set automatically by the system on file creation
442    // and set the fperm param if it's not what we want
443    $auto_fmode = 0666 & ~$umask;
444    if ($auto_fmode != $conf['fmode']) $conf['fperm'] = $conf['fmode'];
445
446    // check what is set automatically by the system on directory creation
447    // and set the dperm param if it's not what we want.
448    $auto_dmode = 0777 & ~$umask;
449    if ($auto_dmode != $conf['dmode']) $conf['dperm'] = $conf['dmode'];
450}
451
452/**
453 * Returns the full absolute URL to the directory where
454 * DokuWiki is installed in (includes a trailing slash)
455 *
456 * !! Can not access $_SERVER values through $INPUT
457 * !! here as this function is called before $INPUT is
458 * !! initialized.
459 *
460 * @author Andreas Gohr <andi@splitbrain.org>
461 *
462 * @param null|bool $abs Return an absolute URL? (null defaults to $conf['canonical'])
463 *
464 * @return string
465 */
466function getBaseURL($abs = null)
467{
468    global $conf;
469
470    $abs ??= $conf['canonical'];
471
472    if (!empty($conf['basedir'])) {
473        $dir = $conf['basedir'];
474    } elseif (substr($_SERVER['SCRIPT_NAME'], -4) == '.php') {
475        $dir = dirname($_SERVER['SCRIPT_NAME']);
476    } elseif (substr($_SERVER['PHP_SELF'], -4) == '.php') {
477        $dir = dirname($_SERVER['PHP_SELF']);
478    } elseif ($_SERVER['DOCUMENT_ROOT'] && $_SERVER['SCRIPT_FILENAME']) {
479        $dir = preg_replace(
480            '/^' . preg_quote($_SERVER['DOCUMENT_ROOT'], '/') . '/',
481            '',
482            $_SERVER['SCRIPT_FILENAME']
483        );
484        $dir = dirname('/' . $dir);
485    } else {
486        $dir = ''; //probably wrong, but we assume it's in the root
487    }
488
489    $dir = str_replace('\\', '/', $dir);             // bugfix for weird WIN behaviour
490    $dir = preg_replace('#//+#', '/', "/$dir/");     // ensure leading and trailing slashes
491
492    //handle script in lib/exe dir
493    $dir = preg_replace('!lib/exe/$!', '', $dir);
494
495    //handle script in lib/plugins dir
496    $dir = preg_replace('!lib/plugins/.*$!', '', $dir);
497
498    //finish here for relative URLs
499    if (!$abs) return $dir;
500
501    //use config if available, trim any slash from end of baseurl to avoid multiple consecutive slashes in the path
502    if (!empty($conf['baseurl'])) return rtrim($conf['baseurl'], '/') . $dir;
503
504    //split hostheader into host and port
505    $hostname = Ip::hostName();
506    $parsed_host = parse_url('http://' . $hostname);
507    $host = $parsed_host['host'] ?? '';
508    $port = $parsed_host['port'] ?? '';
509
510    if (!Ip::isSsl()) {
511        $proto = 'http://';
512        if ($port == '80') {
513            $port = '';
514        }
515    } else {
516        $proto = 'https://';
517        if ($port == '443') {
518            $port = '';
519        }
520    }
521
522    if ($port !== '') $port = ':' . $port;
523
524    return $proto . $host . $port . $dir;
525}
526
527/**
528 * @deprecated 2025-06-03
529 */
530function is_ssl()
531{
532    dbg_deprecated('Ip::isSsl()');
533    return Ip::isSsl();
534}
535
536/**
537 * checks it is windows OS
538 * @return bool
539 */
540function isWindows()
541{
542    return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
543}
544
545/**
546 * print a nice message even if no styles are loaded yet.
547 *
548 * @param integer|string $msg
549 */
550function nice_die($msg)
551{
552    echo<<<EOT
553<!DOCTYPE html>
554<html>
555<head><title>DokuWiki Setup Error</title></head>
556<body style="font-family: Arial, sans-serif">
557    <div style="width:60%; margin: auto; background-color: #fcc;
558                border: 1px solid #faa; padding: 0.5em 1em;">
559        <h1 style="font-size: 120%">DokuWiki Setup Error</h1>
560        <p>$msg</p>
561    </div>
562</body>
563</html>
564EOT;
565    if (defined('DOKU_UNITTEST')) {
566        throw new RuntimeException('nice_die: ' . $msg);
567    }
568    exit(1);
569}
570
571/**
572 * A realpath() replacement
573 *
574 * This function behaves similar to PHP's realpath() but does not resolve
575 * symlinks or accesses upper directories
576 *
577 * @author Andreas Gohr <andi@splitbrain.org>
578 * @author <richpageau at yahoo dot co dot uk>
579 * @link   http://php.net/manual/en/function.realpath.php#75992
580 *
581 * @param string $path
582 * @param bool $exists
583 *
584 * @return bool|string
585 */
586function fullpath($path, $exists = false)
587{
588    static $run = 0;
589    $root  = '';
590    $iswin = (isWindows() || !empty($GLOBALS['DOKU_UNITTEST_ASSUME_WINDOWS']));
591
592    // find the (indestructable) root of the path - keeps windows stuff intact
593    if ($path[0] == '/') {
594        $root = '/';
595    } elseif ($iswin) {
596        // match drive letter and UNC paths
597        if (preg_match('!^([a-zA-z]:)(.*)!', $path, $match)) {
598            $root = $match[1] . '/';
599            $path = $match[2];
600        } elseif (preg_match('!^(\\\\\\\\[^\\\\/]+\\\\[^\\\\/]+[\\\\/])(.*)!', $path, $match)) {
601            $root = $match[1];
602            $path = $match[2];
603        }
604    }
605    $path = str_replace('\\', '/', $path);
606
607    // if the given path wasn't absolute already, prepend the script path and retry
608    if (!$root) {
609        $base = dirname($_SERVER['SCRIPT_FILENAME']);
610        $path = $base . '/' . $path;
611        if ($run == 0) { // avoid endless recursion when base isn't absolute for some reason
612            $run++;
613            return fullpath($path, $exists);
614        }
615    }
616    $run = 0;
617
618    // canonicalize
619    $path = explode('/', $path);
620    $newpath = [];
621    foreach ($path as $p) {
622        if ($p === '' || $p === '.') continue;
623        if ($p === '..') {
624            array_pop($newpath);
625            continue;
626        }
627        $newpath[] = $p;
628    }
629    $finalpath = $root . implode('/', $newpath);
630
631    // check for existence when needed (except when unit testing)
632    if ($exists && !defined('DOKU_UNITTEST') && !file_exists($finalpath)) {
633        return false;
634    }
635    return $finalpath;
636}
637