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, $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} 303 304/** 305 * Checks the existence of certain files and creates them if missing. 306 */ 307function init_files(){ 308 global $conf; 309 310 $files = array($conf['indexdir'].'/page.idx'); 311 312 foreach($files as $file){ 313 if(!file_exists($file)){ 314 $fh = @fopen($file,'a'); 315 if($fh){ 316 fclose($fh); 317 if(!empty($conf['fperm'])) chmod($file, $conf['fperm']); 318 }else{ 319 nice_die("$file is not writable. Check your permissions settings!"); 320 } 321 } 322 } 323} 324 325/** 326 * Returns absolute path 327 * 328 * This tries the given path first, then checks in DOKU_INC. 329 * Check for accessibility on directories as well. 330 * 331 * @author Andreas Gohr <andi@splitbrain.org> 332 * 333 * @param string $path 334 * 335 * @return bool|string 336 */ 337function init_path($path){ 338 // check existence 339 $p = fullpath($path); 340 if(!file_exists($p)){ 341 $p = fullpath(DOKU_INC.$path); 342 if(!file_exists($p)){ 343 return ''; 344 } 345 } 346 347 // check writability 348 if(!@is_writable($p)){ 349 return ''; 350 } 351 352 // check accessability (execute bit) for directories 353 if(@is_dir($p) && !file_exists("$p/.")){ 354 return ''; 355 } 356 357 return $p; 358} 359 360/** 361 * Sets the internal config values fperm and dperm which, when set, 362 * will be used to change the permission of a newly created dir or 363 * file with chmod. Considers the influence of the system's umask 364 * setting the values only if needed. 365 */ 366function init_creationmodes(){ 367 global $conf; 368 369 // Legacy support for old umask/dmask scheme 370 unset($conf['dmask']); 371 unset($conf['fmask']); 372 unset($conf['umask']); 373 unset($conf['fperm']); 374 unset($conf['dperm']); 375 376 // get system umask, fallback to 0 if none available 377 $umask = @umask(); 378 if(!$umask) $umask = 0000; 379 380 // check what is set automatically by the system on file creation 381 // and set the fperm param if it's not what we want 382 $auto_fmode = 0666 & ~$umask; 383 if($auto_fmode != $conf['fmode']) $conf['fperm'] = $conf['fmode']; 384 385 // check what is set automatically by the system on file creation 386 // and set the dperm param if it's not what we want 387 $auto_dmode = $conf['dmode'] & ~$umask; 388 if($auto_dmode != $conf['dmode']) $conf['dperm'] = $conf['dmode']; 389} 390 391/** 392 * Returns the full absolute URL to the directory where 393 * DokuWiki is installed in (includes a trailing slash) 394 * 395 * !! Can not access $_SERVER values through $INPUT 396 * !! here as this function is called before $INPUT is 397 * !! initialized. 398 * 399 * @author Andreas Gohr <andi@splitbrain.org> 400 * 401 * @param null|string $abs 402 * 403 * @return string 404 */ 405function getBaseURL($abs=null){ 406 global $conf; 407 //if canonical url enabled always return absolute 408 if(is_null($abs)) $abs = $conf['canonical']; 409 410 if(!empty($conf['basedir'])){ 411 $dir = $conf['basedir']; 412 }elseif(substr($_SERVER['SCRIPT_NAME'],-4) == '.php'){ 413 $dir = dirname($_SERVER['SCRIPT_NAME']); 414 }elseif(substr($_SERVER['PHP_SELF'],-4) == '.php'){ 415 $dir = dirname($_SERVER['PHP_SELF']); 416 }elseif($_SERVER['DOCUMENT_ROOT'] && $_SERVER['SCRIPT_FILENAME']){ 417 $dir = preg_replace ('/^'.preg_quote($_SERVER['DOCUMENT_ROOT'],'/').'/','', 418 $_SERVER['SCRIPT_FILENAME']); 419 $dir = dirname('/'.$dir); 420 }else{ 421 $dir = '.'; //probably wrong 422 } 423 424 $dir = str_replace('\\','/',$dir); // bugfix for weird WIN behaviour 425 $dir = preg_replace('#//+#','/',"/$dir/"); // ensure leading and trailing slashes 426 427 //handle script in lib/exe dir 428 $dir = preg_replace('!lib/exe/$!','',$dir); 429 430 //handle script in lib/plugins dir 431 $dir = preg_replace('!lib/plugins/.*$!','',$dir); 432 433 //finish here for relative URLs 434 if(!$abs) return $dir; 435 436 //use config option if available, trim any slash from end of baseurl to avoid multiple consecutive slashes in the path 437 if(!empty($conf['baseurl'])) return rtrim($conf['baseurl'],'/').$dir; 438 439 //split hostheader into host and port 440 if(isset($_SERVER['HTTP_HOST'])){ 441 $parsed_host = parse_url('http://'.$_SERVER['HTTP_HOST']); 442 $host = isset($parsed_host['host']) ? $parsed_host['host'] : null; 443 $port = isset($parsed_host['port']) ? $parsed_host['port'] : null; 444 }elseif(isset($_SERVER['SERVER_NAME'])){ 445 $parsed_host = parse_url('http://'.$_SERVER['SERVER_NAME']); 446 $host = isset($parsed_host['host']) ? $parsed_host['host'] : null; 447 $port = isset($parsed_host['port']) ? $parsed_host['port'] : null; 448 }else{ 449 $host = php_uname('n'); 450 $port = ''; 451 } 452 453 if(is_null($port)){ 454 $port = ''; 455 } 456 457 if(!is_ssl()){ 458 $proto = 'http://'; 459 if ($port == '80') { 460 $port = ''; 461 } 462 }else{ 463 $proto = 'https://'; 464 if ($port == '443') { 465 $port = ''; 466 } 467 } 468 469 if($port !== '') $port = ':'.$port; 470 471 return $proto.$host.$port.$dir; 472} 473 474/** 475 * Check if accessed via HTTPS 476 * 477 * Apache leaves ,$_SERVER['HTTPS'] empty when not available, IIS sets it to 'off'. 478 * 'false' and 'disabled' are just guessing 479 * 480 * @returns bool true when SSL is active 481 */ 482function is_ssl(){ 483 // check if we are behind a reverse proxy 484 if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) { 485 if ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') { 486 return true; 487 } else { 488 return false; 489 } 490 } 491 if (!isset($_SERVER['HTTPS']) || 492 preg_match('/^(|off|false|disabled)$/i',$_SERVER['HTTPS'])){ 493 return false; 494 }else{ 495 return true; 496 } 497} 498 499/** 500 * print a nice message even if no styles are loaded yet. 501 * 502 * @param integer|string $msg 503 */ 504function nice_die($msg){ 505 echo<<<EOT 506<!DOCTYPE html> 507<html> 508<head><title>DokuWiki Setup Error</title></head> 509<body style="font-family: Arial, sans-serif"> 510 <div style="width:60%; margin: auto; background-color: #fcc; 511 border: 1px solid #faa; padding: 0.5em 1em;"> 512 <h1 style="font-size: 120%">DokuWiki Setup Error</h1> 513 <p>$msg</p> 514 </div> 515</body> 516</html> 517EOT; 518 exit(1); 519} 520 521/** 522 * A realpath() replacement 523 * 524 * This function behaves similar to PHP's realpath() but does not resolve 525 * symlinks or accesses upper directories 526 * 527 * @author Andreas Gohr <andi@splitbrain.org> 528 * @author <richpageau at yahoo dot co dot uk> 529 * @link http://php.net/manual/en/function.realpath.php#75992 530 * 531 * @param string $path 532 * @param bool $exists 533 * 534 * @return bool|string 535 */ 536function fullpath($path,$exists=false){ 537 static $run = 0; 538 $root = ''; 539 $iswin = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' || @$GLOBALS['DOKU_UNITTEST_ASSUME_WINDOWS']); 540 541 // find the (indestructable) root of the path - keeps windows stuff intact 542 if($path{0} == '/'){ 543 $root = '/'; 544 }elseif($iswin){ 545 // match drive letter and UNC paths 546 if(preg_match('!^([a-zA-z]:)(.*)!',$path,$match)){ 547 $root = $match[1].'/'; 548 $path = $match[2]; 549 }else if(preg_match('!^(\\\\\\\\[^\\\\/]+\\\\[^\\\\/]+[\\\\/])(.*)!',$path,$match)){ 550 $root = $match[1]; 551 $path = $match[2]; 552 } 553 } 554 $path = str_replace('\\','/',$path); 555 556 // if the given path wasn't absolute already, prepend the script path and retry 557 if(!$root){ 558 $base = dirname($_SERVER['SCRIPT_FILENAME']); 559 $path = $base.'/'.$path; 560 if($run == 0){ // avoid endless recursion when base isn't absolute for some reason 561 $run++; 562 return fullpath($path,$exists); 563 } 564 } 565 $run = 0; 566 567 // canonicalize 568 $path=explode('/', $path); 569 $newpath=array(); 570 foreach($path as $p) { 571 if ($p === '' || $p === '.') continue; 572 if ($p==='..') { 573 array_pop($newpath); 574 continue; 575 } 576 array_push($newpath, $p); 577 } 578 $finalpath = $root.implode('/', $newpath); 579 580 // check for existence when needed (except when unit testing) 581 if($exists && !defined('DOKU_UNITTEST') && !file_exists($finalpath)) { 582 return false; 583 } 584 return $finalpath; 585} 586 587