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