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