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 if(defined('E_DEPRECATED')){ // since php 5.3, since php 5.4 E_STRICT is part of E_ALL 40 error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT); 41 }else{ 42 error_reporting(E_ALL ^ E_NOTICE); 43 } 44} else { 45 error_reporting(DOKU_E_LEVEL); 46} 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')) define('DOKU_COOKIE', 'DW'.md5(DOKU_REL.(($conf['securecookie'])?$_SERVER['SERVER_PORT']:''))); 112 113 114// define main script 115if(!defined('DOKU_SCRIPT')) define('DOKU_SCRIPT','doku.php'); 116 117// DEPRECATED, use tpl_basedir() instead 118if(!defined('DOKU_TPL')) define('DOKU_TPL', 119 DOKU_BASE.'lib/tpl/'.$conf['template'].'/'); 120 121// DEPRECATED, use tpl_incdir() instead 122if(!defined('DOKU_TPLINC')) define('DOKU_TPLINC', 123 DOKU_INC.'lib/tpl/'.$conf['template'].'/'); 124 125// make session rewrites XHTML compliant 126@ini_set('arg_separator.output', '&'); 127 128// make sure global zlib does not interfere FS#1132 129@ini_set('zlib.output_compression', 'off'); 130 131// increase PCRE backtrack limit 132@ini_set('pcre.backtrack_limit', '20971520'); 133 134// enable gzip compression if supported 135$conf['gzip_output'] &= (strpos($_SERVER['HTTP_ACCEPT_ENCODING'],'gzip') !== false); 136global $ACT; 137if ($conf['gzip_output'] && 138 !defined('DOKU_DISABLE_GZIP_OUTPUT') && 139 function_exists('ob_gzhandler') && 140 // Disable compression when a (compressed) sitemap might be delivered 141 // See https://bugs.dokuwiki.org/index.php?do=details&task_id=2576 142 $ACT != 'sitemap') { 143 ob_start('ob_gzhandler'); 144} 145 146// init session 147if(!headers_sent() && !defined('NOSESSION')) { 148 if(!defined('DOKU_SESSION_NAME')) define ('DOKU_SESSION_NAME', "DokuWiki"); 149 if(!defined('DOKU_SESSION_LIFETIME')) define ('DOKU_SESSION_LIFETIME', 0); 150 if(!defined('DOKU_SESSION_PATH')) { 151 $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir']; 152 define ('DOKU_SESSION_PATH', $cookieDir); 153 } 154 if(!defined('DOKU_SESSION_DOMAIN')) define ('DOKU_SESSION_DOMAIN', ''); 155 156 // start the session 157 init_session(); 158 159 // load left over messages 160 if(isset($_SESSION[DOKU_COOKIE]['msg'])) { 161 $MSG = $_SESSION[DOKU_COOKIE]['msg']; 162 unset($_SESSION[DOKU_COOKIE]['msg']); 163 } 164} 165 166// kill magic quotes 167if (get_magic_quotes_gpc() && !defined('MAGIC_QUOTES_STRIPPED')) { 168 if (!empty($_GET)) remove_magic_quotes($_GET); 169 if (!empty($_POST)) remove_magic_quotes($_POST); 170 if (!empty($_COOKIE)) remove_magic_quotes($_COOKIE); 171 if (!empty($_REQUEST)) remove_magic_quotes($_REQUEST); 172 @ini_set('magic_quotes_gpc', 0); 173 define('MAGIC_QUOTES_STRIPPED',1); 174} 175if(function_exists('set_magic_quotes_runtime')) @set_magic_quotes_runtime(0); 176@ini_set('magic_quotes_sybase',0); 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 * remove magic quotes recursivly 409 * 410 * @author Andreas Gohr <andi@splitbrain.org> 411 * 412 * @param $array 413 */ 414function remove_magic_quotes(&$array) { 415 foreach (array_keys($array) as $key) { 416 // handle magic quotes in keynames (breaks order) 417 $sk = stripslashes($key); 418 if($sk != $key){ 419 $array[$sk] = $array[$key]; 420 unset($array[$key]); 421 $key = $sk; 422 } 423 424 // do recursion if needed 425 if (is_array($array[$key])) { 426 remove_magic_quotes($array[$key]); 427 }else { 428 $array[$key] = stripslashes($array[$key]); 429 } 430 } 431} 432 433/** 434 * Returns the full absolute URL to the directory where 435 * DokuWiki is installed in (includes a trailing slash) 436 * 437 * !! Can not access $_SERVER values through $INPUT 438 * !! here as this function is called before $INPUT is 439 * !! initialized. 440 * 441 * @author Andreas Gohr <andi@splitbrain.org> 442 * 443 * @param null|string $abs 444 * 445 * @return string 446 */ 447function getBaseURL($abs=null){ 448 global $conf; 449 //if canonical url enabled always return absolute 450 if(is_null($abs)) $abs = $conf['canonical']; 451 452 if(!empty($conf['basedir'])){ 453 $dir = $conf['basedir']; 454 }elseif(substr($_SERVER['SCRIPT_NAME'],-4) == '.php'){ 455 $dir = dirname($_SERVER['SCRIPT_NAME']); 456 }elseif(substr($_SERVER['PHP_SELF'],-4) == '.php'){ 457 $dir = dirname($_SERVER['PHP_SELF']); 458 }elseif($_SERVER['DOCUMENT_ROOT'] && $_SERVER['SCRIPT_FILENAME']){ 459 $dir = preg_replace ('/^'.preg_quote($_SERVER['DOCUMENT_ROOT'],'/').'/','', 460 $_SERVER['SCRIPT_FILENAME']); 461 $dir = dirname('/'.$dir); 462 }else{ 463 $dir = '.'; //probably wrong 464 } 465 466 $dir = str_replace('\\','/',$dir); // bugfix for weird WIN behaviour 467 $dir = preg_replace('#//+#','/',"/$dir/"); // ensure leading and trailing slashes 468 469 //handle script in lib/exe dir 470 $dir = preg_replace('!lib/exe/$!','',$dir); 471 472 //handle script in lib/plugins dir 473 $dir = preg_replace('!lib/plugins/.*$!','',$dir); 474 475 //finish here for relative URLs 476 if(!$abs) return $dir; 477 478 //use config option if available, trim any slash from end of baseurl to avoid multiple consecutive slashes in the path 479 if(!empty($conf['baseurl'])) return rtrim($conf['baseurl'],'/').$dir; 480 481 //split hostheader into host and port 482 if(isset($_SERVER['HTTP_HOST'])){ 483 $parsed_host = parse_url('http://'.$_SERVER['HTTP_HOST']); 484 $host = isset($parsed_host['host']) ? $parsed_host['host'] : null; 485 $port = isset($parsed_host['port']) ? $parsed_host['port'] : null; 486 }elseif(isset($_SERVER['SERVER_NAME'])){ 487 $parsed_host = parse_url('http://'.$_SERVER['SERVER_NAME']); 488 $host = isset($parsed_host['host']) ? $parsed_host['host'] : null; 489 $port = isset($parsed_host['port']) ? $parsed_host['port'] : null; 490 }else{ 491 $host = php_uname('n'); 492 $port = ''; 493 } 494 495 if(is_null($port)){ 496 $port = ''; 497 } 498 499 if(!is_ssl()){ 500 $proto = 'http://'; 501 if ($port == '80') { 502 $port = ''; 503 } 504 }else{ 505 $proto = 'https://'; 506 if ($port == '443') { 507 $port = ''; 508 } 509 } 510 511 if($port !== '') $port = ':'.$port; 512 513 return $proto.$host.$port.$dir; 514} 515 516/** 517 * Check if accessed via HTTPS 518 * 519 * Apache leaves ,$_SERVER['HTTPS'] empty when not available, IIS sets it to 'off'. 520 * 'false' and 'disabled' are just guessing 521 * 522 * @returns bool true when SSL is active 523 */ 524function is_ssl(){ 525 // check if we are behind a reverse proxy 526 if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) { 527 if ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') { 528 return true; 529 } else { 530 return false; 531 } 532 } 533 if (!isset($_SERVER['HTTPS']) || 534 preg_match('/^(|off|false|disabled)$/i',$_SERVER['HTTPS'])){ 535 return false; 536 }else{ 537 return true; 538 } 539} 540 541/** 542 * print a nice message even if no styles are loaded yet. 543 * 544 * @param integer|string $msg 545 */ 546function nice_die($msg){ 547 echo<<<EOT 548<!DOCTYPE html> 549<html> 550<head><title>DokuWiki Setup Error</title></head> 551<body style="font-family: Arial, sans-serif"> 552 <div style="width:60%; margin: auto; background-color: #fcc; 553 border: 1px solid #faa; padding: 0.5em 1em;"> 554 <h1 style="font-size: 120%">DokuWiki Setup Error</h1> 555 <p>$msg</p> 556 </div> 557</body> 558</html> 559EOT; 560 exit(1); 561} 562 563/** 564 * A realpath() replacement 565 * 566 * This function behaves similar to PHP's realpath() but does not resolve 567 * symlinks or accesses upper directories 568 * 569 * @author Andreas Gohr <andi@splitbrain.org> 570 * @author <richpageau at yahoo dot co dot uk> 571 * @link http://php.net/manual/en/function.realpath.php#75992 572 * 573 * @param string $path 574 * @param bool $exists 575 * 576 * @return bool|string 577 */ 578function fullpath($path,$exists=false){ 579 static $run = 0; 580 $root = ''; 581 $iswin = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' || @$GLOBALS['DOKU_UNITTEST_ASSUME_WINDOWS']); 582 583 // find the (indestructable) root of the path - keeps windows stuff intact 584 if($path{0} == '/'){ 585 $root = '/'; 586 }elseif($iswin){ 587 // match drive letter and UNC paths 588 if(preg_match('!^([a-zA-z]:)(.*)!',$path,$match)){ 589 $root = $match[1].'/'; 590 $path = $match[2]; 591 }else if(preg_match('!^(\\\\\\\\[^\\\\/]+\\\\[^\\\\/]+[\\\\/])(.*)!',$path,$match)){ 592 $root = $match[1]; 593 $path = $match[2]; 594 } 595 } 596 $path = str_replace('\\','/',$path); 597 598 // if the given path wasn't absolute already, prepend the script path and retry 599 if(!$root){ 600 $base = dirname($_SERVER['SCRIPT_FILENAME']); 601 $path = $base.'/'.$path; 602 if($run == 0){ // avoid endless recursion when base isn't absolute for some reason 603 $run++; 604 return fullpath($path,$exists); 605 } 606 } 607 $run = 0; 608 609 // canonicalize 610 $path=explode('/', $path); 611 $newpath=array(); 612 foreach($path as $p) { 613 if ($p === '' || $p === '.') continue; 614 if ($p==='..') { 615 array_pop($newpath); 616 continue; 617 } 618 array_push($newpath, $p); 619 } 620 $finalpath = $root.implode('/', $newpath); 621 622 // check for existence when needed (except when unit testing) 623 if($exists && !defined('DOKU_UNITTEST') && !file_exists($finalpath)) { 624 return false; 625 } 626 return $finalpath; 627} 628 629