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 $conf['indexdir'].'/title.idx'); 309 310 foreach($files as $file){ 311 if(!@file_exists($file)){ 312 $fh = @fopen($file,'a'); 313 if($fh){ 314 fclose($fh); 315 if($conf['fperm']) chmod($file, $conf['fperm']); 316 }else{ 317 nice_die("$file is not writable. Check your permissions settings!"); 318 } 319 } 320 } 321} 322 323/** 324 * Returns absolute path 325 * 326 * This tries the given path first, then checks in DOKU_INC. 327 * Check for accessability on directories as well. 328 * 329 * @author Andreas Gohr <andi@splitbrain.org> 330 */ 331function init_path($path){ 332 // check existance 333 $p = fullpath($path); 334 if(!@file_exists($p)){ 335 $p = fullpath(DOKU_INC.$path); 336 if(!@file_exists($p)){ 337 return ''; 338 } 339 } 340 341 // check writability 342 if(!@is_writable($p)){ 343 return ''; 344 } 345 346 // check accessability (execute bit) for directories 347 if(@is_dir($p) && !@file_exists("$p/.")){ 348 return ''; 349 } 350 351 return $p; 352} 353 354/** 355 * Sets the internal config values fperm and dperm which, when set, 356 * will be used to change the permission of a newly created dir or 357 * file with chmod. Considers the influence of the system's umask 358 * setting the values only if needed. 359 */ 360function init_creationmodes(){ 361 global $conf; 362 363 // Legacy support for old umask/dmask scheme 364 unset($conf['dmask']); 365 unset($conf['fmask']); 366 unset($conf['umask']); 367 unset($conf['fperm']); 368 unset($conf['dperm']); 369 370 // get system umask, fallback to 0 if none available 371 $umask = @umask(); 372 if(!$umask) $umask = 0000; 373 374 // check what is set automatically by the system on file creation 375 // and set the fperm param if it's not what we want 376 $auto_fmode = 0666 & ~$umask; 377 if($auto_fmode != $conf['fmode']) $conf['fperm'] = $conf['fmode']; 378 379 // check what is set automatically by the system on file creation 380 // and set the dperm param if it's not what we want 381 $auto_dmode = $conf['dmode'] & ~$umask; 382 if($auto_dmode != $conf['dmode']) $conf['dperm'] = $conf['dmode']; 383} 384 385/** 386 * remove magic quotes recursivly 387 * 388 * @author Andreas Gohr <andi@splitbrain.org> 389 */ 390function remove_magic_quotes(&$array) { 391 foreach (array_keys($array) as $key) { 392 // handle magic quotes in keynames (breaks order) 393 $sk = stripslashes($key); 394 if($sk != $key){ 395 $array[$sk] = $array[$key]; 396 unset($array[$key]); 397 $key = $sk; 398 } 399 400 // do recursion if needed 401 if (is_array($array[$key])) { 402 remove_magic_quotes($array[$key]); 403 }else { 404 $array[$key] = stripslashes($array[$key]); 405 } 406 } 407} 408 409/** 410 * Returns the full absolute URL to the directory where 411 * DokuWiki is installed in (includes a trailing slash) 412 * 413 * @author Andreas Gohr <andi@splitbrain.org> 414 */ 415function getBaseURL($abs=null){ 416 global $conf; 417 //if canonical url enabled always return absolute 418 if(is_null($abs)) $abs = $conf['canonical']; 419 420 if($conf['basedir']){ 421 $dir = $conf['basedir']; 422 }elseif(substr($_SERVER['SCRIPT_NAME'],-4) == '.php'){ 423 $dir = dirname($_SERVER['SCRIPT_NAME']); 424 }elseif(substr($_SERVER['PHP_SELF'],-4) == '.php'){ 425 $dir = dirname($_SERVER['PHP_SELF']); 426 }elseif($_SERVER['DOCUMENT_ROOT'] && $_SERVER['SCRIPT_FILENAME']){ 427 $dir = preg_replace ('/^'.preg_quote($_SERVER['DOCUMENT_ROOT'],'/').'/','', 428 $_SERVER['SCRIPT_FILENAME']); 429 $dir = dirname('/'.$dir); 430 }else{ 431 $dir = '.'; //probably wrong 432 } 433 434 $dir = str_replace('\\','/',$dir); // bugfix for weird WIN behaviour 435 $dir = preg_replace('#//+#','/',"/$dir/"); // ensure leading and trailing slashes 436 437 //handle script in lib/exe dir 438 $dir = preg_replace('!lib/exe/$!','',$dir); 439 440 //handle script in lib/plugins dir 441 $dir = preg_replace('!lib/plugins/.*$!','',$dir); 442 443 //finish here for relative URLs 444 if(!$abs) return $dir; 445 446 //use config option if available, trim any slash from end of baseurl to avoid multiple consecutive slashes in the path 447 if($conf['baseurl']) return rtrim($conf['baseurl'],'/').$dir; 448 449 //split hostheader into host and port 450 $addr = explode(':',$_SERVER['HTTP_HOST']); 451 $host = $addr[0]; 452 $port = ''; 453 if (isset($addr[1])) { 454 $port = $addr[1]; 455 } elseif (isset($_SERVER['SERVER_PORT'])) { 456 $port = $_SERVER['SERVER_PORT']; 457 } 458 if(!is_ssl()){ 459 $proto = 'http://'; 460 if ($port == '80') { 461 $port = ''; 462 } 463 }else{ 464 $proto = 'https://'; 465 if ($port == '443') { 466 $port = ''; 467 } 468 } 469 470 if($port !== '') $port = ':'.$port; 471 472 return $proto.$host.$port.$dir; 473} 474 475/** 476 * Check if accessed via HTTPS 477 * 478 * Apache leaves ,$_SERVER['HTTPS'] empty when not available, IIS sets it to 'off'. 479 * 'false' and 'disabled' are just guessing 480 * 481 * @returns bool true when SSL is active 482 */ 483function is_ssl(){ 484 if (!isset($_SERVER['HTTPS']) || 485 preg_match('/^(|off|false|disabled)$/i',$_SERVER['HTTPS'])){ 486 return false; 487 }else{ 488 return true; 489 } 490} 491 492/** 493 * Append a PHP extension to a given file and adds an exit call 494 * 495 * This is used to migrate some old configfiles. An added PHP extension 496 * ensures the contents are not shown to webusers even if .htaccess files 497 * do not work 498 * 499 * @author Jan Decaluwe <jan@jandecaluwe.com> 500 */ 501function scriptify($file) { 502 // checks 503 if (!is_readable($file)) { 504 return; 505 } 506 $fn = $file.'.php'; 507 if (@file_exists($fn)) { 508 return; 509 } 510 $fh = fopen($fn, 'w'); 511 if (!$fh) { 512 nice_die($fn.' is not writable. Check your permission settings!'); 513 } 514 // write php exit hack first 515 fwrite($fh, "# $fn\n"); 516 fwrite($fh, '# <?php exit()?>'."\n"); 517 fwrite($fh, "# Don't modify the lines above\n"); 518 fwrite($fh, "#\n"); 519 // copy existing lines 520 $lines = file($file); 521 foreach ($lines as $line){ 522 fwrite($fh, $line); 523 } 524 fclose($fh); 525 //try to rename the old file 526 io_rename($file,"$file.old"); 527} 528 529/** 530 * print a nice message even if no styles are loaded yet. 531 */ 532function nice_die($msg){ 533 echo<<<EOT 534<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 535 "http://www.w3.org/TR/html4/loose.dtd"> 536<html> 537<head><title>DokuWiki Setup Error</title></head> 538<body style="font-family: Arial, sans-serif"> 539 <div style="width:60%; margin: auto; background-color: #fcc; 540 border: 1px solid #faa; padding: 0.5em 1em;"> 541 <h1 style="font-size: 120%">DokuWiki Setup Error</h1> 542 <p>$msg</p> 543 </div> 544</body> 545</html> 546EOT; 547 exit; 548} 549 550/** 551 * A realpath() replacement 552 * 553 * This function behaves similar to PHP's realpath() but does not resolve 554 * symlinks or accesses upper directories 555 * 556 * @author Andreas Gohr <andi@splitbrain.org> 557 * @author <richpageau at yahoo dot co dot uk> 558 * @link http://de3.php.net/manual/en/function.realpath.php#75992 559 */ 560function fullpath($path,$exists=false){ 561 static $run = 0; 562 $root = ''; 563 $iswin = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' || @$GLOBALS['DOKU_UNITTEST_ASSUME_WINDOWS']); 564 565 // find the (indestructable) root of the path - keeps windows stuff intact 566 if($path{0} == '/'){ 567 $root = '/'; 568 }elseif($iswin){ 569 // match drive letter and UNC paths 570 if(preg_match('!^([a-zA-z]:)(.*)!',$path,$match)){ 571 $root = $match[1].'/'; 572 $path = $match[2]; 573 }else if(preg_match('!^(\\\\\\\\[^\\\\/]+\\\\[^\\\\/]+[\\\\/])(.*)!',$path,$match)){ 574 $root = $match[1]; 575 $path = $match[2]; 576 } 577 } 578 $path = str_replace('\\','/',$path); 579 580 // if the given path wasn't absolute already, prepend the script path and retry 581 if(!$root){ 582 $base = dirname($_SERVER['SCRIPT_FILENAME']); 583 $path = $base.'/'.$path; 584 if($run == 0){ // avoid endless recursion when base isn't absolute for some reason 585 $run++; 586 return fullpath($path,$exists); 587 } 588 } 589 $run = 0; 590 591 // canonicalize 592 $path=explode('/', $path); 593 $newpath=array(); 594 foreach($path as $p) { 595 if ($p === '' || $p === '.') continue; 596 if ($p==='..') { 597 array_pop($newpath); 598 continue; 599 } 600 array_push($newpath, $p); 601 } 602 $finalpath = $root.implode('/', $newpath); 603 604 // check for existance when needed (except when unit testing) 605 if($exists && !defined('DOKU_UNITTEST') && !@file_exists($finalpath)) { 606 return false; 607 } 608 return $finalpath; 609} 610 611