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