xref: /dokuwiki/inc/init.php (revision 24870174d2ee45460ba6bcfe5f5a0ae94715efd7)
1ed7b5f09Sandi<?php
2ed7b5f09Sandi/**
3ed7b5f09Sandi * Initialize some defaults needed for DokuWiki
4ed7b5f09Sandi */
5*24870174SAndreas Gohruse dokuwiki\Extension\PluginController;
6*24870174SAndreas Gohruse dokuwiki\ErrorHandler;
7*24870174SAndreas Gohruse dokuwiki\Input\Input;
8cbb44eabSAndreas Gohruse dokuwiki\Extension\Event;
9e1d9dcc8SAndreas Gohruse dokuwiki\Extension\EventHandler;
10e1d9dcc8SAndreas Gohr
113272d797SAndreas Gohr/**
123272d797SAndreas Gohr * timing Dokuwiki execution
13f50a239bSTakamura *
14f50a239bSTakamura * @param integer $start
15f50a239bSTakamura *
16f50a239bSTakamura * @return mixed
173272d797SAndreas Gohr */
18a609a9ccSBen Coburnfunction delta_time($start=0) {
19ac4be4d7SPiyush Mishra    return microtime(true)-((float)$start);
20a609a9ccSBen Coburn}
21a609a9ccSBen Coburndefine('DOKU_START_TIME', delta_time());
22a609a9ccSBen Coburn
23ccaeaa85SAndreas Gohrglobal $config_cascade;
24*24870174SAndreas Gohr$config_cascade = [];
25ccaeaa85SAndreas Gohr
2648beefecSAndreas Gohr// if available load a preload config file
27*24870174SAndreas Gohr$preload = fullpath(__DIR__).'/preload.php';
2879e79377SAndreas Gohrif (file_exists($preload)) include($preload);
2948beefecSAndreas Gohr
30ed7b5f09Sandi// define the include path
31*24870174SAndreas Gohrif(!defined('DOKU_INC')) define('DOKU_INC',fullpath(__DIR__.'/../').'/');
32ad15db82Sandi
33c2a6d816SAndreas Gohr// define Plugin dir
34c2a6d816SAndreas Gohrif(!defined('DOKU_PLUGIN'))  define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
35c2a6d816SAndreas Gohr
36e7cb32dcSAndreas Gohr// define config path (packagers may want to change this to /etc/dokuwiki/)
37b7551a6dSEsther Brunnerif(!defined('DOKU_CONF')) define('DOKU_CONF',DOKU_INC.'conf/');
38e7cb32dcSAndreas Gohr
39bad905f1SBen Coburn// check for error reporting override or set error reporting to sane values
4079e79377SAndreas Gohrif (!defined('DOKU_E_LEVEL') && file_exists(DOKU_CONF.'report_e_all')) {
41bad905f1SBen Coburn    define('DOKU_E_LEVEL', E_ALL);
42bad905f1SBen Coburn}
43fc80ed59SAndreas Gohrif (!defined('DOKU_E_LEVEL')) {
444fcd684aSMichael Hamann    error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT);
45fc80ed59SAndreas Gohr} else {
46fc80ed59SAndreas Gohr    error_reporting(DOKU_E_LEVEL);
47fc80ed59SAndreas Gohr}
48c53ea5f2Sandi
49a69722b3SAndreas Gohr// avoid caching issues #1594
50a69722b3SAndreas Gohrheader('Vary: Cookie');
51a69722b3SAndreas Gohr
5250602150SBen Coburn// init memory caches
53db959ae3SAndreas Gohrglobal $cache_revinfo;
54*24870174SAndreas Gohr       $cache_revinfo = [];
55db959ae3SAndreas Gohrglobal $cache_wikifn;
56*24870174SAndreas Gohr       $cache_wikifn = [];
57db959ae3SAndreas Gohrglobal $cache_cleanid;
58*24870174SAndreas Gohr       $cache_cleanid = [];
59db959ae3SAndreas Gohrglobal $cache_authname;
60*24870174SAndreas Gohr       $cache_authname = [];
61db959ae3SAndreas Gohrglobal $cache_metadata;
62*24870174SAndreas Gohr       $cache_metadata = [];
6350602150SBen Coburn
64cca94fbcSRoland Hager// always include 'inc/config_cascade.php'
65cca94fbcSRoland Hager// previously in preload.php set fields of $config_cascade will be merged with the defaults
66e6a6dbfeSAndreas Gohrinclude(DOKU_INC.'inc/config_cascade.php');
67cb043f52SChris Smith
684724a577Sandi//prepare config array()
69ee20e7d1Sandiglobal $conf;
70*24870174SAndreas Gohr$conf = [];
714724a577Sandi
72cb043f52SChris Smith// load the global config file(s)
73*24870174SAndreas Gohrforeach (['default', 'local', 'protected'] as $config_group) {
74f8121585SChris Smith    if (empty($config_cascade['main'][$config_group])) continue;
75b303b92cSChris Smith    foreach ($config_cascade['main'][$config_group] as $config_file) {
7679e79377SAndreas Gohr        if (file_exists($config_file)) {
77f8121585SChris Smith            include($config_file);
78f8121585SChris Smith        }
79cb043f52SChris Smith    }
800a6ead41SAndreas Gohr}
81ad15db82Sandi
82066fee30SAndreas Gohr//prepare license array()
83066fee30SAndreas Gohrglobal $license;
84*24870174SAndreas Gohr$license = [];
85066fee30SAndreas Gohr
86066fee30SAndreas Gohr// load the license file(s)
87*24870174SAndreas Gohrforeach (['default', 'local'] as $config_group) {
88f8121585SChris Smith    if (empty($config_cascade['license'][$config_group])) continue;
89f8121585SChris Smith    foreach ($config_cascade['license'][$config_group] as $config_file) {
9079e79377SAndreas Gohr        if(file_exists($config_file)){
91f8121585SChris Smith            include($config_file);
92f8121585SChris Smith        }
93f8121585SChris Smith    }
94066fee30SAndreas Gohr}
95066fee30SAndreas Gohr
961f8eb24fSAndreas Gohr// set timezone (as in pre 5.3.0 days)
971f8eb24fSAndreas Gohrdate_default_timezone_set(@date_default_timezone_get());
981f8eb24fSAndreas Gohr
99ed7b5f09Sandi// define baseURL
1004b1a4e04SAndreas Gohrif(!defined('DOKU_REL')) define('DOKU_REL',getBaseURL(false));
101ed7b5f09Sandiif(!defined('DOKU_URL')) define('DOKU_URL',getBaseURL(true));
1024b1a4e04SAndreas Gohrif(!defined('DOKU_BASE')){
1034b1a4e04SAndreas Gohr    if($conf['canonical']){
1044b1a4e04SAndreas Gohr        define('DOKU_BASE',DOKU_URL);
1054b1a4e04SAndreas Gohr    }else{
1064b1a4e04SAndreas Gohr        define('DOKU_BASE',DOKU_REL);
1074b1a4e04SAndreas Gohr    }
1084b1a4e04SAndreas Gohr}
1094b1a4e04SAndreas Gohr
110b8595a66SAndreas Gohr// define whitespace
111b4f2363aSAndreas Gohrif(!defined('NL')) define ('NL',"\n");
112b8595a66SAndreas Gohrif(!defined('DOKU_LF')) define ('DOKU_LF',"\n");
113b8595a66SAndreas Gohrif(!defined('DOKU_TAB')) define ('DOKU_TAB',"\t");
114ed7b5f09Sandi
115656c8fb3SAndreas Gohr// define cookie and session id, append server port when securecookie is configured FS#1664
116fb97a12aSMichael Großeif (!defined('DOKU_COOKIE')) {
117*24870174SAndreas Gohr    $serverPort = $_SERVER['SERVER_PORT'] ?? '';
118fb97a12aSMichael Große    define('DOKU_COOKIE', 'DW' . md5(DOKU_REL . (($conf['securecookie']) ? $serverPort : '')));
119abc9c0d2SAndreas Gohr    unset($serverPort);
120fb97a12aSMichael Große}
121ee20e7d1Sandi
122ed7b5f09Sandi// define main script
123ed7b5f09Sandiif(!defined('DOKU_SCRIPT')) define('DOKU_SCRIPT','doku.php');
124ed7b5f09Sandi
125c163dbefSMichael Großeif(!defined('DOKU_TPL')) {
126c163dbefSMichael Große    /**
127c163dbefSMichael Große     * @deprecated 2012-10-13 replaced by more dynamic method
128c163dbefSMichael Große     * @see tpl_basedir()
129c163dbefSMichael Große     */
130c163dbefSMichael Große    define('DOKU_TPL', DOKU_BASE.'lib/tpl/'.$conf['template'].'/');
131c163dbefSMichael Große}
1326b13307fSandi
133c163dbefSMichael Großeif(!defined('DOKU_TPLINC')) {
134c163dbefSMichael Große    /**
135c163dbefSMichael Große     * @deprecated 2012-10-13 replaced by more dynamic method
136c163dbefSMichael Große     * @see tpl_incdir()
137c163dbefSMichael Große     */
138c163dbefSMichael Große    define('DOKU_TPLINC', DOKU_INC.'lib/tpl/'.$conf['template'].'/');
139c163dbefSMichael Große}
14078a6aeb1SAndreas Gohr
141ed7b5f09Sandi// make session rewrites XHTML compliant
1423fc74836Sandi@ini_set('arg_separator.output', '&amp;');
143ed7b5f09Sandi
144d7e6bba9SAndreas Gohr// make sure global zlib does not interfere FS#1132
145d7e6bba9SAndreas Gohr@ini_set('zlib.output_compression', 'off');
146d7e6bba9SAndreas Gohr
1476deb5405SAndreas Gohr// increase PCRE backtrack limit
1486deb5405SAndreas Gohr@ini_set('pcre.backtrack_limit', '20971520');
1496deb5405SAndreas Gohr
15098bda4fdSAndreas Gohr// enable gzip compression if supported
151*24870174SAndreas Gohr$httpAcceptEncoding = $_SERVER['HTTP_ACCEPT_ENCODING'] ?? '';
152fb97a12aSMichael Große$conf['gzip_output'] &= (strpos($httpAcceptEncoding, 'gzip') !== false);
15365f6e7d6SMichael Hamannglobal $ACT;
1543138b5c7SAndreas Gohrif ($conf['gzip_output'] &&
1553138b5c7SAndreas Gohr        !defined('DOKU_DISABLE_GZIP_OUTPUT') &&
15665f6e7d6SMichael Hamann        function_exists('ob_gzhandler') &&
15799e10b7fSMichael Hamann        // Disable compression when a (compressed) sitemap might be delivered
15865f6e7d6SMichael Hamann        // See https://bugs.dokuwiki.org/index.php?do=details&task_id=2576
15999e10b7fSMichael Hamann        $ACT != 'sitemap') {
1603138b5c7SAndreas Gohr    ob_start('ob_gzhandler');
1613138b5c7SAndreas Gohr}
1623138b5c7SAndreas Gohr
163ed7b5f09Sandi// init session
1646534245aSAndreas Gohrif(!headers_sent() && !defined('NOSESSION')) {
165c09f0eb1SGerrit Uitslag    if(!defined('DOKU_SESSION_NAME'))     define ('DOKU_SESSION_NAME', "DokuWiki");
166c09f0eb1SGerrit Uitslag    if(!defined('DOKU_SESSION_LIFETIME')) define ('DOKU_SESSION_LIFETIME', 0);
16755a71a16SGerrit Uitslag    if(!defined('DOKU_SESSION_PATH')) {
16873ab87deSGabriel Birke        $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
16955a71a16SGerrit Uitslag        define ('DOKU_SESSION_PATH', $cookieDir);
170f5c6743cSAndreas Gohr    }
171c09f0eb1SGerrit Uitslag    if(!defined('DOKU_SESSION_DOMAIN'))   define ('DOKU_SESSION_DOMAIN', '');
172c09f0eb1SGerrit Uitslag
1736eb3cdf6SAndreas Gohr    // start the session
1746eb3cdf6SAndreas Gohr    init_session();
17514a122deSAndreas Gohr
17614a122deSAndreas Gohr    // load left over messages
17714a122deSAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['msg'])) {
17814a122deSAndreas Gohr        $MSG = $_SESSION[DOKU_COOKIE]['msg'];
17914a122deSAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['msg']);
18014a122deSAndreas Gohr    }
181bad31ae9SAndreas Gohr}
182ed7b5f09Sandi
183a1637ffdSAndreas Gohr// don't let cookies ever interfere with request vars
184a1637ffdSAndreas Gohr$_REQUEST = array_merge($_GET,$_POST);
185a1637ffdSAndreas Gohr
1863dea4ebcSAndreas Gohr// we don't want a purge URL to be digged
1870e80bb5eSChristopher Smithif(isset($_REQUEST['purge']) && !empty($_SERVER['HTTP_REFERER'])) unset($_REQUEST['purge']);
1883dea4ebcSAndreas Gohr
1891ca31cfeSAndreas Gohr// precalculate file creation modes
1901ca31cfeSAndreas Gohrinit_creationmodes();
191ed7b5f09Sandi
1923dc3a5f1Sandi// make real paths and check them
19398407a7aSandiinit_paths();
1947367b368SAndreas Gohrinit_files();
195ed7b5f09Sandi
196f1986589SMichael Klier// setup plugin controller class (can be overwritten in preload.php)
197f1986589SMichael Klierglobal $plugin_controller_class, $plugin_controller;
198*24870174SAndreas Gohrif (empty($plugin_controller_class)) $plugin_controller_class = PluginController::class;
199f1986589SMichael Klier
200c7cb395cSAdrian Lang// load libraries
201605f8e8dSAndreas Gohrrequire_once(DOKU_INC.'vendor/autoload.php');
202c7cb395cSAdrian Langrequire_once(DOKU_INC.'inc/load.php');
203c7cb395cSAdrian Lang
204642e976cSAndreas Gohr// from now on everything is an exception
205*24870174SAndreas GohrErrorHandler::register();
206642e976cSAndreas Gohr
2070f8f7aaaSDanny Lin// disable gzip if not available
20813c37900SAndreas Gohrdefine('DOKU_HAS_BZIP', function_exists('bzopen'));
20913c37900SAndreas Gohrdefine('DOKU_HAS_GZIP', function_exists('gzopen'));
21013c37900SAndreas Gohrif($conf['compression'] == 'bz2' && !DOKU_HAS_BZIP) {
2110f8f7aaaSDanny Lin    $conf['compression'] = 'gz';
2120f8f7aaaSDanny Lin}
21313c37900SAndreas Gohrif($conf['compression'] == 'gz' && !DOKU_HAS_GZIP) {
2140f8f7aaaSDanny Lin    $conf['compression'] = 0;
2150f8f7aaaSDanny Lin}
2160f8f7aaaSDanny Lin
21789177306SAndreas Gohr// input handle class
21889177306SAndreas Gohrglobal $INPUT;
219*24870174SAndreas Gohr$INPUT = new Input();
22089177306SAndreas Gohr
221f1986589SMichael Klier// initialize plugin controller
222f1986589SMichael Klier$plugin_controller = new $plugin_controller_class();
223f1986589SMichael Klier
224f1986589SMichael Klier// initialize the event handler
225f1986589SMichael Klierglobal $EVENT_HANDLER;
226e1d9dcc8SAndreas Gohr$EVENT_HANDLER = new EventHandler();
227f1986589SMichael Klier
2286d06b26aSDominik Eckelmann$local = $conf['lang'];
229cbb44eabSAndreas GohrEvent::createAndTrigger('INIT_LANG_LOAD', $local, 'init_lang', true);
2306d06b26aSDominik Eckelmann
2316d06b26aSDominik Eckelmann
23216905344SAndreas Gohr// setup authentication system
233c7cb395cSAdrian Langif (!defined('NOSESSION')) {
23416905344SAndreas Gohr    auth_setup();
235c7cb395cSAdrian Lang}
236f62ea8a1Sandi
2375ec3fefcSAndreas Gohr// setup mail system
2385ec3fefcSAndreas Gohrmail_setup();
2395ec3fefcSAndreas Gohr
240042b9fecSAndreas Gohr$nil = null;
241042b9fecSAndreas GohrEvent::createAndTrigger('DOKUWIKI_INIT_DONE', $nil, null, false);
242042b9fecSAndreas Gohr
243f62ea8a1Sandi/**
2446eb3cdf6SAndreas Gohr * Initializes the session
2456eb3cdf6SAndreas Gohr *
2466eb3cdf6SAndreas Gohr * Makes sure the passed session cookie is valid, invalid ones are ignored an a new session ID is issued
2476eb3cdf6SAndreas Gohr *
2486eb3cdf6SAndreas Gohr * @link http://stackoverflow.com/a/33024310/172068
249924e477eSAndreas Gohr * @link http://php.net/manual/en/session.configuration.php#ini.session.sid-length
2506eb3cdf6SAndreas Gohr */
2516eb3cdf6SAndreas Gohrfunction init_session() {
2526eb3cdf6SAndreas Gohr    global $conf;
2536eb3cdf6SAndreas Gohr    session_name(DOKU_SESSION_NAME);
254bf8392ebSAndreas Gohr    session_set_cookie_params([
255bf8392ebSAndreas Gohr        'lifetime' => DOKU_SESSION_LIFETIME,
256bf8392ebSAndreas Gohr        'path' => DOKU_SESSION_PATH,
257bf8392ebSAndreas Gohr        'domain' => DOKU_SESSION_DOMAIN,
258bf8392ebSAndreas Gohr        'secure' => ($conf['securecookie'] && is_ssl()),
259bf8392ebSAndreas Gohr        'httponly' => true,
260bf8392ebSAndreas Gohr        'samesite' => 'Lax',
261bf8392ebSAndreas Gohr    ]);
2626eb3cdf6SAndreas Gohr
2636eb3cdf6SAndreas Gohr    // make sure the session cookie contains a valid session ID
264924e477eSAndreas Gohr    if(isset($_COOKIE[DOKU_SESSION_NAME]) && !preg_match('/^[-,a-zA-Z0-9]{22,256}$/', $_COOKIE[DOKU_SESSION_NAME])) {
2656eb3cdf6SAndreas Gohr        unset($_COOKIE[DOKU_SESSION_NAME]);
2666eb3cdf6SAndreas Gohr    }
2676eb3cdf6SAndreas Gohr
2686eb3cdf6SAndreas Gohr    session_start();
2696eb3cdf6SAndreas Gohr}
2706eb3cdf6SAndreas Gohr
2716eb3cdf6SAndreas Gohr
2726eb3cdf6SAndreas Gohr/**
27398407a7aSandi * Checks paths from config file
27498407a7aSandi */
27598407a7aSandifunction init_paths(){
27698407a7aSandi    global $conf;
27798407a7aSandi
2780ecde6ceSAndreas Gohr    $paths = [
2790ecde6ceSAndreas Gohr        'datadir'   => 'pages',
28098407a7aSandi        'olddir'    => 'attic',
28198407a7aSandi        'mediadir'  => 'media',
282e4f389efSKate Arzamastseva        'mediaolddir' => 'media_attic',
28398407a7aSandi        'metadir'   => 'meta',
284e4f389efSKate Arzamastseva        'mediametadir' => 'media_meta',
28598407a7aSandi        'cachedir'  => 'cache',
286579b0f7eSTNHarris        'indexdir'  => 'index',
287de33a58fSMichael Klier        'lockdir'   => 'locks',
2880ecde6ceSAndreas Gohr        'tmpdir'    => 'tmp',
2890ecde6ceSAndreas Gohr        'logdir'    => 'log',
2900ecde6ceSAndreas Gohr    ];
29198407a7aSandi
29298407a7aSandi    foreach($paths as $c => $p) {
2937f086b67SAnika Henke        $path = empty($conf[$c]) ? $conf['savedir'].'/'.$p : $conf[$c];
2946b9c156cSAnika Henke        $conf[$c] = init_path($path);
295697a39aeSAndreas Gohr        if(empty($conf[$c])) {
296697a39aeSAndreas Gohr            $path = fullpath($path);
2976b9c156cSAnika Henke            nice_die("The $c ('$p') at $path is not found, isn't accessible or writable.
29869dc3177SAndreas Gohr                You should check your config and permission settings.
29969dc3177SAndreas Gohr                Or maybe you want to <a href=\"install.php\">run the
30069dc3177SAndreas Gohr                installer</a>?");
30198407a7aSandi        }
302697a39aeSAndreas Gohr    }
30371726d78SBen Coburn
30471726d78SBen Coburn    // path to old changelog only needed for upgrading
30564159a61SAndreas Gohr    $conf['changelog_old'] = init_path(
306*24870174SAndreas Gohr        $conf['changelog'] ?? $conf['savedir'] . '/changes.log'
30764159a61SAndreas Gohr    );
30871726d78SBen Coburn    if ($conf['changelog_old']=='') { unset($conf['changelog_old']); }
30971726d78SBen Coburn    // hardcoded changelog because it is now a cache that lives in meta
31071726d78SBen Coburn    $conf['changelog'] = $conf['metadir'].'/_dokuwiki.changes';
31199c8d7f2Smichael    $conf['media_changelog'] = $conf['metadir'].'/_media.changes';
31298407a7aSandi}
31398407a7aSandi
31438fb1fc7SGerrit Uitslag/**
31538fb1fc7SGerrit Uitslag * Load the language strings
31638fb1fc7SGerrit Uitslag *
31738fb1fc7SGerrit Uitslag * @param string $langCode language code, as passed by event handler
31838fb1fc7SGerrit Uitslag */
3196d06b26aSDominik Eckelmannfunction init_lang($langCode) {
3206d06b26aSDominik Eckelmann    //prepare language array
321dd7a6159SGerrit Uitslag    global $lang, $config_cascade;
322*24870174SAndreas Gohr    $lang = [];
3236d06b26aSDominik Eckelmann
3246d06b26aSDominik Eckelmann    //load the language files
3251d82c8d3SChristopher Smith    require(DOKU_INC.'inc/lang/en/lang.php');
326dd7a6159SGerrit Uitslag    foreach ($config_cascade['lang']['core'] as $config_file) {
32779e79377SAndreas Gohr        if (file_exists($config_file . 'en/lang.php')) {
328dd7a6159SGerrit Uitslag            include($config_file . 'en/lang.php');
329dd7a6159SGerrit Uitslag        }
330dd7a6159SGerrit Uitslag    }
331dd7a6159SGerrit Uitslag
3326d06b26aSDominik Eckelmann    if ($langCode && $langCode != 'en') {
3336d06b26aSDominik Eckelmann        if (file_exists(DOKU_INC."inc/lang/$langCode/lang.php")) {
3341d82c8d3SChristopher Smith            require(DOKU_INC."inc/lang/$langCode/lang.php");
3356d06b26aSDominik Eckelmann        }
336dd7a6159SGerrit Uitslag        foreach ($config_cascade['lang']['core'] as $config_file) {
33779e79377SAndreas Gohr            if (file_exists($config_file . "$langCode/lang.php")) {
338dd7a6159SGerrit Uitslag                include($config_file . "$langCode/lang.php");
3396d06b26aSDominik Eckelmann            }
340dd7a6159SGerrit Uitslag        }
3416d06b26aSDominik Eckelmann    }
3426d06b26aSDominik Eckelmann}
3436d06b26aSDominik Eckelmann
34498407a7aSandi/**
3456b9c156cSAnika Henke * Checks the existence of certain files and creates them if missing.
3467367b368SAndreas Gohr */
3477367b368SAndreas Gohrfunction init_files(){
3487367b368SAndreas Gohr    global $conf;
3490d8850c4SAndreas Gohr
350*24870174SAndreas Gohr    $files = [$conf['indexdir'].'/page.idx'];
3517367b368SAndreas Gohr
3527367b368SAndreas Gohr    foreach($files as $file){
35379e79377SAndreas Gohr        if(!file_exists($file)){
3540d8850c4SAndreas Gohr            $fh = @fopen($file,'a');
3550d8850c4SAndreas Gohr            if($fh){
3567367b368SAndreas Gohr                fclose($fh);
3573aa75874Smovatica                if($conf['fperm']) chmod($file, $conf['fperm']);
3580d8850c4SAndreas Gohr            }else{
3593816dcbcSAndreas Gohr                nice_die("$file is not writable. Check your permissions settings!");
3600d8850c4SAndreas Gohr            }
3617367b368SAndreas Gohr        }
3627367b368SAndreas Gohr    }
3637367b368SAndreas Gohr}
3647367b368SAndreas Gohr
3657367b368SAndreas Gohr/**
3660d8850c4SAndreas Gohr * Returns absolute path
367f62ea8a1Sandi *
3680d8850c4SAndreas Gohr * This tries the given path first, then checks in DOKU_INC.
3697f086b67SAnika Henke * Check for accessibility on directories as well.
3700d8850c4SAndreas Gohr *
3710d8850c4SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
372f50a239bSTakamura *
373f50a239bSTakamura * @param string $path
374f50a239bSTakamura *
375f50a239bSTakamura * @return bool|string
376f62ea8a1Sandi */
377f62ea8a1Sandifunction init_path($path){
3786b9c156cSAnika Henke    // check existence
37900976812SAndreas Gohr    $p = fullpath($path);
38079e79377SAndreas Gohr    if(!file_exists($p)){
38100976812SAndreas Gohr        $p = fullpath(DOKU_INC.$path);
38279e79377SAndreas Gohr        if(!file_exists($p)){
3838fc4e739Sandi            return '';
384f62ea8a1Sandi        }
3850d8850c4SAndreas Gohr    }
3860d8850c4SAndreas Gohr
3870d8850c4SAndreas Gohr    // check writability
3880d8850c4SAndreas Gohr    if(!@is_writable($p)){
3890d8850c4SAndreas Gohr        return '';
3900d8850c4SAndreas Gohr    }
3910d8850c4SAndreas Gohr
3920d8850c4SAndreas Gohr    // check accessability (execute bit) for directories
39379e79377SAndreas Gohr    if(@is_dir($p) && !file_exists("$p/.")){
3940d8850c4SAndreas Gohr        return '';
3950d8850c4SAndreas Gohr    }
3960d8850c4SAndreas Gohr
3970d8850c4SAndreas Gohr    return $p;
3980d8850c4SAndreas Gohr}
3998c4f28e8Sjan
400ed7b5f09Sandi/**
4011ca31cfeSAndreas Gohr * Sets the internal config values fperm and dperm which, when set,
4021ca31cfeSAndreas Gohr * will be used to change the permission of a newly created dir or
4031ca31cfeSAndreas Gohr * file with chmod. Considers the influence of the system's umask
4041ca31cfeSAndreas Gohr * setting the values only if needed.
4051ca31cfeSAndreas Gohr */
4061ca31cfeSAndreas Gohrfunction init_creationmodes(){
4071ca31cfeSAndreas Gohr    global $conf;
4081ca31cfeSAndreas Gohr
4091ca31cfeSAndreas Gohr    // Legacy support for old umask/dmask scheme
4101ca31cfeSAndreas Gohr    unset($conf['dmask']);
4111ca31cfeSAndreas Gohr    unset($conf['fmask']);
4121ca31cfeSAndreas Gohr    unset($conf['umask']);
41323420346SDamien Regad
41423420346SDamien Regad    $conf['fperm'] = false;
41523420346SDamien Regad    $conf['dperm'] = false;
4161ca31cfeSAndreas Gohr
4179f3cdec3SAndreas Gohr    // get system umask, fallback to 0 if none available
4189f3cdec3SAndreas Gohr    $umask = @umask();
4199f3cdec3SAndreas Gohr    if(!$umask) $umask = 0000;
4201ca31cfeSAndreas Gohr
4211ca31cfeSAndreas Gohr    // check what is set automatically by the system on file creation
4221ca31cfeSAndreas Gohr    // and set the fperm param if it's not what we want
423bd539124SAndreas Gohr    $auto_fmode = 0666 & ~$umask;
4241ca31cfeSAndreas Gohr    if($auto_fmode != $conf['fmode']) $conf['fperm'] = $conf['fmode'];
4251ca31cfeSAndreas Gohr
426bd539124SAndreas Gohr    // check what is set automatically by the system on directory creation
427bd539124SAndreas Gohr    // and set the dperm param if it's not what we want.
428bd539124SAndreas Gohr    $auto_dmode = 0777 & ~$umask;
4291ca31cfeSAndreas Gohr    if($auto_dmode != $conf['dmode']) $conf['dperm'] = $conf['dmode'];
4301ca31cfeSAndreas Gohr}
4311ca31cfeSAndreas Gohr
4321ca31cfeSAndreas Gohr/**
433ed7b5f09Sandi * Returns the full absolute URL to the directory where
434ed7b5f09Sandi * DokuWiki is installed in (includes a trailing slash)
435ed7b5f09Sandi *
436585bf44eSChristopher Smith * !! Can not access $_SERVER values through $INPUT
437585bf44eSChristopher Smith * !! here as this function is called before $INPUT is
438585bf44eSChristopher Smith * !! initialized.
439585bf44eSChristopher Smith *
440ed7b5f09Sandi * @author Andreas Gohr <andi@splitbrain.org>
441f50a239bSTakamura *
442f50a239bSTakamura * @param null|string $abs
443f50a239bSTakamura *
444f50a239bSTakamura * @return string
445ed7b5f09Sandi */
4464b1a4e04SAndreas Gohrfunction getBaseURL($abs=null){
447ed7b5f09Sandi    global $conf;
448ed7b5f09Sandi    //if canonical url enabled always return absolute
4494b1a4e04SAndreas Gohr    if(is_null($abs)) $abs = $conf['canonical'];
450ed7b5f09Sandi
4511858e4d7SGerry Weißbach    if(!empty($conf['basedir'])){
45246c73e01SChris Smith        $dir = $conf['basedir'];
45389aa05dbSAndreas Gohr    }elseif(substr($_SERVER['SCRIPT_NAME'],-4) == '.php'){
45446c73e01SChris Smith        $dir = dirname($_SERVER['SCRIPT_NAME']);
45589aa05dbSAndreas Gohr    }elseif(substr($_SERVER['PHP_SELF'],-4) == '.php'){
45646c73e01SChris Smith        $dir = dirname($_SERVER['PHP_SELF']);
457093ec9e4Sandi    }elseif($_SERVER['DOCUMENT_ROOT'] && $_SERVER['SCRIPT_FILENAME']){
458093ec9e4Sandi        $dir = preg_replace ('/^'.preg_quote($_SERVER['DOCUMENT_ROOT'],'/').'/','',
459093ec9e4Sandi                $_SERVER['SCRIPT_FILENAME']);
46046c73e01SChris Smith        $dir = dirname('/'.$dir);
46192b83b77Sandi    }else{
46246c73e01SChris Smith        $dir = '.'; //probably wrong
46392b83b77Sandi    }
464ed7b5f09Sandi
46546c73e01SChris Smith    $dir = str_replace('\\','/',$dir);             // bugfix for weird WIN behaviour
46646c73e01SChris Smith    $dir = preg_replace('#//+#','/',"/$dir/");     // ensure leading and trailing slashes
467ed7b5f09Sandi
468f62ea8a1Sandi    //handle script in lib/exe dir
469f62ea8a1Sandi    $dir = preg_replace('!lib/exe/$!','',$dir);
470f62ea8a1Sandi
471488d5fa0SMichael Klier chi@chimeric.de    //handle script in lib/plugins dir
472488d5fa0SMichael Klier chi@chimeric.de    $dir = preg_replace('!lib/plugins/.*$!','',$dir);
473488d5fa0SMichael Klier chi@chimeric.de
474ed7b5f09Sandi    //finish here for relative URLs
475ed7b5f09Sandi    if(!$abs) return $dir;
476ed7b5f09Sandi
47764159a61SAndreas Gohr    //use config if available, trim any slash from end of baseurl to avoid multiple consecutive slashes in the path
4781858e4d7SGerry Weißbach    if(!empty($conf['baseurl'])) return rtrim($conf['baseurl'],'/').$dir;
479ef7b3ecdSAndreas Gohr
480e82e3526SAndreas Gohr    //split hostheader into host and port
4815627186cSAndreas Gohr    if(isset($_SERVER['HTTP_HOST'])){
482204b27c8SMichael Hamann        $parsed_host = parse_url('http://'.$_SERVER['HTTP_HOST']);
483*24870174SAndreas Gohr        $host = $parsed_host['host'] ?? null;
484*24870174SAndreas Gohr        $port = $parsed_host['port'] ?? null;
4855627186cSAndreas Gohr    }elseif(isset($_SERVER['SERVER_NAME'])){
486204b27c8SMichael Hamann        $parsed_host = parse_url('http://'.$_SERVER['SERVER_NAME']);
487*24870174SAndreas Gohr        $host = $parsed_host['host'] ?? null;
488*24870174SAndreas Gohr        $port = $parsed_host['port'] ?? null;
4895627186cSAndreas Gohr    }else{
4905627186cSAndreas Gohr        $host = php_uname('n');
491c66972f2SAdrian Lang        $port = '';
4925627186cSAndreas Gohr    }
4935627186cSAndreas Gohr
494204b27c8SMichael Hamann    if(is_null($port)){
495204b27c8SMichael Hamann        $port = '';
496204b27c8SMichael Hamann    }
497204b27c8SMichael Hamann
498f5c6743cSAndreas Gohr    if(!is_ssl()){
499ed7b5f09Sandi        $proto = 'http://';
500e82e3526SAndreas Gohr        if ($port == '80') {
501ed7b5f09Sandi            $port = '';
502ed7b5f09Sandi        }
503ed7b5f09Sandi    }else{
504ed7b5f09Sandi        $proto = 'https://';
505e82e3526SAndreas Gohr        if ($port == '443') {
506ed7b5f09Sandi            $port = '';
507ed7b5f09Sandi        }
508ed7b5f09Sandi    }
509ed7b5f09Sandi
510c66972f2SAdrian Lang    if($port !== '') $port = ':'.$port;
511e82e3526SAndreas Gohr
512ed7b5f09Sandi    return $proto.$host.$port.$dir;
513ed7b5f09Sandi}
514ed7b5f09Sandi
515b000c6d4Sandi/**
516f5c6743cSAndreas Gohr * Check if accessed via HTTPS
517f5c6743cSAndreas Gohr *
518f5c6743cSAndreas Gohr * Apache leaves ,$_SERVER['HTTPS'] empty when not available, IIS sets it to 'off'.
519f5c6743cSAndreas Gohr * 'false' and 'disabled' are just guessing
520f5c6743cSAndreas Gohr *
521f5c6743cSAndreas Gohr * @returns bool true when SSL is active
522f5c6743cSAndreas Gohr */
523f5c6743cSAndreas Gohrfunction is_ssl() {
52419738e65SEnrico Tagliavini    // check if we are behind a reverse proxy
52519738e65SEnrico Tagliavini    if(isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
52619738e65SEnrico Tagliavini        if($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
52719738e65SEnrico Tagliavini            return true;
52819738e65SEnrico Tagliavini        } else {
52919738e65SEnrico Tagliavini            return false;
53019738e65SEnrico Tagliavini        }
53119738e65SEnrico Tagliavini    }
532c66972f2SAdrian Lang    if(!isset($_SERVER['HTTPS']) ||
533c66972f2SAdrian Lang        preg_match('/^(|off|false|disabled)$/i', $_SERVER['HTTPS'])) {
534f5c6743cSAndreas Gohr        return false;
535f5c6743cSAndreas Gohr    } else {
536f5c6743cSAndreas Gohr        return true;
537f5c6743cSAndreas Gohr    }
538f5c6743cSAndreas Gohr}
539f5c6743cSAndreas Gohr
540f5c6743cSAndreas Gohr/**
54126714386SAndreas Gohr * checks it is windows OS
54226714386SAndreas Gohr * @return bool
54326714386SAndreas Gohr */
54426714386SAndreas Gohrfunction isWindows() {
545*24870174SAndreas Gohr    return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
54626714386SAndreas Gohr}
54726714386SAndreas Gohr
54826714386SAndreas Gohr/**
5493816dcbcSAndreas Gohr * print a nice message even if no styles are loaded yet.
550f50a239bSTakamura *
551f50a239bSTakamura * @param integer|string $msg
5523816dcbcSAndreas Gohr */
5533816dcbcSAndreas Gohrfunction nice_die($msg){
5543816dcbcSAndreas Gohr    echo<<<EOT
555c8839c22SAnika Henke<!DOCTYPE html>
5563816dcbcSAndreas Gohr<html>
5573816dcbcSAndreas Gohr<head><title>DokuWiki Setup Error</title></head>
5583816dcbcSAndreas Gohr<body style="font-family: Arial, sans-serif">
5593816dcbcSAndreas Gohr    <div style="width:60%; margin: auto; background-color: #fcc;
5603816dcbcSAndreas Gohr                border: 1px solid #faa; padding: 0.5em 1em;">
5613816dcbcSAndreas Gohr        <h1 style="font-size: 120%">DokuWiki Setup Error</h1>
5623816dcbcSAndreas Gohr        <p>$msg</p>
5633816dcbcSAndreas Gohr    </div>
5643816dcbcSAndreas Gohr</body>
5653816dcbcSAndreas Gohr</html>
5663816dcbcSAndreas GohrEOT;
5673862da0eSAndreas Gohr    if(defined('DOKU_UNITTEST')) {
5683862da0eSAndreas Gohr        throw new RuntimeException('nice_die: '.$msg);
5693862da0eSAndreas Gohr    }
5700a4266d4SElan Ruusamäe    exit(1);
5713816dcbcSAndreas Gohr}
5723816dcbcSAndreas Gohr
57300976812SAndreas Gohr/**
57400976812SAndreas Gohr * A realpath() replacement
57500976812SAndreas Gohr *
57600976812SAndreas Gohr * This function behaves similar to PHP's realpath() but does not resolve
57700976812SAndreas Gohr * symlinks or accesses upper directories
57800976812SAndreas Gohr *
5794761d30cSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
58000976812SAndreas Gohr * @author <richpageau at yahoo dot co dot uk>
58159752844SAnders Sandblad * @link   http://php.net/manual/en/function.realpath.php#75992
582f50a239bSTakamura *
583f50a239bSTakamura * @param string $path
584f50a239bSTakamura * @param bool $exists
585f50a239bSTakamura *
586f50a239bSTakamura * @return bool|string
58700976812SAndreas Gohr */
588b328697dSAndreas Gohrfunction fullpath($path,$exists=false){
5894761d30cSAndreas Gohr    static $run = 0;
5904761d30cSAndreas Gohr    $root  = '';
591724970e6SAndreas Gohr    $iswin = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' || !empty($GLOBALS['DOKU_UNITTEST_ASSUME_WINDOWS']));
59200976812SAndreas Gohr
5934761d30cSAndreas Gohr    // find the (indestructable) root of the path - keeps windows stuff intact
5942401f18dSSyntaxseed    if($path[0] == '/'){
5954761d30cSAndreas Gohr        $root = '/';
5964761d30cSAndreas Gohr    }elseif($iswin){
5974761d30cSAndreas Gohr        // match drive letter and UNC paths
5984761d30cSAndreas Gohr        if (preg_match('!^([a-zA-z]:)(.*)!',$path,$match)) {
599b9c4302bSAndreas Gohr            $root = $match[1].'/';
6004761d30cSAndreas Gohr            $path = $match[2];
6014761d30cSAndreas Gohr        } elseif (preg_match('!^(\\\\\\\\[^\\\\/]+\\\\[^\\\\/]+[\\\\/])(.*)!',$path,$match)) {
6024761d30cSAndreas Gohr            $root = $match[1];
6034761d30cSAndreas Gohr            $path = $match[2];
60400976812SAndreas Gohr        }
6054761d30cSAndreas Gohr    }
6064761d30cSAndreas Gohr    $path = str_replace('\\','/',$path);
6074761d30cSAndreas Gohr
6084761d30cSAndreas Gohr    // if the given path wasn't absolute already, prepend the script path and retry
6094761d30cSAndreas Gohr    if(!$root){
6104761d30cSAndreas Gohr        $base = dirname($_SERVER['SCRIPT_FILENAME']);
6114761d30cSAndreas Gohr        $path = $base.'/'.$path;
6124761d30cSAndreas Gohr        if($run == 0){ // avoid endless recursion when base isn't absolute for some reason
6134761d30cSAndreas Gohr            $run++;
614b328697dSAndreas Gohr            return fullpath($path,$exists);
6154761d30cSAndreas Gohr        }
6164761d30cSAndreas Gohr    }
6174761d30cSAndreas Gohr    $run = 0;
61800976812SAndreas Gohr
61900976812SAndreas Gohr    // canonicalize
62000976812SAndreas Gohr    $path=explode('/', $path);
621*24870174SAndreas Gohr    $newpath=[];
622ef38bfe8SAndreas Gohr    foreach($path as $p) {
623ef38bfe8SAndreas Gohr        if ($p === '' || $p === '.') continue;
624ef38bfe8SAndreas Gohr        if ($p==='..') {
62500976812SAndreas Gohr            array_pop($newpath);
62600976812SAndreas Gohr            continue;
62700976812SAndreas Gohr        }
628*24870174SAndreas Gohr        $newpath[] = $p;
62900976812SAndreas Gohr    }
6304761d30cSAndreas Gohr    $finalpath = $root.implode('/', $newpath);
63100976812SAndreas Gohr
6326b9c156cSAnika Henke    // check for existence when needed (except when unit testing)
63379e79377SAndreas Gohr    if($exists && !defined('DOKU_UNITTEST') && !file_exists($finalpath)) {
6344761d30cSAndreas Gohr        return false;
63500976812SAndreas Gohr    }
6364761d30cSAndreas Gohr    return $finalpath;
63700976812SAndreas Gohr}
63800976812SAndreas Gohr
639