xref: /dokuwiki/inc/init.php (revision 6c16a3a9aa602bb7e269fb6d5d18e1353e17f97f)
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 & ~E_STRICT);
48} else {
49    error_reporting(DOKU_E_LEVEL);
50}
51
52// avoid caching issues #1594
53header('Vary: Cookie');
54
55// init memory caches
56global $cache_revinfo;
57       $cache_revinfo = [];
58global $cache_wikifn;
59       $cache_wikifn = [];
60global $cache_cleanid;
61       $cache_cleanid = [];
62global $cache_authname;
63       $cache_authname = [];
64global $cache_metadata;
65       $cache_metadata = [];
66
67// always include 'inc/config_cascade.php'
68// previously in preload.php set fields of $config_cascade will be merged with the defaults
69include(DOKU_INC . 'inc/config_cascade.php');
70
71//prepare config array()
72global $conf;
73$conf = [];
74
75// load the global config file(s)
76foreach (['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);
81        }
82    }
83}
84
85//prepare license array()
86global $license;
87$license = [];
88
89// load the license file(s)
90foreach (['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);
95        }
96    }
97}
98
99// set timezone (as in pre 5.3.0 days)
100date_default_timezone_set(@date_default_timezone_get());
101
102// define baseURL
103if (!defined('DOKU_REL')) define('DOKU_REL', getBaseURL(false));
104if (!defined('DOKU_URL')) define('DOKU_URL', getBaseURL(true));
105if (!defined('DOKU_BASE')) {
106    if ($conf['canonical']) {
107        define('DOKU_BASE', DOKU_URL);
108    } else {
109        define('DOKU_BASE', DOKU_REL);
110    }
111}
112
113// define whitespace
114if (!defined('NL')) define('NL', "\n");
115if (!defined('DOKU_LF')) define('DOKU_LF', "\n");
116if (!defined('DOKU_TAB')) define('DOKU_TAB', "\t");
117
118// define cookie and session id, append server port when securecookie is configured FS#1664
119if (!defined('DOKU_COOKIE')) {
120    $serverPort = $_SERVER['SERVER_PORT'] ?? '';
121    define('DOKU_COOKIE', 'DW' . md5(DOKU_REL . (($conf['securecookie']) ? $serverPort : '')));
122    unset($serverPort);
123}
124
125// define main script
126if (!defined('DOKU_SCRIPT')) define('DOKU_SCRIPT', 'doku.php');
127
128if (!defined('DOKU_TPL')) {
129    /**
130     * @deprecated 2012-10-13 replaced by more dynamic method
131     * @see tpl_basedir()
132     */
133    define('DOKU_TPL', DOKU_BASE . 'lib/tpl/' . $conf['template'] . '/');
134}
135
136if (!defined('DOKU_TPLINC')) {
137    /**
138     * @deprecated 2012-10-13 replaced by more dynamic method
139     * @see tpl_incdir()
140     */
141    define('DOKU_TPLINC', DOKU_INC . 'lib/tpl/' . $conf['template'] . '/');
142}
143
144// make session rewrites XHTML compliant
145@ini_set('arg_separator.output', '&amp;');
146
147// make sure global zlib does not interfere FS#1132
148@ini_set('zlib.output_compression', 'off');
149
150// increase PCRE backtrack limit
151@ini_set('pcre.backtrack_limit', '20971520');
152
153// enable gzip compression if supported
154$httpAcceptEncoding = $_SERVER['HTTP_ACCEPT_ENCODING'] ?? '';
155$conf['gzip_output'] &= (strpos($httpAcceptEncoding, 'gzip') !== false);
156global $ACT;
157if (
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'
164) {
165    ob_start('ob_gzhandler');
166}
167
168// init session
169if (!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);
175    }
176    if (!defined('DOKU_SESSION_DOMAIN'))   define('DOKU_SESSION_DOMAIN', '');
177
178    // start the session
179    init_session();
180
181    // load left over messages
182    if (isset($_SESSION[DOKU_COOKIE]['msg'])) {
183        $MSG = $_SESSION[DOKU_COOKIE]['msg'];
184        unset($_SESSION[DOKU_COOKIE]['msg']);
185    }
186}
187
188// don't let cookies ever interfere with request vars
189$_REQUEST = array_merge($_GET, $_POST);
190
191// we don't want a purge URL to be digged
192if (isset($_REQUEST['purge']) && !empty($_SERVER['HTTP_REFERER'])) unset($_REQUEST['purge']);
193
194// precalculate file creation modes
195init_creationmodes();
196
197// make real paths and check them
198init_paths();
199init_files();
200
201// setup plugin controller class (can be overwritten in preload.php)
202global $plugin_controller_class, $plugin_controller;
203if (empty($plugin_controller_class)) $plugin_controller_class = PluginController::class;
204
205// load libraries
206require_once(DOKU_INC . 'vendor/autoload.php');
207require_once(DOKU_INC . 'inc/load.php');
208
209// from now on everything is an exception
210ErrorHandler::register();
211
212// disable gzip if not available
213define('DOKU_HAS_BZIP', function_exists('bzopen'));
214define('DOKU_HAS_GZIP', function_exists('gzopen'));
215if ($conf['compression'] == 'bz2' && !DOKU_HAS_BZIP) {
216    $conf['compression'] = 'gz';
217}
218if ($conf['compression'] == 'gz' && !DOKU_HAS_GZIP) {
219    $conf['compression'] = 0;
220}
221
222// input handle class
223global $INPUT;
224$INPUT = new Input();
225
226// initialize plugin controller
227$plugin_controller = new $plugin_controller_class();
228
229// initialize the event handler
230global $EVENT_HANDLER;
231$EVENT_HANDLER = new EventHandler();
232
233$local = $conf['lang'];
234Event::createAndTrigger('INIT_LANG_LOAD', $local, 'init_lang', true);
235
236
237// setup authentication system
238if (!defined('NOSESSION')) {
239    auth_setup();
240}
241
242// setup mail system
243mail_setup();
244
245$nil = null;
246Event::createAndTrigger('DOKUWIKI_INIT_DONE', $nil, null, false);
247
248/**
249 * Initializes the session
250 *
251 * Makes sure the passed session cookie is valid, invalid ones are ignored an a new session ID is issued
252 *
253 * @link http://stackoverflow.com/a/33024310/172068
254 * @link http://php.net/manual/en/session.configuration.php#ini.session.sid-length
255 */
256function init_session()
257{
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',
267    ]);
268
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]);
272    }
273
274    session_start();
275}
276
277
278/**
279 * Checks paths from config file
280 */
281function init_paths()
282{
283    global $conf;
284
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',
297    ];
298
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>?");
308        }
309    }
310
311    // path to old changelog only needed for upgrading
312    $conf['changelog_old'] = init_path(
313        $conf['changelog'] ?? $conf['savedir'] . '/changes.log'
314    );
315    if ($conf['changelog_old'] == '') {
316        unset($conf['changelog_old']);
317    }
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';
321}
322
323/**
324 * Load the language strings
325 *
326 * @param string $langCode language code, as passed by event handler
327 */
328function init_lang($langCode)
329{
330    //prepare language array
331    global $lang, $config_cascade;
332    $lang = [];
333
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');
339        }
340    }
341
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");
345        }
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");
349            }
350        }
351    }
352}
353
354/**
355 * Checks the existence of certain files and creates them if missing.
356 */
357function init_files()
358{
359    global $conf;
360
361    $files = [$conf['indexdir'] . '/page.idx'];
362
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!");
371            }
372        }
373    }
374}
375
376/**
377 * Returns absolute path
378 *
379 * This tries the given path first, then checks in DOKU_INC.
380 * Check for accessibility on directories as well.
381 *
382 * @author Andreas Gohr <andi@splitbrain.org>
383 *
384 * @param string $path
385 *
386 * @return bool|string
387 */
388function init_path($path)
389{
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 '';
396        }
397    }
398
399    // check writability
400    if (!@is_writable($p)) {
401        return '';
402    }
403
404    // check accessability (execute bit) for directories
405    if (@is_dir($p) && !file_exists("$p/.")) {
406        return '';
407    }
408
409    return $p;
410}
411
412/**
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.
417 */
418function init_creationmodes()
419{
420    global $conf;
421
422    // Legacy support for old umask/dmask scheme
423    unset($conf['dmask']);
424    unset($conf['fmask']);
425    unset($conf['umask']);
426
427    $conf['fperm'] = false;
428    $conf['dperm'] = false;
429
430    // get system umask, fallback to 0 if none available
431    $umask = @umask();
432    if (!$umask) $umask = 0000;
433
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'];
438
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'];
443}
444
445/**
446 * Returns the full absolute URL to the directory where
447 * DokuWiki is installed in (includes a trailing slash)
448 *
449 * !! Can not access $_SERVER values through $INPUT
450 * !! here as this function is called before $INPUT is
451 * !! initialized.
452 *
453 * @author Andreas Gohr <andi@splitbrain.org>
454 *
455 * @param null|bool $abs Return an absolute URL? (null defaults to $conf['canonical'])
456 *
457 * @return string
458 */
459function getBaseURL($abs = null)
460{
461    global $conf;
462
463    $abs ??= $conf['canonical'];
464
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'], '/') . '/',
474            '',
475            $_SERVER['SCRIPT_FILENAME']
476        );
477        $dir = dirname('/' . $dir);
478    } else {
479        $dir = '.'; //probably wrong
480    }
481
482    $dir = str_replace('\\', '/', $dir);             // bugfix for weird WIN behaviour
483    $dir = preg_replace('#//+#', '/', "/$dir/");     // ensure leading and trailing slashes
484
485    //handle script in lib/exe dir
486    $dir = preg_replace('!lib/exe/$!', '', $dir);
487
488    //handle script in lib/plugins dir
489    $dir = preg_replace('!lib/plugins/.*$!', '', $dir);
490
491    //finish here for relative URLs
492    if (!$abs) return $dir;
493
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;
496
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 = '';
509    }
510
511    if (!is_ssl()) {
512        $proto = 'http://';
513        if ($port == '80') {
514            $port = '';
515        }
516    } else {
517        $proto = 'https://';
518        if ($port == '443') {
519            $port = '';
520        }
521    }
522
523    if ($port !== '') $port = ':' . $port;
524
525    return $proto . $host . $port . $dir;
526}
527
528/**
529 * Check if accessed via HTTPS
530 *
531 * Apache leaves ,$_SERVER['HTTPS'] empty when not available, IIS sets it to 'off'.
532 * 'false' and 'disabled' are just guessing
533 *
534 * @returns bool true when SSL is active
535 */
536function is_ssl()
537{
538    // check if we are behind a reverse proxy
539    if (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') == 'https') {
540        return true;
541    }
542
543    if (preg_match('/^(|off|false|disabled)$/i', $_SERVER['HTTPS'] ?? 'off')) {
544        return false;
545    }
546
547    return true;
548}
549
550/**
551 * checks it is windows OS
552 * @return bool
553 */
554function isWindows()
555{
556    return (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN');
557}
558
559/**
560 * print a nice message even if no styles are loaded yet.
561 *
562 * @param integer|string $msg
563 */
564function nice_die($msg)
565{
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>
578EOT;
579    if (defined('DOKU_UNITTEST')) {
580        throw new RuntimeException('nice_die: ' . $msg);
581    }
582    exit(1);
583}
584
585/**
586 * A realpath() replacement
587 *
588 * This function behaves similar to PHP's realpath() but does not resolve
589 * symlinks or accesses upper directories
590 *
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
594 *
595 * @param string $path
596 * @param bool $exists
597 *
598 * @return bool|string
599 */
600function fullpath($path, $exists = false)
601{
602    static $run = 0;
603    $root  = '';
604    $iswin = (isWindows() || !empty($GLOBALS['DOKU_UNITTEST_ASSUME_WINDOWS']));
605
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];
617        }
618    }
619    $path = str_replace('\\', '/', $path);
620
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);
628        }
629    }
630    $run = 0;
631
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;
640        }
641        $newpath[] = $p;
642    }
643    $finalpath = $root . implode('/', $newpath);
644
645    // check for existence when needed (except when unit testing)
646    if ($exists && !defined('DOKU_UNITTEST') && !file_exists($finalpath)) {
647        return false;
648    }
649    return $finalpath;
650}
651