xref: /dokuwiki/inc/init.php (revision 87a99fa3f2b3acb3a82613dda4b0cb402de7efe5)
1<?php
2/**
3 * Initialize some defaults needed for DokuWiki
4 */
5
6// start timing Dokuwiki execution
7function delta_time($start=0) {
8    return microtime(true)-((float)$start);
9}
10define('DOKU_START_TIME', delta_time());
11
12global $config_cascade;
13$config_cascade = array();
14
15// if available load a preload config file
16$preload = fullpath(dirname(__FILE__)).'/preload.php';
17if (@file_exists($preload)) include($preload);
18
19// define the include path
20if(!defined('DOKU_INC')) define('DOKU_INC',fullpath(dirname(__FILE__).'/../').'/');
21
22// define Plugin dir
23if(!defined('DOKU_PLUGIN'))  define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
24
25// define config path (packagers may want to change this to /etc/dokuwiki/)
26if(!defined('DOKU_CONF')) define('DOKU_CONF',DOKU_INC.'conf/');
27
28// check for error reporting override or set error reporting to sane values
29if (!defined('DOKU_E_LEVEL') && @file_exists(DOKU_CONF.'report_e_all')) {
30    define('DOKU_E_LEVEL', E_ALL);
31}
32if (!defined('DOKU_E_LEVEL')) {
33    if(defined('E_DEPRECATED')){ // since php 5.3, since php 5.4 E_STRICT is part of E_ALL
34        error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT);
35    }else{
36        error_reporting(E_ALL ^ E_NOTICE);
37    }
38} else {
39    error_reporting(DOKU_E_LEVEL);
40}
41
42// init memory caches
43global $cache_revinfo;
44       $cache_revinfo = array();
45global $cache_wikifn;
46       $cache_wikifn = array();
47global $cache_cleanid;
48       $cache_cleanid = array();
49global $cache_authname;
50       $cache_authname = array();
51global $cache_metadata;
52       $cache_metadata = array();
53
54// always include 'inc/config_cascade.php'
55// previously in preload.php set fields of $config_cascade will be merged with the defaults
56include(DOKU_INC.'inc/config_cascade.php');
57
58//prepare config array()
59global $conf;
60$conf = array();
61
62// load the global config file(s)
63foreach (array('default','local','protected') as $config_group) {
64    if (empty($config_cascade['main'][$config_group])) continue;
65    foreach ($config_cascade['main'][$config_group] as $config_file) {
66        if (@file_exists($config_file)) {
67            include($config_file);
68        }
69    }
70}
71
72//prepare license array()
73global $license;
74$license = array();
75
76// load the license file(s)
77foreach (array('default','local') as $config_group) {
78    if (empty($config_cascade['license'][$config_group])) continue;
79    foreach ($config_cascade['license'][$config_group] as $config_file) {
80        if(@file_exists($config_file)){
81            include($config_file);
82        }
83    }
84}
85
86// set timezone (as in pre 5.3.0 days)
87date_default_timezone_set(@date_default_timezone_get());
88
89// define baseURL
90if(!defined('DOKU_REL')) define('DOKU_REL',getBaseURL(false));
91if(!defined('DOKU_URL')) define('DOKU_URL',getBaseURL(true));
92if(!defined('DOKU_BASE')){
93    if($conf['canonical']){
94        define('DOKU_BASE',DOKU_URL);
95    }else{
96        define('DOKU_BASE',DOKU_REL);
97    }
98}
99
100// define whitespace
101if(!defined('DOKU_LF')) define ('DOKU_LF',"\n");
102if(!defined('DOKU_TAB')) define ('DOKU_TAB',"\t");
103
104// define cookie and session id, append server port when securecookie is configured FS#1664
105if (!defined('DOKU_COOKIE')) define('DOKU_COOKIE', 'DW'.md5(DOKU_REL.(($conf['securecookie'])?$_SERVER['SERVER_PORT']:'')));
106
107
108// define main script
109if(!defined('DOKU_SCRIPT')) define('DOKU_SCRIPT','doku.php');
110
111// DEPRECATED, use tpl_basedir() instead
112if(!defined('DOKU_TPL')) define('DOKU_TPL',
113        DOKU_BASE.'lib/tpl/'.$conf['template'].'/');
114
115// DEPRECATED, use tpl_incdir() instead
116if(!defined('DOKU_TPLINC')) define('DOKU_TPLINC',
117        DOKU_INC.'lib/tpl/'.$conf['template'].'/');
118
119// make session rewrites XHTML compliant
120@ini_set('arg_separator.output', '&amp;');
121
122// make sure global zlib does not interfere FS#1132
123@ini_set('zlib.output_compression', 'off');
124
125// increase PCRE backtrack limit
126@ini_set('pcre.backtrack_limit', '20971520');
127
128// enable gzip compression if supported
129$conf['gzip_output'] &= (strpos($_SERVER['HTTP_ACCEPT_ENCODING'],'gzip') !== false);
130if ($conf['gzip_output'] &&
131        !defined('DOKU_DISABLE_GZIP_OUTPUT') &&
132        function_exists('ob_gzhandler')) {
133    ob_start('ob_gzhandler');
134}
135
136// init session
137if (!headers_sent() && !defined('NOSESSION')){
138    session_name("DokuWiki");
139    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
140    if (version_compare(PHP_VERSION, '5.2.0', '>')) {
141        session_set_cookie_params(0,$cookieDir,'',($conf['securecookie'] && is_ssl()),true);
142    }else{
143        session_set_cookie_params(0,$cookieDir,'',($conf['securecookie'] && is_ssl()));
144    }
145    session_start();
146
147    // load left over messages
148    if(isset($_SESSION[DOKU_COOKIE]['msg'])){
149        $MSG = $_SESSION[DOKU_COOKIE]['msg'];
150        unset($_SESSION[DOKU_COOKIE]['msg']);
151    }
152}
153
154// kill magic quotes
155if (get_magic_quotes_gpc() && !defined('MAGIC_QUOTES_STRIPPED')) {
156    if (!empty($_GET))    remove_magic_quotes($_GET);
157    if (!empty($_POST))   remove_magic_quotes($_POST);
158    if (!empty($_COOKIE)) remove_magic_quotes($_COOKIE);
159    if (!empty($_REQUEST)) remove_magic_quotes($_REQUEST);
160    @ini_set('magic_quotes_gpc', 0);
161    define('MAGIC_QUOTES_STRIPPED',1);
162}
163@set_magic_quotes_runtime(0);
164@ini_set('magic_quotes_sybase',0);
165
166// don't let cookies ever interfere with request vars
167$_REQUEST = array_merge($_GET,$_POST);
168
169// we don't want a purge URL to be digged
170if(isset($_REQUEST['purge']) && $_SERVER['HTTP_REFERER']) unset($_REQUEST['purge']);
171
172// disable gzip if not available
173if($conf['compression'] == 'bz2' && !function_exists('bzopen')){
174    $conf['compression'] = 'gz';
175}
176if($conf['compression'] == 'gz' && !function_exists('gzopen')){
177    $conf['compression'] = 0;
178}
179
180// fix dateformat for upgraders
181if(strpos($conf['dformat'],'%') === false){
182    $conf['dformat'] = '%Y/%m/%d %H:%M';
183}
184
185// precalculate file creation modes
186init_creationmodes();
187
188// make real paths and check them
189init_paths();
190init_files();
191
192// setup plugin controller class (can be overwritten in preload.php)
193$plugin_types = array('admin','syntax','action','renderer', 'helper','remote');
194global $plugin_controller_class, $plugin_controller;
195if (empty($plugin_controller_class)) $plugin_controller_class = 'Doku_Plugin_Controller';
196
197// load libraries
198require_once(DOKU_INC.'inc/load.php');
199
200// initialize plugin controller
201$plugin_controller = new $plugin_controller_class();
202
203// initialize the event handler
204global $EVENT_HANDLER;
205$EVENT_HANDLER = new Doku_Event_Handler();
206
207$local = $conf['lang'];
208trigger_event('INIT_LANG_LOAD', $local, 'init_lang', true);
209
210
211// setup authentication system
212if (!defined('NOSESSION')) {
213    auth_setup();
214}
215
216// setup mail system
217mail_setup();
218
219/**
220 * Checks paths from config file
221 */
222function init_paths(){
223    global $conf;
224
225    $paths = array('datadir'   => 'pages',
226            'olddir'    => 'attic',
227            'mediadir'  => 'media',
228            'mediaolddir' => 'media_attic',
229            'metadir'   => 'meta',
230            'mediametadir' => 'media_meta',
231            'cachedir'  => 'cache',
232            'indexdir'  => 'index',
233            'lockdir'   => 'locks',
234            'tmpdir'    => 'tmp');
235
236    foreach($paths as $c => $p) {
237        $path = empty($conf[$c]) ? $conf['savedir'].'/'.$p : $conf[$c];
238        $conf[$c] = init_path($path);
239        if(empty($conf[$c]))
240            nice_die("The $c ('$p') at $path is not found, isn't accessible or writable.
241                You should check your config and permission settings.
242                Or maybe you want to <a href=\"install.php\">run the
243                installer</a>?");
244    }
245
246    // path to old changelog only needed for upgrading
247    $conf['changelog_old'] = init_path((isset($conf['changelog']))?($conf['changelog']):($conf['savedir'].'/changes.log'));
248    if ($conf['changelog_old']=='') { unset($conf['changelog_old']); }
249    // hardcoded changelog because it is now a cache that lives in meta
250    $conf['changelog'] = $conf['metadir'].'/_dokuwiki.changes';
251    $conf['media_changelog'] = $conf['metadir'].'/_media.changes';
252}
253
254function init_lang($langCode) {
255    //prepare language array
256    global $lang;
257    $lang = array();
258
259    //load the language files
260    require_once(DOKU_INC.'inc/lang/en/lang.php');
261    if ($langCode && $langCode != 'en') {
262        if (file_exists(DOKU_INC."inc/lang/$langCode/lang.php")) {
263            require_once(DOKU_INC."inc/lang/$langCode/lang.php");
264        }
265    }
266}
267
268/**
269 * Checks the existence of certain files and creates them if missing.
270 */
271function init_files(){
272    global $conf;
273
274    $files = array($conf['indexdir'].'/page.idx');
275
276    foreach($files as $file){
277        if(!@file_exists($file)){
278            $fh = @fopen($file,'a');
279            if($fh){
280                fclose($fh);
281                if($conf['fperm']) chmod($file, $conf['fperm']);
282            }else{
283                nice_die("$file is not writable. Check your permissions settings!");
284            }
285        }
286    }
287
288    # create title index (needs to have same length as page.idx)
289    /*
290    $file = $conf['indexdir'].'/title.idx';
291    if(!@file_exists($file)){
292        $pages = file($conf['indexdir'].'/page.idx');
293        $pages = count($pages);
294        $fh = @fopen($file,'a');
295        if($fh){
296            for($i=0; $i<$pages; $i++){
297                fwrite($fh,"\n");
298            }
299            fclose($fh);
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 accessibility on directories as well.
312 *
313 * @author Andreas Gohr <andi@splitbrain.org>
314 */
315function init_path($path){
316    // check existence
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    if(isset($_SERVER['HTTP_HOST'])){
435        $parsed_host = parse_url('http://'.$_SERVER['HTTP_HOST']);
436        $host = $parsed_host['host'];
437        $port = $parsed_host['port'];
438    }elseif(isset($_SERVER['SERVER_NAME'])){
439        $parsed_host = parse_url('http://'.$_SERVER['SERVER_NAME']);
440        $host = $parsed_host['host'];
441        $port = $parsed_host['port'];
442    }else{
443        $host = php_uname('n');
444        $port = '';
445    }
446
447    if(!$port && isset($_SERVER['SERVER_PORT'])) {
448        $port = $_SERVER['SERVER_PORT'];
449    }
450
451    if(is_null($port)){
452        $port = '';
453    }
454
455    if(!is_ssl()){
456        $proto = 'http://';
457        if ($port == '80') {
458            $port = '';
459        }
460    }else{
461        $proto = 'https://';
462        if ($port == '443') {
463            $port = '';
464        }
465    }
466
467    if($port !== '') $port = ':'.$port;
468
469    return $proto.$host.$port.$dir;
470}
471
472/**
473 * Check if accessed via HTTPS
474 *
475 * Apache leaves ,$_SERVER['HTTPS'] empty when not available, IIS sets it to 'off'.
476 * 'false' and 'disabled' are just guessing
477 *
478 * @returns bool true when SSL is active
479 */
480function is_ssl(){
481    if (!isset($_SERVER['HTTPS']) ||
482        preg_match('/^(|off|false|disabled)$/i',$_SERVER['HTTPS'])){
483        return false;
484    }else{
485        return true;
486    }
487}
488
489/**
490 * print a nice message even if no styles are loaded yet.
491 */
492function nice_die($msg){
493    echo<<<EOT
494<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
495    "http://www.w3.org/TR/html4/loose.dtd">
496<html>
497<head><title>DokuWiki Setup Error</title></head>
498<body style="font-family: Arial, sans-serif">
499    <div style="width:60%; margin: auto; background-color: #fcc;
500                border: 1px solid #faa; padding: 0.5em 1em;">
501        <h1 style="font-size: 120%">DokuWiki Setup Error</h1>
502        <p>$msg</p>
503    </div>
504</body>
505</html>
506EOT;
507    exit;
508}
509
510/**
511 * A realpath() replacement
512 *
513 * This function behaves similar to PHP's realpath() but does not resolve
514 * symlinks or accesses upper directories
515 *
516 * @author Andreas Gohr <andi@splitbrain.org>
517 * @author <richpageau at yahoo dot co dot uk>
518 * @link   http://de3.php.net/manual/en/function.realpath.php#75992
519 */
520function fullpath($path,$exists=false){
521    static $run = 0;
522    $root  = '';
523    $iswin = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' || @$GLOBALS['DOKU_UNITTEST_ASSUME_WINDOWS']);
524
525    // find the (indestructable) root of the path - keeps windows stuff intact
526    if($path{0} == '/'){
527        $root = '/';
528    }elseif($iswin){
529        // match drive letter and UNC paths
530        if(preg_match('!^([a-zA-z]:)(.*)!',$path,$match)){
531            $root = $match[1].'/';
532            $path = $match[2];
533        }else if(preg_match('!^(\\\\\\\\[^\\\\/]+\\\\[^\\\\/]+[\\\\/])(.*)!',$path,$match)){
534            $root = $match[1];
535            $path = $match[2];
536        }
537    }
538    $path = str_replace('\\','/',$path);
539
540    // if the given path wasn't absolute already, prepend the script path and retry
541    if(!$root){
542        $base = dirname($_SERVER['SCRIPT_FILENAME']);
543        $path = $base.'/'.$path;
544        if($run == 0){ // avoid endless recursion when base isn't absolute for some reason
545            $run++;
546            return fullpath($path,$exists);
547        }
548    }
549    $run = 0;
550
551    // canonicalize
552    $path=explode('/', $path);
553    $newpath=array();
554    foreach($path as $p) {
555        if ($p === '' || $p === '.') continue;
556        if ($p==='..') {
557            array_pop($newpath);
558            continue;
559        }
560        array_push($newpath, $p);
561    }
562    $finalpath = $root.implode('/', $newpath);
563
564    // check for existence when needed (except when unit testing)
565    if($exists && !defined('DOKU_UNITTEST') && !@file_exists($finalpath)) {
566        return false;
567    }
568    return $finalpath;
569}
570
571