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