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// init memory caches 46global $cache_revinfo; 47 $cache_revinfo = array(); 48global $cache_wikifn; 49 $cache_wikifn = array(); 50global $cache_cleanid; 51 $cache_cleanid = array(); 52global $cache_authname; 53 $cache_authname = array(); 54global $cache_metadata; 55 $cache_metadata = array(); 56 57// always include 'inc/config_cascade.php' 58// previously in preload.php set fields of $config_cascade will be merged with the defaults 59include(DOKU_INC.'inc/config_cascade.php'); 60 61//prepare config array() 62global $conf; 63$conf = array(); 64 65// load the global config file(s) 66foreach (array('default','local','protected') as $config_group) { 67 if (empty($config_cascade['main'][$config_group])) continue; 68 foreach ($config_cascade['main'][$config_group] as $config_file) { 69 if (file_exists($config_file)) { 70 include($config_file); 71 } 72 } 73} 74 75//prepare license array() 76global $license; 77$license = array(); 78 79// load the license file(s) 80foreach (array('default','local') as $config_group) { 81 if (empty($config_cascade['license'][$config_group])) continue; 82 foreach ($config_cascade['license'][$config_group] as $config_file) { 83 if(file_exists($config_file)){ 84 include($config_file); 85 } 86 } 87} 88 89// set timezone (as in pre 5.3.0 days) 90date_default_timezone_set(@date_default_timezone_get()); 91 92// define baseURL 93if(!defined('DOKU_REL')) define('DOKU_REL',getBaseURL(false)); 94if(!defined('DOKU_URL')) define('DOKU_URL',getBaseURL(true)); 95if(!defined('DOKU_BASE')){ 96 if($conf['canonical']){ 97 define('DOKU_BASE',DOKU_URL); 98 }else{ 99 define('DOKU_BASE',DOKU_REL); 100 } 101} 102 103// define whitespace 104if(!defined('DOKU_LF')) define ('DOKU_LF',"\n"); 105if(!defined('DOKU_TAB')) define ('DOKU_TAB',"\t"); 106 107// define cookie and session id, append server port when securecookie is configured FS#1664 108if (!defined('DOKU_COOKIE')) define('DOKU_COOKIE', 'DW'.md5(DOKU_REL.(($conf['securecookie'])?$_SERVER['SERVER_PORT']:''))); 109 110 111// define main script 112if(!defined('DOKU_SCRIPT')) define('DOKU_SCRIPT','doku.php'); 113 114// DEPRECATED, use tpl_basedir() instead 115if(!defined('DOKU_TPL')) define('DOKU_TPL', 116 DOKU_BASE.'lib/tpl/'.$conf['template'].'/'); 117 118// DEPRECATED, use tpl_incdir() instead 119if(!defined('DOKU_TPLINC')) define('DOKU_TPLINC', 120 DOKU_INC.'lib/tpl/'.$conf['template'].'/'); 121 122// make session rewrites XHTML compliant 123@ini_set('arg_separator.output', '&'); 124 125// make sure global zlib does not interfere FS#1132 126@ini_set('zlib.output_compression', 'off'); 127 128// increase PCRE backtrack limit 129@ini_set('pcre.backtrack_limit', '20971520'); 130 131// enable gzip compression if supported 132$conf['gzip_output'] &= (strpos($_SERVER['HTTP_ACCEPT_ENCODING'],'gzip') !== false); 133global $ACT; 134if ($conf['gzip_output'] && 135 !defined('DOKU_DISABLE_GZIP_OUTPUT') && 136 function_exists('ob_gzhandler') && 137 // Disable compression when a (compressed) sitemap might be delivered 138 // See https://bugs.dokuwiki.org/index.php?do=details&task_id=2576 139 $ACT != 'sitemap') { 140 ob_start('ob_gzhandler'); 141} 142 143// init session 144if(!headers_sent() && !defined('NOSESSION')) { 145 if(!defined('DOKU_SESSION_NAME')) define ('DOKU_SESSION_NAME', "DokuWiki"); 146 if(!defined('DOKU_SESSION_LIFETIME')) define ('DOKU_SESSION_LIFETIME', 0); 147 if(!defined('DOKU_SESSION_PATH')) { 148 $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir']; 149 define ('DOKU_SESSION_PATH', $cookieDir); 150 } 151 if(!defined('DOKU_SESSION_DOMAIN')) define ('DOKU_SESSION_DOMAIN', ''); 152 153 // start the session 154 init_session(); 155 156 // load left over messages 157 if(isset($_SESSION[DOKU_COOKIE]['msg'])) { 158 $MSG = $_SESSION[DOKU_COOKIE]['msg']; 159 unset($_SESSION[DOKU_COOKIE]['msg']); 160 } 161} 162 163// don't let cookies ever interfere with request vars 164$_REQUEST = array_merge($_GET,$_POST); 165 166// we don't want a purge URL to be digged 167if(isset($_REQUEST['purge']) && !empty($_SERVER['HTTP_REFERER'])) unset($_REQUEST['purge']); 168 169// precalculate file creation modes 170init_creationmodes(); 171 172// make real paths and check them 173init_paths(); 174init_files(); 175 176// setup plugin controller class (can be overwritten in preload.php) 177$plugin_types = array('auth', 'admin','syntax','action','renderer', 'helper','remote'); 178global $plugin_controller_class, $plugin_controller; 179if (empty($plugin_controller_class)) $plugin_controller_class = 'Doku_Plugin_Controller'; 180 181// load libraries 182require_once(DOKU_INC.'vendor/autoload.php'); 183require_once(DOKU_INC.'inc/load.php'); 184 185// disable gzip if not available 186define('DOKU_HAS_BZIP', function_exists('bzopen')); 187define('DOKU_HAS_GZIP', function_exists('gzopen')); 188if($conf['compression'] == 'bz2' && !DOKU_HAS_BZIP) { 189 $conf['compression'] = 'gz'; 190} 191if($conf['compression'] == 'gz' && !DOKU_HAS_GZIP) { 192 $conf['compression'] = 0; 193} 194 195// input handle class 196global $INPUT; 197$INPUT = new Input(); 198 199// initialize plugin controller 200$plugin_controller = new $plugin_controller_class(); 201 202// initialize the event handler 203global $EVENT_HANDLER; 204$EVENT_HANDLER = new Doku_Event_Handler(); 205 206$local = $conf['lang']; 207trigger_event('INIT_LANG_LOAD', $local, 'init_lang', true); 208 209 210// setup authentication system 211if (!defined('NOSESSION')) { 212 auth_setup(); 213} 214 215// setup mail system 216mail_setup(); 217 218/** 219 * Initializes the session 220 * 221 * Makes sure the passed session cookie is valid, invalid ones are ignored an a new session ID is issued 222 * 223 * @link http://stackoverflow.com/a/33024310/172068 224 * @link http://php.net/manual/en/session.configuration.php#ini.session.sid-length 225 */ 226function init_session() { 227 global $conf; 228 session_name(DOKU_SESSION_NAME); 229 session_set_cookie_params(DOKU_SESSION_LIFETIME, DOKU_SESSION_PATH, DOKU_SESSION_DOMAIN, ($conf['securecookie'] && is_ssl()), true); 230 231 // make sure the session cookie contains a valid session ID 232 if(isset($_COOKIE[DOKU_SESSION_NAME]) && !preg_match('/^[-,a-zA-Z0-9]{22,256}$/', $_COOKIE[DOKU_SESSION_NAME])) { 233 unset($_COOKIE[DOKU_SESSION_NAME]); 234 } 235 236 session_start(); 237} 238 239 240/** 241 * Checks paths from config file 242 */ 243function init_paths(){ 244 global $conf; 245 246 $paths = array('datadir' => 'pages', 247 'olddir' => 'attic', 248 'mediadir' => 'media', 249 'mediaolddir' => 'media_attic', 250 'metadir' => 'meta', 251 'mediametadir' => 'media_meta', 252 'cachedir' => 'cache', 253 'indexdir' => 'index', 254 'lockdir' => 'locks', 255 'tmpdir' => 'tmp'); 256 257 foreach($paths as $c => $p) { 258 $path = empty($conf[$c]) ? $conf['savedir'].'/'.$p : $conf[$c]; 259 $conf[$c] = init_path($path); 260 if(empty($conf[$c])) 261 nice_die("The $c ('$p') at $path is not found, isn't accessible or writable. 262 You should check your config and permission settings. 263 Or maybe you want to <a href=\"install.php\">run the 264 installer</a>?"); 265 } 266 267 // path to old changelog only needed for upgrading 268 $conf['changelog_old'] = init_path((isset($conf['changelog']))?($conf['changelog']):($conf['savedir'].'/changes.log')); 269 if ($conf['changelog_old']=='') { unset($conf['changelog_old']); } 270 // hardcoded changelog because it is now a cache that lives in meta 271 $conf['changelog'] = $conf['metadir'].'/_dokuwiki.changes'; 272 $conf['media_changelog'] = $conf['metadir'].'/_media.changes'; 273} 274 275/** 276 * Load the language strings 277 * 278 * @param string $langCode language code, as passed by event handler 279 */ 280function init_lang($langCode) { 281 //prepare language array 282 global $lang, $config_cascade; 283 $lang = array(); 284 285 //load the language files 286 require(DOKU_INC.'inc/lang/en/lang.php'); 287 foreach ($config_cascade['lang']['core'] as $config_file) { 288 if (file_exists($config_file . 'en/lang.php')) { 289 include($config_file . 'en/lang.php'); 290 } 291 } 292 293 if ($langCode && $langCode != 'en') { 294 if (file_exists(DOKU_INC."inc/lang/$langCode/lang.php")) { 295 require(DOKU_INC."inc/lang/$langCode/lang.php"); 296 } 297 foreach ($config_cascade['lang']['core'] as $config_file) { 298 if (file_exists($config_file . "$langCode/lang.php")) { 299 include($config_file . "$langCode/lang.php"); 300 } 301 } 302 } 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 * checks it is windows OS 502 * @return bool 503 */ 504function isWindows() { 505 return (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? true : false; 506} 507 508/** 509 * print a nice message even if no styles are loaded yet. 510 * 511 * @param integer|string $msg 512 */ 513function nice_die($msg){ 514 echo<<<EOT 515<!DOCTYPE html> 516<html> 517<head><title>DokuWiki Setup Error</title></head> 518<body style="font-family: Arial, sans-serif"> 519 <div style="width:60%; margin: auto; background-color: #fcc; 520 border: 1px solid #faa; padding: 0.5em 1em;"> 521 <h1 style="font-size: 120%">DokuWiki Setup Error</h1> 522 <p>$msg</p> 523 </div> 524</body> 525</html> 526EOT; 527 exit(1); 528} 529 530/** 531 * A realpath() replacement 532 * 533 * This function behaves similar to PHP's realpath() but does not resolve 534 * symlinks or accesses upper directories 535 * 536 * @author Andreas Gohr <andi@splitbrain.org> 537 * @author <richpageau at yahoo dot co dot uk> 538 * @link http://php.net/manual/en/function.realpath.php#75992 539 * 540 * @param string $path 541 * @param bool $exists 542 * 543 * @return bool|string 544 */ 545function fullpath($path,$exists=false){ 546 static $run = 0; 547 $root = ''; 548 $iswin = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' || @$GLOBALS['DOKU_UNITTEST_ASSUME_WINDOWS']); 549 550 // find the (indestructable) root of the path - keeps windows stuff intact 551 if($path{0} == '/'){ 552 $root = '/'; 553 }elseif($iswin){ 554 // match drive letter and UNC paths 555 if(preg_match('!^([a-zA-z]:)(.*)!',$path,$match)){ 556 $root = $match[1].'/'; 557 $path = $match[2]; 558 }else if(preg_match('!^(\\\\\\\\[^\\\\/]+\\\\[^\\\\/]+[\\\\/])(.*)!',$path,$match)){ 559 $root = $match[1]; 560 $path = $match[2]; 561 } 562 } 563 $path = str_replace('\\','/',$path); 564 565 // if the given path wasn't absolute already, prepend the script path and retry 566 if(!$root){ 567 $base = dirname($_SERVER['SCRIPT_FILENAME']); 568 $path = $base.'/'.$path; 569 if($run == 0){ // avoid endless recursion when base isn't absolute for some reason 570 $run++; 571 return fullpath($path,$exists); 572 } 573 } 574 $run = 0; 575 576 // canonicalize 577 $path=explode('/', $path); 578 $newpath=array(); 579 foreach($path as $p) { 580 if ($p === '' || $p === '.') continue; 581 if ($p==='..') { 582 array_pop($newpath); 583 continue; 584 } 585 array_push($newpath, $p); 586 } 587 $finalpath = $root.implode('/', $newpath); 588 589 // check for existence when needed (except when unit testing) 590 if($exists && !defined('DOKU_UNITTEST') && !file_exists($finalpath)) { 591 return false; 592 } 593 return $finalpath; 594} 595 596