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