Merge pull request #3358 from dokuwiki-translate/lang_update_222_1609172169
[dokuwiki.git] / inc / init.php
blob5cf1b56e998bc7b349f595853956c7d60e3fb35d
1 <?php
2 /**
3 * Initialize some defaults needed for DokuWiki
4 */
6 use dokuwiki\Extension\Event;
7 use dokuwiki\Extension\EventHandler;
9 /**
10 * timing Dokuwiki execution
12 * @param integer $start
14 * @return mixed
16 function delta_time($start=0) {
17 return microtime(true)-((float)$start);
19 define('DOKU_START_TIME', delta_time());
21 global $config_cascade;
22 $config_cascade = array();
24 // if available load a preload config file
25 $preload = fullpath(dirname(__FILE__)).'/preload.php';
26 if (file_exists($preload)) include($preload);
28 // define the include path
29 if(!defined('DOKU_INC')) define('DOKU_INC',fullpath(dirname(__FILE__).'/../').'/');
31 // define Plugin dir
32 if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
34 // define config path (packagers may want to change this to /etc/dokuwiki/)
35 if(!defined('DOKU_CONF')) define('DOKU_CONF',DOKU_INC.'conf/');
37 // check for error reporting override or set error reporting to sane values
38 if (!defined('DOKU_E_LEVEL') && file_exists(DOKU_CONF.'report_e_all')) {
39 define('DOKU_E_LEVEL', E_ALL);
41 if (!defined('DOKU_E_LEVEL')) {
42 error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT);
43 } else {
44 error_reporting(DOKU_E_LEVEL);
47 // avoid caching issues #1594
48 header('Vary: Cookie');
50 // init memory caches
51 global $cache_revinfo;
52 $cache_revinfo = array();
53 global $cache_wikifn;
54 $cache_wikifn = array();
55 global $cache_cleanid;
56 $cache_cleanid = array();
57 global $cache_authname;
58 $cache_authname = array();
59 global $cache_metadata;
60 $cache_metadata = array();
62 // always include 'inc/config_cascade.php'
63 // previously in preload.php set fields of $config_cascade will be merged with the defaults
64 include(DOKU_INC.'inc/config_cascade.php');
66 //prepare config array()
67 global $conf;
68 $conf = array();
70 // load the global config file(s)
71 foreach (array('default','local','protected') as $config_group) {
72 if (empty($config_cascade['main'][$config_group])) continue;
73 foreach ($config_cascade['main'][$config_group] as $config_file) {
74 if (file_exists($config_file)) {
75 include($config_file);
80 //prepare license array()
81 global $license;
82 $license = array();
84 // load the license file(s)
85 foreach (array('default','local') as $config_group) {
86 if (empty($config_cascade['license'][$config_group])) continue;
87 foreach ($config_cascade['license'][$config_group] as $config_file) {
88 if(file_exists($config_file)){
89 include($config_file);
94 // set timezone (as in pre 5.3.0 days)
95 date_default_timezone_set(@date_default_timezone_get());
97 // define baseURL
98 if(!defined('DOKU_REL')) define('DOKU_REL',getBaseURL(false));
99 if(!defined('DOKU_URL')) define('DOKU_URL',getBaseURL(true));
100 if(!defined('DOKU_BASE')){
101 if($conf['canonical']){
102 define('DOKU_BASE',DOKU_URL);
103 }else{
104 define('DOKU_BASE',DOKU_REL);
108 // define whitespace
109 if(!defined('NL')) define ('NL',"\n");
110 if(!defined('DOKU_LF')) define ('DOKU_LF',"\n");
111 if(!defined('DOKU_TAB')) define ('DOKU_TAB',"\t");
113 // define cookie and session id, append server port when securecookie is configured FS#1664
114 if (!defined('DOKU_COOKIE')) {
115 $serverPort = isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : '';
116 define('DOKU_COOKIE', 'DW' . md5(DOKU_REL . (($conf['securecookie']) ? $serverPort : '')));
117 unset($serverPort);
120 // define main script
121 if(!defined('DOKU_SCRIPT')) define('DOKU_SCRIPT','doku.php');
123 if(!defined('DOKU_TPL')) {
125 * @deprecated 2012-10-13 replaced by more dynamic method
126 * @see tpl_basedir()
128 define('DOKU_TPL', DOKU_BASE.'lib/tpl/'.$conf['template'].'/');
131 if(!defined('DOKU_TPLINC')) {
133 * @deprecated 2012-10-13 replaced by more dynamic method
134 * @see tpl_incdir()
136 define('DOKU_TPLINC', DOKU_INC.'lib/tpl/'.$conf['template'].'/');
139 // make session rewrites XHTML compliant
140 @ini_set('arg_separator.output', '&amp;');
142 // make sure global zlib does not interfere FS#1132
143 @ini_set('zlib.output_compression', 'off');
145 // increase PCRE backtrack limit
146 @ini_set('pcre.backtrack_limit', '20971520');
148 // enable gzip compression if supported
149 $httpAcceptEncoding = isset($_SERVER['HTTP_ACCEPT_ENCODING']) ? $_SERVER['HTTP_ACCEPT_ENCODING'] : '';
150 $conf['gzip_output'] &= (strpos($httpAcceptEncoding, 'gzip') !== false);
151 global $ACT;
152 if ($conf['gzip_output'] &&
153 !defined('DOKU_DISABLE_GZIP_OUTPUT') &&
154 function_exists('ob_gzhandler') &&
155 // Disable compression when a (compressed) sitemap might be delivered
156 // See https://bugs.dokuwiki.org/index.php?do=details&task_id=2576
157 $ACT != 'sitemap') {
158 ob_start('ob_gzhandler');
161 // init session
162 if(!headers_sent() && !defined('NOSESSION')) {
163 if(!defined('DOKU_SESSION_NAME')) define ('DOKU_SESSION_NAME', "DokuWiki");
164 if(!defined('DOKU_SESSION_LIFETIME')) define ('DOKU_SESSION_LIFETIME', 0);
165 if(!defined('DOKU_SESSION_PATH')) {
166 $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
167 define ('DOKU_SESSION_PATH', $cookieDir);
169 if(!defined('DOKU_SESSION_DOMAIN')) define ('DOKU_SESSION_DOMAIN', '');
171 // start the session
172 init_session();
174 // load left over messages
175 if(isset($_SESSION[DOKU_COOKIE]['msg'])) {
176 $MSG = $_SESSION[DOKU_COOKIE]['msg'];
177 unset($_SESSION[DOKU_COOKIE]['msg']);
181 // don't let cookies ever interfere with request vars
182 $_REQUEST = array_merge($_GET,$_POST);
184 // we don't want a purge URL to be digged
185 if(isset($_REQUEST['purge']) && !empty($_SERVER['HTTP_REFERER'])) unset($_REQUEST['purge']);
187 // precalculate file creation modes
188 init_creationmodes();
190 // make real paths and check them
191 init_paths();
192 init_files();
194 // setup plugin controller class (can be overwritten in preload.php)
195 global $plugin_controller_class, $plugin_controller;
196 if (empty($plugin_controller_class)) $plugin_controller_class = dokuwiki\Extension\PluginController::class;
198 // load libraries
199 require_once(DOKU_INC.'vendor/autoload.php');
200 require_once(DOKU_INC.'inc/load.php');
202 // from now on everything is an exception
203 \dokuwiki\ErrorHandler::register();
205 // disable gzip if not available
206 define('DOKU_HAS_BZIP', function_exists('bzopen'));
207 define('DOKU_HAS_GZIP', function_exists('gzopen'));
208 if($conf['compression'] == 'bz2' && !DOKU_HAS_BZIP) {
209 $conf['compression'] = 'gz';
211 if($conf['compression'] == 'gz' && !DOKU_HAS_GZIP) {
212 $conf['compression'] = 0;
215 // input handle class
216 global $INPUT;
217 $INPUT = new \dokuwiki\Input\Input();
219 // initialize plugin controller
220 $plugin_controller = new $plugin_controller_class();
222 // initialize the event handler
223 global $EVENT_HANDLER;
224 $EVENT_HANDLER = new EventHandler();
226 $local = $conf['lang'];
227 Event::createAndTrigger('INIT_LANG_LOAD', $local, 'init_lang', true);
230 // setup authentication system
231 if (!defined('NOSESSION')) {
232 auth_setup();
235 // setup mail system
236 mail_setup();
239 * Initializes the session
241 * Makes sure the passed session cookie is valid, invalid ones are ignored an a new session ID is issued
243 * @link http://stackoverflow.com/a/33024310/172068
244 * @link http://php.net/manual/en/session.configuration.php#ini.session.sid-length
246 function init_session() {
247 global $conf;
248 session_name(DOKU_SESSION_NAME);
249 session_set_cookie_params(
250 DOKU_SESSION_LIFETIME,
251 DOKU_SESSION_PATH,
252 DOKU_SESSION_DOMAIN,
253 ($conf['securecookie'] && is_ssl()),
254 true
257 // make sure the session cookie contains a valid session ID
258 if(isset($_COOKIE[DOKU_SESSION_NAME]) && !preg_match('/^[-,a-zA-Z0-9]{22,256}$/', $_COOKIE[DOKU_SESSION_NAME])) {
259 unset($_COOKIE[DOKU_SESSION_NAME]);
262 session_start();
267 * Checks paths from config file
269 function init_paths(){
270 global $conf;
272 $paths = [
273 'datadir' => 'pages',
274 'olddir' => 'attic',
275 'mediadir' => 'media',
276 'mediaolddir' => 'media_attic',
277 'metadir' => 'meta',
278 'mediametadir' => 'media_meta',
279 'cachedir' => 'cache',
280 'indexdir' => 'index',
281 'lockdir' => 'locks',
282 'tmpdir' => 'tmp',
283 'logdir' => 'log',
286 foreach($paths as $c => $p) {
287 $path = empty($conf[$c]) ? $conf['savedir'].'/'.$p : $conf[$c];
288 $conf[$c] = init_path($path);
289 if(empty($conf[$c]))
290 nice_die("The $c ('$p') at $path is not found, isn't accessible or writable.
291 You should check your config and permission settings.
292 Or maybe you want to <a href=\"install.php\">run the
293 installer</a>?");
296 // path to old changelog only needed for upgrading
297 $conf['changelog_old'] = init_path(
298 (isset($conf['changelog'])) ? ($conf['changelog']) : ($conf['savedir'] . '/changes.log')
300 if ($conf['changelog_old']=='') { unset($conf['changelog_old']); }
301 // hardcoded changelog because it is now a cache that lives in meta
302 $conf['changelog'] = $conf['metadir'].'/_dokuwiki.changes';
303 $conf['media_changelog'] = $conf['metadir'].'/_media.changes';
307 * Load the language strings
309 * @param string $langCode language code, as passed by event handler
311 function init_lang($langCode) {
312 //prepare language array
313 global $lang, $config_cascade;
314 $lang = array();
316 //load the language files
317 require(DOKU_INC.'inc/lang/en/lang.php');
318 foreach ($config_cascade['lang']['core'] as $config_file) {
319 if (file_exists($config_file . 'en/lang.php')) {
320 include($config_file . 'en/lang.php');
324 if ($langCode && $langCode != 'en') {
325 if (file_exists(DOKU_INC."inc/lang/$langCode/lang.php")) {
326 require(DOKU_INC."inc/lang/$langCode/lang.php");
328 foreach ($config_cascade['lang']['core'] as $config_file) {
329 if (file_exists($config_file . "$langCode/lang.php")) {
330 include($config_file . "$langCode/lang.php");
337 * Checks the existence of certain files and creates them if missing.
339 function init_files(){
340 global $conf;
342 $files = array($conf['indexdir'].'/page.idx');
344 foreach($files as $file){
345 if(!file_exists($file)){
346 $fh = @fopen($file,'a');
347 if($fh){
348 fclose($fh);
349 if($conf['fperm']) chmod($file, $conf['fperm']);
350 }else{
351 nice_die("$file is not writable. Check your permissions settings!");
358 * Returns absolute path
360 * This tries the given path first, then checks in DOKU_INC.
361 * Check for accessibility on directories as well.
363 * @author Andreas Gohr <andi@splitbrain.org>
365 * @param string $path
367 * @return bool|string
369 function init_path($path){
370 // check existence
371 $p = fullpath($path);
372 if(!file_exists($p)){
373 $p = fullpath(DOKU_INC.$path);
374 if(!file_exists($p)){
375 return '';
379 // check writability
380 if(!@is_writable($p)){
381 return '';
384 // check accessability (execute bit) for directories
385 if(@is_dir($p) && !file_exists("$p/.")){
386 return '';
389 return $p;
393 * Sets the internal config values fperm and dperm which, when set,
394 * will be used to change the permission of a newly created dir or
395 * file with chmod. Considers the influence of the system's umask
396 * setting the values only if needed.
398 function init_creationmodes(){
399 global $conf;
401 // Legacy support for old umask/dmask scheme
402 unset($conf['dmask']);
403 unset($conf['fmask']);
404 unset($conf['umask']);
405 unset($conf['fperm']);
406 unset($conf['dperm']);
408 // get system umask, fallback to 0 if none available
409 $umask = @umask();
410 if(!$umask) $umask = 0000;
412 // check what is set automatically by the system on file creation
413 // and set the fperm param if it's not what we want
414 $auto_fmode = $conf['fmode'] & ~$umask;
415 if($auto_fmode != $conf['fmode']) $conf['fperm'] = $conf['fmode'];
417 // check what is set automatically by the system on file creation
418 // and set the dperm param if it's not what we want
419 $auto_dmode = $conf['dmode'] & ~$umask;
420 if($auto_dmode != $conf['dmode']) $conf['dperm'] = $conf['dmode'];
424 * Returns the full absolute URL to the directory where
425 * DokuWiki is installed in (includes a trailing slash)
427 * !! Can not access $_SERVER values through $INPUT
428 * !! here as this function is called before $INPUT is
429 * !! initialized.
431 * @author Andreas Gohr <andi@splitbrain.org>
433 * @param null|string $abs
435 * @return string
437 function getBaseURL($abs=null){
438 global $conf;
439 //if canonical url enabled always return absolute
440 if(is_null($abs)) $abs = $conf['canonical'];
442 if(!empty($conf['basedir'])){
443 $dir = $conf['basedir'];
444 }elseif(substr($_SERVER['SCRIPT_NAME'],-4) == '.php'){
445 $dir = dirname($_SERVER['SCRIPT_NAME']);
446 }elseif(substr($_SERVER['PHP_SELF'],-4) == '.php'){
447 $dir = dirname($_SERVER['PHP_SELF']);
448 }elseif($_SERVER['DOCUMENT_ROOT'] && $_SERVER['SCRIPT_FILENAME']){
449 $dir = preg_replace ('/^'.preg_quote($_SERVER['DOCUMENT_ROOT'],'/').'/','',
450 $_SERVER['SCRIPT_FILENAME']);
451 $dir = dirname('/'.$dir);
452 }else{
453 $dir = '.'; //probably wrong
456 $dir = str_replace('\\','/',$dir); // bugfix for weird WIN behaviour
457 $dir = preg_replace('#//+#','/',"/$dir/"); // ensure leading and trailing slashes
459 //handle script in lib/exe dir
460 $dir = preg_replace('!lib/exe/$!','',$dir);
462 //handle script in lib/plugins dir
463 $dir = preg_replace('!lib/plugins/.*$!','',$dir);
465 //finish here for relative URLs
466 if(!$abs) return $dir;
468 //use config if available, trim any slash from end of baseurl to avoid multiple consecutive slashes in the path
469 if(!empty($conf['baseurl'])) return rtrim($conf['baseurl'],'/').$dir;
471 //split hostheader into host and port
472 if(isset($_SERVER['HTTP_HOST'])){
473 $parsed_host = parse_url('http://'.$_SERVER['HTTP_HOST']);
474 $host = isset($parsed_host['host']) ? $parsed_host['host'] : null;
475 $port = isset($parsed_host['port']) ? $parsed_host['port'] : null;
476 }elseif(isset($_SERVER['SERVER_NAME'])){
477 $parsed_host = parse_url('http://'.$_SERVER['SERVER_NAME']);
478 $host = isset($parsed_host['host']) ? $parsed_host['host'] : null;
479 $port = isset($parsed_host['port']) ? $parsed_host['port'] : null;
480 }else{
481 $host = php_uname('n');
482 $port = '';
485 if(is_null($port)){
486 $port = '';
489 if(!is_ssl()){
490 $proto = 'http://';
491 if ($port == '80') {
492 $port = '';
494 }else{
495 $proto = 'https://';
496 if ($port == '443') {
497 $port = '';
501 if($port !== '') $port = ':'.$port;
503 return $proto.$host.$port.$dir;
507 * Check if accessed via HTTPS
509 * Apache leaves ,$_SERVER['HTTPS'] empty when not available, IIS sets it to 'off'.
510 * 'false' and 'disabled' are just guessing
512 * @returns bool true when SSL is active
514 function is_ssl() {
515 // check if we are behind a reverse proxy
516 if(isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
517 if($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
518 return true;
519 } else {
520 return false;
523 if(!isset($_SERVER['HTTPS']) ||
524 preg_match('/^(|off|false|disabled)$/i', $_SERVER['HTTPS'])) {
525 return false;
526 } else {
527 return true;
532 * checks it is windows OS
533 * @return bool
535 function isWindows() {
536 return (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? true : false;
540 * print a nice message even if no styles are loaded yet.
542 * @param integer|string $msg
544 function nice_die($msg){
545 echo<<<EOT
546 <!DOCTYPE html>
547 <html>
548 <head><title>DokuWiki Setup Error</title></head>
549 <body style="font-family: Arial, sans-serif">
550 <div style="width:60%; margin: auto; background-color: #fcc;
551 border: 1px solid #faa; padding: 0.5em 1em;">
552 <h1 style="font-size: 120%">DokuWiki Setup Error</h1>
553 <p>$msg</p>
554 </div>
555 </body>
556 </html>
557 EOT;
558 if(defined('DOKU_UNITTEST')) {
559 throw new RuntimeException('nice_die: '.$msg);
561 exit(1);
565 * A realpath() replacement
567 * This function behaves similar to PHP's realpath() but does not resolve
568 * symlinks or accesses upper directories
570 * @author Andreas Gohr <andi@splitbrain.org>
571 * @author <richpageau at yahoo dot co dot uk>
572 * @link http://php.net/manual/en/function.realpath.php#75992
574 * @param string $path
575 * @param bool $exists
577 * @return bool|string
579 function fullpath($path,$exists=false){
580 static $run = 0;
581 $root = '';
582 $iswin = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' || !empty($GLOBALS['DOKU_UNITTEST_ASSUME_WINDOWS']));
584 // find the (indestructable) root of the path - keeps windows stuff intact
585 if($path[0] == '/'){
586 $root = '/';
587 }elseif($iswin){
588 // match drive letter and UNC paths
589 if(preg_match('!^([a-zA-z]:)(.*)!',$path,$match)){
590 $root = $match[1].'/';
591 $path = $match[2];
592 }else if(preg_match('!^(\\\\\\\\[^\\\\/]+\\\\[^\\\\/]+[\\\\/])(.*)!',$path,$match)){
593 $root = $match[1];
594 $path = $match[2];
597 $path = str_replace('\\','/',$path);
599 // if the given path wasn't absolute already, prepend the script path and retry
600 if(!$root){
601 $base = dirname($_SERVER['SCRIPT_FILENAME']);
602 $path = $base.'/'.$path;
603 if($run == 0){ // avoid endless recursion when base isn't absolute for some reason
604 $run++;
605 return fullpath($path,$exists);
608 $run = 0;
610 // canonicalize
611 $path=explode('/', $path);
612 $newpath=array();
613 foreach($path as $p) {
614 if ($p === '' || $p === '.') continue;
615 if ($p==='..') {
616 array_pop($newpath);
617 continue;
619 array_push($newpath, $p);
621 $finalpath = $root.implode('/', $newpath);
623 // check for existence when needed (except when unit testing)
624 if($exists && !defined('DOKU_UNITTEST') && !file_exists($finalpath)) {
625 return false;
627 return $finalpath;