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 198if($conf['compression'] == 'bz2' && !function_exists('bzopen')){ 199 $conf['compression'] = 'gz'; 200} 201if($conf['compression'] == 'gz' && !function_exists('gzopen')){ 202 $conf['compression'] = 0; 203} 204 205// input handle class 206global $INPUT; 207$INPUT = new Input(); 208 209// initialize plugin controller 210$plugin_controller = new $plugin_controller_class(); 211 212// initialize the event handler 213global $EVENT_HANDLER; 214$EVENT_HANDLER = new Doku_Event_Handler(); 215 216$local = $conf['lang']; 217trigger_event('INIT_LANG_LOAD', $local, 'init_lang', true); 218 219 220// setup authentication system 221if (!defined('NOSESSION')) { 222 auth_setup(); 223} 224 225// setup mail system 226mail_setup(); 227 228/** 229 * Checks paths from config file 230 */ 231function init_paths(){ 232 global $conf; 233 234 $paths = array('datadir' => 'pages', 235 'olddir' => 'attic', 236 'mediadir' => 'media', 237 'mediaolddir' => 'media_attic', 238 'metadir' => 'meta', 239 'mediametadir' => 'media_meta', 240 'cachedir' => 'cache', 241 'indexdir' => 'index', 242 'lockdir' => 'locks', 243 'tmpdir' => 'tmp'); 244 245 foreach($paths as $c => $p) { 246 $path = empty($conf[$c]) ? $conf['savedir'].'/'.$p : $conf[$c]; 247 $conf[$c] = init_path($path); 248 if(empty($conf[$c])) 249 nice_die("The $c ('$p') at $path is not found, isn't accessible or writable. 250 You should check your config and permission settings. 251 Or maybe you want to <a href=\"install.php\">run the 252 installer</a>?"); 253 } 254 255 // path to old changelog only needed for upgrading 256 $conf['changelog_old'] = init_path((isset($conf['changelog']))?($conf['changelog']):($conf['savedir'].'/changes.log')); 257 if ($conf['changelog_old']=='') { unset($conf['changelog_old']); } 258 // hardcoded changelog because it is now a cache that lives in meta 259 $conf['changelog'] = $conf['metadir'].'/_dokuwiki.changes'; 260 $conf['media_changelog'] = $conf['metadir'].'/_media.changes'; 261} 262 263/** 264 * Load the language strings 265 * 266 * @param string $langCode language code, as passed by event handler 267 */ 268function init_lang($langCode) { 269 //prepare language array 270 global $lang, $config_cascade; 271 $lang = array(); 272 273 //load the language files 274 require(DOKU_INC.'inc/lang/en/lang.php'); 275 foreach ($config_cascade['lang']['core'] as $config_file) { 276 if (file_exists($config_file . 'en/lang.php')) { 277 include($config_file . 'en/lang.php'); 278 } 279 } 280 281 if ($langCode && $langCode != 'en') { 282 if (file_exists(DOKU_INC."inc/lang/$langCode/lang.php")) { 283 require(DOKU_INC."inc/lang/$langCode/lang.php"); 284 } 285 foreach ($config_cascade['lang']['core'] as $config_file) { 286 if (file_exists($config_file . "$langCode/lang.php")) { 287 include($config_file . "$langCode/lang.php"); 288 } 289 } 290 } 291} 292 293/** 294 * Checks the existence of certain files and creates them if missing. 295 */ 296function init_files(){ 297 global $conf; 298 299 $files = array($conf['indexdir'].'/page.idx'); 300 301 foreach($files as $file){ 302 if(!file_exists($file)){ 303 $fh = @fopen($file,'a'); 304 if($fh){ 305 fclose($fh); 306 if(!empty($conf['fperm'])) chmod($file, $conf['fperm']); 307 }else{ 308 nice_die("$file is not writable. Check your permissions settings!"); 309 } 310 } 311 } 312 313 # create title index (needs to have same length as page.idx) 314 /* 315 $file = $conf['indexdir'].'/title.idx'; 316 if(!file_exists($file)){ 317 $pages = file($conf['indexdir'].'/page.idx'); 318 $pages = count($pages); 319 $fh = @fopen($file,'a'); 320 if($fh){ 321 for($i=0; $i<$pages; $i++){ 322 fwrite($fh,"\n"); 323 } 324 fclose($fh); 325 }else{ 326 nice_die("$file is not writable. Check your permissions settings!"); 327 } 328 } 329 */ 330} 331 332/** 333 * Returns absolute path 334 * 335 * This tries the given path first, then checks in DOKU_INC. 336 * Check for accessibility on directories as well. 337 * 338 * @author Andreas Gohr <andi@splitbrain.org> 339 */ 340function init_path($path){ 341 // check existence 342 $p = fullpath($path); 343 if(!file_exists($p)){ 344 $p = fullpath(DOKU_INC.$path); 345 if(!file_exists($p)){ 346 return ''; 347 } 348 } 349 350 // check writability 351 if(!@is_writable($p)){ 352 return ''; 353 } 354 355 // check accessability (execute bit) for directories 356 if(@is_dir($p) && !file_exists("$p/.")){ 357 return ''; 358 } 359 360 return $p; 361} 362 363/** 364 * Sets the internal config values fperm and dperm which, when set, 365 * will be used to change the permission of a newly created dir or 366 * file with chmod. Considers the influence of the system's umask 367 * setting the values only if needed. 368 */ 369function init_creationmodes(){ 370 global $conf; 371 372 // Legacy support for old umask/dmask scheme 373 unset($conf['dmask']); 374 unset($conf['fmask']); 375 unset($conf['umask']); 376 unset($conf['fperm']); 377 unset($conf['dperm']); 378 379 // get system umask, fallback to 0 if none available 380 $umask = @umask(); 381 if(!$umask) $umask = 0000; 382 383 // check what is set automatically by the system on file creation 384 // and set the fperm param if it's not what we want 385 $auto_fmode = 0666 & ~$umask; 386 if($auto_fmode != $conf['fmode']) $conf['fperm'] = $conf['fmode']; 387 388 // check what is set automatically by the system on file creation 389 // and set the dperm param if it's not what we want 390 $auto_dmode = $conf['dmode'] & ~$umask; 391 if($auto_dmode != $conf['dmode']) $conf['dperm'] = $conf['dmode']; 392} 393 394/** 395 * remove magic quotes recursivly 396 * 397 * @author Andreas Gohr <andi@splitbrain.org> 398 */ 399function remove_magic_quotes(&$array) { 400 foreach (array_keys($array) as $key) { 401 // handle magic quotes in keynames (breaks order) 402 $sk = stripslashes($key); 403 if($sk != $key){ 404 $array[$sk] = $array[$key]; 405 unset($array[$key]); 406 $key = $sk; 407 } 408 409 // do recursion if needed 410 if (is_array($array[$key])) { 411 remove_magic_quotes($array[$key]); 412 }else { 413 $array[$key] = stripslashes($array[$key]); 414 } 415 } 416} 417 418/** 419 * Returns the full absolute URL to the directory where 420 * DokuWiki is installed in (includes a trailing slash) 421 * 422 * !! Can not access $_SERVER values through $INPUT 423 * !! here as this function is called before $INPUT is 424 * !! initialized. 425 * 426 * @author Andreas Gohr <andi@splitbrain.org> 427 */ 428function getBaseURL($abs=null){ 429 global $conf; 430 //if canonical url enabled always return absolute 431 if(is_null($abs)) $abs = $conf['canonical']; 432 433 if(!empty($conf['basedir'])){ 434 $dir = $conf['basedir']; 435 }elseif(substr($_SERVER['SCRIPT_NAME'],-4) == '.php'){ 436 $dir = dirname($_SERVER['SCRIPT_NAME']); 437 }elseif(substr($_SERVER['PHP_SELF'],-4) == '.php'){ 438 $dir = dirname($_SERVER['PHP_SELF']); 439 }elseif($_SERVER['DOCUMENT_ROOT'] && $_SERVER['SCRIPT_FILENAME']){ 440 $dir = preg_replace ('/^'.preg_quote($_SERVER['DOCUMENT_ROOT'],'/').'/','', 441 $_SERVER['SCRIPT_FILENAME']); 442 $dir = dirname('/'.$dir); 443 }else{ 444 $dir = '.'; //probably wrong 445 } 446 447 $dir = str_replace('\\','/',$dir); // bugfix for weird WIN behaviour 448 $dir = preg_replace('#//+#','/',"/$dir/"); // ensure leading and trailing slashes 449 450 //handle script in lib/exe dir 451 $dir = preg_replace('!lib/exe/$!','',$dir); 452 453 //handle script in lib/plugins dir 454 $dir = preg_replace('!lib/plugins/.*$!','',$dir); 455 456 //finish here for relative URLs 457 if(!$abs) return $dir; 458 459 //use config option if available, trim any slash from end of baseurl to avoid multiple consecutive slashes in the path 460 if(!empty($conf['baseurl'])) return rtrim($conf['baseurl'],'/').$dir; 461 462 //split hostheader into host and port 463 if(isset($_SERVER['HTTP_HOST'])){ 464 $parsed_host = parse_url('http://'.$_SERVER['HTTP_HOST']); 465 $host = isset($parsed_host['host']) ? $parsed_host['host'] : null; 466 $port = isset($parsed_host['port']) ? $parsed_host['port'] : null; 467 }elseif(isset($_SERVER['SERVER_NAME'])){ 468 $parsed_host = parse_url('http://'.$_SERVER['SERVER_NAME']); 469 $host = isset($parsed_host['host']) ? $parsed_host['host'] : null; 470 $port = isset($parsed_host['port']) ? $parsed_host['port'] : null; 471 }else{ 472 $host = php_uname('n'); 473 $port = ''; 474 } 475 476 if(is_null($port)){ 477 $port = ''; 478 } 479 480 if(!is_ssl()){ 481 $proto = 'http://'; 482 if ($port == '80') { 483 $port = ''; 484 } 485 }else{ 486 $proto = 'https://'; 487 if ($port == '443') { 488 $port = ''; 489 } 490 } 491 492 if($port !== '') $port = ':'.$port; 493 494 return $proto.$host.$port.$dir; 495} 496 497/** 498 * Check if accessed via HTTPS 499 * 500 * Apache leaves ,$_SERVER['HTTPS'] empty when not available, IIS sets it to 'off'. 501 * 'false' and 'disabled' are just guessing 502 * 503 * @returns bool true when SSL is active 504 */ 505function is_ssl(){ 506 // check if we are behind a reverse proxy 507 if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) { 508 if ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') { 509 return true; 510 } else { 511 return false; 512 } 513 } 514 if (!isset($_SERVER['HTTPS']) || 515 preg_match('/^(|off|false|disabled)$/i',$_SERVER['HTTPS'])){ 516 return false; 517 }else{ 518 return true; 519 } 520} 521 522/** 523 * print a nice message even if no styles are loaded yet. 524 */ 525function nice_die($msg){ 526 echo<<<EOT 527<!DOCTYPE html> 528<html> 529<head><title>DokuWiki Setup Error</title></head> 530<body style="font-family: Arial, sans-serif"> 531 <div style="width:60%; margin: auto; background-color: #fcc; 532 border: 1px solid #faa; padding: 0.5em 1em;"> 533 <h1 style="font-size: 120%">DokuWiki Setup Error</h1> 534 <p>$msg</p> 535 </div> 536</body> 537</html> 538EOT; 539 exit(1); 540} 541 542/** 543 * A realpath() replacement 544 * 545 * This function behaves similar to PHP's realpath() but does not resolve 546 * symlinks or accesses upper directories 547 * 548 * @author Andreas Gohr <andi@splitbrain.org> 549 * @author <richpageau at yahoo dot co dot uk> 550 * @link http://de3.php.net/manual/en/function.realpath.php#75992 551 */ 552function fullpath($path,$exists=false){ 553 static $run = 0; 554 $root = ''; 555 $iswin = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' || @$GLOBALS['DOKU_UNITTEST_ASSUME_WINDOWS']); 556 557 // find the (indestructable) root of the path - keeps windows stuff intact 558 if($path{0} == '/'){ 559 $root = '/'; 560 }elseif($iswin){ 561 // match drive letter and UNC paths 562 if(preg_match('!^([a-zA-z]:)(.*)!',$path,$match)){ 563 $root = $match[1].'/'; 564 $path = $match[2]; 565 }else if(preg_match('!^(\\\\\\\\[^\\\\/]+\\\\[^\\\\/]+[\\\\/])(.*)!',$path,$match)){ 566 $root = $match[1]; 567 $path = $match[2]; 568 } 569 } 570 $path = str_replace('\\','/',$path); 571 572 // if the given path wasn't absolute already, prepend the script path and retry 573 if(!$root){ 574 $base = dirname($_SERVER['SCRIPT_FILENAME']); 575 $path = $base.'/'.$path; 576 if($run == 0){ // avoid endless recursion when base isn't absolute for some reason 577 $run++; 578 return fullpath($path,$exists); 579 } 580 } 581 $run = 0; 582 583 // canonicalize 584 $path=explode('/', $path); 585 $newpath=array(); 586 foreach($path as $p) { 587 if ($p === '' || $p === '.') continue; 588 if ($p==='..') { 589 array_pop($newpath); 590 continue; 591 } 592 array_push($newpath, $p); 593 } 594 $finalpath = $root.implode('/', $newpath); 595 596 // check for existence when needed (except when unit testing) 597 if($exists && !defined('DOKU_UNITTEST') && !file_exists($finalpath)) { 598 return false; 599 } 600 return $finalpath; 601} 602 603