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