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