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', '&'); 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 'mediaolddir' => 'media_attic', 234 'metadir' => 'meta', 235 'mediametadir' => 'media_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 /* 280 $file = $conf['indexdir'].'/title.idx'; 281 if(!@file_exists($file)){ 282 $pages = file($conf['indexdir'].'/page.idx'); 283 $pages = count($pages); 284 $fh = @fopen($file,'a'); 285 if($fh){ 286 for($i=0; $i<$pages; $i++){ 287 fwrite($fh,"\n"); 288 } 289 fclose($fh); 290 }else{ 291 nice_die("$file is not writable. Check your permissions settings!"); 292 } 293 } 294 */ 295} 296 297/** 298 * Returns absolute path 299 * 300 * This tries the given path first, then checks in DOKU_INC. 301 * Check for accessability on directories as well. 302 * 303 * @author Andreas Gohr <andi@splitbrain.org> 304 */ 305function init_path($path){ 306 // check existance 307 $p = fullpath($path); 308 if(!@file_exists($p)){ 309 $p = fullpath(DOKU_INC.$path); 310 if(!@file_exists($p)){ 311 return ''; 312 } 313 } 314 315 // check writability 316 if(!@is_writable($p)){ 317 return ''; 318 } 319 320 // check accessability (execute bit) for directories 321 if(@is_dir($p) && !@file_exists("$p/.")){ 322 return ''; 323 } 324 325 return $p; 326} 327 328/** 329 * Sets the internal config values fperm and dperm which, when set, 330 * will be used to change the permission of a newly created dir or 331 * file with chmod. Considers the influence of the system's umask 332 * setting the values only if needed. 333 */ 334function init_creationmodes(){ 335 global $conf; 336 337 // Legacy support for old umask/dmask scheme 338 unset($conf['dmask']); 339 unset($conf['fmask']); 340 unset($conf['umask']); 341 unset($conf['fperm']); 342 unset($conf['dperm']); 343 344 // get system umask, fallback to 0 if none available 345 $umask = @umask(); 346 if(!$umask) $umask = 0000; 347 348 // check what is set automatically by the system on file creation 349 // and set the fperm param if it's not what we want 350 $auto_fmode = 0666 & ~$umask; 351 if($auto_fmode != $conf['fmode']) $conf['fperm'] = $conf['fmode']; 352 353 // check what is set automatically by the system on file creation 354 // and set the dperm param if it's not what we want 355 $auto_dmode = $conf['dmode'] & ~$umask; 356 if($auto_dmode != $conf['dmode']) $conf['dperm'] = $conf['dmode']; 357} 358 359/** 360 * remove magic quotes recursivly 361 * 362 * @author Andreas Gohr <andi@splitbrain.org> 363 */ 364function remove_magic_quotes(&$array) { 365 foreach (array_keys($array) as $key) { 366 // handle magic quotes in keynames (breaks order) 367 $sk = stripslashes($key); 368 if($sk != $key){ 369 $array[$sk] = $array[$key]; 370 unset($array[$key]); 371 $key = $sk; 372 } 373 374 // do recursion if needed 375 if (is_array($array[$key])) { 376 remove_magic_quotes($array[$key]); 377 }else { 378 $array[$key] = stripslashes($array[$key]); 379 } 380 } 381} 382 383/** 384 * Returns the full absolute URL to the directory where 385 * DokuWiki is installed in (includes a trailing slash) 386 * 387 * @author Andreas Gohr <andi@splitbrain.org> 388 */ 389function getBaseURL($abs=null){ 390 global $conf; 391 //if canonical url enabled always return absolute 392 if(is_null($abs)) $abs = $conf['canonical']; 393 394 if($conf['basedir']){ 395 $dir = $conf['basedir']; 396 }elseif(substr($_SERVER['SCRIPT_NAME'],-4) == '.php'){ 397 $dir = dirname($_SERVER['SCRIPT_NAME']); 398 }elseif(substr($_SERVER['PHP_SELF'],-4) == '.php'){ 399 $dir = dirname($_SERVER['PHP_SELF']); 400 }elseif($_SERVER['DOCUMENT_ROOT'] && $_SERVER['SCRIPT_FILENAME']){ 401 $dir = preg_replace ('/^'.preg_quote($_SERVER['DOCUMENT_ROOT'],'/').'/','', 402 $_SERVER['SCRIPT_FILENAME']); 403 $dir = dirname('/'.$dir); 404 }else{ 405 $dir = '.'; //probably wrong 406 } 407 408 $dir = str_replace('\\','/',$dir); // bugfix for weird WIN behaviour 409 $dir = preg_replace('#//+#','/',"/$dir/"); // ensure leading and trailing slashes 410 411 //handle script in lib/exe dir 412 $dir = preg_replace('!lib/exe/$!','',$dir); 413 414 //handle script in lib/plugins dir 415 $dir = preg_replace('!lib/plugins/.*$!','',$dir); 416 417 //finish here for relative URLs 418 if(!$abs) return $dir; 419 420 //use config option if available, trim any slash from end of baseurl to avoid multiple consecutive slashes in the path 421 if($conf['baseurl']) return rtrim($conf['baseurl'],'/').$dir; 422 423 //split hostheader into host and port 424 if(isset($_SERVER['HTTP_HOST'])){ 425 $parsed_host = parse_url('http://'.$_SERVER['HTTP_HOST']); 426 $host = $parsed_host['host']; 427 $port = $parsed_host['port']; 428 }elseif(isset($_SERVER['SERVER_NAME'])){ 429 $parsed_host = parse_url('http://'.$_SERVER['SERVER_NAME']); 430 $host = $parsed_host['host']; 431 $port = $parsed_host['port']; 432 }else{ 433 $host = php_uname('n'); 434 $port = ''; 435 } 436 437 if(!$port && isset($_SERVER['SERVER_PORT'])) { 438 $port = $_SERVER['SERVER_PORT']; 439 } 440 441 if(is_null($port)){ 442 $port = ''; 443 } 444 445 if(!is_ssl()){ 446 $proto = 'http://'; 447 if ($port == '80') { 448 $port = ''; 449 } 450 }else{ 451 $proto = 'https://'; 452 if ($port == '443') { 453 $port = ''; 454 } 455 } 456 457 if($port !== '') $port = ':'.$port; 458 459 return $proto.$host.$port.$dir; 460} 461 462/** 463 * Check if accessed via HTTPS 464 * 465 * Apache leaves ,$_SERVER['HTTPS'] empty when not available, IIS sets it to 'off'. 466 * 'false' and 'disabled' are just guessing 467 * 468 * @returns bool true when SSL is active 469 */ 470function is_ssl(){ 471 if (!isset($_SERVER['HTTPS']) || 472 preg_match('/^(|off|false|disabled)$/i',$_SERVER['HTTPS'])){ 473 return false; 474 }else{ 475 return true; 476 } 477} 478 479/** 480 * print a nice message even if no styles are loaded yet. 481 */ 482function nice_die($msg){ 483 echo<<<EOT 484<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 485 "http://www.w3.org/TR/html4/loose.dtd"> 486<html> 487<head><title>DokuWiki Setup Error</title></head> 488<body style="font-family: Arial, sans-serif"> 489 <div style="width:60%; margin: auto; background-color: #fcc; 490 border: 1px solid #faa; padding: 0.5em 1em;"> 491 <h1 style="font-size: 120%">DokuWiki Setup Error</h1> 492 <p>$msg</p> 493 </div> 494</body> 495</html> 496EOT; 497 exit; 498} 499 500/** 501 * A realpath() replacement 502 * 503 * This function behaves similar to PHP's realpath() but does not resolve 504 * symlinks or accesses upper directories 505 * 506 * @author Andreas Gohr <andi@splitbrain.org> 507 * @author <richpageau at yahoo dot co dot uk> 508 * @link http://de3.php.net/manual/en/function.realpath.php#75992 509 */ 510function fullpath($path,$exists=false){ 511 static $run = 0; 512 $root = ''; 513 $iswin = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' || @$GLOBALS['DOKU_UNITTEST_ASSUME_WINDOWS']); 514 515 // find the (indestructable) root of the path - keeps windows stuff intact 516 if($path{0} == '/'){ 517 $root = '/'; 518 }elseif($iswin){ 519 // match drive letter and UNC paths 520 if(preg_match('!^([a-zA-z]:)(.*)!',$path,$match)){ 521 $root = $match[1].'/'; 522 $path = $match[2]; 523 }else if(preg_match('!^(\\\\\\\\[^\\\\/]+\\\\[^\\\\/]+[\\\\/])(.*)!',$path,$match)){ 524 $root = $match[1]; 525 $path = $match[2]; 526 } 527 } 528 $path = str_replace('\\','/',$path); 529 530 // if the given path wasn't absolute already, prepend the script path and retry 531 if(!$root){ 532 $base = dirname($_SERVER['SCRIPT_FILENAME']); 533 $path = $base.'/'.$path; 534 if($run == 0){ // avoid endless recursion when base isn't absolute for some reason 535 $run++; 536 return fullpath($path,$exists); 537 } 538 } 539 $run = 0; 540 541 // canonicalize 542 $path=explode('/', $path); 543 $newpath=array(); 544 foreach($path as $p) { 545 if ($p === '' || $p === '.') continue; 546 if ($p==='..') { 547 array_pop($newpath); 548 continue; 549 } 550 array_push($newpath, $p); 551 } 552 $finalpath = $root.implode('/', $newpath); 553 554 // check for existance when needed (except when unit testing) 555 if($exists && !defined('DOKU_UNITTEST') && !@file_exists($finalpath)) { 556 return false; 557 } 558 return $finalpath; 559} 560 561