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