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