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