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