xref: /dokuwiki/inc/init.php (revision 2400ddcb0585bd4bba5d4abeb1be8e2f4ebc56d6)
1<?php
2/**
3 * Initialize some defaults needed for DokuWiki
4 */
5
6/**
7 * timing Dokuwiki execution
8 */
9function delta_time($start=0) {
10    return microtime(true)-((float)$start);
11}
12define('DOKU_START_TIME', delta_time());
13
14global $config_cascade;
15$config_cascade = array();
16
17// if available load a preload config file
18$preload = fullpath(dirname(__FILE__)).'/preload.php';
19if (@file_exists($preload)) include($preload);
20
21// define the include path
22if(!defined('DOKU_INC')) define('DOKU_INC',fullpath(dirname(__FILE__).'/../').'/');
23
24// define Plugin dir
25if(!defined('DOKU_PLUGIN'))  define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
26
27// define config path (packagers may want to change this to /etc/dokuwiki/)
28if(!defined('DOKU_CONF')) define('DOKU_CONF',DOKU_INC.'conf/');
29
30// check for error reporting override or set error reporting to sane values
31if (!defined('DOKU_E_LEVEL') && @file_exists(DOKU_CONF.'report_e_all')) {
32    define('DOKU_E_LEVEL', E_ALL);
33}
34if (!defined('DOKU_E_LEVEL')) {
35    if(defined('E_DEPRECATED')){ // since php 5.3, since php 5.4 E_STRICT is part of E_ALL
36        error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT);
37    }else{
38        error_reporting(E_ALL ^ E_NOTICE);
39    }
40} else {
41    error_reporting(DOKU_E_LEVEL);
42}
43
44// init memory caches
45global $cache_revinfo;
46       $cache_revinfo = array();
47global $cache_wikifn;
48       $cache_wikifn = array();
49global $cache_cleanid;
50       $cache_cleanid = array();
51global $cache_authname;
52       $cache_authname = array();
53global $cache_metadata;
54       $cache_metadata = array();
55
56// always include 'inc/config_cascade.php'
57// previously in preload.php set fields of $config_cascade will be merged with the defaults
58include(DOKU_INC.'inc/config_cascade.php');
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 license array()
75global $license;
76$license = array();
77
78// load the license file(s)
79foreach (array('default','local') as $config_group) {
80    if (empty($config_cascade['license'][$config_group])) continue;
81    foreach ($config_cascade['license'][$config_group] as $config_file) {
82        if(@file_exists($config_file)){
83            include($config_file);
84        }
85    }
86}
87
88// set timezone (as in pre 5.3.0 days)
89date_default_timezone_set(@date_default_timezone_get());
90
91// define baseURL
92if(!defined('DOKU_REL')) define('DOKU_REL',getBaseURL(false));
93if(!defined('DOKU_URL')) define('DOKU_URL',getBaseURL(true));
94if(!defined('DOKU_BASE')){
95    if($conf['canonical']){
96        define('DOKU_BASE',DOKU_URL);
97    }else{
98        define('DOKU_BASE',DOKU_REL);
99    }
100}
101
102// define whitespace
103if(!defined('DOKU_LF')) define ('DOKU_LF',"\n");
104if(!defined('DOKU_TAB')) define ('DOKU_TAB',"\t");
105
106// define cookie and session id, append server port when securecookie is configured FS#1664
107if (!defined('DOKU_COOKIE')) define('DOKU_COOKIE', 'DW'.md5(DOKU_REL.(($conf['securecookie'])?$_SERVER['SERVER_PORT']:'')));
108
109
110// define main script
111if(!defined('DOKU_SCRIPT')) define('DOKU_SCRIPT','doku.php');
112
113// DEPRECATED, use tpl_basedir() instead
114if(!defined('DOKU_TPL')) define('DOKU_TPL',
115        DOKU_BASE.'lib/tpl/'.$conf['template'].'/');
116
117// DEPRECATED, use tpl_incdir() instead
118if(!defined('DOKU_TPLINC')) define('DOKU_TPLINC',
119        DOKU_INC.'lib/tpl/'.$conf['template'].'/');
120
121// make session rewrites XHTML compliant
122@ini_set('arg_separator.output', '&amp;');
123
124// make sure global zlib does not interfere FS#1132
125@ini_set('zlib.output_compression', 'off');
126
127// increase PCRE backtrack limit
128@ini_set('pcre.backtrack_limit', '20971520');
129
130// enable gzip compression if supported
131$conf['gzip_output'] &= (strpos($_SERVER['HTTP_ACCEPT_ENCODING'],'gzip') !== false);
132global $ACT;
133if ($conf['gzip_output'] &&
134        !defined('DOKU_DISABLE_GZIP_OUTPUT') &&
135        function_exists('ob_gzhandler') &&
136        // Disable compression when a (compressed) sitemap might be delivered
137        // See https://bugs.dokuwiki.org/index.php?do=details&task_id=2576
138        $ACT != 'sitemap') {
139    ob_start('ob_gzhandler');
140}
141
142// init session
143if (!headers_sent() && !defined('NOSESSION')){
144    session_name("DokuWiki");
145    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
146    if (version_compare(PHP_VERSION, '5.2.0', '>')) {
147        session_set_cookie_params(0,$cookieDir,'',($conf['securecookie'] && is_ssl()),true);
148    }else{
149        session_set_cookie_params(0,$cookieDir,'',($conf['securecookie'] && is_ssl()));
150    }
151    session_start();
152
153    // load left over messages
154    if(isset($_SESSION[DOKU_COOKIE]['msg'])){
155        $MSG = $_SESSION[DOKU_COOKIE]['msg'];
156        unset($_SESSION[DOKU_COOKIE]['msg']);
157    }
158}
159
160// kill magic quotes
161if (get_magic_quotes_gpc() && !defined('MAGIC_QUOTES_STRIPPED')) {
162    if (!empty($_GET))    remove_magic_quotes($_GET);
163    if (!empty($_POST))   remove_magic_quotes($_POST);
164    if (!empty($_COOKIE)) remove_magic_quotes($_COOKIE);
165    if (!empty($_REQUEST)) remove_magic_quotes($_REQUEST);
166    @ini_set('magic_quotes_gpc', 0);
167    define('MAGIC_QUOTES_STRIPPED',1);
168}
169if(function_exists('set_magic_quotes_runtime')) @set_magic_quotes_runtime(0);
170@ini_set('magic_quotes_sybase',0);
171
172// don't let cookies ever interfere with request vars
173$_REQUEST = array_merge($_GET,$_POST);
174
175// we don't want a purge URL to be digged
176if(isset($_REQUEST['purge']) && $_SERVER['HTTP_REFERER']) unset($_REQUEST['purge']);
177
178// disable gzip if not available
179if($conf['compression'] == 'bz2' && !function_exists('bzopen')){
180    $conf['compression'] = 'gz';
181}
182if($conf['compression'] == 'gz' && !function_exists('gzopen')){
183    $conf['compression'] = 0;
184}
185
186// precalculate file creation modes
187init_creationmodes();
188
189// make real paths and check them
190init_paths();
191init_files();
192
193// setup plugin controller class (can be overwritten in preload.php)
194$plugin_types = array('auth', 'admin','syntax','action','renderer', 'helper','remote');
195global $plugin_controller_class, $plugin_controller;
196if (empty($plugin_controller_class)) $plugin_controller_class = 'Doku_Plugin_Controller';
197
198// load libraries
199require_once(DOKU_INC.'inc/load.php');
200
201// input handle class
202global $INPUT;
203$INPUT = new Input();
204
205// initialize plugin controller
206$plugin_controller = new $plugin_controller_class();
207
208// initialize the event handler
209global $EVENT_HANDLER;
210$EVENT_HANDLER = new Doku_Event_Handler();
211
212$local = $conf['lang'];
213trigger_event('INIT_LANG_LOAD', $local, 'init_lang', true);
214
215
216// setup authentication system
217if (!defined('NOSESSION')) {
218    auth_setup();
219}
220
221// setup mail system
222mail_setup();
223
224/**
225 * Checks paths from config file
226 */
227function init_paths(){
228    global $conf;
229
230    $paths = array('datadir'   => 'pages',
231            'olddir'    => 'attic',
232            'mediadir'  => 'media',
233            'mediaolddir' => 'media_attic',
234            'metadir'   => 'meta',
235            'mediametadir' => 'media_meta',
236            'cachedir'  => 'cache',
237            'indexdir'  => 'index',
238            'lockdir'   => 'locks',
239            'tmpdir'    => 'tmp');
240
241    foreach($paths as $c => $p) {
242        $path = empty($conf[$c]) ? $conf['savedir'].'/'.$p : $conf[$c];
243        $conf[$c] = init_path($path);
244        if(empty($conf[$c]))
245            nice_die("The $c ('$p') at $path is not found, 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
259function init_lang($langCode) {
260    //prepare language array
261    global $lang;
262    $lang = array();
263
264    //load the language files
265    require(DOKU_INC.'inc/lang/en/lang.php');
266    if ($langCode && $langCode != 'en') {
267        if (file_exists(DOKU_INC."inc/lang/$langCode/lang.php")) {
268            require(DOKU_INC."inc/lang/$langCode/lang.php");
269        }
270    }
271}
272
273/**
274 * Checks the existence of certain files and creates them if missing.
275 */
276function init_files(){
277    global $conf;
278
279    $files = array($conf['indexdir'].'/page.idx');
280
281    foreach($files as $file){
282        if(!@file_exists($file)){
283            $fh = @fopen($file,'a');
284            if($fh){
285                fclose($fh);
286                if(!empty($conf['fperm'])) chmod($file, $conf['fperm']);
287            }else{
288                nice_die("$file is not writable. Check your permissions settings!");
289            }
290        }
291    }
292
293    # create title index (needs to have same length as page.idx)
294    /*
295    $file = $conf['indexdir'].'/title.idx';
296    if(!@file_exists($file)){
297        $pages = file($conf['indexdir'].'/page.idx');
298        $pages = count($pages);
299        $fh = @fopen($file,'a');
300        if($fh){
301            for($i=0; $i<$pages; $i++){
302                fwrite($fh,"\n");
303            }
304            fclose($fh);
305        }else{
306            nice_die("$file is not writable. Check your permissions settings!");
307        }
308    }
309    */
310}
311
312/**
313 * Returns absolute path
314 *
315 * This tries the given path first, then checks in DOKU_INC.
316 * Check for accessibility on directories as well.
317 *
318 * @author Andreas Gohr <andi@splitbrain.org>
319 */
320function init_path($path){
321    // check existence
322    $p = fullpath($path);
323    if(!@file_exists($p)){
324        $p = fullpath(DOKU_INC.$path);
325        if(!@file_exists($p)){
326            return '';
327        }
328    }
329
330    // check writability
331    if(!@is_writable($p)){
332        return '';
333    }
334
335    // check accessability (execute bit) for directories
336    if(@is_dir($p) && !@file_exists("$p/.")){
337        return '';
338    }
339
340    return $p;
341}
342
343/**
344 * Sets the internal config values fperm and dperm which, when set,
345 * will be used to change the permission of a newly created dir or
346 * file with chmod. Considers the influence of the system's umask
347 * setting the values only if needed.
348 */
349function init_creationmodes(){
350    global $conf;
351
352    // Legacy support for old umask/dmask scheme
353    unset($conf['dmask']);
354    unset($conf['fmask']);
355    unset($conf['umask']);
356    unset($conf['fperm']);
357    unset($conf['dperm']);
358
359    // get system umask, fallback to 0 if none available
360    $umask = @umask();
361    if(!$umask) $umask = 0000;
362
363    // check what is set automatically by the system on file creation
364    // and set the fperm param if it's not what we want
365    $auto_fmode = 0666 & ~$umask;
366    if($auto_fmode != $conf['fmode']) $conf['fperm'] = $conf['fmode'];
367
368    // check what is set automatically by the system on file creation
369    // and set the dperm param if it's not what we want
370    $auto_dmode = $conf['dmode'] & ~$umask;
371    if($auto_dmode != $conf['dmode']) $conf['dperm'] = $conf['dmode'];
372}
373
374/**
375 * remove magic quotes recursivly
376 *
377 * @author Andreas Gohr <andi@splitbrain.org>
378 */
379function remove_magic_quotes(&$array) {
380    foreach (array_keys($array) as $key) {
381        // handle magic quotes in keynames (breaks order)
382        $sk = stripslashes($key);
383        if($sk != $key){
384            $array[$sk] = $array[$key];
385            unset($array[$key]);
386            $key = $sk;
387        }
388
389        // do recursion if needed
390        if (is_array($array[$key])) {
391            remove_magic_quotes($array[$key]);
392        }else {
393            $array[$key] = stripslashes($array[$key]);
394        }
395    }
396}
397
398/**
399 * Returns the full absolute URL to the directory where
400 * DokuWiki is installed in (includes a trailing slash)
401 *
402 * @author Andreas Gohr <andi@splitbrain.org>
403 */
404function getBaseURL($abs=null){
405    global $conf;
406    //if canonical url enabled always return absolute
407    if(is_null($abs)) $abs = $conf['canonical'];
408
409    if($conf['basedir']){
410        $dir = $conf['basedir'];
411    }elseif(substr($_SERVER['SCRIPT_NAME'],-4) == '.php'){
412        $dir = dirname($_SERVER['SCRIPT_NAME']);
413    }elseif(substr($_SERVER['PHP_SELF'],-4) == '.php'){
414        $dir = dirname($_SERVER['PHP_SELF']);
415    }elseif($_SERVER['DOCUMENT_ROOT'] && $_SERVER['SCRIPT_FILENAME']){
416        $dir = preg_replace ('/^'.preg_quote($_SERVER['DOCUMENT_ROOT'],'/').'/','',
417                $_SERVER['SCRIPT_FILENAME']);
418        $dir = dirname('/'.$dir);
419    }else{
420        $dir = '.'; //probably wrong
421    }
422
423    $dir = str_replace('\\','/',$dir);             // bugfix for weird WIN behaviour
424    $dir = preg_replace('#//+#','/',"/$dir/");     // ensure leading and trailing slashes
425
426    //handle script in lib/exe dir
427    $dir = preg_replace('!lib/exe/$!','',$dir);
428
429    //handle script in lib/plugins dir
430    $dir = preg_replace('!lib/plugins/.*$!','',$dir);
431
432    //finish here for relative URLs
433    if(!$abs) return $dir;
434
435    //use config option if available, trim any slash from end of baseurl to avoid multiple consecutive slashes in the path
436    if($conf['baseurl']) return rtrim($conf['baseurl'],'/').$dir;
437
438    //split hostheader into host and port
439    if(isset($_SERVER['HTTP_HOST'])){
440        $parsed_host = parse_url('http://'.$_SERVER['HTTP_HOST']);
441        $host = $parsed_host['host'];
442        $port = $parsed_host['port'];
443    }elseif(isset($_SERVER['SERVER_NAME'])){
444        $parsed_host = parse_url('http://'.$_SERVER['SERVER_NAME']);
445        $host = $parsed_host['host'];
446        $port = $parsed_host['port'];
447    }else{
448        $host = php_uname('n');
449        $port = '';
450    }
451
452    if(!$port && isset($_SERVER['SERVER_PORT'])) {
453        $port = $_SERVER['SERVER_PORT'];
454    }
455
456    if(is_null($port)){
457        $port = '';
458    }
459
460    if(!is_ssl()){
461        $proto = 'http://';
462        if ($port == '80') {
463            $port = '';
464        }
465    }else{
466        $proto = 'https://';
467        if ($port == '443') {
468            $port = '';
469        }
470    }
471
472    if($port !== '') $port = ':'.$port;
473
474    return $proto.$host.$port.$dir;
475}
476
477/**
478 * Check if accessed via HTTPS
479 *
480 * Apache leaves ,$_SERVER['HTTPS'] empty when not available, IIS sets it to 'off'.
481 * 'false' and 'disabled' are just guessing
482 *
483 * @returns bool true when SSL is active
484 */
485function is_ssl(){
486    if (!isset($_SERVER['HTTPS']) ||
487        preg_match('/^(|off|false|disabled)$/i',$_SERVER['HTTPS'])){
488        return false;
489    }else{
490        return true;
491    }
492}
493
494/**
495 * print a nice message even if no styles are loaded yet.
496 */
497function nice_die($msg){
498    echo<<<EOT
499<!DOCTYPE html>
500<html>
501<head><title>DokuWiki Setup Error</title></head>
502<body style="font-family: Arial, sans-serif">
503    <div style="width:60%; margin: auto; background-color: #fcc;
504                border: 1px solid #faa; padding: 0.5em 1em;">
505        <h1 style="font-size: 120%">DokuWiki Setup Error</h1>
506        <p>$msg</p>
507    </div>
508</body>
509</html>
510EOT;
511    exit;
512}
513
514/**
515 * A realpath() replacement
516 *
517 * This function behaves similar to PHP's realpath() but does not resolve
518 * symlinks or accesses upper directories
519 *
520 * @author Andreas Gohr <andi@splitbrain.org>
521 * @author <richpageau at yahoo dot co dot uk>
522 * @link   http://de3.php.net/manual/en/function.realpath.php#75992
523 */
524function fullpath($path,$exists=false){
525    static $run = 0;
526    $root  = '';
527    $iswin = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' || @$GLOBALS['DOKU_UNITTEST_ASSUME_WINDOWS']);
528
529    // find the (indestructable) root of the path - keeps windows stuff intact
530    if($path{0} == '/'){
531        $root = '/';
532    }elseif($iswin){
533        // match drive letter and UNC paths
534        if(preg_match('!^([a-zA-z]:)(.*)!',$path,$match)){
535            $root = $match[1].'/';
536            $path = $match[2];
537        }else if(preg_match('!^(\\\\\\\\[^\\\\/]+\\\\[^\\\\/]+[\\\\/])(.*)!',$path,$match)){
538            $root = $match[1];
539            $path = $match[2];
540        }
541    }
542    $path = str_replace('\\','/',$path);
543
544    // if the given path wasn't absolute already, prepend the script path and retry
545    if(!$root){
546        $base = dirname($_SERVER['SCRIPT_FILENAME']);
547        $path = $base.'/'.$path;
548        if($run == 0){ // avoid endless recursion when base isn't absolute for some reason
549            $run++;
550            return fullpath($path,$exists);
551        }
552    }
553    $run = 0;
554
555    // canonicalize
556    $path=explode('/', $path);
557    $newpath=array();
558    foreach($path as $p) {
559        if ($p === '' || $p === '.') continue;
560        if ($p==='..') {
561            array_pop($newpath);
562            continue;
563        }
564        array_push($newpath, $p);
565    }
566    $finalpath = $root.implode('/', $newpath);
567
568    // check for existence when needed (except when unit testing)
569    if($exists && !defined('DOKU_UNITTEST') && !@file_exists($finalpath)) {
570        return false;
571    }
572    return $finalpath;
573}
574
575