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