source: documentation/trunk/packages/dokuwiki-2011-05-25a/inc/init.php@ 30098

Last change on this file since 30098 was 25027, checked in by jmt12, 12 years ago

Adding the packages directory, and within it a configured version of dokuwiki all ready to run

File size: 16.2 KB
Line 
1<?php
2/**
3 * Initialize some defaults needed for DokuWiki
4 */
5
6// start timing Dokuwiki execution
7function delta_time($start=0) {
8 return microtime(true)-((float)$start);
9}
10define('DOKU_START_TIME', delta_time());
11
12global $config_cascade;
13$config_cascade = array();
14
15// if available load a preload config file
16$preload = fullpath(dirname(__FILE__)).'/preload.php';
17if (@file_exists($preload)) include($preload);
18
19// define the include path
20if(!defined('DOKU_INC')) define('DOKU_INC',fullpath(dirname(__FILE__).'/../').'/');
21
22// define Plugin dir
23if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
24
25// define config path (packagers may want to change this to /etc/dokuwiki/)
26if(!defined('DOKU_CONF')) define('DOKU_CONF',DOKU_INC.'conf/');
27
28// check for error reporting override or set error reporting to sane values
29if (!defined('DOKU_E_LEVEL') && @file_exists(DOKU_CONF.'report_e_all')) {
30 define('DOKU_E_LEVEL', E_ALL);
31}
32if (!defined('DOKU_E_LEVEL')) {
33 if(defined('E_DEPRECATED')){ // since php 5.3
34 error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
35 }else{
36 error_reporting(E_ALL ^ E_NOTICE);
37 }
38} else {
39 error_reporting(DOKU_E_LEVEL);
40}
41
42// init memory caches
43global $cache_revinfo;
44 $cache_revinfo = array();
45global $cache_wikifn;
46 $cache_wikifn = array();
47global $cache_cleanid;
48 $cache_cleanid = array();
49global $cache_authname;
50 $cache_authname = array();
51global $cache_metadata;
52 $cache_metadata = array();
53
54// always include 'inc/config_cascade.php'
55// previously in preload.php set fields of $config_cascade will be merged with the defaults
56include(DOKU_INC.'inc/config_cascade.php');
57
58//prepare config array()
59global $conf;
60$conf = array();
61
62// load the global config file(s)
63foreach (array('default','local','protected') as $config_group) {
64 if (empty($config_cascade['main'][$config_group])) continue;
65 foreach ($config_cascade['main'][$config_group] as $config_file) {
66 if (@file_exists($config_file)) {
67 include($config_file);
68 }
69 }
70}
71
72//prepare language array
73global $lang;
74$lang = array();
75
76//load the language files
77require_once(DOKU_INC.'inc/lang/en/lang.php');
78if ( $conf['lang'] && $conf['lang'] != 'en' ) {
79 require_once(DOKU_INC.'inc/lang/'.$conf['lang'].'/lang.php');
80}
81
82//prepare license array()
83global $license;
84$license = array();
85
86// load the license file(s)
87foreach (array('default','local') as $config_group) {
88 if (empty($config_cascade['license'][$config_group])) continue;
89 foreach ($config_cascade['license'][$config_group] as $config_file) {
90 if(@file_exists($config_file)){
91 include($config_file);
92 }
93 }
94}
95
96// set timezone (as in pre 5.3.0 days)
97date_default_timezone_set(@date_default_timezone_get());
98
99// define baseURL
100if(!defined('DOKU_REL')) define('DOKU_REL',getBaseURL(false));
101if(!defined('DOKU_URL')) define('DOKU_URL',getBaseURL(true));
102if(!defined('DOKU_BASE')){
103 if($conf['canonical']){
104 define('DOKU_BASE',DOKU_URL);
105 }else{
106 define('DOKU_BASE',DOKU_REL);
107 }
108}
109
110// define whitespace
111if(!defined('DOKU_LF')) define ('DOKU_LF',"\n");
112if(!defined('DOKU_TAB')) define ('DOKU_TAB',"\t");
113
114// define cookie and session id, append server port when securecookie is configured FS#1664
115if (!defined('DOKU_COOKIE')) define('DOKU_COOKIE', 'DW'.md5(DOKU_REL.(($conf['securecookie'])?$_SERVER['SERVER_PORT']:'')));
116
117
118// define main script
119if(!defined('DOKU_SCRIPT')) define('DOKU_SCRIPT','doku.php');
120
121// define Template baseURL
122if(!defined('DOKU_TPL')) define('DOKU_TPL',
123 DOKU_BASE.'lib/tpl/'.$conf['template'].'/');
124
125// define real Template directory
126if(!defined('DOKU_TPLINC')) define('DOKU_TPLINC',
127 DOKU_INC.'lib/tpl/'.$conf['template'].'/');
128
129// make session rewrites XHTML compliant
130@ini_set('arg_separator.output', '&amp;');
131
132// make sure global zlib does not interfere FS#1132
133@ini_set('zlib.output_compression', 'off');
134
135// increase PCRE backtrack limit
136@ini_set('pcre.backtrack_limit', '20971520');
137
138// enable gzip compression if supported
139$conf['gzip_output'] &= (strpos($_SERVER['HTTP_ACCEPT_ENCODING'],'gzip') !== false);
140if ($conf['gzip_output'] &&
141 !defined('DOKU_DISABLE_GZIP_OUTPUT') &&
142 function_exists('ob_gzhandler')) {
143 ob_start('ob_gzhandler');
144}
145
146// init session
147if (!headers_sent() && !defined('NOSESSION')){
148 session_name("DokuWiki");
149 if (version_compare(PHP_VERSION, '5.2.0', '>')) {
150 session_set_cookie_params(0,DOKU_REL,'',($conf['securecookie'] && is_ssl()),true);
151 }else{
152 session_set_cookie_params(0,DOKU_REL,'',($conf['securecookie'] && is_ssl()));
153 }
154 session_start();
155
156 // load left over messages
157 if(isset($_SESSION[DOKU_COOKIE]['msg'])){
158 $MSG = $_SESSION[DOKU_COOKIE]['msg'];
159 unset($_SESSION[DOKU_COOKIE]['msg']);
160 }
161}
162
163// kill magic quotes
164if (get_magic_quotes_gpc() && !defined('MAGIC_QUOTES_STRIPPED')) {
165 if (!empty($_GET)) remove_magic_quotes($_GET);
166 if (!empty($_POST)) remove_magic_quotes($_POST);
167 if (!empty($_COOKIE)) remove_magic_quotes($_COOKIE);
168 if (!empty($_REQUEST)) remove_magic_quotes($_REQUEST);
169 @ini_set('magic_quotes_gpc', 0);
170 define('MAGIC_QUOTES_STRIPPED',1);
171}
172@set_magic_quotes_runtime(0);
173@ini_set('magic_quotes_sybase',0);
174
175// don't let cookies ever interfere with request vars
176$_REQUEST = array_merge($_GET,$_POST);
177
178// we don't want a purge URL to be digged
179if(isset($_REQUEST['purge']) && $_SERVER['HTTP_REFERER']) unset($_REQUEST['purge']);
180
181// disable gzip if not available
182if($conf['compression'] == 'bz2' && !function_exists('bzopen')){
183 $conf['compression'] = 'gz';
184}
185if($conf['compression'] == 'gz' && !function_exists('gzopen')){
186 $conf['compression'] = 0;
187}
188
189// fix dateformat for upgraders
190if(strpos($conf['dformat'],'%') === false){
191 $conf['dformat'] = '%Y/%m/%d %H:%M';
192}
193
194// precalculate file creation modes
195init_creationmodes();
196
197// make real paths and check them
198init_paths();
199init_files();
200
201// setup plugin controller class (can be overwritten in preload.php)
202$plugin_types = array('admin','syntax','action','renderer', 'helper');
203global $plugin_controller_class, $plugin_controller;
204if (empty($plugin_controller_class)) $plugin_controller_class = 'Doku_Plugin_Controller';
205
206// load libraries
207require_once(DOKU_INC.'inc/load.php');
208
209// initialize plugin controller
210$plugin_controller = new $plugin_controller_class();
211
212// initialize the event handler
213global $EVENT_HANDLER;
214$EVENT_HANDLER = new Doku_Event_Handler();
215
216// setup authentication system
217if (!defined('NOSESSION')) {
218 auth_setup();
219}
220
221// setup mail system
222mail_setup();
223
224/**
225 * Checks paths from config file
226 */
227function init_paths(){
228 global $conf;
229
230 $paths = array('datadir' => 'pages',
231 'olddir' => 'attic',
232 'mediadir' => 'media',
233 'metadir' => 'meta',
234 'cachedir' => 'cache',
235 'indexdir' => 'index',
236 'lockdir' => 'locks',
237 'tmpdir' => 'tmp');
238
239 foreach($paths as $c => $p){
240 if(empty($conf[$c])) $conf[$c] = $conf['savedir'].'/'.$p;
241 $conf[$c] = init_path($conf[$c]);
242 if(empty($conf[$c])) nice_die("The $c ('$p') does not exist, isn't accessible or writable.
243 You should check your config and permission settings.
244 Or maybe you want to <a href=\"install.php\">run the
245 installer</a>?");
246 }
247
248 // path to old changelog only needed for upgrading
249 $conf['changelog_old'] = init_path((isset($conf['changelog']))?($conf['changelog']):($conf['savedir'].'/changes.log'));
250 if ($conf['changelog_old']=='') { unset($conf['changelog_old']); }
251 // hardcoded changelog because it is now a cache that lives in meta
252 $conf['changelog'] = $conf['metadir'].'/_dokuwiki.changes';
253 $conf['media_changelog'] = $conf['metadir'].'/_media.changes';
254}
255
256/**
257 * Checks the existance of certain files and creates them if missing.
258 */
259function init_files(){
260 global $conf;
261
262 $files = array($conf['indexdir'].'/page.idx');
263
264 foreach($files as $file){
265 if(!@file_exists($file)){
266 $fh = @fopen($file,'a');
267 if($fh){
268 fclose($fh);
269 if($conf['fperm']) chmod($file, $conf['fperm']);
270 }else{
271 nice_die("$file is not writable. Check your permissions settings!");
272 }
273 }
274 }
275
276 # create title index (needs to have same length as page.idx)
277 /*
278 $file = $conf['indexdir'].'/title.idx';
279 if(!@file_exists($file)){
280 $pages = file($conf['indexdir'].'/page.idx');
281 $pages = count($pages);
282 $fh = @fopen($file,'a');
283 if($fh){
284 for($i=0; $i<$pages; $i++){
285 fwrite($fh,"\n");
286 }
287 fclose($fh);
288 }else{
289 nice_die("$file is not writable. Check your permissions settings!");
290 }
291 }
292 */
293}
294
295/**
296 * Returns absolute path
297 *
298 * This tries the given path first, then checks in DOKU_INC.
299 * Check for accessability on directories as well.
300 *
301 * @author Andreas Gohr <[email protected]>
302 */
303function init_path($path){
304 // check existance
305 $p = fullpath($path);
306 if(!@file_exists($p)){
307 $p = fullpath(DOKU_INC.$path);
308 if(!@file_exists($p)){
309 return '';
310 }
311 }
312
313 // check writability
314 if(!@is_writable($p)){
315 return '';
316 }
317
318 // check accessability (execute bit) for directories
319 if(@is_dir($p) && !@file_exists("$p/.")){
320 return '';
321 }
322
323 return $p;
324}
325
326/**
327 * Sets the internal config values fperm and dperm which, when set,
328 * will be used to change the permission of a newly created dir or
329 * file with chmod. Considers the influence of the system's umask
330 * setting the values only if needed.
331 */
332function init_creationmodes(){
333 global $conf;
334
335 // Legacy support for old umask/dmask scheme
336 unset($conf['dmask']);
337 unset($conf['fmask']);
338 unset($conf['umask']);
339 unset($conf['fperm']);
340 unset($conf['dperm']);
341
342 // get system umask, fallback to 0 if none available
343 $umask = @umask();
344 if(!$umask) $umask = 0000;
345
346 // check what is set automatically by the system on file creation
347 // and set the fperm param if it's not what we want
348 $auto_fmode = 0666 & ~$umask;
349 if($auto_fmode != $conf['fmode']) $conf['fperm'] = $conf['fmode'];
350
351 // check what is set automatically by the system on file creation
352 // and set the dperm param if it's not what we want
353 $auto_dmode = $conf['dmode'] & ~$umask;
354 if($auto_dmode != $conf['dmode']) $conf['dperm'] = $conf['dmode'];
355}
356
357/**
358 * remove magic quotes recursivly
359 *
360 * @author Andreas Gohr <[email protected]>
361 */
362function remove_magic_quotes(&$array) {
363 foreach (array_keys($array) as $key) {
364 // handle magic quotes in keynames (breaks order)
365 $sk = stripslashes($key);
366 if($sk != $key){
367 $array[$sk] = $array[$key];
368 unset($array[$key]);
369 $key = $sk;
370 }
371
372 // do recursion if needed
373 if (is_array($array[$key])) {
374 remove_magic_quotes($array[$key]);
375 }else {
376 $array[$key] = stripslashes($array[$key]);
377 }
378 }
379}
380
381/**
382 * Returns the full absolute URL to the directory where
383 * DokuWiki is installed in (includes a trailing slash)
384 *
385 * @author Andreas Gohr <[email protected]>
386 */
387function getBaseURL($abs=null){
388 global $conf;
389 //if canonical url enabled always return absolute
390 if(is_null($abs)) $abs = $conf['canonical'];
391
392 if($conf['basedir']){
393 $dir = $conf['basedir'];
394 }elseif(substr($_SERVER['SCRIPT_NAME'],-4) == '.php'){
395 $dir = dirname($_SERVER['SCRIPT_NAME']);
396 }elseif(substr($_SERVER['PHP_SELF'],-4) == '.php'){
397 $dir = dirname($_SERVER['PHP_SELF']);
398 }elseif($_SERVER['DOCUMENT_ROOT'] && $_SERVER['SCRIPT_FILENAME']){
399 $dir = preg_replace ('/^'.preg_quote($_SERVER['DOCUMENT_ROOT'],'/').'/','',
400 $_SERVER['SCRIPT_FILENAME']);
401 $dir = dirname('/'.$dir);
402 }else{
403 $dir = '.'; //probably wrong
404 }
405
406 $dir = str_replace('\\','/',$dir); // bugfix for weird WIN behaviour
407 $dir = preg_replace('#//+#','/',"/$dir/"); // ensure leading and trailing slashes
408
409 //handle script in lib/exe dir
410 $dir = preg_replace('!lib/exe/$!','',$dir);
411
412 //handle script in lib/plugins dir
413 $dir = preg_replace('!lib/plugins/.*$!','',$dir);
414
415 //finish here for relative URLs
416 if(!$abs) return $dir;
417
418 //use config option if available, trim any slash from end of baseurl to avoid multiple consecutive slashes in the path
419 if($conf['baseurl']) return rtrim($conf['baseurl'],'/').$dir;
420
421 //split hostheader into host and port
422 if(isset($_SERVER['HTTP_HOST'])){
423 $parsed_host = parse_url('http://'.$_SERVER['HTTP_HOST']);
424 $host = $parsed_host['host'];
425 $port = $parsed_host['port'];
426 }elseif(isset($_SERVER['SERVER_NAME'])){
427 $parsed_host = parse_url('http://'.$_SERVER['SERVER_NAME']);
428 $host = $parsed_host['host'];
429 $port = $parsed_host['port'];
430 }else{
431 $host = php_uname('n');
432 $port = '';
433 }
434
435 if(!$port && isset($_SERVER['SERVER_PORT'])) {
436 $port = $_SERVER['SERVER_PORT'];
437 }
438
439 if(is_null($port)){
440 $port = '';
441 }
442
443 if(!is_ssl()){
444 $proto = 'http://';
445 if ($port == '80') {
446 $port = '';
447 }
448 }else{
449 $proto = 'https://';
450 if ($port == '443') {
451 $port = '';
452 }
453 }
454
455 if($port !== '') $port = ':'.$port;
456
457 return $proto.$host.$port.$dir;
458}
459
460/**
461 * Check if accessed via HTTPS
462 *
463 * Apache leaves ,$_SERVER['HTTPS'] empty when not available, IIS sets it to 'off'.
464 * 'false' and 'disabled' are just guessing
465 *
466 * @returns bool true when SSL is active
467 */
468function is_ssl(){
469 if (!isset($_SERVER['HTTPS']) ||
470 preg_match('/^(|off|false|disabled)$/i',$_SERVER['HTTPS'])){
471 return false;
472 }else{
473 return true;
474 }
475}
476
477/**
478 * print a nice message even if no styles are loaded yet.
479 */
480function nice_die($msg){
481 echo<<<EOT
482<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
483 "http://www.w3.org/TR/html4/loose.dtd">
484<html>
485<head><title>DokuWiki Setup Error</title></head>
486<body style="font-family: Arial, sans-serif">
487 <div style="width:60%; margin: auto; background-color: #fcc;
488 border: 1px solid #faa; padding: 0.5em 1em;">
489 <h1 style="font-size: 120%">DokuWiki Setup Error</h1>
490 <p>$msg</p>
491 </div>
492</body>
493</html>
494EOT;
495 exit;
496}
497
498/**
499 * A realpath() replacement
500 *
501 * This function behaves similar to PHP's realpath() but does not resolve
502 * symlinks or accesses upper directories
503 *
504 * @author Andreas Gohr <[email protected]>
505 * @author <richpageau at yahoo dot co dot uk>
506 * @link http://de3.php.net/manual/en/function.realpath.php#75992
507 */
508function fullpath($path,$exists=false){
509 static $run = 0;
510 $root = '';
511 $iswin = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' || @$GLOBALS['DOKU_UNITTEST_ASSUME_WINDOWS']);
512
513 // find the (indestructable) root of the path - keeps windows stuff intact
514 if($path{0} == '/'){
515 $root = '/';
516 }elseif($iswin){
517 // match drive letter and UNC paths
518 if(preg_match('!^([a-zA-z]:)(.*)!',$path,$match)){
519 $root = $match[1].'/';
520 $path = $match[2];
521 }else if(preg_match('!^(\\\\\\\\[^\\\\/]+\\\\[^\\\\/]+[\\\\/])(.*)!',$path,$match)){
522 $root = $match[1];
523 $path = $match[2];
524 }
525 }
526 $path = str_replace('\\','/',$path);
527
528 // if the given path wasn't absolute already, prepend the script path and retry
529 if(!$root){
530 $base = dirname($_SERVER['SCRIPT_FILENAME']);
531 $path = $base.'/'.$path;
532 if($run == 0){ // avoid endless recursion when base isn't absolute for some reason
533 $run++;
534 return fullpath($path,$exists);
535 }
536 }
537 $run = 0;
538
539 // canonicalize
540 $path=explode('/', $path);
541 $newpath=array();
542 foreach($path as $p) {
543 if ($p === '' || $p === '.') continue;
544 if ($p==='..') {
545 array_pop($newpath);
546 continue;
547 }
548 array_push($newpath, $p);
549 }
550 $finalpath = $root.implode('/', $newpath);
551
552 // check for existance when needed (except when unit testing)
553 if($exists && !defined('DOKU_UNITTEST') && !@file_exists($finalpath)) {
554 return false;
555 }
556 return $finalpath;
557}
558
Note: See TracBrowser for help on using the repository browser.