xref: /dokuwiki/inc/init.php (revision 73ab87de7441c9c0eac123c1c44c2cf1ffdbe189)
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    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
152    if (version_compare(PHP_VERSION, '5.2.0', '>')) {
153        session_set_cookie_params(0,$cookieDir,'',($conf['securecookie'] && is_ssl()),true);
154    }else{
155        session_set_cookie_params(0,$cookieDir,'',($conf['securecookie'] && is_ssl()));
156    }
157    session_start();
158
159    // load left over messages
160    if(isset($_SESSION[DOKU_COOKIE]['msg'])){
161        $MSG = $_SESSION[DOKU_COOKIE]['msg'];
162        unset($_SESSION[DOKU_COOKIE]['msg']);
163    }
164}
165
166// kill magic quotes
167if (get_magic_quotes_gpc() && !defined('MAGIC_QUOTES_STRIPPED')) {
168    if (!empty($_GET))    remove_magic_quotes($_GET);
169    if (!empty($_POST))   remove_magic_quotes($_POST);
170    if (!empty($_COOKIE)) remove_magic_quotes($_COOKIE);
171    if (!empty($_REQUEST)) remove_magic_quotes($_REQUEST);
172    @ini_set('magic_quotes_gpc', 0);
173    define('MAGIC_QUOTES_STRIPPED',1);
174}
175@set_magic_quotes_runtime(0);
176@ini_set('magic_quotes_sybase',0);
177
178// don't let cookies ever interfere with request vars
179$_REQUEST = array_merge($_GET,$_POST);
180
181// we don't want a purge URL to be digged
182if(isset($_REQUEST['purge']) && $_SERVER['HTTP_REFERER']) unset($_REQUEST['purge']);
183
184// disable gzip if not available
185if($conf['compression'] == 'bz2' && !function_exists('bzopen')){
186    $conf['compression'] = 'gz';
187}
188if($conf['compression'] == 'gz' && !function_exists('gzopen')){
189    $conf['compression'] = 0;
190}
191
192// fix dateformat for upgraders
193if(strpos($conf['dformat'],'%') === false){
194    $conf['dformat'] = '%Y/%m/%d %H:%M';
195}
196
197// precalculate file creation modes
198init_creationmodes();
199
200// make real paths and check them
201init_paths();
202init_files();
203
204// setup plugin controller class (can be overwritten in preload.php)
205$plugin_types = array('admin','syntax','action','renderer', 'helper');
206global $plugin_controller_class, $plugin_controller;
207if (empty($plugin_controller_class)) $plugin_controller_class = 'Doku_Plugin_Controller';
208
209// load libraries
210require_once(DOKU_INC.'inc/load.php');
211
212// initialize plugin controller
213$plugin_controller = new $plugin_controller_class();
214
215// initialize the event handler
216global $EVENT_HANDLER;
217$EVENT_HANDLER = new Doku_Event_Handler();
218
219// setup authentication system
220if (!defined('NOSESSION')) {
221    auth_setup();
222}
223
224// setup mail system
225mail_setup();
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 * print a nice message even if no styles are loaded yet.
467 */
468function nice_die($msg){
469    echo<<<EOT
470<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
471    "http://www.w3.org/TR/html4/loose.dtd">
472<html>
473<head><title>DokuWiki Setup Error</title></head>
474<body style="font-family: Arial, sans-serif">
475    <div style="width:60%; margin: auto; background-color: #fcc;
476                border: 1px solid #faa; padding: 0.5em 1em;">
477        <h1 style="font-size: 120%">DokuWiki Setup Error</h1>
478        <p>$msg</p>
479    </div>
480</body>
481</html>
482EOT;
483    exit;
484}
485
486/**
487 * A realpath() replacement
488 *
489 * This function behaves similar to PHP's realpath() but does not resolve
490 * symlinks or accesses upper directories
491 *
492 * @author Andreas Gohr <andi@splitbrain.org>
493 * @author <richpageau at yahoo dot co dot uk>
494 * @link   http://de3.php.net/manual/en/function.realpath.php#75992
495 */
496function fullpath($path,$exists=false){
497    static $run = 0;
498    $root  = '';
499    $iswin = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' || @$GLOBALS['DOKU_UNITTEST_ASSUME_WINDOWS']);
500
501    // find the (indestructable) root of the path - keeps windows stuff intact
502    if($path{0} == '/'){
503        $root = '/';
504    }elseif($iswin){
505        // match drive letter and UNC paths
506        if(preg_match('!^([a-zA-z]:)(.*)!',$path,$match)){
507            $root = $match[1].'/';
508            $path = $match[2];
509        }else if(preg_match('!^(\\\\\\\\[^\\\\/]+\\\\[^\\\\/]+[\\\\/])(.*)!',$path,$match)){
510            $root = $match[1];
511            $path = $match[2];
512        }
513    }
514    $path = str_replace('\\','/',$path);
515
516    // if the given path wasn't absolute already, prepend the script path and retry
517    if(!$root){
518        $base = dirname($_SERVER['SCRIPT_FILENAME']);
519        $path = $base.'/'.$path;
520        if($run == 0){ // avoid endless recursion when base isn't absolute for some reason
521            $run++;
522            return fullpath($path,$exists);
523        }
524    }
525    $run = 0;
526
527    // canonicalize
528    $path=explode('/', $path);
529    $newpath=array();
530    foreach($path as $p) {
531        if ($p === '' || $p === '.') continue;
532        if ($p==='..') {
533            array_pop($newpath);
534            continue;
535        }
536        array_push($newpath, $p);
537    }
538    $finalpath = $root.implode('/', $newpath);
539
540    // check for existance when needed (except when unit testing)
541    if($exists && !defined('DOKU_UNITTEST') && !@file_exists($finalpath)) {
542        return false;
543    }
544    return $finalpath;
545}
546
547