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