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