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