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