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