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