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