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