1<?php 2/** 3 * Initialize some defaults needed for DokuWiki 4 */ 5 6 7/** 8 * timing Dokuwiki execution 9 * 10 * @param integer $start 11 * 12 * @return mixed 13 */ 14function delta_time($start=0) { 15 return microtime(true)-((float)$start); 16} 17define('DOKU_START_TIME', delta_time()); 18 19global $config_cascade; 20$config_cascade = array(); 21 22// if available load a preload config file 23$preload = fullpath(dirname(__FILE__)).'/preload.php'; 24if (file_exists($preload)) include($preload); 25 26// define the include path 27if(!defined('DOKU_INC')) define('DOKU_INC',fullpath(dirname(__FILE__).'/../').'/'); 28 29// define Plugin dir 30if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/'); 31 32// define config path (packagers may want to change this to /etc/dokuwiki/) 33if(!defined('DOKU_CONF')) define('DOKU_CONF',DOKU_INC.'conf/'); 34 35// check for error reporting override or set error reporting to sane values 36if (!defined('DOKU_E_LEVEL') && file_exists(DOKU_CONF.'report_e_all')) { 37 define('DOKU_E_LEVEL', E_ALL); 38} 39if (!defined('DOKU_E_LEVEL')) { 40 error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT); 41} else { 42 error_reporting(DOKU_E_LEVEL); 43} 44 45// avoid caching issues #1594 46header('Vary: Cookie'); 47 48// init memory caches 49global $cache_revinfo; 50 $cache_revinfo = array(); 51global $cache_wikifn; 52 $cache_wikifn = array(); 53global $cache_cleanid; 54 $cache_cleanid = array(); 55global $cache_authname; 56 $cache_authname = array(); 57global $cache_metadata; 58 $cache_metadata = array(); 59 60// always include 'inc/config_cascade.php' 61// previously in preload.php set fields of $config_cascade will be merged with the defaults 62include(DOKU_INC.'inc/config_cascade.php'); 63 64//prepare config array() 65global $conf; 66$conf = array(); 67 68// load the global config file(s) 69foreach (array('default','local','protected') as $config_group) { 70 if (empty($config_cascade['main'][$config_group])) continue; 71 foreach ($config_cascade['main'][$config_group] as $config_file) { 72 if (file_exists($config_file)) { 73 include($config_file); 74 } 75 } 76} 77 78//prepare license array() 79global $license; 80$license = array(); 81 82// load the license file(s) 83foreach (array('default','local') as $config_group) { 84 if (empty($config_cascade['license'][$config_group])) continue; 85 foreach ($config_cascade['license'][$config_group] as $config_file) { 86 if(file_exists($config_file)){ 87 include($config_file); 88 } 89 } 90} 91 92// set timezone (as in pre 5.3.0 days) 93date_default_timezone_set(@date_default_timezone_get()); 94 95// define baseURL 96if(!defined('DOKU_REL')) define('DOKU_REL',getBaseURL(false)); 97if(!defined('DOKU_URL')) define('DOKU_URL',getBaseURL(true)); 98if(!defined('DOKU_BASE')){ 99 if($conf['canonical']){ 100 define('DOKU_BASE',DOKU_URL); 101 }else{ 102 define('DOKU_BASE',DOKU_REL); 103 } 104} 105 106// define whitespace 107if(!defined('DOKU_LF')) define ('DOKU_LF',"\n"); 108if(!defined('DOKU_TAB')) define ('DOKU_TAB',"\t"); 109 110// define cookie and session id, append server port when securecookie is configured FS#1664 111if (!defined('DOKU_COOKIE')) { 112 $serverPort = isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : ''; 113 define('DOKU_COOKIE', 'DW' . md5(DOKU_REL . (($conf['securecookie']) ? $serverPort : ''))); 114} 115 116 117// define main script 118if(!defined('DOKU_SCRIPT')) define('DOKU_SCRIPT','doku.php'); 119 120if(!defined('DOKU_TPL')) { 121 /** 122 * @deprecated 2012-10-13 replaced by more dynamic method 123 * @see tpl_basedir() 124 */ 125 define('DOKU_TPL', DOKU_BASE.'lib/tpl/'.$conf['template'].'/'); 126} 127 128if(!defined('DOKU_TPLINC')) { 129 /** 130 * @deprecated 2012-10-13 replaced by more dynamic method 131 * @see tpl_incdir() 132 */ 133 define('DOKU_TPLINC', DOKU_INC.'lib/tpl/'.$conf['template'].'/'); 134} 135 136// make session rewrites XHTML compliant 137@ini_set('arg_separator.output', '&'); 138 139// make sure global zlib does not interfere FS#1132 140@ini_set('zlib.output_compression', 'off'); 141 142// increase PCRE backtrack limit 143@ini_set('pcre.backtrack_limit', '20971520'); 144 145// enable gzip compression if supported 146$httpAcceptEncoding = isset($_SERVER['HTTP_ACCEPT_ENCODING']) ? $_SERVER['HTTP_ACCEPT_ENCODING'] : ''; 147$conf['gzip_output'] &= (strpos($httpAcceptEncoding, 'gzip') !== false); 148global $ACT; 149if ($conf['gzip_output'] && 150 !defined('DOKU_DISABLE_GZIP_OUTPUT') && 151 function_exists('ob_gzhandler') && 152 // Disable compression when a (compressed) sitemap might be delivered 153 // See https://bugs.dokuwiki.org/index.php?do=details&task_id=2576 154 $ACT != 'sitemap') { 155 ob_start('ob_gzhandler'); 156} 157 158// init session 159if(!headers_sent() && !defined('NOSESSION')) { 160 if(!defined('DOKU_SESSION_NAME')) define ('DOKU_SESSION_NAME', "DokuWiki"); 161 if(!defined('DOKU_SESSION_LIFETIME')) define ('DOKU_SESSION_LIFETIME', 0); 162 if(!defined('DOKU_SESSION_PATH')) { 163 $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir']; 164 define ('DOKU_SESSION_PATH', $cookieDir); 165 } 166 if(!defined('DOKU_SESSION_DOMAIN')) define ('DOKU_SESSION_DOMAIN', ''); 167 168 // start the session 169 init_session(); 170 171 // load left over messages 172 if(isset($_SESSION[DOKU_COOKIE]['msg'])) { 173 $MSG = $_SESSION[DOKU_COOKIE]['msg']; 174 unset($_SESSION[DOKU_COOKIE]['msg']); 175 } 176} 177 178// don't let cookies ever interfere with request vars 179$_REQUEST = array_merge($_GET,$_POST); 180 181// we don't want a purge URL to be digged 182if(isset($_REQUEST['purge']) && !empty($_SERVER['HTTP_REFERER'])) unset($_REQUEST['purge']); 183 184// precalculate file creation modes 185init_creationmodes(); 186 187// make real paths and check them 188init_paths(); 189init_files(); 190 191// setup plugin controller class (can be overwritten in preload.php) 192$plugin_types = array('auth', 'admin','syntax','action','renderer', 'helper','remote'); 193global $plugin_controller_class, $plugin_controller; 194if (empty($plugin_controller_class)) $plugin_controller_class = 'Doku_Plugin_Controller'; 195 196// load libraries 197require_once(DOKU_INC.'vendor/autoload.php'); 198require_once(DOKU_INC.'inc/load.php'); 199 200// disable gzip if not available 201define('DOKU_HAS_BZIP', function_exists('bzopen')); 202define('DOKU_HAS_GZIP', function_exists('gzopen')); 203if($conf['compression'] == 'bz2' && !DOKU_HAS_BZIP) { 204 $conf['compression'] = 'gz'; 205} 206if($conf['compression'] == 'gz' && !DOKU_HAS_GZIP) { 207 $conf['compression'] = 0; 208} 209 210// input handle class 211global $INPUT; 212$INPUT = new Input(); 213 214// initialize plugin controller 215$plugin_controller = new $plugin_controller_class(); 216 217// initialize the event handler 218global $EVENT_HANDLER; 219$EVENT_HANDLER = new Doku_Event_Handler(); 220 221$local = $conf['lang']; 222trigger_event('INIT_LANG_LOAD', $local, 'init_lang', true); 223 224 225// setup authentication system 226if (!defined('NOSESSION')) { 227 auth_setup(); 228} 229 230// setup mail system 231mail_setup(); 232 233/** 234 * Initializes the session 235 * 236 * Makes sure the passed session cookie is valid, invalid ones are ignored an a new session ID is issued 237 * 238 * @link http://stackoverflow.com/a/33024310/172068 239 * @link http://php.net/manual/en/session.configuration.php#ini.session.sid-length 240 */ 241function init_session() { 242 global $conf; 243 session_name(DOKU_SESSION_NAME); 244 session_set_cookie_params(DOKU_SESSION_LIFETIME, DOKU_SESSION_PATH, DOKU_SESSION_DOMAIN, ($conf['securecookie'] && is_ssl()), true); 245 246 // make sure the session cookie contains a valid session ID 247 if(isset($_COOKIE[DOKU_SESSION_NAME]) && !preg_match('/^[-,a-zA-Z0-9]{22,256}$/', $_COOKIE[DOKU_SESSION_NAME])) { 248 unset($_COOKIE[DOKU_SESSION_NAME]); 249 } 250 251 session_start(); 252} 253 254 255/** 256 * Checks paths from config file 257 */ 258function init_paths(){ 259 global $conf; 260 261 $paths = array('datadir' => 'pages', 262 'olddir' => 'attic', 263 'mediadir' => 'media', 264 'mediaolddir' => 'media_attic', 265 'metadir' => 'meta', 266 'mediametadir' => 'media_meta', 267 'cachedir' => 'cache', 268 'indexdir' => 'index', 269 'lockdir' => 'locks', 270 'tmpdir' => 'tmp'); 271 272 foreach($paths as $c => $p) { 273 $path = empty($conf[$c]) ? $conf['savedir'].'/'.$p : $conf[$c]; 274 $conf[$c] = init_path($path); 275 if(empty($conf[$c])) 276 nice_die("The $c ('$p') at $path is not found, isn't accessible or writable. 277 You should check your config and permission settings. 278 Or maybe you want to <a href=\"install.php\">run the 279 installer</a>?"); 280 } 281 282 // path to old changelog only needed for upgrading 283 $conf['changelog_old'] = init_path((isset($conf['changelog']))?($conf['changelog']):($conf['savedir'].'/changes.log')); 284 if ($conf['changelog_old']=='') { unset($conf['changelog_old']); } 285 // hardcoded changelog because it is now a cache that lives in meta 286 $conf['changelog'] = $conf['metadir'].'/_dokuwiki.changes'; 287 $conf['media_changelog'] = $conf['metadir'].'/_media.changes'; 288} 289 290/** 291 * Load the language strings 292 * 293 * @param string $langCode language code, as passed by event handler 294 */ 295function init_lang($langCode) { 296 //prepare language array 297 global $lang, $config_cascade; 298 $lang = array(); 299 300 //load the language files 301 require(DOKU_INC.'inc/lang/en/lang.php'); 302 foreach ($config_cascade['lang']['core'] as $config_file) { 303 if (file_exists($config_file . 'en/lang.php')) { 304 include($config_file . 'en/lang.php'); 305 } 306 } 307 308 if ($langCode && $langCode != 'en') { 309 if (file_exists(DOKU_INC."inc/lang/$langCode/lang.php")) { 310 require(DOKU_INC."inc/lang/$langCode/lang.php"); 311 } 312 foreach ($config_cascade['lang']['core'] as $config_file) { 313 if (file_exists($config_file . "$langCode/lang.php")) { 314 include($config_file . "$langCode/lang.php"); 315 } 316 } 317 } 318} 319 320/** 321 * Checks the existence of certain files and creates them if missing. 322 */ 323function init_files(){ 324 global $conf; 325 326 $files = array($conf['indexdir'].'/page.idx'); 327 328 foreach($files as $file){ 329 if(!file_exists($file)){ 330 $fh = @fopen($file,'a'); 331 if($fh){ 332 fclose($fh); 333 if(!empty($conf['fperm'])) chmod($file, $conf['fperm']); 334 }else{ 335 nice_die("$file is not writable. Check your permissions settings!"); 336 } 337 } 338 } 339} 340 341/** 342 * Returns absolute path 343 * 344 * This tries the given path first, then checks in DOKU_INC. 345 * Check for accessibility on directories as well. 346 * 347 * @author Andreas Gohr <andi@splitbrain.org> 348 * 349 * @param string $path 350 * 351 * @return bool|string 352 */ 353function init_path($path){ 354 // check existence 355 $p = fullpath($path); 356 if(!file_exists($p)){ 357 $p = fullpath(DOKU_INC.$path); 358 if(!file_exists($p)){ 359 return ''; 360 } 361 } 362 363 // check writability 364 if(!@is_writable($p)){ 365 return ''; 366 } 367 368 // check accessability (execute bit) for directories 369 if(@is_dir($p) && !file_exists("$p/.")){ 370 return ''; 371 } 372 373 return $p; 374} 375 376/** 377 * Sets the internal config values fperm and dperm which, when set, 378 * will be used to change the permission of a newly created dir or 379 * file with chmod. Considers the influence of the system's umask 380 * setting the values only if needed. 381 */ 382function init_creationmodes(){ 383 global $conf; 384 385 // Legacy support for old umask/dmask scheme 386 unset($conf['dmask']); 387 unset($conf['fmask']); 388 unset($conf['umask']); 389 unset($conf['fperm']); 390 unset($conf['dperm']); 391 392 // get system umask, fallback to 0 if none available 393 $umask = @umask(); 394 if(!$umask) $umask = 0000; 395 396 // check what is set automatically by the system on file creation 397 // and set the fperm param if it's not what we want 398 $auto_fmode = 0666 & ~$umask; 399 if($auto_fmode != $conf['fmode']) $conf['fperm'] = $conf['fmode']; 400 401 // check what is set automatically by the system on file creation 402 // and set the dperm param if it's not what we want 403 $auto_dmode = $conf['dmode'] & ~$umask; 404 if($auto_dmode != $conf['dmode']) $conf['dperm'] = $conf['dmode']; 405} 406 407/** 408 * Returns the full absolute URL to the directory where 409 * DokuWiki is installed in (includes a trailing slash) 410 * 411 * !! Can not access $_SERVER values through $INPUT 412 * !! here as this function is called before $INPUT is 413 * !! initialized. 414 * 415 * @author Andreas Gohr <andi@splitbrain.org> 416 * 417 * @param null|string $abs 418 * 419 * @return string 420 */ 421function getBaseURL($abs=null){ 422 global $conf; 423 //if canonical url enabled always return absolute 424 if(is_null($abs)) $abs = $conf['canonical']; 425 426 if(!empty($conf['basedir'])){ 427 $dir = $conf['basedir']; 428 }elseif(substr($_SERVER['SCRIPT_NAME'],-4) == '.php'){ 429 $dir = dirname($_SERVER['SCRIPT_NAME']); 430 }elseif(substr($_SERVER['PHP_SELF'],-4) == '.php'){ 431 $dir = dirname($_SERVER['PHP_SELF']); 432 }elseif($_SERVER['DOCUMENT_ROOT'] && $_SERVER['SCRIPT_FILENAME']){ 433 $dir = preg_replace ('/^'.preg_quote($_SERVER['DOCUMENT_ROOT'],'/').'/','', 434 $_SERVER['SCRIPT_FILENAME']); 435 $dir = dirname('/'.$dir); 436 }else{ 437 $dir = '.'; //probably wrong 438 } 439 440 $dir = str_replace('\\','/',$dir); // bugfix for weird WIN behaviour 441 $dir = preg_replace('#//+#','/',"/$dir/"); // ensure leading and trailing slashes 442 443 //handle script in lib/exe dir 444 $dir = preg_replace('!lib/exe/$!','',$dir); 445 446 //handle script in lib/plugins dir 447 $dir = preg_replace('!lib/plugins/.*$!','',$dir); 448 449 //finish here for relative URLs 450 if(!$abs) return $dir; 451 452 //use config option if available, trim any slash from end of baseurl to avoid multiple consecutive slashes in the path 453 if(!empty($conf['baseurl'])) return rtrim($conf['baseurl'],'/').$dir; 454 455 //split hostheader into host and port 456 if(isset($_SERVER['HTTP_HOST'])){ 457 $parsed_host = parse_url('http://'.$_SERVER['HTTP_HOST']); 458 $host = isset($parsed_host['host']) ? $parsed_host['host'] : null; 459 $port = isset($parsed_host['port']) ? $parsed_host['port'] : null; 460 }elseif(isset($_SERVER['SERVER_NAME'])){ 461 $parsed_host = parse_url('http://'.$_SERVER['SERVER_NAME']); 462 $host = isset($parsed_host['host']) ? $parsed_host['host'] : null; 463 $port = isset($parsed_host['port']) ? $parsed_host['port'] : null; 464 }else{ 465 $host = php_uname('n'); 466 $port = ''; 467 } 468 469 if(is_null($port)){ 470 $port = ''; 471 } 472 473 if(!is_ssl()){ 474 $proto = 'http://'; 475 if ($port == '80') { 476 $port = ''; 477 } 478 }else{ 479 $proto = 'https://'; 480 if ($port == '443') { 481 $port = ''; 482 } 483 } 484 485 if($port !== '') $port = ':'.$port; 486 487 return $proto.$host.$port.$dir; 488} 489 490/** 491 * Check if accessed via HTTPS 492 * 493 * Apache leaves ,$_SERVER['HTTPS'] empty when not available, IIS sets it to 'off'. 494 * 'false' and 'disabled' are just guessing 495 * 496 * @returns bool true when SSL is active 497 */ 498function is_ssl() { 499 // check if we are behind a reverse proxy 500 if(isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) { 501 if($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') { 502 return true; 503 } else { 504 return false; 505 } 506 } 507 if(!isset($_SERVER['HTTPS']) || 508 preg_match('/^(|off|false|disabled)$/i', $_SERVER['HTTPS'])) { 509 return false; 510 } else { 511 return true; 512 } 513} 514 515/** 516 * checks it is windows OS 517 * @return bool 518 */ 519function isWindows() { 520 return (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? true : false; 521} 522 523/** 524 * print a nice message even if no styles are loaded yet. 525 * 526 * @param integer|string $msg 527 */ 528function nice_die($msg){ 529 echo<<<EOT 530<!DOCTYPE html> 531<html> 532<head><title>DokuWiki Setup Error</title></head> 533<body style="font-family: Arial, sans-serif"> 534 <div style="width:60%; margin: auto; background-color: #fcc; 535 border: 1px solid #faa; padding: 0.5em 1em;"> 536 <h1 style="font-size: 120%">DokuWiki Setup Error</h1> 537 <p>$msg</p> 538 </div> 539</body> 540</html> 541EOT; 542 if(defined('DOKU_UNITTEST')) { 543 throw new RuntimeException('nice_die: '.$msg); 544 } 545 exit(1); 546} 547 548/** 549 * A realpath() replacement 550 * 551 * This function behaves similar to PHP's realpath() but does not resolve 552 * symlinks or accesses upper directories 553 * 554 * @author Andreas Gohr <andi@splitbrain.org> 555 * @author <richpageau at yahoo dot co dot uk> 556 * @link http://php.net/manual/en/function.realpath.php#75992 557 * 558 * @param string $path 559 * @param bool $exists 560 * 561 * @return bool|string 562 */ 563function fullpath($path,$exists=false){ 564 static $run = 0; 565 $root = ''; 566 $iswin = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' || !empty($GLOBALS['DOKU_UNITTEST_ASSUME_WINDOWS'])); 567 568 // find the (indestructable) root of the path - keeps windows stuff intact 569 if($path{0} == '/'){ 570 $root = '/'; 571 }elseif($iswin){ 572 // match drive letter and UNC paths 573 if(preg_match('!^([a-zA-z]:)(.*)!',$path,$match)){ 574 $root = $match[1].'/'; 575 $path = $match[2]; 576 }else if(preg_match('!^(\\\\\\\\[^\\\\/]+\\\\[^\\\\/]+[\\\\/])(.*)!',$path,$match)){ 577 $root = $match[1]; 578 $path = $match[2]; 579 } 580 } 581 $path = str_replace('\\','/',$path); 582 583 // if the given path wasn't absolute already, prepend the script path and retry 584 if(!$root){ 585 $base = dirname($_SERVER['SCRIPT_FILENAME']); 586 $path = $base.'/'.$path; 587 if($run == 0){ // avoid endless recursion when base isn't absolute for some reason 588 $run++; 589 return fullpath($path,$exists); 590 } 591 } 592 $run = 0; 593 594 // canonicalize 595 $path=explode('/', $path); 596 $newpath=array(); 597 foreach($path as $p) { 598 if ($p === '' || $p === '.') continue; 599 if ($p==='..') { 600 array_pop($newpath); 601 continue; 602 } 603 array_push($newpath, $p); 604 } 605 $finalpath = $root.implode('/', $newpath); 606 607 // check for existence when needed (except when unit testing) 608 if($exists && !defined('DOKU_UNITTEST') && !file_exists($finalpath)) { 609 return false; 610 } 611 return $finalpath; 612} 613 614