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