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