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