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 /* 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 $addr = explode(':',$_SERVER['HTTP_HOST']); 425 $host = $addr[0]; 426 $port = ''; 427 if (isset($addr[1])) { 428 $port = $addr[1]; 429 } elseif (isset($_SERVER['SERVER_PORT'])) { 430 $port = $_SERVER['SERVER_PORT']; 431 } 432 if(!is_ssl()){ 433 $proto = 'http://'; 434 if ($port == '80') { 435 $port = ''; 436 } 437 }else{ 438 $proto = 'https://'; 439 if ($port == '443') { 440 $port = ''; 441 } 442 } 443 444 if($port !== '') $port = ':'.$port; 445 446 return $proto.$host.$port.$dir; 447} 448 449/** 450 * Check if accessed via HTTPS 451 * 452 * Apache leaves ,$_SERVER['HTTPS'] empty when not available, IIS sets it to 'off'. 453 * 'false' and 'disabled' are just guessing 454 * 455 * @returns bool true when SSL is active 456 */ 457function is_ssl(){ 458 if (!isset($_SERVER['HTTPS']) || 459 preg_match('/^(|off|false|disabled)$/i',$_SERVER['HTTPS'])){ 460 return false; 461 }else{ 462 return true; 463 } 464} 465 466/** 467 * print a nice message even if no styles are loaded yet. 468 */ 469function nice_die($msg){ 470 echo<<<EOT 471<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 472 "http://www.w3.org/TR/html4/loose.dtd"> 473<html> 474<head><title>DokuWiki Setup Error</title></head> 475<body style="font-family: Arial, sans-serif"> 476 <div style="width:60%; margin: auto; background-color: #fcc; 477 border: 1px solid #faa; padding: 0.5em 1em;"> 478 <h1 style="font-size: 120%">DokuWiki Setup Error</h1> 479 <p>$msg</p> 480 </div> 481</body> 482</html> 483EOT; 484 exit; 485} 486 487/** 488 * A realpath() replacement 489 * 490 * This function behaves similar to PHP's realpath() but does not resolve 491 * symlinks or accesses upper directories 492 * 493 * @author Andreas Gohr <andi@splitbrain.org> 494 * @author <richpageau at yahoo dot co dot uk> 495 * @link http://de3.php.net/manual/en/function.realpath.php#75992 496 */ 497function fullpath($path,$exists=false){ 498 static $run = 0; 499 $root = ''; 500 $iswin = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' || @$GLOBALS['DOKU_UNITTEST_ASSUME_WINDOWS']); 501 502 // find the (indestructable) root of the path - keeps windows stuff intact 503 if($path{0} == '/'){ 504 $root = '/'; 505 }elseif($iswin){ 506 // match drive letter and UNC paths 507 if(preg_match('!^([a-zA-z]:)(.*)!',$path,$match)){ 508 $root = $match[1].'/'; 509 $path = $match[2]; 510 }else if(preg_match('!^(\\\\\\\\[^\\\\/]+\\\\[^\\\\/]+[\\\\/])(.*)!',$path,$match)){ 511 $root = $match[1]; 512 $path = $match[2]; 513 } 514 } 515 $path = str_replace('\\','/',$path); 516 517 // if the given path wasn't absolute already, prepend the script path and retry 518 if(!$root){ 519 $base = dirname($_SERVER['SCRIPT_FILENAME']); 520 $path = $base.'/'.$path; 521 if($run == 0){ // avoid endless recursion when base isn't absolute for some reason 522 $run++; 523 return fullpath($path,$exists); 524 } 525 } 526 $run = 0; 527 528 // canonicalize 529 $path=explode('/', $path); 530 $newpath=array(); 531 foreach($path as $p) { 532 if ($p === '' || $p === '.') continue; 533 if ($p==='..') { 534 array_pop($newpath); 535 continue; 536 } 537 array_push($newpath, $p); 538 } 539 $finalpath = $root.implode('/', $newpath); 540 541 // check for existance when needed (except when unit testing) 542 if($exists && !defined('DOKU_UNITTEST') && !@file_exists($finalpath)) { 543 return false; 544 } 545 return $finalpath; 546} 547 548