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