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