1<?php 2/** 3 * Initialize some defaults needed for DokuWiki 4 */ 5 6/** 7 * timing Dokuwiki execution 8 */ 9function delta_time($start=0) { 10 return microtime(true)-((float)$start); 11} 12define('DOKU_START_TIME', delta_time()); 13 14global $config_cascade; 15$config_cascade = array(); 16 17// if available load a preload config file 18$preload = fullpath(dirname(__FILE__)).'/preload.php'; 19if (file_exists($preload)) include($preload); 20 21// define the include path 22if(!defined('DOKU_INC')) define('DOKU_INC',fullpath(dirname(__FILE__).'/../').'/'); 23 24// define Plugin dir 25if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/'); 26 27// define config path (packagers may want to change this to /etc/dokuwiki/) 28if(!defined('DOKU_CONF')) define('DOKU_CONF',DOKU_INC.'conf/'); 29 30// check for error reporting override or set error reporting to sane values 31if (!defined('DOKU_E_LEVEL') && file_exists(DOKU_CONF.'report_e_all')) { 32 define('DOKU_E_LEVEL', E_ALL); 33} 34if (!defined('DOKU_E_LEVEL')) { 35 if(defined('E_DEPRECATED')){ // since php 5.3, since php 5.4 E_STRICT is part of E_ALL 36 error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT); 37 }else{ 38 error_reporting(E_ALL ^ E_NOTICE); 39 } 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 session_name(DOKU_SESSION_NAME); 153 session_set_cookie_params(DOKU_SESSION_LIFETIME, DOKU_SESSION_PATH, DOKU_SESSION_DOMAIN, ($conf['securecookie'] && is_ssl()), true); 154 session_start(); 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// kill magic quotes 164if (get_magic_quotes_gpc() && !defined('MAGIC_QUOTES_STRIPPED')) { 165 if (!empty($_GET)) remove_magic_quotes($_GET); 166 if (!empty($_POST)) remove_magic_quotes($_POST); 167 if (!empty($_COOKIE)) remove_magic_quotes($_COOKIE); 168 if (!empty($_REQUEST)) remove_magic_quotes($_REQUEST); 169 @ini_set('magic_quotes_gpc', 0); 170 define('MAGIC_QUOTES_STRIPPED',1); 171} 172if(function_exists('set_magic_quotes_runtime')) @set_magic_quotes_runtime(0); 173@ini_set('magic_quotes_sybase',0); 174 175// don't let cookies ever interfere with request vars 176$_REQUEST = array_merge($_GET,$_POST); 177 178// we don't want a purge URL to be digged 179if(isset($_REQUEST['purge']) && !empty($_SERVER['HTTP_REFERER'])) unset($_REQUEST['purge']); 180 181// precalculate file creation modes 182init_creationmodes(); 183 184// make real paths and check them 185init_paths(); 186init_files(); 187 188// setup plugin controller class (can be overwritten in preload.php) 189$plugin_types = array('auth', 'admin','syntax','action','renderer', 'helper','remote'); 190global $plugin_controller_class, $plugin_controller; 191if (empty($plugin_controller_class)) $plugin_controller_class = 'Doku_Plugin_Controller'; 192 193// load libraries 194require_once(DOKU_INC.'vendor/autoload.php'); 195require_once(DOKU_INC.'inc/load.php'); 196 197// disable gzip if not available 198define('DOKU_HAS_BZIP', function_exists('bzopen')); 199define('DOKU_HAS_GZIP', function_exists('gzopen')); 200if($conf['compression'] == 'bz2' && !DOKU_HAS_BZIP) { 201 $conf['compression'] = 'gz'; 202} 203if($conf['compression'] == 'gz' && !DOKU_HAS_GZIP) { 204 $conf['compression'] = 0; 205} 206 207// input handle class 208global $INPUT; 209$INPUT = new Input(); 210 211// initialize plugin controller 212$plugin_controller = new $plugin_controller_class(); 213 214// initialize the event handler 215global $EVENT_HANDLER; 216$EVENT_HANDLER = new Doku_Event_Handler(); 217 218$local = $conf['lang']; 219trigger_event('INIT_LANG_LOAD', $local, 'init_lang', true); 220 221 222// setup authentication system 223if (!defined('NOSESSION')) { 224 auth_setup(); 225} 226 227// setup mail system 228mail_setup(); 229 230/** 231 * Checks paths from config file 232 */ 233function init_paths(){ 234 global $conf; 235 236 $paths = array('datadir' => 'pages', 237 'olddir' => 'attic', 238 'mediadir' => 'media', 239 'mediaolddir' => 'media_attic', 240 'metadir' => 'meta', 241 'mediametadir' => 'media_meta', 242 'cachedir' => 'cache', 243 'indexdir' => 'index', 244 'lockdir' => 'locks', 245 'tmpdir' => 'tmp'); 246 247 foreach($paths as $c => $p) { 248 $path = empty($conf[$c]) ? $conf['savedir'].'/'.$p : $conf[$c]; 249 $conf[$c] = init_path($path); 250 if(empty($conf[$c])) 251 nice_die("The $c ('$p') at $path is not found, isn't accessible or writable. 252 You should check your config and permission settings. 253 Or maybe you want to <a href=\"install.php\">run the 254 installer</a>?"); 255 } 256 257 // path to old changelog only needed for upgrading 258 $conf['changelog_old'] = init_path((isset($conf['changelog']))?($conf['changelog']):($conf['savedir'].'/changes.log')); 259 if ($conf['changelog_old']=='') { unset($conf['changelog_old']); } 260 // hardcoded changelog because it is now a cache that lives in meta 261 $conf['changelog'] = $conf['metadir'].'/_dokuwiki.changes'; 262 $conf['media_changelog'] = $conf['metadir'].'/_media.changes'; 263} 264 265/** 266 * Load the language strings 267 * 268 * @param string $langCode language code, as passed by event handler 269 */ 270function init_lang($langCode) { 271 //prepare language array 272 global $lang, $config_cascade; 273 $lang = array(); 274 275 //load the language files 276 require(DOKU_INC.'inc/lang/en/lang.php'); 277 foreach ($config_cascade['lang']['core'] as $config_file) { 278 if (file_exists($config_file . 'en/lang.php')) { 279 include($config_file . 'en/lang.php'); 280 } 281 } 282 283 if ($langCode && $langCode != 'en') { 284 if (file_exists(DOKU_INC."inc/lang/$langCode/lang.php")) { 285 require(DOKU_INC."inc/lang/$langCode/lang.php"); 286 } 287 foreach ($config_cascade['lang']['core'] as $config_file) { 288 if (file_exists($config_file . "$langCode/lang.php")) { 289 include($config_file . "$langCode/lang.php"); 290 } 291 } 292 } 293} 294 295/** 296 * Checks the existence of certain files and creates them if missing. 297 */ 298function init_files(){ 299 global $conf; 300 301 $files = array($conf['indexdir'].'/page.idx'); 302 303 foreach($files as $file){ 304 if(!file_exists($file)){ 305 $fh = @fopen($file,'a'); 306 if($fh){ 307 fclose($fh); 308 if(!empty($conf['fperm'])) chmod($file, $conf['fperm']); 309 }else{ 310 nice_die("$file is not writable. Check your permissions settings!"); 311 } 312 } 313 } 314} 315 316/** 317 * Returns absolute path 318 * 319 * This tries the given path first, then checks in DOKU_INC. 320 * Check for accessibility on directories as well. 321 * 322 * @author Andreas Gohr <andi@splitbrain.org> 323 */ 324function init_path($path){ 325 // check existence 326 $p = fullpath($path); 327 if(!file_exists($p)){ 328 $p = fullpath(DOKU_INC.$path); 329 if(!file_exists($p)){ 330 return ''; 331 } 332 } 333 334 // check writability 335 if(!@is_writable($p)){ 336 return ''; 337 } 338 339 // check accessability (execute bit) for directories 340 if(@is_dir($p) && !file_exists("$p/.")){ 341 return ''; 342 } 343 344 return $p; 345} 346 347/** 348 * Sets the internal config values fperm and dperm which, when set, 349 * will be used to change the permission of a newly created dir or 350 * file with chmod. Considers the influence of the system's umask 351 * setting the values only if needed. 352 */ 353function init_creationmodes(){ 354 global $conf; 355 356 // Legacy support for old umask/dmask scheme 357 unset($conf['dmask']); 358 unset($conf['fmask']); 359 unset($conf['umask']); 360 unset($conf['fperm']); 361 unset($conf['dperm']); 362 363 // get system umask, fallback to 0 if none available 364 $umask = @umask(); 365 if(!$umask) $umask = 0000; 366 367 // check what is set automatically by the system on file creation 368 // and set the fperm param if it's not what we want 369 $auto_fmode = 0666 & ~$umask; 370 if($auto_fmode != $conf['fmode']) $conf['fperm'] = $conf['fmode']; 371 372 // check what is set automatically by the system on file creation 373 // and set the dperm param if it's not what we want 374 $auto_dmode = $conf['dmode'] & ~$umask; 375 if($auto_dmode != $conf['dmode']) $conf['dperm'] = $conf['dmode']; 376} 377 378/** 379 * remove magic quotes recursivly 380 * 381 * @author Andreas Gohr <andi@splitbrain.org> 382 */ 383function remove_magic_quotes(&$array) { 384 foreach (array_keys($array) as $key) { 385 // handle magic quotes in keynames (breaks order) 386 $sk = stripslashes($key); 387 if($sk != $key){ 388 $array[$sk] = $array[$key]; 389 unset($array[$key]); 390 $key = $sk; 391 } 392 393 // do recursion if needed 394 if (is_array($array[$key])) { 395 remove_magic_quotes($array[$key]); 396 }else { 397 $array[$key] = stripslashes($array[$key]); 398 } 399 } 400} 401 402/** 403 * Returns the full absolute URL to the directory where 404 * DokuWiki is installed in (includes a trailing slash) 405 * 406 * !! Can not access $_SERVER values through $INPUT 407 * !! here as this function is called before $INPUT is 408 * !! initialized. 409 * 410 * @author Andreas Gohr <andi@splitbrain.org> 411 */ 412function getBaseURL($abs=null){ 413 global $conf; 414 //if canonical url enabled always return absolute 415 if(is_null($abs)) $abs = $conf['canonical']; 416 417 if(!empty($conf['basedir'])){ 418 $dir = $conf['basedir']; 419 }elseif(substr($_SERVER['SCRIPT_NAME'],-4) == '.php'){ 420 $dir = dirname($_SERVER['SCRIPT_NAME']); 421 }elseif(substr($_SERVER['PHP_SELF'],-4) == '.php'){ 422 $dir = dirname($_SERVER['PHP_SELF']); 423 }elseif($_SERVER['DOCUMENT_ROOT'] && $_SERVER['SCRIPT_FILENAME']){ 424 $dir = preg_replace ('/^'.preg_quote($_SERVER['DOCUMENT_ROOT'],'/').'/','', 425 $_SERVER['SCRIPT_FILENAME']); 426 $dir = dirname('/'.$dir); 427 }else{ 428 $dir = '.'; //probably wrong 429 } 430 431 $dir = str_replace('\\','/',$dir); // bugfix for weird WIN behaviour 432 $dir = preg_replace('#//+#','/',"/$dir/"); // ensure leading and trailing slashes 433 434 //handle script in lib/exe dir 435 $dir = preg_replace('!lib/exe/$!','',$dir); 436 437 //handle script in lib/plugins dir 438 $dir = preg_replace('!lib/plugins/.*$!','',$dir); 439 440 //finish here for relative URLs 441 if(!$abs) return $dir; 442 443 //use config option if available, trim any slash from end of baseurl to avoid multiple consecutive slashes in the path 444 if(!empty($conf['baseurl'])) return rtrim($conf['baseurl'],'/').$dir; 445 446 //split hostheader into host and port 447 if(isset($_SERVER['HTTP_HOST'])){ 448 $parsed_host = parse_url('http://'.$_SERVER['HTTP_HOST']); 449 $host = isset($parsed_host['host']) ? $parsed_host['host'] : null; 450 $port = isset($parsed_host['port']) ? $parsed_host['port'] : null; 451 }elseif(isset($_SERVER['SERVER_NAME'])){ 452 $parsed_host = parse_url('http://'.$_SERVER['SERVER_NAME']); 453 $host = isset($parsed_host['host']) ? $parsed_host['host'] : null; 454 $port = isset($parsed_host['port']) ? $parsed_host['port'] : null; 455 }else{ 456 $host = php_uname('n'); 457 $port = ''; 458 } 459 460 if(is_null($port)){ 461 $port = ''; 462 } 463 464 if(!is_ssl()){ 465 $proto = 'http://'; 466 if ($port == '80') { 467 $port = ''; 468 } 469 }else{ 470 $proto = 'https://'; 471 if ($port == '443') { 472 $port = ''; 473 } 474 } 475 476 if($port !== '') $port = ':'.$port; 477 478 return $proto.$host.$port.$dir; 479} 480 481/** 482 * Check if accessed via HTTPS 483 * 484 * Apache leaves ,$_SERVER['HTTPS'] empty when not available, IIS sets it to 'off'. 485 * 'false' and 'disabled' are just guessing 486 * 487 * @returns bool true when SSL is active 488 */ 489function is_ssl(){ 490 // check if we are behind a reverse proxy 491 if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) { 492 if ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') { 493 return true; 494 } else { 495 return false; 496 } 497 } 498 if (!isset($_SERVER['HTTPS']) || 499 preg_match('/^(|off|false|disabled)$/i',$_SERVER['HTTPS'])){ 500 return false; 501 }else{ 502 return true; 503 } 504} 505 506/** 507 * print a nice message even if no styles are loaded yet. 508 */ 509function nice_die($msg){ 510 echo<<<EOT 511<!DOCTYPE html> 512<html> 513<head><title>DokuWiki Setup Error</title></head> 514<body style="font-family: Arial, sans-serif"> 515 <div style="width:60%; margin: auto; background-color: #fcc; 516 border: 1px solid #faa; padding: 0.5em 1em;"> 517 <h1 style="font-size: 120%">DokuWiki Setup Error</h1> 518 <p>$msg</p> 519 </div> 520</body> 521</html> 522EOT; 523 exit(1); 524} 525 526/** 527 * A realpath() replacement 528 * 529 * This function behaves similar to PHP's realpath() but does not resolve 530 * symlinks or accesses upper directories 531 * 532 * @author Andreas Gohr <andi@splitbrain.org> 533 * @author <richpageau at yahoo dot co dot uk> 534 * @link http://php.net/manual/en/function.realpath.php#75992 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