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