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