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