1<?php 2/** 3 * Initialize some defaults needed for DokuWiki 4 */ 5 6// start timing Dokuwiki execution 7function delta_time($start=0) { 8 list($usec, $sec) = explode(" ", microtime()); 9 return ((float)$usec+(float)$sec)-((float)$start); 10} 11define('DOKU_START_TIME', delta_time()); 12 13global $config_cascade; 14$config_cascade = ''; 15 16// if available load a preload config file 17$preload = fullpath(dirname(__FILE__)).'/preload.php'; 18if (@file_exists($preload)) include($preload); 19 20// define the include path 21if(!defined('DOKU_INC')) define('DOKU_INC',fullpath(dirname(__FILE__).'/../').'/'); 22 23// define Plugin dir 24if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/'); 25 26// define config path (packagers may want to change this to /etc/dokuwiki/) 27if(!defined('DOKU_CONF')) define('DOKU_CONF',DOKU_INC.'conf/'); 28 29// check for error reporting override or set error reporting to sane values 30if (!defined('DOKU_E_LEVEL') && @file_exists(DOKU_CONF.'report_e_all')) { 31 define('DOKU_E_LEVEL', E_ALL); 32} 33if (!defined('DOKU_E_LEVEL')) { 34 if(defined('E_DEPRECATED')){ // since php 5.3 35 error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED); 36 }else{ 37 error_reporting(E_ALL ^ E_NOTICE); 38 } 39} else { 40 error_reporting(DOKU_E_LEVEL); 41} 42 43// init memory caches 44global $cache_revinfo; 45 $cache_revinfo = array(); 46global $cache_wikifn; 47 $cache_wikifn = array(); 48global $cache_cleanid; 49 $cache_cleanid = array(); 50global $cache_authname; 51 $cache_authname = array(); 52global $cache_metadata; 53 $cache_metadata = array(); 54 55//set the configuration cascade - but only if its not already been set in preload.php 56if (empty($config_cascade)) { 57 include(DOKU_INC.'inc/config_cascade.php'); 58} 59 60//prepare config array() 61global $conf; 62$conf = array(); 63 64// load the global config file(s) 65foreach (array('default','local','protected') as $config_group) { 66 if (empty($config_cascade['main'][$config_group])) continue; 67 foreach ($config_cascade['main'][$config_group] as $config_file) { 68 if (@file_exists($config_file)) { 69 include($config_file); 70 } 71 } 72} 73 74//prepare language array 75global $lang; 76$lang = array(); 77 78//load the language files 79require_once(DOKU_INC.'inc/lang/en/lang.php'); 80if ( $conf['lang'] && $conf['lang'] != 'en' ) { 81 require_once(DOKU_INC.'inc/lang/'.$conf['lang'].'/lang.php'); 82} 83 84//prepare license array() 85global $license; 86$license = array(); 87 88// load the license file(s) 89foreach (array('default','local') as $config_group) { 90 if (empty($config_cascade['license'][$config_group])) continue; 91 foreach ($config_cascade['license'][$config_group] as $config_file) { 92 if(@file_exists($config_file)){ 93 include($config_file); 94 } 95 } 96} 97 98// set timezone (as in pre 5.3.0 days) 99date_default_timezone_set(@date_default_timezone_get()); 100 101// define baseURL 102if(!defined('DOKU_REL')) define('DOKU_REL',getBaseURL(false)); 103if(!defined('DOKU_URL')) define('DOKU_URL',getBaseURL(true)); 104if(!defined('DOKU_BASE')){ 105 if($conf['canonical']){ 106 define('DOKU_BASE',DOKU_URL); 107 }else{ 108 define('DOKU_BASE',DOKU_REL); 109 } 110} 111 112// define whitespace 113if(!defined('DOKU_LF')) define ('DOKU_LF',"\n"); 114if(!defined('DOKU_TAB')) define ('DOKU_TAB',"\t"); 115 116// define cookie and session id, append server port when securecookie is configured FS#1664 117if (!defined('DOKU_COOKIE')) define('DOKU_COOKIE', 'DW'.md5(DOKU_REL.(($conf['securecookie'])?$_SERVER['SERVER_PORT']:''))); 118 119 120// define main script 121if(!defined('DOKU_SCRIPT')) define('DOKU_SCRIPT','doku.php'); 122 123// define Template baseURL 124if(!defined('DOKU_TPL')) define('DOKU_TPL', 125 DOKU_BASE.'lib/tpl/'.$conf['template'].'/'); 126 127// define real Template directory 128if(!defined('DOKU_TPLINC')) define('DOKU_TPLINC', 129 DOKU_INC.'lib/tpl/'.$conf['template'].'/'); 130 131// make session rewrites XHTML compliant 132@ini_set('arg_separator.output', '&'); 133 134// make sure global zlib does not interfere FS#1132 135@ini_set('zlib.output_compression', 'off'); 136 137// increase PCRE backtrack limit 138@ini_set('pcre.backtrack_limit', '20971520'); 139 140// enable gzip compression if supported 141$conf['gzip_output'] &= (strpos($_SERVER['HTTP_ACCEPT_ENCODING'],'gzip') !== false); 142if ($conf['gzip_output'] && 143 !defined('DOKU_DISABLE_GZIP_OUTPUT') && 144 function_exists('ob_gzhandler')) { 145 ob_start('ob_gzhandler'); 146} 147 148// init session 149if (!headers_sent() && !defined('NOSESSION')){ 150 session_name("DokuWiki"); 151 if (version_compare(PHP_VERSION, '5.2.0', '>')) { 152 session_set_cookie_params(0,DOKU_REL,'',($conf['securecookie'] && is_ssl()),true); 153 }else{ 154 session_set_cookie_params(0,DOKU_REL,'',($conf['securecookie'] && is_ssl())); 155 } 156 session_start(); 157 158 // load left over messages 159 if(isset($_SESSION[DOKU_COOKIE]['msg'])){ 160 $MSG = $_SESSION[DOKU_COOKIE]['msg']; 161 unset($_SESSION[DOKU_COOKIE]['msg']); 162 } 163} 164 165// kill magic quotes 166if (get_magic_quotes_gpc() && !defined('MAGIC_QUOTES_STRIPPED')) { 167 if (!empty($_GET)) remove_magic_quotes($_GET); 168 if (!empty($_POST)) remove_magic_quotes($_POST); 169 if (!empty($_COOKIE)) remove_magic_quotes($_COOKIE); 170 if (!empty($_REQUEST)) remove_magic_quotes($_REQUEST); 171 @ini_set('magic_quotes_gpc', 0); 172 define('MAGIC_QUOTES_STRIPPED',1); 173} 174@set_magic_quotes_runtime(0); 175@ini_set('magic_quotes_sybase',0); 176 177// don't let cookies ever interfere with request vars 178$_REQUEST = array_merge($_GET,$_POST); 179 180// we don't want a purge URL to be digged 181if(isset($_REQUEST['purge']) && $_SERVER['HTTP_REFERER']) unset($_REQUEST['purge']); 182 183// disable gzip if not available 184if($conf['compression'] == 'bz2' && !function_exists('bzopen')){ 185 $conf['compression'] = 'gz'; 186} 187if($conf['compression'] == 'gz' && !function_exists('gzopen')){ 188 $conf['compression'] = 0; 189} 190 191// fix dateformat for upgraders 192if(strpos($conf['dformat'],'%') === false){ 193 $conf['dformat'] = '%Y/%m/%d %H:%M'; 194} 195 196// precalculate file creation modes 197init_creationmodes(); 198 199// make real paths and check them 200init_paths(); 201init_files(); 202 203// setup plugin controller class (can be overwritten in preload.php) 204$plugin_types = array('admin','syntax','action','renderer', 'helper'); 205global $plugin_controller_class, $plugin_controller; 206if (empty($plugin_controller_class)) $plugin_controller_class = 'Doku_Plugin_Controller'; 207 208// load libraries 209require_once(DOKU_INC.'inc/load.php'); 210 211// initialize plugin controller 212$plugin_controller = new $plugin_controller_class(); 213 214// initialize the event handler 215global $EVENT_HANDLER; 216$EVENT_HANDLER = new Doku_Event_Handler(); 217 218// setup authentication system 219if (!defined('NOSESSION')) { 220 auth_setup(); 221} 222 223// setup mail system 224mail_setup(); 225 226/** 227 * Checks paths from config file 228 */ 229function init_paths(){ 230 global $conf; 231 232 $paths = array('datadir' => 'pages', 233 'olddir' => 'attic', 234 'mediadir' => 'media', 235 'metadir' => 'meta', 236 'cachedir' => 'cache', 237 'indexdir' => 'index', 238 'lockdir' => 'locks', 239 'tmpdir' => 'tmp'); 240 241 foreach($paths as $c => $p){ 242 if(empty($conf[$c])) $conf[$c] = $conf['savedir'].'/'.$p; 243 $conf[$c] = init_path($conf[$c]); 244 if(empty($conf[$c])) nice_die("The $c ('$p') does not exist, isn't accessible or writable. 245 You should check your config and permission settings. 246 Or maybe you want to <a href=\"install.php\">run the 247 installer</a>?"); 248 } 249 250 // path to old changelog only needed for upgrading 251 $conf['changelog_old'] = init_path((isset($conf['changelog']))?($conf['changelog']):($conf['savedir'].'/changes.log')); 252 if ($conf['changelog_old']=='') { unset($conf['changelog_old']); } 253 // hardcoded changelog because it is now a cache that lives in meta 254 $conf['changelog'] = $conf['metadir'].'/_dokuwiki.changes'; 255 $conf['media_changelog'] = $conf['metadir'].'/_media.changes'; 256} 257 258/** 259 * Checks the existance of certain files and creates them if missing. 260 */ 261function init_files(){ 262 global $conf; 263 264 $files = array($conf['indexdir'].'/page.idx'); 265 266 foreach($files as $file){ 267 if(!@file_exists($file)){ 268 $fh = @fopen($file,'a'); 269 if($fh){ 270 fclose($fh); 271 if($conf['fperm']) chmod($file, $conf['fperm']); 272 }else{ 273 nice_die("$file is not writable. Check your permissions settings!"); 274 } 275 } 276 } 277 278 # create title index (needs to have same length as page.idx) 279 $file = $conf['indexdir'].'/title.idx'; 280 if(!@file_exists($file)){ 281 $pages = file($conf['indexdir'].'/page.idx'); 282 $pages = count($pages); 283 $fh = @fopen($file,'a'); 284 if($fh){ 285 for($i=0; $i<$pages; $i++){ 286 fwrite($fh,"\n"); 287 } 288 fclose($fh); 289 }else{ 290 nice_die("$file is not writable. Check your permissions settings!"); 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 <andi@splitbrain.org> 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 <andi@splitbrain.org> 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 <andi@splitbrain.org> 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 $addr = explode(':',$_SERVER['HTTP_HOST']); 423 $host = $addr[0]; 424 $port = ''; 425 if (isset($addr[1])) { 426 $port = $addr[1]; 427 } elseif (isset($_SERVER['SERVER_PORT'])) { 428 $port = $_SERVER['SERVER_PORT']; 429 } 430 if(!is_ssl()){ 431 $proto = 'http://'; 432 if ($port == '80') { 433 $port = ''; 434 } 435 }else{ 436 $proto = 'https://'; 437 if ($port == '443') { 438 $port = ''; 439 } 440 } 441 442 if($port !== '') $port = ':'.$port; 443 444 return $proto.$host.$port.$dir; 445} 446 447/** 448 * Check if accessed via HTTPS 449 * 450 * Apache leaves ,$_SERVER['HTTPS'] empty when not available, IIS sets it to 'off'. 451 * 'false' and 'disabled' are just guessing 452 * 453 * @returns bool true when SSL is active 454 */ 455function is_ssl(){ 456 if (!isset($_SERVER['HTTPS']) || 457 preg_match('/^(|off|false|disabled)$/i',$_SERVER['HTTPS'])){ 458 return false; 459 }else{ 460 return true; 461 } 462} 463 464/** 465 * print a nice message even if no styles are loaded yet. 466 */ 467function nice_die($msg){ 468 echo<<<EOT 469<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 470 "http://www.w3.org/TR/html4/loose.dtd"> 471<html> 472<head><title>DokuWiki Setup Error</title></head> 473<body style="font-family: Arial, sans-serif"> 474 <div style="width:60%; margin: auto; background-color: #fcc; 475 border: 1px solid #faa; padding: 0.5em 1em;"> 476 <h1 style="font-size: 120%">DokuWiki Setup Error</h1> 477 <p>$msg</p> 478 </div> 479</body> 480</html> 481EOT; 482 exit; 483} 484 485/** 486 * A realpath() replacement 487 * 488 * This function behaves similar to PHP's realpath() but does not resolve 489 * symlinks or accesses upper directories 490 * 491 * @author Andreas Gohr <andi@splitbrain.org> 492 * @author <richpageau at yahoo dot co dot uk> 493 * @link http://de3.php.net/manual/en/function.realpath.php#75992 494 */ 495function fullpath($path,$exists=false){ 496 static $run = 0; 497 $root = ''; 498 $iswin = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' || @$GLOBALS['DOKU_UNITTEST_ASSUME_WINDOWS']); 499 500 // find the (indestructable) root of the path - keeps windows stuff intact 501 if($path{0} == '/'){ 502 $root = '/'; 503 }elseif($iswin){ 504 // match drive letter and UNC paths 505 if(preg_match('!^([a-zA-z]:)(.*)!',$path,$match)){ 506 $root = $match[1].'/'; 507 $path = $match[2]; 508 }else if(preg_match('!^(\\\\\\\\[^\\\\/]+\\\\[^\\\\/]+[\\\\/])(.*)!',$path,$match)){ 509 $root = $match[1]; 510 $path = $match[2]; 511 } 512 } 513 $path = str_replace('\\','/',$path); 514 515 // if the given path wasn't absolute already, prepend the script path and retry 516 if(!$root){ 517 $base = dirname($_SERVER['SCRIPT_FILENAME']); 518 $path = $base.'/'.$path; 519 if($run == 0){ // avoid endless recursion when base isn't absolute for some reason 520 $run++; 521 return fullpath($path,$exists); 522 } 523 } 524 $run = 0; 525 526 // canonicalize 527 $path=explode('/', $path); 528 $newpath=array(); 529 foreach($path as $p) { 530 if ($p === '' || $p === '.') continue; 531 if ($p==='..') { 532 array_pop($newpath); 533 continue; 534 } 535 array_push($newpath, $p); 536 } 537 $finalpath = $root.implode('/', $newpath); 538 539 // check for existance when needed (except when unit testing) 540 if($exists && !defined('DOKU_UNITTEST') && !@file_exists($finalpath)) { 541 return false; 542 } 543 return $finalpath; 544} 545 546