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