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