xref: /dokuwiki/inc/init.php (revision f8369d7d6e37248d6523fdac6e1d760fca4f1b52)
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// initialize plugin controller
201$plugin_controller = new $plugin_controller_class();
202
203// initialize the event handler
204global $EVENT_HANDLER;
205$EVENT_HANDLER = new Doku_Event_Handler();
206
207$local = $conf['lang'];
208trigger_event('INIT_LANG_LOAD', $local, 'init_lang', true);
209
210
211// setup authentication system
212if (!defined('NOSESSION')) {
213    auth_setup();
214}
215
216// setup mail system
217mail_setup();
218
219/**
220 * Checks paths from config file
221 */
222function init_paths(){
223    global $conf;
224
225    $paths = array('datadir'   => 'pages',
226            'olddir'    => 'attic',
227            'mediadir'  => 'media',
228            'mediaolddir' => 'media_attic',
229            'metadir'   => 'meta',
230            'mediametadir' => 'media_meta',
231            'cachedir'  => 'cache',
232            'indexdir'  => 'index',
233            'lockdir'   => 'locks',
234            'tmpdir'    => 'tmp');
235
236    foreach($paths as $c => $p){
237        if(empty($conf[$c]))  $conf[$c] = $conf['savedir'].'/'.$p;
238        $conf[$c]             = init_path($conf[$c]);
239        if(empty($conf[$c]))  nice_die("The $c ('$p') does not exist, isn't accessible or writable.
240                You should check your config and permission settings.
241                Or maybe you want to <a href=\"install.php\">run the
242                installer</a>?");
243    }
244
245    // path to old changelog only needed for upgrading
246    $conf['changelog_old'] = init_path((isset($conf['changelog']))?($conf['changelog']):($conf['savedir'].'/changes.log'));
247    if ($conf['changelog_old']=='') { unset($conf['changelog_old']); }
248    // hardcoded changelog because it is now a cache that lives in meta
249    $conf['changelog'] = $conf['metadir'].'/_dokuwiki.changes';
250    $conf['media_changelog'] = $conf['metadir'].'/_media.changes';
251}
252
253function init_lang($langCode) {
254    //prepare language array
255    global $lang;
256    $lang = array();
257
258    //load the language files
259    require_once(DOKU_INC.'inc/lang/en/lang.php');
260    if ($langCode && $langCode != 'en') {
261        if (file_exists(DOKU_INC."inc/lang/$langCode/lang.php")) {
262            require_once(DOKU_INC."inc/lang/$langCode/lang.php");
263        }
264    }
265}
266
267/**
268 * Checks the existance of certain files and creates them if missing.
269 */
270function init_files(){
271    global $conf;
272
273    $files = array($conf['indexdir'].'/page.idx');
274
275    foreach($files as $file){
276        if(!@file_exists($file)){
277            $fh = @fopen($file,'a');
278            if($fh){
279                fclose($fh);
280                if($conf['fperm']) chmod($file, $conf['fperm']);
281            }else{
282                nice_die("$file is not writable. Check your permissions settings!");
283            }
284        }
285    }
286
287    # create title index (needs to have same length as page.idx)
288    /*
289    $file = $conf['indexdir'].'/title.idx';
290    if(!@file_exists($file)){
291        $pages = file($conf['indexdir'].'/page.idx');
292        $pages = count($pages);
293        $fh = @fopen($file,'a');
294        if($fh){
295            for($i=0; $i<$pages; $i++){
296                fwrite($fh,"\n");
297            }
298            fclose($fh);
299        }else{
300            nice_die("$file is not writable. Check your permissions settings!");
301        }
302    }
303    */
304}
305
306/**
307 * Returns absolute path
308 *
309 * This tries the given path first, then checks in DOKU_INC.
310 * Check for accessability on directories as well.
311 *
312 * @author Andreas Gohr <andi@splitbrain.org>
313 */
314function init_path($path){
315    // check existance
316    $p = fullpath($path);
317    if(!@file_exists($p)){
318        $p = fullpath(DOKU_INC.$path);
319        if(!@file_exists($p)){
320            return '';
321        }
322    }
323
324    // check writability
325    if(!@is_writable($p)){
326        return '';
327    }
328
329    // check accessability (execute bit) for directories
330    if(@is_dir($p) && !@file_exists("$p/.")){
331        return '';
332    }
333
334    return $p;
335}
336
337/**
338 * Sets the internal config values fperm and dperm which, when set,
339 * will be used to change the permission of a newly created dir or
340 * file with chmod. Considers the influence of the system's umask
341 * setting the values only if needed.
342 */
343function init_creationmodes(){
344    global $conf;
345
346    // Legacy support for old umask/dmask scheme
347    unset($conf['dmask']);
348    unset($conf['fmask']);
349    unset($conf['umask']);
350    unset($conf['fperm']);
351    unset($conf['dperm']);
352
353    // get system umask, fallback to 0 if none available
354    $umask = @umask();
355    if(!$umask) $umask = 0000;
356
357    // check what is set automatically by the system on file creation
358    // and set the fperm param if it's not what we want
359    $auto_fmode = 0666 & ~$umask;
360    if($auto_fmode != $conf['fmode']) $conf['fperm'] = $conf['fmode'];
361
362    // check what is set automatically by the system on file creation
363    // and set the dperm param if it's not what we want
364    $auto_dmode = $conf['dmode'] & ~$umask;
365    if($auto_dmode != $conf['dmode']) $conf['dperm'] = $conf['dmode'];
366}
367
368/**
369 * remove magic quotes recursivly
370 *
371 * @author Andreas Gohr <andi@splitbrain.org>
372 */
373function remove_magic_quotes(&$array) {
374    foreach (array_keys($array) as $key) {
375        // handle magic quotes in keynames (breaks order)
376        $sk = stripslashes($key);
377        if($sk != $key){
378            $array[$sk] = $array[$key];
379            unset($array[$key]);
380            $key = $sk;
381        }
382
383        // do recursion if needed
384        if (is_array($array[$key])) {
385            remove_magic_quotes($array[$key]);
386        }else {
387            $array[$key] = stripslashes($array[$key]);
388        }
389    }
390}
391
392/**
393 * Returns the full absolute URL to the directory where
394 * DokuWiki is installed in (includes a trailing slash)
395 *
396 * @author Andreas Gohr <andi@splitbrain.org>
397 */
398function getBaseURL($abs=null){
399    global $conf;
400    //if canonical url enabled always return absolute
401    if(is_null($abs)) $abs = $conf['canonical'];
402
403    if($conf['basedir']){
404        $dir = $conf['basedir'];
405    }elseif(substr($_SERVER['SCRIPT_NAME'],-4) == '.php'){
406        $dir = dirname($_SERVER['SCRIPT_NAME']);
407    }elseif(substr($_SERVER['PHP_SELF'],-4) == '.php'){
408        $dir = dirname($_SERVER['PHP_SELF']);
409    }elseif($_SERVER['DOCUMENT_ROOT'] && $_SERVER['SCRIPT_FILENAME']){
410        $dir = preg_replace ('/^'.preg_quote($_SERVER['DOCUMENT_ROOT'],'/').'/','',
411                $_SERVER['SCRIPT_FILENAME']);
412        $dir = dirname('/'.$dir);
413    }else{
414        $dir = '.'; //probably wrong
415    }
416
417    $dir = str_replace('\\','/',$dir);             // bugfix for weird WIN behaviour
418    $dir = preg_replace('#//+#','/',"/$dir/");     // ensure leading and trailing slashes
419
420    //handle script in lib/exe dir
421    $dir = preg_replace('!lib/exe/$!','',$dir);
422
423    //handle script in lib/plugins dir
424    $dir = preg_replace('!lib/plugins/.*$!','',$dir);
425
426    //finish here for relative URLs
427    if(!$abs) return $dir;
428
429    //use config option if available, trim any slash from end of baseurl to avoid multiple consecutive slashes in the path
430    if($conf['baseurl']) return rtrim($conf['baseurl'],'/').$dir;
431
432    //split hostheader into host and port
433    if(isset($_SERVER['HTTP_HOST'])){
434        $parsed_host = parse_url('http://'.$_SERVER['HTTP_HOST']);
435        $host = $parsed_host['host'];
436        $port = $parsed_host['port'];
437    }elseif(isset($_SERVER['SERVER_NAME'])){
438        $parsed_host = parse_url('http://'.$_SERVER['SERVER_NAME']);
439        $host = $parsed_host['host'];
440        $port = $parsed_host['port'];
441    }else{
442        $host = php_uname('n');
443        $port = '';
444    }
445
446    if(!$port && isset($_SERVER['SERVER_PORT'])) {
447        $port = $_SERVER['SERVER_PORT'];
448    }
449
450    if(is_null($port)){
451        $port = '';
452    }
453
454    if(!is_ssl()){
455        $proto = 'http://';
456        if ($port == '80') {
457            $port = '';
458        }
459    }else{
460        $proto = 'https://';
461        if ($port == '443') {
462            $port = '';
463        }
464    }
465
466    if($port !== '') $port = ':'.$port;
467
468    return $proto.$host.$port.$dir;
469}
470
471/**
472 * Check if accessed via HTTPS
473 *
474 * Apache leaves ,$_SERVER['HTTPS'] empty when not available, IIS sets it to 'off'.
475 * 'false' and 'disabled' are just guessing
476 *
477 * @returns bool true when SSL is active
478 */
479function is_ssl(){
480    if (!isset($_SERVER['HTTPS']) ||
481        preg_match('/^(|off|false|disabled)$/i',$_SERVER['HTTPS'])){
482        return false;
483    }else{
484        return true;
485    }
486}
487
488/**
489 * print a nice message even if no styles are loaded yet.
490 */
491function nice_die($msg){
492    echo<<<EOT
493<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
494    "http://www.w3.org/TR/html4/loose.dtd">
495<html>
496<head><title>DokuWiki Setup Error</title></head>
497<body style="font-family: Arial, sans-serif">
498    <div style="width:60%; margin: auto; background-color: #fcc;
499                border: 1px solid #faa; padding: 0.5em 1em;">
500        <h1 style="font-size: 120%">DokuWiki Setup Error</h1>
501        <p>$msg</p>
502    </div>
503</body>
504</html>
505EOT;
506    exit;
507}
508
509/**
510 * A realpath() replacement
511 *
512 * This function behaves similar to PHP's realpath() but does not resolve
513 * symlinks or accesses upper directories
514 *
515 * @author Andreas Gohr <andi@splitbrain.org>
516 * @author <richpageau at yahoo dot co dot uk>
517 * @link   http://de3.php.net/manual/en/function.realpath.php#75992
518 */
519function fullpath($path,$exists=false){
520    static $run = 0;
521    $root  = '';
522    $iswin = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' || @$GLOBALS['DOKU_UNITTEST_ASSUME_WINDOWS']);
523
524    // find the (indestructable) root of the path - keeps windows stuff intact
525    if($path{0} == '/'){
526        $root = '/';
527    }elseif($iswin){
528        // match drive letter and UNC paths
529        if(preg_match('!^([a-zA-z]:)(.*)!',$path,$match)){
530            $root = $match[1].'/';
531            $path = $match[2];
532        }else if(preg_match('!^(\\\\\\\\[^\\\\/]+\\\\[^\\\\/]+[\\\\/])(.*)!',$path,$match)){
533            $root = $match[1];
534            $path = $match[2];
535        }
536    }
537    $path = str_replace('\\','/',$path);
538
539    // if the given path wasn't absolute already, prepend the script path and retry
540    if(!$root){
541        $base = dirname($_SERVER['SCRIPT_FILENAME']);
542        $path = $base.'/'.$path;
543        if($run == 0){ // avoid endless recursion when base isn't absolute for some reason
544            $run++;
545            return fullpath($path,$exists);
546        }
547    }
548    $run = 0;
549
550    // canonicalize
551    $path=explode('/', $path);
552    $newpath=array();
553    foreach($path as $p) {
554        if ($p === '' || $p === '.') continue;
555        if ($p==='..') {
556            array_pop($newpath);
557            continue;
558        }
559        array_push($newpath, $p);
560    }
561    $finalpath = $root.implode('/', $newpath);
562
563    // check for existance when needed (except when unit testing)
564    if($exists && !defined('DOKU_UNITTEST') && !@file_exists($finalpath)) {
565        return false;
566    }
567    return $finalpath;
568}
569
570