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