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