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