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