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