xref: /dokuwiki/inc/init.php (revision bc6ecc12f39db1fe4b3e22e2a939f70691d6d1fc)
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',realpath(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_BASE')) define('DOKU_BASE',getBaseURL());
57  if(!defined('DOKU_URL'))  define('DOKU_URL',getBaseURL(true));
58
59  // define cookie and session id
60  if (!defined('DOKU_COOKIE')) define('DOKU_COOKIE', 'DW'.md5(DOKU_URL));
61
62  // define Plugin dir
63  if(!defined('DOKU_PLUGIN'))  define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
64
65  // define main script
66  if(!defined('DOKU_SCRIPT')) define('DOKU_SCRIPT','doku.php');
67
68  // define Template baseURL
69  if(!defined('DOKU_TPL')) define('DOKU_TPL',
70                                  DOKU_BASE.'lib/tpl/'.$conf['template'].'/');
71
72  // define real Template directory
73  if(!defined('DOKU_TPLINC')) define('DOKU_TPLINC',
74                                  DOKU_INC.'lib/tpl/'.$conf['template'].'/');
75
76  // make session rewrites XHTML compliant
77  @ini_set('arg_separator.output', '&amp;');
78
79  // enable gzip compression
80  if ($conf['gzip_output'] &&
81      !defined('DOKU_DISABLE_GZIP_OUTPUT') &&
82      function_exists('ob_gzhandler') &&
83      preg_match('/gzip|deflate/', $_SERVER['HTTP_ACCEPT_ENCODING'])) {
84    ob_start('ob_gzhandler');
85  }
86
87  // init session
88  if (!headers_sent() && !defined('NOSESSION')){
89    session_name("DokuWiki");
90    session_start();
91  }
92
93  // kill magic quotes
94  if (get_magic_quotes_gpc() && !defined('MAGIC_QUOTES_STRIPPED')) {
95    if (!empty($_GET))    remove_magic_quotes($_GET);
96    if (!empty($_POST))   remove_magic_quotes($_POST);
97    if (!empty($_COOKIE)) remove_magic_quotes($_COOKIE);
98    if (!empty($_REQUEST)) remove_magic_quotes($_REQUEST);
99#    if (!empty($_SESSION)) remove_magic_quotes($_SESSION); #FIXME needed ?
100    @ini_set('magic_quotes_gpc', 0);
101    define('MAGIC_QUOTES_STRIPPED',1);
102  }
103  @set_magic_quotes_runtime(0);
104  @ini_set('magic_quotes_sybase',0);
105
106  // disable gzip if not available
107  if($conf['compression'] == 'bz' && !function_exists('bzopen')){
108    $conf['compression'] = 'gz';
109  }
110  if($conf['compression'] == 'gz' && !function_exists('gzopen')){
111    $conf['compression'] = 0;
112  }
113
114  // precalculate file creation modes
115  init_creationmodes();
116
117  // make real paths and check them
118  init_paths();
119  init_files();
120
121  // automatic upgrade to script versions of certain files
122  scriptify(DOKU_CONF.'users.auth');
123  scriptify(DOKU_CONF.'acl.auth');
124
125
126/**
127 * Checks paths from config file
128 */
129function init_paths(){
130  global $conf;
131
132  $paths = array('datadir'   => 'pages',
133                 'olddir'    => 'attic',
134                 'mediadir'  => 'media',
135                 'metadir'   => 'meta',
136                 'cachedir'  => 'cache',
137                 'indexdir'  => 'index',
138                 'lockdir'   => 'locks');
139
140  foreach($paths as $c => $p){
141    if(empty($conf[$c]))  $conf[$c] = $conf['savedir'].'/'.$p;
142    $conf[$c]             = init_path($conf[$c]);
143    if(empty($conf[$c]))  nice_die("The $c ('$p') does not exist, isn't accessable or writable.
144                               You should check your config and permission settings.
145                               Or maybe you want to <a href=\"install.php\">run the
146                               installer</a>?");
147  }
148
149  // path to old changelog only needed for upgrading
150  $conf['changelog_old'] = init_path((isset($conf['changelog']))?($conf['changelog']):($conf['savedir'].'/changes.log'));
151  if ($conf['changelog_old']=='') { unset($conf['changelog_old']); }
152  // hardcoded changelog because it is now a cache that lives in meta
153  $conf['changelog'] = $conf['metadir'].'/_dokuwiki.changes';
154}
155
156/**
157 * Checks the existance of certain files and creates them if missing.
158 */
159function init_files(){
160  global $conf;
161
162  $files = array( $conf['indexdir'].'/page.idx');
163
164  foreach($files as $file){
165    if(!@file_exists($file)){
166      $fh = @fopen($file,'a');
167      if($fh){
168        fclose($fh);
169        if($conf['fperm']) chmod($file, $conf['fperm']);
170      }else{
171        nice_die("$file is not writable. Check your permissions settings!");
172      }
173    }
174  }
175}
176
177/**
178 * Returns absolute path
179 *
180 * This tries the given path first, then checks in DOKU_INC.
181 * Check for accessability on directories as well.
182 *
183 * @author Andreas Gohr <andi@splitbrain.org>
184 */
185function init_path($path){
186  // check existance
187  $p = realpath($path);
188  if(!@file_exists($p)){
189    $p = realpath(DOKU_INC.$path);
190    if(!@file_exists($p)){
191      return '';
192    }
193  }
194
195  // check writability
196  if(!@is_writable($p)){
197    return '';
198  }
199
200  // check accessability (execute bit) for directories
201  if(@is_dir($p) && !@file_exists("$p/.")){
202    return '';
203  }
204
205  return $p;
206}
207
208/**
209 * Sets the internal config values fperm and dperm which, when set,
210 * will be used to change the permission of a newly created dir or
211 * file with chmod. Considers the influence of the system's umask
212 * setting the values only if needed.
213 */
214function init_creationmodes(){
215  global $conf;
216
217  // Legacy support for old umask/dmask scheme
218  unset($conf['dmask']);
219  unset($conf['fmask']);
220  unset($conf['umask']);
221  unset($conf['fperm']);
222  unset($conf['dperm']);
223
224  // get system umask, fallback to 0 if none available
225  $umask = @umask();
226  if(!$umask) $umask = 0000;
227
228  // check what is set automatically by the system on file creation
229  // and set the fperm param if it's not what we want
230  $auto_fmode = 0666 & ~$umask;
231  if($auto_fmode != $conf['fmode']) $conf['fperm'] = $conf['fmode'];
232
233  // check what is set automatically by the system on file creation
234  // and set the dperm param if it's not what we want
235  $auto_dmode = $conf['dmode'] & ~$umask;
236  if($auto_dmode != $conf['dmode']) $conf['dperm'] = $conf['dmode'];
237}
238
239/**
240 * remove magic quotes recursivly
241 *
242 * @author Andreas Gohr <andi@splitbrain.org>
243 */
244function remove_magic_quotes(&$array) {
245  foreach (array_keys($array) as $key) {
246    if (is_array($array[$key])) {
247      remove_magic_quotes($array[$key]);
248    }else {
249      $array[$key] = stripslashes($array[$key]);
250    }
251  }
252}
253
254/**
255 * Returns the full absolute URL to the directory where
256 * DokuWiki is installed in (includes a trailing slash)
257 *
258 * @author Andreas Gohr <andi@splitbrain.org>
259 */
260function getBaseURL($abs=false){
261  global $conf;
262  //if canonical url enabled always return absolute
263  if($conf['canonical']) $abs = true;
264
265  if($conf['basedir']){
266    $dir = $conf['basedir'].'/';
267  }elseif(substr($_SERVER['SCRIPT_NAME'],-4) == '.php'){
268    $dir = dirname($_SERVER['SCRIPT_NAME']).'/';
269  }elseif(substr($_SERVER['PHP_SELF'],-4) == '.php'){
270    $dir = dirname($_SERVER['PHP_SELF']).'/';
271  }elseif($_SERVER['DOCUMENT_ROOT'] && $_SERVER['SCRIPT_FILENAME']){
272    $dir = preg_replace ('/^'.preg_quote($_SERVER['DOCUMENT_ROOT'],'/').'/','',
273                         $_SERVER['SCRIPT_FILENAME']);
274    $dir = dirname('/'.$dir).'/';
275  }else{
276    $dir = './'; //probably wrong
277  }
278
279  $dir = str_replace('\\','/',$dir); #bugfix for weird WIN behaviour
280  $dir = preg_replace('#//+#','/',$dir);
281
282  //handle script in lib/exe dir
283  $dir = preg_replace('!lib/exe/$!','',$dir);
284
285  //handle script in lib/plugins dir
286  $dir = preg_replace('!lib/plugins/.*$!','',$dir);
287
288  //finish here for relative URLs
289  if(!$abs) return $dir;
290
291  //use config option if available
292  if($conf['baseurl']) return $conf['baseurl'].$dir;
293
294  //split hostheader into host and port
295  list($host,$port) = explode(':',$_SERVER['HTTP_HOST']);
296  if(!$port)  $port = $_SERVER['SERVER_PORT'];
297  if(!$port)  $port = 80;
298
299  // see if HTTPS is enabled - apache leaves this empty when not available,
300  // IIS sets it to 'off', 'false' and 'disabled' are just guessing
301  if (preg_match('/^(|off|false|disabled)$/i',$_SERVER['HTTPS'])){
302    $proto = 'http://';
303    if ($port == '80') {
304      $port='';
305    }
306  }else{
307    $proto = 'https://';
308    if ($port == '443') {
309      $port='';
310    }
311  }
312
313  if($port) $port = ':'.$port;
314
315  return $proto.$host.$port.$dir;
316}
317
318/**
319 * Append a PHP extension to a given file and adds an exit call
320 *
321 * This is used to migrate some old configfiles. An added PHP extension
322 * ensures the contents are not shown to webusers even if .htaccess files
323 * do not work
324 *
325 * @author Jan Decaluwe <jan@jandecaluwe.com>
326 */
327function scriptify($file) {
328  // checks
329  if (!is_readable($file)) {
330    return;
331  }
332  $fn = $file.'.php';
333  if (@file_exists($fn)) {
334    return;
335  }
336  $fh = fopen($fn, 'w');
337  if (!$fh) {
338    nice_die($fn.' is not writable. Check your permission settings!');
339  }
340  // write php exit hack first
341  fwrite($fh, "# $fn\n");
342  fwrite($fh, '# <?php exit()?>'."\n");
343  fwrite($fh, "# Don't modify the lines above\n");
344  fwrite($fh, "#\n");
345  // copy existing lines
346  $lines = file($file);
347  foreach ($lines as $line){
348    fwrite($fh, $line);
349  }
350  fclose($fh);
351  //try to rename the old file
352  io_rename($file,"$file.old");
353}
354
355/**
356 * print a nice message even if no styles are loaded yet.
357 */
358function nice_die($msg){
359  echo<<<EOT
360  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
361   "http://www.w3.org/TR/html4/loose.dtd">
362  <html>
363    <head><title>DokuWiki Setup Error</title></head>
364    <body style="font-family: Arial, sans-serif">
365      <div style="width:60%; margin: auto; background-color: #fcc;
366                  border: 1px solid #faa; padding: 0.5em 1em;">
367      <h1 style="font-size: 120%">DokuWiki Setup Error</h1>
368      <p>$msg</p>
369      </div>
370    </body>
371  </html>
372EOT;
373  exit;
374}
375
376
377//Setup VIM: ex: et ts=2 enc=utf-8 :
378