xref: /dokuwiki/inc/init.php (revision 8033346cf828c3eca006804313a56dada4021684)
1ed7b5f09Sandi<?php
2d4f83172SAndreas Gohr
3ed7b5f09Sandi/**
4ed7b5f09Sandi * Initialize some defaults needed for DokuWiki
5ed7b5f09Sandi */
6d4f83172SAndreas Gohr
724870174SAndreas Gohruse dokuwiki\Extension\PluginController;
824870174SAndreas Gohruse dokuwiki\ErrorHandler;
924870174SAndreas Gohruse dokuwiki\Input\Input;
10cbb44eabSAndreas Gohruse dokuwiki\Extension\Event;
11e1d9dcc8SAndreas Gohruse dokuwiki\Extension\EventHandler;
12e1d9dcc8SAndreas Gohr
133272d797SAndreas Gohr/**
143272d797SAndreas Gohr * timing Dokuwiki execution
15f50a239bSTakamura *
16f50a239bSTakamura * @param integer $start
17f50a239bSTakamura *
18f50a239bSTakamura * @return mixed
193272d797SAndreas Gohr */
20d868eb89SAndreas Gohrfunction delta_time($start = 0)
21d868eb89SAndreas Gohr{
22ac4be4d7SPiyush Mishra    return microtime(true) - ((float)$start);
23a609a9ccSBen Coburn}
24a609a9ccSBen Coburndefine('DOKU_START_TIME', delta_time());
25a609a9ccSBen Coburn
26ccaeaa85SAndreas Gohrglobal $config_cascade;
2724870174SAndreas Gohr$config_cascade = [];
28ccaeaa85SAndreas Gohr
2948beefecSAndreas Gohr// if available load a preload config file
3024870174SAndreas Gohr$preload = fullpath(__DIR__) . '/preload.php';
3179e79377SAndreas Gohrif (file_exists($preload)) include($preload);
3248beefecSAndreas Gohr
33ed7b5f09Sandi// define the include path
3424870174SAndreas Gohrif (!defined('DOKU_INC')) define('DOKU_INC', fullpath(__DIR__ . '/../') . '/');
35ad15db82Sandi
36c2a6d816SAndreas Gohr// define Plugin dir
37c2a6d816SAndreas Gohrif (!defined('DOKU_PLUGIN'))  define('DOKU_PLUGIN', DOKU_INC . 'lib/plugins/');
38c2a6d816SAndreas Gohr
39e7cb32dcSAndreas Gohr// define config path (packagers may want to change this to /etc/dokuwiki/)
40b7551a6dSEsther Brunnerif (!defined('DOKU_CONF')) define('DOKU_CONF', DOKU_INC . 'conf/');
41e7cb32dcSAndreas Gohr
42bad905f1SBen Coburn// check for error reporting override or set error reporting to sane values
4379e79377SAndreas Gohrif (!defined('DOKU_E_LEVEL') && file_exists(DOKU_CONF . 'report_e_all')) {
44bad905f1SBen Coburn    define('DOKU_E_LEVEL', E_ALL);
45bad905f1SBen Coburn}
46fc80ed59SAndreas Gohrif (!defined('DOKU_E_LEVEL')) {
474fcd684aSMichael Hamann    error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT);
48fc80ed59SAndreas Gohr} else {
49fc80ed59SAndreas Gohr    error_reporting(DOKU_E_LEVEL);
50fc80ed59SAndreas Gohr}
51c53ea5f2Sandi
52a69722b3SAndreas Gohr// avoid caching issues #1594
53a69722b3SAndreas Gohrheader('Vary: Cookie');
54a69722b3SAndreas Gohr
5550602150SBen Coburn// init memory caches
56db959ae3SAndreas Gohrglobal $cache_revinfo;
5724870174SAndreas Gohr       $cache_revinfo = [];
58db959ae3SAndreas Gohrglobal $cache_wikifn;
5924870174SAndreas Gohr       $cache_wikifn = [];
60db959ae3SAndreas Gohrglobal $cache_cleanid;
6124870174SAndreas Gohr       $cache_cleanid = [];
62db959ae3SAndreas Gohrglobal $cache_authname;
6324870174SAndreas Gohr       $cache_authname = [];
64db959ae3SAndreas Gohrglobal $cache_metadata;
6524870174SAndreas Gohr       $cache_metadata = [];
6650602150SBen Coburn
67cca94fbcSRoland Hager// always include 'inc/config_cascade.php'
68cca94fbcSRoland Hager// previously in preload.php set fields of $config_cascade will be merged with the defaults
69e6a6dbfeSAndreas Gohrinclude(DOKU_INC . 'inc/config_cascade.php');
70cb043f52SChris Smith
714724a577Sandi//prepare config array()
72ee20e7d1Sandiglobal $conf;
7324870174SAndreas Gohr$conf = [];
744724a577Sandi
75cb043f52SChris Smith// load the global config file(s)
7624870174SAndreas Gohrforeach (['default', 'local', 'protected'] as $config_group) {
77f8121585SChris Smith    if (empty($config_cascade['main'][$config_group])) continue;
78b303b92cSChris Smith    foreach ($config_cascade['main'][$config_group] as $config_file) {
7979e79377SAndreas Gohr        if (file_exists($config_file)) {
80f8121585SChris Smith            include($config_file);
81f8121585SChris Smith        }
82cb043f52SChris Smith    }
830a6ead41SAndreas Gohr}
84ad15db82Sandi
85066fee30SAndreas Gohr//prepare license array()
86066fee30SAndreas Gohrglobal $license;
8724870174SAndreas Gohr$license = [];
88066fee30SAndreas Gohr
89066fee30SAndreas Gohr// load the license file(s)
9024870174SAndreas Gohrforeach (['default', 'local'] as $config_group) {
91f8121585SChris Smith    if (empty($config_cascade['license'][$config_group])) continue;
92f8121585SChris Smith    foreach ($config_cascade['license'][$config_group] as $config_file) {
9379e79377SAndreas Gohr        if (file_exists($config_file)) {
94f8121585SChris Smith            include($config_file);
95f8121585SChris Smith        }
96f8121585SChris Smith    }
97066fee30SAndreas Gohr}
98066fee30SAndreas Gohr
991f8eb24fSAndreas Gohr// set timezone (as in pre 5.3.0 days)
1001f8eb24fSAndreas Gohrdate_default_timezone_set(@date_default_timezone_get());
1011f8eb24fSAndreas Gohr
102ed7b5f09Sandi// define baseURL
1034b1a4e04SAndreas Gohrif (!defined('DOKU_REL')) define('DOKU_REL', getBaseURL(false));
104ed7b5f09Sandiif (!defined('DOKU_URL')) define('DOKU_URL', getBaseURL(true));
1054b1a4e04SAndreas Gohrif (!defined('DOKU_BASE')) {
1064b1a4e04SAndreas Gohr    if ($conf['canonical']) {
1074b1a4e04SAndreas Gohr        define('DOKU_BASE', DOKU_URL);
1084b1a4e04SAndreas Gohr    } else {
1094b1a4e04SAndreas Gohr        define('DOKU_BASE', DOKU_REL);
1104b1a4e04SAndreas Gohr    }
1114b1a4e04SAndreas Gohr}
1124b1a4e04SAndreas Gohr
113b8595a66SAndreas Gohr// define whitespace
114b4f2363aSAndreas Gohrif (!defined('NL')) define('NL', "\n");
115b8595a66SAndreas Gohrif (!defined('DOKU_LF')) define('DOKU_LF', "\n");
116b8595a66SAndreas Gohrif (!defined('DOKU_TAB')) define('DOKU_TAB', "\t");
117ed7b5f09Sandi
118656c8fb3SAndreas Gohr// define cookie and session id, append server port when securecookie is configured FS#1664
119fb97a12aSMichael Großeif (!defined('DOKU_COOKIE')) {
12024870174SAndreas Gohr    $serverPort = $_SERVER['SERVER_PORT'] ?? '';
121fb97a12aSMichael Große    define('DOKU_COOKIE', 'DW' . md5(DOKU_REL . (($conf['securecookie']) ? $serverPort : '')));
122abc9c0d2SAndreas Gohr    unset($serverPort);
123fb97a12aSMichael Große}
124ee20e7d1Sandi
125ed7b5f09Sandi// define main script
126ed7b5f09Sandiif (!defined('DOKU_SCRIPT')) define('DOKU_SCRIPT', 'doku.php');
127ed7b5f09Sandi
128c163dbefSMichael Großeif (!defined('DOKU_TPL')) {
129c163dbefSMichael Große    /**
130c163dbefSMichael Große     * @deprecated 2012-10-13 replaced by more dynamic method
131c163dbefSMichael Große     * @see tpl_basedir()
132c163dbefSMichael Große     */
133c163dbefSMichael Große    define('DOKU_TPL', DOKU_BASE . 'lib/tpl/' . $conf['template'] . '/');
134c163dbefSMichael Große}
1356b13307fSandi
136c163dbefSMichael Großeif (!defined('DOKU_TPLINC')) {
137c163dbefSMichael Große    /**
138c163dbefSMichael Große     * @deprecated 2012-10-13 replaced by more dynamic method
139c163dbefSMichael Große     * @see tpl_incdir()
140c163dbefSMichael Große     */
141c163dbefSMichael Große    define('DOKU_TPLINC', DOKU_INC . 'lib/tpl/' . $conf['template'] . '/');
142c163dbefSMichael Große}
14378a6aeb1SAndreas Gohr
144ed7b5f09Sandi// make session rewrites XHTML compliant
1453fc74836Sandi@ini_set('arg_separator.output', '&amp;');
146ed7b5f09Sandi
147d7e6bba9SAndreas Gohr// make sure global zlib does not interfere FS#1132
148d7e6bba9SAndreas Gohr@ini_set('zlib.output_compression', 'off');
149d7e6bba9SAndreas Gohr
1506deb5405SAndreas Gohr// increase PCRE backtrack limit
1516deb5405SAndreas Gohr@ini_set('pcre.backtrack_limit', '20971520');
1526deb5405SAndreas Gohr
15398bda4fdSAndreas Gohr// enable gzip compression if supported
15424870174SAndreas Gohr$httpAcceptEncoding = $_SERVER['HTTP_ACCEPT_ENCODING'] ?? '';
155fb97a12aSMichael Große$conf['gzip_output'] &= (strpos($httpAcceptEncoding, 'gzip') !== false);
15665f6e7d6SMichael Hamannglobal $ACT;
1577d34963bSAndreas Gohrif (
1587d34963bSAndreas Gohr    $conf['gzip_output'] &&
1593138b5c7SAndreas Gohr        !defined('DOKU_DISABLE_GZIP_OUTPUT') &&
16065f6e7d6SMichael Hamann        function_exists('ob_gzhandler') &&
16199e10b7fSMichael Hamann        // Disable compression when a (compressed) sitemap might be delivered
16265f6e7d6SMichael Hamann        // See https://bugs.dokuwiki.org/index.php?do=details&task_id=2576
1637d34963bSAndreas Gohr        $ACT != 'sitemap'
1647d34963bSAndreas Gohr) {
1653138b5c7SAndreas Gohr    ob_start('ob_gzhandler');
1663138b5c7SAndreas Gohr}
1673138b5c7SAndreas Gohr
168ed7b5f09Sandi// init session
1696534245aSAndreas Gohrif (!headers_sent() && !defined('NOSESSION')) {
170c09f0eb1SGerrit Uitslag    if (!defined('DOKU_SESSION_NAME'))     define('DOKU_SESSION_NAME', "DokuWiki");
171c09f0eb1SGerrit Uitslag    if (!defined('DOKU_SESSION_LIFETIME')) define('DOKU_SESSION_LIFETIME', 0);
17255a71a16SGerrit Uitslag    if (!defined('DOKU_SESSION_PATH')) {
17373ab87deSGabriel Birke        $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
17455a71a16SGerrit Uitslag        define('DOKU_SESSION_PATH', $cookieDir);
175f5c6743cSAndreas Gohr    }
176c09f0eb1SGerrit Uitslag    if (!defined('DOKU_SESSION_DOMAIN'))   define('DOKU_SESSION_DOMAIN', '');
177c09f0eb1SGerrit Uitslag
1786eb3cdf6SAndreas Gohr    // start the session
1796eb3cdf6SAndreas Gohr    init_session();
18014a122deSAndreas Gohr
18114a122deSAndreas Gohr    // load left over messages
18214a122deSAndreas Gohr    if (isset($_SESSION[DOKU_COOKIE]['msg'])) {
18314a122deSAndreas Gohr        $MSG = $_SESSION[DOKU_COOKIE]['msg'];
18414a122deSAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['msg']);
18514a122deSAndreas Gohr    }
186bad31ae9SAndreas Gohr}
187ed7b5f09Sandi
188a1637ffdSAndreas Gohr// don't let cookies ever interfere with request vars
189a1637ffdSAndreas Gohr$_REQUEST = array_merge($_GET, $_POST);
190a1637ffdSAndreas Gohr
1913dea4ebcSAndreas Gohr// we don't want a purge URL to be digged
1920e80bb5eSChristopher Smithif (isset($_REQUEST['purge']) && !empty($_SERVER['HTTP_REFERER'])) unset($_REQUEST['purge']);
1933dea4ebcSAndreas Gohr
1941ca31cfeSAndreas Gohr// precalculate file creation modes
1951ca31cfeSAndreas Gohrinit_creationmodes();
196ed7b5f09Sandi
1973dc3a5f1Sandi// make real paths and check them
19898407a7aSandiinit_paths();
1997367b368SAndreas Gohrinit_files();
200ed7b5f09Sandi
201f1986589SMichael Klier// setup plugin controller class (can be overwritten in preload.php)
202f1986589SMichael Klierglobal $plugin_controller_class, $plugin_controller;
20324870174SAndreas Gohrif (empty($plugin_controller_class)) $plugin_controller_class = PluginController::class;
204f1986589SMichael Klier
2054602718bSAndreas Gohr// autoloader
206c7cb395cSAdrian Langrequire_once(DOKU_INC . 'inc/load.php');
207c7cb395cSAdrian Lang
208642e976cSAndreas Gohr// from now on everything is an exception
20924870174SAndreas GohrErrorHandler::register();
210642e976cSAndreas Gohr
2110f8f7aaaSDanny Lin// disable gzip if not available
21213c37900SAndreas Gohrdefine('DOKU_HAS_BZIP', function_exists('bzopen'));
21313c37900SAndreas Gohrdefine('DOKU_HAS_GZIP', function_exists('gzopen'));
21413c37900SAndreas Gohrif ($conf['compression'] == 'bz2' && !DOKU_HAS_BZIP) {
2150f8f7aaaSDanny Lin    $conf['compression'] = 'gz';
2160f8f7aaaSDanny Lin}
21713c37900SAndreas Gohrif ($conf['compression'] == 'gz' && !DOKU_HAS_GZIP) {
2180f8f7aaaSDanny Lin    $conf['compression'] = 0;
2190f8f7aaaSDanny Lin}
2200f8f7aaaSDanny Lin
22189177306SAndreas Gohr// input handle class
22289177306SAndreas Gohrglobal $INPUT;
22324870174SAndreas Gohr$INPUT = new Input();
22489177306SAndreas Gohr
225f1986589SMichael Klier// initialize plugin controller
226f1986589SMichael Klier$plugin_controller = new $plugin_controller_class();
227f1986589SMichael Klier
228f1986589SMichael Klier// initialize the event handler
229f1986589SMichael Klierglobal $EVENT_HANDLER;
230e1d9dcc8SAndreas Gohr$EVENT_HANDLER = new EventHandler();
231f1986589SMichael Klier
2326d06b26aSDominik Eckelmann$local = $conf['lang'];
233cbb44eabSAndreas GohrEvent::createAndTrigger('INIT_LANG_LOAD', $local, 'init_lang', true);
2346d06b26aSDominik Eckelmann
2356d06b26aSDominik Eckelmann
23616905344SAndreas Gohr// setup authentication system
237c7cb395cSAdrian Langif (!defined('NOSESSION')) {
23816905344SAndreas Gohr    auth_setup();
239c7cb395cSAdrian Lang}
240f62ea8a1Sandi
2415ec3fefcSAndreas Gohr// setup mail system
2425ec3fefcSAndreas Gohrmail_setup();
2435ec3fefcSAndreas Gohr
244042b9fecSAndreas Gohr$nil = null;
245042b9fecSAndreas GohrEvent::createAndTrigger('DOKUWIKI_INIT_DONE', $nil, null, false);
246042b9fecSAndreas Gohr
247f62ea8a1Sandi/**
2486eb3cdf6SAndreas Gohr * Initializes the session
2496eb3cdf6SAndreas Gohr *
2506eb3cdf6SAndreas Gohr * Makes sure the passed session cookie is valid, invalid ones are ignored an a new session ID is issued
2516eb3cdf6SAndreas Gohr *
2526eb3cdf6SAndreas Gohr * @link http://stackoverflow.com/a/33024310/172068
253924e477eSAndreas Gohr * @link http://php.net/manual/en/session.configuration.php#ini.session.sid-length
2546eb3cdf6SAndreas Gohr */
255d868eb89SAndreas Gohrfunction init_session()
256d868eb89SAndreas Gohr{
2576eb3cdf6SAndreas Gohr    global $conf;
2586eb3cdf6SAndreas Gohr    session_name(DOKU_SESSION_NAME);
259bf8392ebSAndreas Gohr    session_set_cookie_params([
260bf8392ebSAndreas Gohr        'lifetime' => DOKU_SESSION_LIFETIME,
261bf8392ebSAndreas Gohr        'path' => DOKU_SESSION_PATH,
262bf8392ebSAndreas Gohr        'domain' => DOKU_SESSION_DOMAIN,
263bf8392ebSAndreas Gohr        'secure' => ($conf['securecookie'] && is_ssl()),
264bf8392ebSAndreas Gohr        'httponly' => true,
265bf8392ebSAndreas Gohr        'samesite' => 'Lax',
266bf8392ebSAndreas Gohr    ]);
2676eb3cdf6SAndreas Gohr
2686eb3cdf6SAndreas Gohr    // make sure the session cookie contains a valid session ID
269924e477eSAndreas Gohr    if (isset($_COOKIE[DOKU_SESSION_NAME]) && !preg_match('/^[-,a-zA-Z0-9]{22,256}$/', $_COOKIE[DOKU_SESSION_NAME])) {
2706eb3cdf6SAndreas Gohr        unset($_COOKIE[DOKU_SESSION_NAME]);
2716eb3cdf6SAndreas Gohr    }
2726eb3cdf6SAndreas Gohr
2736eb3cdf6SAndreas Gohr    session_start();
2746eb3cdf6SAndreas Gohr}
2756eb3cdf6SAndreas Gohr
2766eb3cdf6SAndreas Gohr
2776eb3cdf6SAndreas Gohr/**
27898407a7aSandi * Checks paths from config file
27998407a7aSandi */
280d868eb89SAndreas Gohrfunction init_paths()
281d868eb89SAndreas Gohr{
28298407a7aSandi    global $conf;
28398407a7aSandi
2840ecde6ceSAndreas Gohr    $paths = [
2850ecde6ceSAndreas Gohr        'datadir'   => 'pages',
28698407a7aSandi        'olddir'    => 'attic',
28798407a7aSandi        'mediadir'  => 'media',
288e4f389efSKate Arzamastseva        'mediaolddir' => 'media_attic',
28998407a7aSandi        'metadir'   => 'meta',
290e4f389efSKate Arzamastseva        'mediametadir' => 'media_meta',
29198407a7aSandi        'cachedir'  => 'cache',
292579b0f7eSTNHarris        'indexdir'  => 'index',
293de33a58fSMichael Klier        'lockdir'   => 'locks',
2940ecde6ceSAndreas Gohr        'tmpdir'    => 'tmp',
2950ecde6ceSAndreas Gohr        'logdir'    => 'log',
2960ecde6ceSAndreas Gohr    ];
29798407a7aSandi
29898407a7aSandi    foreach ($paths as $c => $p) {
2997f086b67SAnika Henke        $path = empty($conf[$c]) ? $conf['savedir'] . '/' . $p : $conf[$c];
3006b9c156cSAnika Henke        $conf[$c] = init_path($path);
301697a39aeSAndreas Gohr        if (empty($conf[$c])) {
302697a39aeSAndreas Gohr            $path = fullpath($path);
3036b9c156cSAnika Henke            nice_die("The $c ('$p') at $path is not found, isn't accessible or writable.
30469dc3177SAndreas Gohr                You should check your config and permission settings.
30569dc3177SAndreas Gohr                Or maybe you want to <a href=\"install.php\">run the
30669dc3177SAndreas Gohr                installer</a>?");
30798407a7aSandi        }
308697a39aeSAndreas Gohr    }
30971726d78SBen Coburn
31071726d78SBen Coburn    // path to old changelog only needed for upgrading
31164159a61SAndreas Gohr    $conf['changelog_old'] = init_path(
31224870174SAndreas Gohr        $conf['changelog'] ?? $conf['savedir'] . '/changes.log'
31364159a61SAndreas Gohr    );
314177d6836SAndreas Gohr    if ($conf['changelog_old'] == '') {
315d4f83172SAndreas Gohr        unset($conf['changelog_old']);
316d4f83172SAndreas Gohr    }
31771726d78SBen Coburn    // hardcoded changelog because it is now a cache that lives in meta
31871726d78SBen Coburn    $conf['changelog'] = $conf['metadir'] . '/_dokuwiki.changes';
31999c8d7f2Smichael    $conf['media_changelog'] = $conf['metadir'] . '/_media.changes';
32098407a7aSandi}
32198407a7aSandi
32238fb1fc7SGerrit Uitslag/**
32338fb1fc7SGerrit Uitslag * Load the language strings
32438fb1fc7SGerrit Uitslag *
32538fb1fc7SGerrit Uitslag * @param string $langCode language code, as passed by event handler
32638fb1fc7SGerrit Uitslag */
327d868eb89SAndreas Gohrfunction init_lang($langCode)
328d868eb89SAndreas Gohr{
3296d06b26aSDominik Eckelmann    //prepare language array
330dd7a6159SGerrit Uitslag    global $lang, $config_cascade;
33124870174SAndreas Gohr    $lang = [];
3326d06b26aSDominik Eckelmann
3336d06b26aSDominik Eckelmann    //load the language files
3341d82c8d3SChristopher Smith    require(DOKU_INC . 'inc/lang/en/lang.php');
335dd7a6159SGerrit Uitslag    foreach ($config_cascade['lang']['core'] as $config_file) {
33679e79377SAndreas Gohr        if (file_exists($config_file . 'en/lang.php')) {
337dd7a6159SGerrit Uitslag            include($config_file . 'en/lang.php');
338dd7a6159SGerrit Uitslag        }
339dd7a6159SGerrit Uitslag    }
340dd7a6159SGerrit Uitslag
3416d06b26aSDominik Eckelmann    if ($langCode && $langCode != 'en') {
3426d06b26aSDominik Eckelmann        if (file_exists(DOKU_INC . "inc/lang/$langCode/lang.php")) {
3431d82c8d3SChristopher Smith            require(DOKU_INC . "inc/lang/$langCode/lang.php");
3446d06b26aSDominik Eckelmann        }
345dd7a6159SGerrit Uitslag        foreach ($config_cascade['lang']['core'] as $config_file) {
34679e79377SAndreas Gohr            if (file_exists($config_file . "$langCode/lang.php")) {
347dd7a6159SGerrit Uitslag                include($config_file . "$langCode/lang.php");
3486d06b26aSDominik Eckelmann            }
349dd7a6159SGerrit Uitslag        }
3506d06b26aSDominik Eckelmann    }
3516d06b26aSDominik Eckelmann}
3526d06b26aSDominik Eckelmann
35398407a7aSandi/**
3546b9c156cSAnika Henke * Checks the existence of certain files and creates them if missing.
3557367b368SAndreas Gohr */
356d868eb89SAndreas Gohrfunction init_files()
357d868eb89SAndreas Gohr{
3587367b368SAndreas Gohr    global $conf;
3590d8850c4SAndreas Gohr
36024870174SAndreas Gohr    $files = [$conf['indexdir'] . '/page.idx'];
3617367b368SAndreas Gohr
3627367b368SAndreas Gohr    foreach ($files as $file) {
36379e79377SAndreas Gohr        if (!file_exists($file)) {
3640d8850c4SAndreas Gohr            $fh = @fopen($file, 'a');
3650d8850c4SAndreas Gohr            if ($fh) {
3667367b368SAndreas Gohr                fclose($fh);
3673aa75874Smovatica                if ($conf['fperm']) chmod($file, $conf['fperm']);
3680d8850c4SAndreas Gohr            } else {
3693816dcbcSAndreas Gohr                nice_die("$file is not writable. Check your permissions settings!");
3700d8850c4SAndreas Gohr            }
3717367b368SAndreas Gohr        }
3727367b368SAndreas Gohr    }
3737367b368SAndreas Gohr}
3747367b368SAndreas Gohr
3757367b368SAndreas Gohr/**
3760d8850c4SAndreas Gohr * Returns absolute path
377f62ea8a1Sandi *
3780d8850c4SAndreas Gohr * This tries the given path first, then checks in DOKU_INC.
3797f086b67SAnika Henke * Check for accessibility on directories as well.
3800d8850c4SAndreas Gohr *
3810d8850c4SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
382f50a239bSTakamura *
383f50a239bSTakamura * @param string $path
384f50a239bSTakamura *
385f50a239bSTakamura * @return bool|string
386f62ea8a1Sandi */
387d868eb89SAndreas Gohrfunction init_path($path)
388d868eb89SAndreas Gohr{
3896b9c156cSAnika Henke    // check existence
39000976812SAndreas Gohr    $p = fullpath($path);
39179e79377SAndreas Gohr    if (!file_exists($p)) {
39200976812SAndreas Gohr        $p = fullpath(DOKU_INC . $path);
39379e79377SAndreas Gohr        if (!file_exists($p)) {
3948fc4e739Sandi            return '';
395f62ea8a1Sandi        }
3960d8850c4SAndreas Gohr    }
3970d8850c4SAndreas Gohr
3980d8850c4SAndreas Gohr    // check writability
3990d8850c4SAndreas Gohr    if (!@is_writable($p)) {
4000d8850c4SAndreas Gohr        return '';
4010d8850c4SAndreas Gohr    }
4020d8850c4SAndreas Gohr
4030d8850c4SAndreas Gohr    // check accessability (execute bit) for directories
40479e79377SAndreas Gohr    if (@is_dir($p) && !file_exists("$p/.")) {
4050d8850c4SAndreas Gohr        return '';
4060d8850c4SAndreas Gohr    }
4070d8850c4SAndreas Gohr
4080d8850c4SAndreas Gohr    return $p;
4090d8850c4SAndreas Gohr}
4108c4f28e8Sjan
411ed7b5f09Sandi/**
4121ca31cfeSAndreas Gohr * Sets the internal config values fperm and dperm which, when set,
4131ca31cfeSAndreas Gohr * will be used to change the permission of a newly created dir or
4141ca31cfeSAndreas Gohr * file with chmod. Considers the influence of the system's umask
4151ca31cfeSAndreas Gohr * setting the values only if needed.
4161ca31cfeSAndreas Gohr */
417d868eb89SAndreas Gohrfunction init_creationmodes()
418d868eb89SAndreas Gohr{
4191ca31cfeSAndreas Gohr    global $conf;
4201ca31cfeSAndreas Gohr
4211ca31cfeSAndreas Gohr    // Legacy support for old umask/dmask scheme
4221ca31cfeSAndreas Gohr    unset($conf['dmask']);
4231ca31cfeSAndreas Gohr    unset($conf['fmask']);
4241ca31cfeSAndreas Gohr    unset($conf['umask']);
42523420346SDamien Regad
42623420346SDamien Regad    $conf['fperm'] = false;
42723420346SDamien Regad    $conf['dperm'] = false;
4281ca31cfeSAndreas Gohr
4299f3cdec3SAndreas Gohr    // get system umask, fallback to 0 if none available
4309f3cdec3SAndreas Gohr    $umask = @umask();
4319f3cdec3SAndreas Gohr    if (!$umask) $umask = 0000;
4321ca31cfeSAndreas Gohr
4331ca31cfeSAndreas Gohr    // check what is set automatically by the system on file creation
4341ca31cfeSAndreas Gohr    // and set the fperm param if it's not what we want
435bd539124SAndreas Gohr    $auto_fmode = 0666 & ~$umask;
4361ca31cfeSAndreas Gohr    if ($auto_fmode != $conf['fmode']) $conf['fperm'] = $conf['fmode'];
4371ca31cfeSAndreas Gohr
438bd539124SAndreas Gohr    // check what is set automatically by the system on directory creation
439bd539124SAndreas Gohr    // and set the dperm param if it's not what we want.
440bd539124SAndreas Gohr    $auto_dmode = 0777 & ~$umask;
4411ca31cfeSAndreas Gohr    if ($auto_dmode != $conf['dmode']) $conf['dperm'] = $conf['dmode'];
4421ca31cfeSAndreas Gohr}
4431ca31cfeSAndreas Gohr
4441ca31cfeSAndreas Gohr/**
445ed7b5f09Sandi * Returns the full absolute URL to the directory where
446ed7b5f09Sandi * DokuWiki is installed in (includes a trailing slash)
447ed7b5f09Sandi *
448585bf44eSChristopher Smith * !! Can not access $_SERVER values through $INPUT
449585bf44eSChristopher Smith * !! here as this function is called before $INPUT is
450585bf44eSChristopher Smith * !! initialized.
451585bf44eSChristopher Smith *
452ed7b5f09Sandi * @author Andreas Gohr <andi@splitbrain.org>
453f50a239bSTakamura *
4543bfb10aeSAndreas Gohr * @param null|bool $abs Return an absolute URL? (null defaults to $conf['canonical'])
455f50a239bSTakamura *
456f50a239bSTakamura * @return string
457ed7b5f09Sandi */
458d868eb89SAndreas Gohrfunction getBaseURL($abs = null)
459d868eb89SAndreas Gohr{
460ed7b5f09Sandi    global $conf;
4613bfb10aeSAndreas Gohr
4623bfb10aeSAndreas Gohr    $abs ??= $conf['canonical'];
463ed7b5f09Sandi
4641858e4d7SGerry Weißbach    if (!empty($conf['basedir'])) {
46546c73e01SChris Smith        $dir = $conf['basedir'];
46689aa05dbSAndreas Gohr    } elseif (substr($_SERVER['SCRIPT_NAME'], -4) == '.php') {
46746c73e01SChris Smith        $dir = dirname($_SERVER['SCRIPT_NAME']);
46889aa05dbSAndreas Gohr    } elseif (substr($_SERVER['PHP_SELF'], -4) == '.php') {
46946c73e01SChris Smith        $dir = dirname($_SERVER['PHP_SELF']);
470093ec9e4Sandi    } elseif ($_SERVER['DOCUMENT_ROOT'] && $_SERVER['SCRIPT_FILENAME']) {
471dccd6b2bSAndreas Gohr        $dir = preg_replace(
472dccd6b2bSAndreas Gohr            '/^' . preg_quote($_SERVER['DOCUMENT_ROOT'], '/') . '/',
473dccd6b2bSAndreas Gohr            '',
474dccd6b2bSAndreas Gohr            $_SERVER['SCRIPT_FILENAME']
475dccd6b2bSAndreas Gohr        );
47646c73e01SChris Smith        $dir = dirname('/' . $dir);
47792b83b77Sandi    } else {
47846c73e01SChris Smith        $dir = '.'; //probably wrong
47992b83b77Sandi    }
480ed7b5f09Sandi
48146c73e01SChris Smith    $dir = str_replace('\\', '/', $dir);             // bugfix for weird WIN behaviour
48246c73e01SChris Smith    $dir = preg_replace('#//+#', '/', "/$dir/");     // ensure leading and trailing slashes
483ed7b5f09Sandi
484f62ea8a1Sandi    //handle script in lib/exe dir
485f62ea8a1Sandi    $dir = preg_replace('!lib/exe/$!', '', $dir);
486f62ea8a1Sandi
487488d5fa0SMichael Klier chi@chimeric.de    //handle script in lib/plugins dir
488488d5fa0SMichael Klier chi@chimeric.de    $dir = preg_replace('!lib/plugins/.*$!', '', $dir);
489488d5fa0SMichael Klier chi@chimeric.de
490ed7b5f09Sandi    //finish here for relative URLs
491ed7b5f09Sandi    if (!$abs) return $dir;
492ed7b5f09Sandi
49364159a61SAndreas Gohr    //use config if available, trim any slash from end of baseurl to avoid multiple consecutive slashes in the path
4941858e4d7SGerry Weißbach    if (!empty($conf['baseurl'])) return rtrim($conf['baseurl'], '/') . $dir;
495ef7b3ecdSAndreas Gohr
496e82e3526SAndreas Gohr    //split hostheader into host and port
4975627186cSAndreas Gohr    if (isset($_SERVER['HTTP_HOST'])) {
498*8033346cSm-martin-78        if ((!empty($conf['trustedproxy'])) && isset($_SERVER['HTTP_X_FORWARDED_HOST'])
499*8033346cSm-martin-78             && preg_match('/' . $conf['trustedproxy'] . '/', $_SERVER['REMOTE_ADDR'])) {
5005ab8f4a0Sm-martin-78            $cur_host = $_SERVER['HTTP_X_FORWARDED_HOST'];
5012a339739Sm-martin-78        } else {
5022a339739Sm-martin-78            $cur_host = $_SERVER['HTTP_HOST'];
5035ab8f4a0Sm-martin-78        }
5045ab8f4a0Sm-martin-78        $parsed_host = parse_url('http://' . $cur_host);
5053bfb10aeSAndreas Gohr        $host = $parsed_host['host'] ?? '';
5063bfb10aeSAndreas Gohr        $port = $parsed_host['port'] ?? '';
5075627186cSAndreas Gohr    } elseif (isset($_SERVER['SERVER_NAME'])) {
508204b27c8SMichael Hamann        $parsed_host = parse_url('http://' . $_SERVER['SERVER_NAME']);
5093bfb10aeSAndreas Gohr        $host = $parsed_host['host'] ?? '';
5103bfb10aeSAndreas Gohr        $port = $parsed_host['port'] ?? '';
5115627186cSAndreas Gohr    } else {
5125627186cSAndreas Gohr        $host = php_uname('n');
513c66972f2SAdrian Lang        $port = '';
5145627186cSAndreas Gohr    }
5155627186cSAndreas Gohr
516f5c6743cSAndreas Gohr    if (!is_ssl()) {
517ed7b5f09Sandi        $proto = 'http://';
518e82e3526SAndreas Gohr        if ($port == '80') {
519ed7b5f09Sandi            $port = '';
520ed7b5f09Sandi        }
521ed7b5f09Sandi    } else {
522ed7b5f09Sandi        $proto = 'https://';
523e82e3526SAndreas Gohr        if ($port == '443') {
524ed7b5f09Sandi            $port = '';
525ed7b5f09Sandi        }
526ed7b5f09Sandi    }
527ed7b5f09Sandi
528c66972f2SAdrian Lang    if ($port !== '') $port = ':' . $port;
529e82e3526SAndreas Gohr
530ed7b5f09Sandi    return $proto . $host . $port . $dir;
531ed7b5f09Sandi}
532ed7b5f09Sandi
533b000c6d4Sandi/**
534f5c6743cSAndreas Gohr * Check if accessed via HTTPS
535f5c6743cSAndreas Gohr *
536f5c6743cSAndreas Gohr * Apache leaves ,$_SERVER['HTTPS'] empty when not available, IIS sets it to 'off'.
537f5c6743cSAndreas Gohr * 'false' and 'disabled' are just guessing
538f5c6743cSAndreas Gohr *
539f5c6743cSAndreas Gohr * @returns bool true when SSL is active
540f5c6743cSAndreas Gohr */
541d868eb89SAndreas Gohrfunction is_ssl()
542d868eb89SAndreas Gohr{
54319738e65SEnrico Tagliavini    // check if we are behind a reverse proxy
544*8033346cSm-martin-78    if ((!empty($conf['trustedproxy'])) && isset($_SERVER['HTTP_X_FORWARDED_PROTO'])
545*8033346cSm-martin-78         && preg_match('/' . $conf['trustedproxy'] . '/', $_SERVER['REMOTE_ADDR'])
546*8033346cSm-martin-78         && ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) {
547f5c6743cSAndreas Gohr        return true;
548f5c6743cSAndreas Gohr    }
5496bdc2fb9SAndreas Gohr
5506bdc2fb9SAndreas Gohr    if (preg_match('/^(|off|false|disabled)$/i', $_SERVER['HTTPS'] ?? 'off')) {
5516bdc2fb9SAndreas Gohr        return false;
5526bdc2fb9SAndreas Gohr    }
5536bdc2fb9SAndreas Gohr
5546bdc2fb9SAndreas Gohr    return true;
555f5c6743cSAndreas Gohr}
556f5c6743cSAndreas Gohr
557f5c6743cSAndreas Gohr/**
55826714386SAndreas Gohr * checks it is windows OS
55926714386SAndreas Gohr * @return bool
56026714386SAndreas Gohr */
561d868eb89SAndreas Gohrfunction isWindows()
562d868eb89SAndreas Gohr{
56394c7e51fSfiwswe    return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
56426714386SAndreas Gohr}
56526714386SAndreas Gohr
56626714386SAndreas Gohr/**
5673816dcbcSAndreas Gohr * print a nice message even if no styles are loaded yet.
568f50a239bSTakamura *
569f50a239bSTakamura * @param integer|string $msg
5703816dcbcSAndreas Gohr */
571d868eb89SAndreas Gohrfunction nice_die($msg)
572d868eb89SAndreas Gohr{
5733816dcbcSAndreas Gohr    echo<<<EOT
574c8839c22SAnika Henke<!DOCTYPE html>
5753816dcbcSAndreas Gohr<html>
5763816dcbcSAndreas Gohr<head><title>DokuWiki Setup Error</title></head>
5773816dcbcSAndreas Gohr<body style="font-family: Arial, sans-serif">
5783816dcbcSAndreas Gohr    <div style="width:60%; margin: auto; background-color: #fcc;
5793816dcbcSAndreas Gohr                border: 1px solid #faa; padding: 0.5em 1em;">
5803816dcbcSAndreas Gohr        <h1 style="font-size: 120%">DokuWiki Setup Error</h1>
5813816dcbcSAndreas Gohr        <p>$msg</p>
5823816dcbcSAndreas Gohr    </div>
5833816dcbcSAndreas Gohr</body>
5843816dcbcSAndreas Gohr</html>
5853816dcbcSAndreas GohrEOT;
5863862da0eSAndreas Gohr    if (defined('DOKU_UNITTEST')) {
5873862da0eSAndreas Gohr        throw new RuntimeException('nice_die: ' . $msg);
5883862da0eSAndreas Gohr    }
5890a4266d4SElan Ruusamäe    exit(1);
5903816dcbcSAndreas Gohr}
5913816dcbcSAndreas Gohr
59200976812SAndreas Gohr/**
59300976812SAndreas Gohr * A realpath() replacement
59400976812SAndreas Gohr *
59500976812SAndreas Gohr * This function behaves similar to PHP's realpath() but does not resolve
59600976812SAndreas Gohr * symlinks or accesses upper directories
59700976812SAndreas Gohr *
5984761d30cSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
59900976812SAndreas Gohr * @author <richpageau at yahoo dot co dot uk>
60059752844SAnders Sandblad * @link   http://php.net/manual/en/function.realpath.php#75992
601f50a239bSTakamura *
602f50a239bSTakamura * @param string $path
603f50a239bSTakamura * @param bool $exists
604f50a239bSTakamura *
605f50a239bSTakamura * @return bool|string
60600976812SAndreas Gohr */
607d868eb89SAndreas Gohrfunction fullpath($path, $exists = false)
608d868eb89SAndreas Gohr{
6094761d30cSAndreas Gohr    static $run = 0;
6104761d30cSAndreas Gohr    $root  = '';
6116c16a3a9Sfiwswe    $iswin = (isWindows() || !empty($GLOBALS['DOKU_UNITTEST_ASSUME_WINDOWS']));
61200976812SAndreas Gohr
6134761d30cSAndreas Gohr    // find the (indestructable) root of the path - keeps windows stuff intact
6142401f18dSSyntaxseed    if ($path[0] == '/') {
6154761d30cSAndreas Gohr        $root = '/';
6164761d30cSAndreas Gohr    } elseif ($iswin) {
6174761d30cSAndreas Gohr        // match drive letter and UNC paths
6184761d30cSAndreas Gohr        if (preg_match('!^([a-zA-z]:)(.*)!', $path, $match)) {
619b9c4302bSAndreas Gohr            $root = $match[1] . '/';
6204761d30cSAndreas Gohr            $path = $match[2];
6214761d30cSAndreas Gohr        } elseif (preg_match('!^(\\\\\\\\[^\\\\/]+\\\\[^\\\\/]+[\\\\/])(.*)!', $path, $match)) {
6224761d30cSAndreas Gohr            $root = $match[1];
6234761d30cSAndreas Gohr            $path = $match[2];
62400976812SAndreas Gohr        }
6254761d30cSAndreas Gohr    }
6264761d30cSAndreas Gohr    $path = str_replace('\\', '/', $path);
6274761d30cSAndreas Gohr
6284761d30cSAndreas Gohr    // if the given path wasn't absolute already, prepend the script path and retry
6294761d30cSAndreas Gohr    if (!$root) {
6304761d30cSAndreas Gohr        $base = dirname($_SERVER['SCRIPT_FILENAME']);
6314761d30cSAndreas Gohr        $path = $base . '/' . $path;
6324761d30cSAndreas Gohr        if ($run == 0) { // avoid endless recursion when base isn't absolute for some reason
6334761d30cSAndreas Gohr            $run++;
634b328697dSAndreas Gohr            return fullpath($path, $exists);
6354761d30cSAndreas Gohr        }
6364761d30cSAndreas Gohr    }
6374761d30cSAndreas Gohr    $run = 0;
63800976812SAndreas Gohr
63900976812SAndreas Gohr    // canonicalize
64000976812SAndreas Gohr    $path = explode('/', $path);
64124870174SAndreas Gohr    $newpath = [];
642ef38bfe8SAndreas Gohr    foreach ($path as $p) {
643ef38bfe8SAndreas Gohr        if ($p === '' || $p === '.') continue;
644ef38bfe8SAndreas Gohr        if ($p === '..') {
64500976812SAndreas Gohr            array_pop($newpath);
64600976812SAndreas Gohr            continue;
64700976812SAndreas Gohr        }
64824870174SAndreas Gohr        $newpath[] = $p;
64900976812SAndreas Gohr    }
6504761d30cSAndreas Gohr    $finalpath = $root . implode('/', $newpath);
65100976812SAndreas Gohr
6526b9c156cSAnika Henke    // check for existence when needed (except when unit testing)
65379e79377SAndreas Gohr    if ($exists && !defined('DOKU_UNITTEST') && !file_exists($finalpath)) {
6544761d30cSAndreas Gohr        return false;
65500976812SAndreas Gohr    }
6564761d30cSAndreas Gohr    return $finalpath;
65700976812SAndreas Gohr}
658