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