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