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