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