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 $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir']; 150 if (version_compare(PHP_VERSION, '5.2.0', '>')) { 151 session_set_cookie_params(0,$cookieDir,'',($conf['securecookie'] && is_ssl()),true); 152 }else{ 153 session_set_cookie_params(0,$cookieDir,'',($conf['securecookie'] && is_ssl())); 154 } 155 session_start(); 156 157 // load left over messages 158 if(isset($_SESSION[DOKU_COOKIE]['msg'])){ 159 $MSG = $_SESSION[DOKU_COOKIE]['msg']; 160 unset($_SESSION[DOKU_COOKIE]['msg']); 161 } 162} 163 164// kill magic quotes 165if (get_magic_quotes_gpc() && !defined('MAGIC_QUOTES_STRIPPED')) { 166 if (!empty($_GET)) remove_magic_quotes($_GET); 167 if (!empty($_POST)) remove_magic_quotes($_POST); 168 if (!empty($_COOKIE)) remove_magic_quotes($_COOKIE); 169 if (!empty($_REQUEST)) remove_magic_quotes($_REQUEST); 170 @ini_set('magic_quotes_gpc', 0); 171 define('MAGIC_QUOTES_STRIPPED',1); 172} 173@set_magic_quotes_runtime(0); 174@ini_set('magic_quotes_sybase',0); 175 176// don't let cookies ever interfere with request vars 177$_REQUEST = array_merge($_GET,$_POST); 178 179// we don't want a purge URL to be digged 180if(isset($_REQUEST['purge']) && $_SERVER['HTTP_REFERER']) unset($_REQUEST['purge']); 181 182// disable gzip if not available 183if($conf['compression'] == 'bz2' && !function_exists('bzopen')){ 184 $conf['compression'] = 'gz'; 185} 186if($conf['compression'] == 'gz' && !function_exists('gzopen')){ 187 $conf['compression'] = 0; 188} 189 190// fix dateformat for upgraders 191if(strpos($conf['dformat'],'%') === false){ 192 $conf['dformat'] = '%Y/%m/%d %H:%M'; 193} 194 195// precalculate file creation modes 196init_creationmodes(); 197 198// make real paths and check them 199init_paths(); 200init_files(); 201 202// setup plugin controller class (can be overwritten in preload.php) 203$plugin_types = array('admin','syntax','action','renderer', 'helper'); 204global $plugin_controller_class, $plugin_controller; 205if (empty($plugin_controller_class)) $plugin_controller_class = 'Doku_Plugin_Controller'; 206 207// load libraries 208require_once(DOKU_INC.'inc/load.php'); 209 210// initialize plugin controller 211$plugin_controller = new $plugin_controller_class(); 212 213// initialize the event handler 214global $EVENT_HANDLER; 215$EVENT_HANDLER = new Doku_Event_Handler(); 216 217// setup authentication system 218if (!defined('NOSESSION')) { 219 auth_setup(); 220} 221 222// setup mail system 223mail_setup(); 224 225/** 226 * Checks paths from config file 227 */ 228function init_paths(){ 229 global $conf; 230 231 $paths = array('datadir' => 'pages', 232 'olddir' => 'attic', 233 'mediadir' => 'media', 234 'metadir' => 'meta', 235 'cachedir' => 'cache', 236 'indexdir' => 'index', 237 'lockdir' => 'locks', 238 'tmpdir' => 'tmp'); 239 240 foreach($paths as $c => $p){ 241 if(empty($conf[$c])) $conf[$c] = $conf['savedir'].'/'.$p; 242 $conf[$c] = init_path($conf[$c]); 243 if(empty($conf[$c])) nice_die("The $c ('$p') does not exist, isn't accessible or writable. 244 You should check your config and permission settings. 245 Or maybe you want to <a href=\"install.php\">run the 246 installer</a>?"); 247 } 248 249 // path to old changelog only needed for upgrading 250 $conf['changelog_old'] = init_path((isset($conf['changelog']))?($conf['changelog']):($conf['savedir'].'/changes.log')); 251 if ($conf['changelog_old']=='') { unset($conf['changelog_old']); } 252 // hardcoded changelog because it is now a cache that lives in meta 253 $conf['changelog'] = $conf['metadir'].'/_dokuwiki.changes'; 254 $conf['media_changelog'] = $conf['metadir'].'/_media.changes'; 255} 256 257/** 258 * Checks the existance of certain files and creates them if missing. 259 */ 260function init_files(){ 261 global $conf; 262 263 $files = array($conf['indexdir'].'/page.idx'); 264 265 foreach($files as $file){ 266 if(!@file_exists($file)){ 267 $fh = @fopen($file,'a'); 268 if($fh){ 269 fclose($fh); 270 if($conf['fperm']) chmod($file, $conf['fperm']); 271 }else{ 272 nice_die("$file is not writable. Check your permissions settings!"); 273 } 274 } 275 } 276 277 # create title index (needs to have same length as page.idx) 278 /* 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/** 297 * Returns absolute path 298 * 299 * This tries the given path first, then checks in DOKU_INC. 300 * Check for accessability on directories as well. 301 * 302 * @author Andreas Gohr <andi@splitbrain.org> 303 */ 304function init_path($path){ 305 // check existance 306 $p = fullpath($path); 307 if(!@file_exists($p)){ 308 $p = fullpath(DOKU_INC.$path); 309 if(!@file_exists($p)){ 310 return ''; 311 } 312 } 313 314 // check writability 315 if(!@is_writable($p)){ 316 return ''; 317 } 318 319 // check accessability (execute bit) for directories 320 if(@is_dir($p) && !@file_exists("$p/.")){ 321 return ''; 322 } 323 324 return $p; 325} 326 327/** 328 * Sets the internal config values fperm and dperm which, when set, 329 * will be used to change the permission of a newly created dir or 330 * file with chmod. Considers the influence of the system's umask 331 * setting the values only if needed. 332 */ 333function init_creationmodes(){ 334 global $conf; 335 336 // Legacy support for old umask/dmask scheme 337 unset($conf['dmask']); 338 unset($conf['fmask']); 339 unset($conf['umask']); 340 unset($conf['fperm']); 341 unset($conf['dperm']); 342 343 // get system umask, fallback to 0 if none available 344 $umask = @umask(); 345 if(!$umask) $umask = 0000; 346 347 // check what is set automatically by the system on file creation 348 // and set the fperm param if it's not what we want 349 $auto_fmode = 0666 & ~$umask; 350 if($auto_fmode != $conf['fmode']) $conf['fperm'] = $conf['fmode']; 351 352 // check what is set automatically by the system on file creation 353 // and set the dperm param if it's not what we want 354 $auto_dmode = $conf['dmode'] & ~$umask; 355 if($auto_dmode != $conf['dmode']) $conf['dperm'] = $conf['dmode']; 356} 357 358/** 359 * remove magic quotes recursivly 360 * 361 * @author Andreas Gohr <andi@splitbrain.org> 362 */ 363function remove_magic_quotes(&$array) { 364 foreach (array_keys($array) as $key) { 365 // handle magic quotes in keynames (breaks order) 366 $sk = stripslashes($key); 367 if($sk != $key){ 368 $array[$sk] = $array[$key]; 369 unset($array[$key]); 370 $key = $sk; 371 } 372 373 // do recursion if needed 374 if (is_array($array[$key])) { 375 remove_magic_quotes($array[$key]); 376 }else { 377 $array[$key] = stripslashes($array[$key]); 378 } 379 } 380} 381 382/** 383 * Returns the full absolute URL to the directory where 384 * DokuWiki is installed in (includes a trailing slash) 385 * 386 * @author Andreas Gohr <andi@splitbrain.org> 387 */ 388function getBaseURL($abs=null){ 389 global $conf; 390 //if canonical url enabled always return absolute 391 if(is_null($abs)) $abs = $conf['canonical']; 392 393 if($conf['basedir']){ 394 $dir = $conf['basedir']; 395 }elseif(substr($_SERVER['SCRIPT_NAME'],-4) == '.php'){ 396 $dir = dirname($_SERVER['SCRIPT_NAME']); 397 }elseif(substr($_SERVER['PHP_SELF'],-4) == '.php'){ 398 $dir = dirname($_SERVER['PHP_SELF']); 399 }elseif($_SERVER['DOCUMENT_ROOT'] && $_SERVER['SCRIPT_FILENAME']){ 400 $dir = preg_replace ('/^'.preg_quote($_SERVER['DOCUMENT_ROOT'],'/').'/','', 401 $_SERVER['SCRIPT_FILENAME']); 402 $dir = dirname('/'.$dir); 403 }else{ 404 $dir = '.'; //probably wrong 405 } 406 407 $dir = str_replace('\\','/',$dir); // bugfix for weird WIN behaviour 408 $dir = preg_replace('#//+#','/',"/$dir/"); // ensure leading and trailing slashes 409 410 //handle script in lib/exe dir 411 $dir = preg_replace('!lib/exe/$!','',$dir); 412 413 //handle script in lib/plugins dir 414 $dir = preg_replace('!lib/plugins/.*$!','',$dir); 415 416 //finish here for relative URLs 417 if(!$abs) return $dir; 418 419 //use config option if available, trim any slash from end of baseurl to avoid multiple consecutive slashes in the path 420 if($conf['baseurl']) return rtrim($conf['baseurl'],'/').$dir; 421 422 //split hostheader into host and port 423 if(isset($_SERVER['HTTP_HOST'])){ 424 $parsed_host = parse_url('http://'.$_SERVER['HTTP_HOST']); 425 $host = $parsed_host['host']; 426 $port = $parsed_host['port']; 427 }elseif(isset($_SERVER['SERVER_NAME'])){ 428 $parsed_host = parse_url('http://'.$_SERVER['SERVER_NAME']); 429 $host = $parsed_host['host']; 430 $port = $parsed_host['port']; 431 }else{ 432 $host = php_uname('n'); 433 $port = ''; 434 } 435 436 if(!$port && isset($_SERVER['SERVER_PORT'])) { 437 $port = $_SERVER['SERVER_PORT']; 438 } 439 440 if(is_null($port)){ 441 $port = ''; 442 } 443 444 if(!is_ssl()){ 445 $proto = 'http://'; 446 if ($port == '80') { 447 $port = ''; 448 } 449 }else{ 450 $proto = 'https://'; 451 if ($port == '443') { 452 $port = ''; 453 } 454 } 455 456 if($port !== '') $port = ':'.$port; 457 458 return $proto.$host.$port.$dir; 459} 460 461/** 462 * Check if accessed via HTTPS 463 * 464 * Apache leaves ,$_SERVER['HTTPS'] empty when not available, IIS sets it to 'off'. 465 * 'false' and 'disabled' are just guessing 466 * 467 * @returns bool true when SSL is active 468 */ 469function is_ssl(){ 470 if (!isset($_SERVER['HTTPS']) || 471 preg_match('/^(|off|false|disabled)$/i',$_SERVER['HTTPS'])){ 472 return false; 473 }else{ 474 return true; 475 } 476} 477 478/** 479 * print a nice message even if no styles are loaded yet. 480 */ 481function nice_die($msg){ 482 echo<<<EOT 483<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 484 "http://www.w3.org/TR/html4/loose.dtd"> 485<html> 486<head><title>DokuWiki Setup Error</title></head> 487<body style="font-family: Arial, sans-serif"> 488 <div style="width:60%; margin: auto; background-color: #fcc; 489 border: 1px solid #faa; padding: 0.5em 1em;"> 490 <h1 style="font-size: 120%">DokuWiki Setup Error</h1> 491 <p>$msg</p> 492 </div> 493</body> 494</html> 495EOT; 496 exit; 497} 498 499/** 500 * A realpath() replacement 501 * 502 * This function behaves similar to PHP's realpath() but does not resolve 503 * symlinks or accesses upper directories 504 * 505 * @author Andreas Gohr <andi@splitbrain.org> 506 * @author <richpageau at yahoo dot co dot uk> 507 * @link http://de3.php.net/manual/en/function.realpath.php#75992 508 */ 509function fullpath($path,$exists=false){ 510 static $run = 0; 511 $root = ''; 512 $iswin = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' || @$GLOBALS['DOKU_UNITTEST_ASSUME_WINDOWS']); 513 514 // find the (indestructable) root of the path - keeps windows stuff intact 515 if($path{0} == '/'){ 516 $root = '/'; 517 }elseif($iswin){ 518 // match drive letter and UNC paths 519 if(preg_match('!^([a-zA-z]:)(.*)!',$path,$match)){ 520 $root = $match[1].'/'; 521 $path = $match[2]; 522 }else if(preg_match('!^(\\\\\\\\[^\\\\/]+\\\\[^\\\\/]+[\\\\/])(.*)!',$path,$match)){ 523 $root = $match[1]; 524 $path = $match[2]; 525 } 526 } 527 $path = str_replace('\\','/',$path); 528 529 // if the given path wasn't absolute already, prepend the script path and retry 530 if(!$root){ 531 $base = dirname($_SERVER['SCRIPT_FILENAME']); 532 $path = $base.'/'.$path; 533 if($run == 0){ // avoid endless recursion when base isn't absolute for some reason 534 $run++; 535 return fullpath($path,$exists); 536 } 537 } 538 $run = 0; 539 540 // canonicalize 541 $path=explode('/', $path); 542 $newpath=array(); 543 foreach($path as $p) { 544 if ($p === '' || $p === '.') continue; 545 if ($p==='..') { 546 array_pop($newpath); 547 continue; 548 } 549 array_push($newpath, $p); 550 } 551 $finalpath = $root.implode('/', $newpath); 552 553 // check for existance when needed (except when unit testing) 554 if($exists && !defined('DOKU_UNITTEST') && !@file_exists($finalpath)) { 555 return false; 556 } 557 return $finalpath; 558} 559 560