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