xref: /dokuwiki/inc/init.php (revision e0c5fc941a03b9dfd1ff0a9b1f2485a6e2d85956)
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')) {
47e086ef6cSlvl1ch43l    error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
48fc80ed59SAndreas Gohr} else {
49fc80ed59SAndreas Gohr    error_reporting(DOKU_E_LEVEL);
50fc80ed59SAndreas Gohr}
51c53ea5f2Sandi
526a9b3303SAndreas Gohr// autoloader
536a9b3303SAndreas Gohrrequire_once(DOKU_INC . 'inc/load.php');
546a9b3303SAndreas Gohr
55a69722b3SAndreas Gohr// avoid caching issues #1594
56a69722b3SAndreas Gohrheader('Vary: Cookie');
57a69722b3SAndreas Gohr
5850602150SBen Coburn// init memory caches
59db959ae3SAndreas Gohrglobal $cache_revinfo;
6024870174SAndreas Gohr       $cache_revinfo = [];
61db959ae3SAndreas Gohrglobal $cache_wikifn;
6224870174SAndreas Gohr       $cache_wikifn = [];
63db959ae3SAndreas Gohrglobal $cache_cleanid;
6424870174SAndreas Gohr       $cache_cleanid = [];
65db959ae3SAndreas Gohrglobal $cache_authname;
6624870174SAndreas Gohr       $cache_authname = [];
67db959ae3SAndreas Gohrglobal $cache_metadata;
6824870174SAndreas Gohr       $cache_metadata = [];
6950602150SBen Coburn
70cca94fbcSRoland Hager// always include 'inc/config_cascade.php'
71cca94fbcSRoland Hager// previously in preload.php set fields of $config_cascade will be merged with the defaults
72e6a6dbfeSAndreas Gohrinclude(DOKU_INC . 'inc/config_cascade.php');
73cb043f52SChris Smith
744724a577Sandi//prepare config array()
75ee20e7d1Sandiglobal $conf;
7624870174SAndreas Gohr$conf = [];
774724a577Sandi
78cb043f52SChris Smith// load the global config file(s)
7924870174SAndreas Gohrforeach (['default', 'local', 'protected'] as $config_group) {
80f8121585SChris Smith    if (empty($config_cascade['main'][$config_group])) continue;
81b303b92cSChris Smith    foreach ($config_cascade['main'][$config_group] as $config_file) {
8279e79377SAndreas Gohr        if (file_exists($config_file)) {
83f8121585SChris Smith            include($config_file);
84f8121585SChris Smith        }
85cb043f52SChris Smith    }
860a6ead41SAndreas Gohr}
87ad15db82Sandi
886a9b3303SAndreas Gohr// precalculate file creation modes
896a9b3303SAndreas Gohrinit_creationmodes();
906a9b3303SAndreas Gohr
916a9b3303SAndreas Gohr// make real paths and check them
926a9b3303SAndreas Gohrinit_paths();
936a9b3303SAndreas Gohrinit_files();
946a9b3303SAndreas Gohr
95066fee30SAndreas Gohr//prepare license array()
96066fee30SAndreas Gohrglobal $license;
9724870174SAndreas Gohr$license = [];
98066fee30SAndreas Gohr
99066fee30SAndreas Gohr// load the license file(s)
10024870174SAndreas Gohrforeach (['default', 'local'] as $config_group) {
101f8121585SChris Smith    if (empty($config_cascade['license'][$config_group])) continue;
102f8121585SChris Smith    foreach ($config_cascade['license'][$config_group] as $config_file) {
10379e79377SAndreas Gohr        if (file_exists($config_file)) {
104f8121585SChris Smith            include($config_file);
105f8121585SChris Smith        }
106f8121585SChris Smith    }
107066fee30SAndreas Gohr}
108066fee30SAndreas Gohr
109*e0c5fc94Sfjf2002if (empty($conf)) {
110*e0c5fc94Sfjf2002    nice_die("No configuration found in " . DOKU_CONF . ".");
111*e0c5fc94Sfjf2002}
112*e0c5fc94Sfjf2002
1131f8eb24fSAndreas Gohr// set timezone (as in pre 5.3.0 days)
1141f8eb24fSAndreas Gohrdate_default_timezone_set(@date_default_timezone_get());
1151f8eb24fSAndreas Gohr
1166a9b3303SAndreas Gohr
1176a9b3303SAndreas Gohr// don't let cookies ever interfere with request vars
1186a9b3303SAndreas Gohr$_REQUEST = array_merge($_GET, $_POST);
1196a9b3303SAndreas Gohr// input handle class
1206a9b3303SAndreas Gohrglobal $INPUT;
1216a9b3303SAndreas Gohr$INPUT = new Input();
1226a9b3303SAndreas Gohr
1236a9b3303SAndreas Gohr
124ed7b5f09Sandi// define baseURL
1254b1a4e04SAndreas Gohrif (!defined('DOKU_REL')) define('DOKU_REL', getBaseURL(false));
126ed7b5f09Sandiif (!defined('DOKU_URL')) define('DOKU_URL', getBaseURL(true));
1274b1a4e04SAndreas Gohrif (!defined('DOKU_BASE')) {
1284b1a4e04SAndreas Gohr    if ($conf['canonical']) {
1294b1a4e04SAndreas Gohr        define('DOKU_BASE', DOKU_URL);
1304b1a4e04SAndreas Gohr    } else {
1314b1a4e04SAndreas Gohr        define('DOKU_BASE', DOKU_REL);
1324b1a4e04SAndreas Gohr    }
1334b1a4e04SAndreas Gohr}
1344b1a4e04SAndreas Gohr
135b8595a66SAndreas Gohr// define whitespace
136b4f2363aSAndreas Gohrif (!defined('NL')) define('NL', "\n");
137b8595a66SAndreas Gohrif (!defined('DOKU_LF')) define('DOKU_LF', "\n");
138b8595a66SAndreas Gohrif (!defined('DOKU_TAB')) define('DOKU_TAB', "\t");
139ed7b5f09Sandi
140656c8fb3SAndreas Gohr// define cookie and session id, append server port when securecookie is configured FS#1664
141fb97a12aSMichael Großeif (!defined('DOKU_COOKIE')) {
14224870174SAndreas Gohr    $serverPort = $_SERVER['SERVER_PORT'] ?? '';
143fb97a12aSMichael Große    define('DOKU_COOKIE', 'DW' . md5(DOKU_REL . (($conf['securecookie']) ? $serverPort : '')));
144abc9c0d2SAndreas Gohr    unset($serverPort);
145fb97a12aSMichael Große}
146ee20e7d1Sandi
147ed7b5f09Sandi// define main script
148ed7b5f09Sandiif (!defined('DOKU_SCRIPT')) define('DOKU_SCRIPT', 'doku.php');
149ed7b5f09Sandi
150c163dbefSMichael Großeif (!defined('DOKU_TPL')) {
151c163dbefSMichael Große    /**
152c163dbefSMichael Große     * @deprecated 2012-10-13 replaced by more dynamic method
153c163dbefSMichael Große     * @see tpl_basedir()
154c163dbefSMichael Große     */
155c163dbefSMichael Große    define('DOKU_TPL', DOKU_BASE . 'lib/tpl/' . $conf['template'] . '/');
156c163dbefSMichael Große}
1576b13307fSandi
158c163dbefSMichael Großeif (!defined('DOKU_TPLINC')) {
159c163dbefSMichael Große    /**
160c163dbefSMichael Große     * @deprecated 2012-10-13 replaced by more dynamic method
161c163dbefSMichael Große     * @see tpl_incdir()
162c163dbefSMichael Große     */
163c163dbefSMichael Große    define('DOKU_TPLINC', DOKU_INC . 'lib/tpl/' . $conf['template'] . '/');
164c163dbefSMichael Große}
16578a6aeb1SAndreas Gohr
166ed7b5f09Sandi// make session rewrites XHTML compliant
1673fc74836Sandi@ini_set('arg_separator.output', '&amp;');
168ed7b5f09Sandi
169d7e6bba9SAndreas Gohr// make sure global zlib does not interfere FS#1132
170d7e6bba9SAndreas Gohr@ini_set('zlib.output_compression', 'off');
171d7e6bba9SAndreas Gohr
1726deb5405SAndreas Gohr// increase PCRE backtrack limit
1736deb5405SAndreas Gohr@ini_set('pcre.backtrack_limit', '20971520');
1746deb5405SAndreas Gohr
17598bda4fdSAndreas Gohr// enable gzip compression if supported
17624870174SAndreas Gohr$httpAcceptEncoding = $_SERVER['HTTP_ACCEPT_ENCODING'] ?? '';
177fb97a12aSMichael Große$conf['gzip_output'] &= (strpos($httpAcceptEncoding, 'gzip') !== false);
17865f6e7d6SMichael Hamannglobal $ACT;
1797d34963bSAndreas Gohrif (
1807d34963bSAndreas Gohr    $conf['gzip_output'] &&
1813138b5c7SAndreas Gohr        !defined('DOKU_DISABLE_GZIP_OUTPUT') &&
18265f6e7d6SMichael Hamann        function_exists('ob_gzhandler') &&
18399e10b7fSMichael Hamann        // Disable compression when a (compressed) sitemap might be delivered
18465f6e7d6SMichael Hamann        // See https://bugs.dokuwiki.org/index.php?do=details&task_id=2576
1857d34963bSAndreas Gohr        $ACT != 'sitemap'
1867d34963bSAndreas Gohr) {
1873138b5c7SAndreas Gohr    ob_start('ob_gzhandler');
1883138b5c7SAndreas Gohr}
1893138b5c7SAndreas Gohr
190ed7b5f09Sandi// init session
1916534245aSAndreas Gohrif (!headers_sent() && !defined('NOSESSION')) {
192c09f0eb1SGerrit Uitslag    if (!defined('DOKU_SESSION_NAME'))     define('DOKU_SESSION_NAME', "DokuWiki");
193c09f0eb1SGerrit Uitslag    if (!defined('DOKU_SESSION_LIFETIME')) define('DOKU_SESSION_LIFETIME', 0);
19455a71a16SGerrit Uitslag    if (!defined('DOKU_SESSION_PATH')) {
19573ab87deSGabriel Birke        $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
19655a71a16SGerrit Uitslag        define('DOKU_SESSION_PATH', $cookieDir);
197f5c6743cSAndreas Gohr    }
198c09f0eb1SGerrit Uitslag    if (!defined('DOKU_SESSION_DOMAIN'))   define('DOKU_SESSION_DOMAIN', '');
199c09f0eb1SGerrit Uitslag
2006eb3cdf6SAndreas Gohr    // start the session
2016eb3cdf6SAndreas Gohr    init_session();
20214a122deSAndreas Gohr
20314a122deSAndreas Gohr    // load left over messages
20414a122deSAndreas Gohr    if (isset($_SESSION[DOKU_COOKIE]['msg'])) {
20514a122deSAndreas Gohr        $MSG = $_SESSION[DOKU_COOKIE]['msg'];
20614a122deSAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['msg']);
20714a122deSAndreas Gohr    }
208bad31ae9SAndreas Gohr}
209ed7b5f09Sandi
210a1637ffdSAndreas Gohr
2113dea4ebcSAndreas Gohr// we don't want a purge URL to be digged
2120e80bb5eSChristopher Smithif (isset($_REQUEST['purge']) && !empty($_SERVER['HTTP_REFERER'])) unset($_REQUEST['purge']);
2133dea4ebcSAndreas Gohr
214ed7b5f09Sandi
215f1986589SMichael Klier// setup plugin controller class (can be overwritten in preload.php)
216f1986589SMichael Klierglobal $plugin_controller_class, $plugin_controller;
21724870174SAndreas Gohrif (empty($plugin_controller_class)) $plugin_controller_class = PluginController::class;
218f1986589SMichael Klier
219642e976cSAndreas Gohr// from now on everything is an exception
22024870174SAndreas GohrErrorHandler::register();
221642e976cSAndreas Gohr
2220f8f7aaaSDanny Lin// disable gzip if not available
22313c37900SAndreas Gohrdefine('DOKU_HAS_BZIP', function_exists('bzopen'));
22413c37900SAndreas Gohrdefine('DOKU_HAS_GZIP', function_exists('gzopen'));
22513c37900SAndreas Gohrif ($conf['compression'] == 'bz2' && !DOKU_HAS_BZIP) {
2260f8f7aaaSDanny Lin    $conf['compression'] = 'gz';
2270f8f7aaaSDanny Lin}
22813c37900SAndreas Gohrif ($conf['compression'] == 'gz' && !DOKU_HAS_GZIP) {
2290f8f7aaaSDanny Lin    $conf['compression'] = 0;
2300f8f7aaaSDanny Lin}
2310f8f7aaaSDanny Lin
232f1986589SMichael Klier// initialize plugin controller
233f1986589SMichael Klier$plugin_controller = new $plugin_controller_class();
234f1986589SMichael Klier
235f1986589SMichael Klier// initialize the event handler
236f1986589SMichael Klierglobal $EVENT_HANDLER;
237e1d9dcc8SAndreas Gohr$EVENT_HANDLER = new EventHandler();
238f1986589SMichael Klier
2396d06b26aSDominik Eckelmann$local = $conf['lang'];
240cbb44eabSAndreas GohrEvent::createAndTrigger('INIT_LANG_LOAD', $local, 'init_lang', true);
2416d06b26aSDominik Eckelmann
2426d06b26aSDominik Eckelmann
24316905344SAndreas Gohr// setup authentication system
244c7cb395cSAdrian Langif (!defined('NOSESSION')) {
24516905344SAndreas Gohr    auth_setup();
246c7cb395cSAdrian Lang}
247f62ea8a1Sandi
2485ec3fefcSAndreas Gohr// setup mail system
2495ec3fefcSAndreas Gohrmail_setup();
2505ec3fefcSAndreas Gohr
251042b9fecSAndreas Gohr$nil = null;
252042b9fecSAndreas GohrEvent::createAndTrigger('DOKUWIKI_INIT_DONE', $nil, null, false);
253042b9fecSAndreas Gohr
254f62ea8a1Sandi/**
2556eb3cdf6SAndreas Gohr * Initializes the session
2566eb3cdf6SAndreas Gohr *
2576eb3cdf6SAndreas Gohr * Makes sure the passed session cookie is valid, invalid ones are ignored an a new session ID is issued
2586eb3cdf6SAndreas Gohr *
2596eb3cdf6SAndreas Gohr * @link http://stackoverflow.com/a/33024310/172068
260924e477eSAndreas Gohr * @link http://php.net/manual/en/session.configuration.php#ini.session.sid-length
2616eb3cdf6SAndreas Gohr */
262d868eb89SAndreas Gohrfunction init_session()
263d868eb89SAndreas Gohr{
2646eb3cdf6SAndreas Gohr    global $conf;
2656eb3cdf6SAndreas Gohr    session_name(DOKU_SESSION_NAME);
266bf8392ebSAndreas Gohr    session_set_cookie_params([
267bf8392ebSAndreas Gohr        'lifetime' => DOKU_SESSION_LIFETIME,
268bf8392ebSAndreas Gohr        'path' => DOKU_SESSION_PATH,
269bf8392ebSAndreas Gohr        'domain' => DOKU_SESSION_DOMAIN,
27033cb4e01SAndreas Gohr        'secure' => ($conf['securecookie'] && \dokuwiki\Ip::isSsl()),
271bf8392ebSAndreas Gohr        'httponly' => true,
272bf8392ebSAndreas Gohr        'samesite' => 'Lax',
273bf8392ebSAndreas Gohr    ]);
2746eb3cdf6SAndreas Gohr
2756eb3cdf6SAndreas Gohr    // make sure the session cookie contains a valid session ID
276924e477eSAndreas Gohr    if (isset($_COOKIE[DOKU_SESSION_NAME]) && !preg_match('/^[-,a-zA-Z0-9]{22,256}$/', $_COOKIE[DOKU_SESSION_NAME])) {
2776eb3cdf6SAndreas Gohr        unset($_COOKIE[DOKU_SESSION_NAME]);
2786eb3cdf6SAndreas Gohr    }
2796eb3cdf6SAndreas Gohr
2806eb3cdf6SAndreas Gohr    session_start();
2816eb3cdf6SAndreas Gohr}
2826eb3cdf6SAndreas Gohr
2836eb3cdf6SAndreas Gohr
2846eb3cdf6SAndreas Gohr/**
28598407a7aSandi * Checks paths from config file
28698407a7aSandi */
287d868eb89SAndreas Gohrfunction init_paths()
288d868eb89SAndreas Gohr{
28998407a7aSandi    global $conf;
29098407a7aSandi
2910ecde6ceSAndreas Gohr    $paths = [
2920ecde6ceSAndreas Gohr        'datadir'   => 'pages',
29398407a7aSandi        'olddir'    => 'attic',
29498407a7aSandi        'mediadir'  => 'media',
295e4f389efSKate Arzamastseva        'mediaolddir' => 'media_attic',
29698407a7aSandi        'metadir'   => 'meta',
297e4f389efSKate Arzamastseva        'mediametadir' => 'media_meta',
29898407a7aSandi        'cachedir'  => 'cache',
299579b0f7eSTNHarris        'indexdir'  => 'index',
300de33a58fSMichael Klier        'lockdir'   => 'locks',
3010ecde6ceSAndreas Gohr        'tmpdir'    => 'tmp',
3020ecde6ceSAndreas Gohr        'logdir'    => 'log',
3030ecde6ceSAndreas Gohr    ];
30498407a7aSandi
30598407a7aSandi    foreach ($paths as $c => $p) {
3067f086b67SAnika Henke        $path = empty($conf[$c]) ? $conf['savedir'] . '/' . $p : $conf[$c];
3076b9c156cSAnika Henke        $conf[$c] = init_path($path);
308697a39aeSAndreas Gohr        if (empty($conf[$c])) {
309697a39aeSAndreas Gohr            $path = fullpath($path);
3106b9c156cSAnika Henke            nice_die("The $c ('$p') at $path is not found, isn't accessible or writable.
31169dc3177SAndreas Gohr                You should check your config and permission settings.
31269dc3177SAndreas Gohr                Or maybe you want to <a href=\"install.php\">run the
31369dc3177SAndreas Gohr                installer</a>?");
31498407a7aSandi        }
315697a39aeSAndreas Gohr    }
31671726d78SBen Coburn
31771726d78SBen Coburn    // path to old changelog only needed for upgrading
31864159a61SAndreas Gohr    $conf['changelog_old'] = init_path(
31924870174SAndreas Gohr        $conf['changelog'] ?? $conf['savedir'] . '/changes.log'
32064159a61SAndreas Gohr    );
321177d6836SAndreas Gohr    if ($conf['changelog_old'] == '') {
322d4f83172SAndreas Gohr        unset($conf['changelog_old']);
323d4f83172SAndreas Gohr    }
32471726d78SBen Coburn    // hardcoded changelog because it is now a cache that lives in meta
32571726d78SBen Coburn    $conf['changelog'] = $conf['metadir'] . '/_dokuwiki.changes';
32699c8d7f2Smichael    $conf['media_changelog'] = $conf['metadir'] . '/_media.changes';
32798407a7aSandi}
32898407a7aSandi
32938fb1fc7SGerrit Uitslag/**
33038fb1fc7SGerrit Uitslag * Load the language strings
33138fb1fc7SGerrit Uitslag *
33238fb1fc7SGerrit Uitslag * @param string $langCode language code, as passed by event handler
33338fb1fc7SGerrit Uitslag */
334d868eb89SAndreas Gohrfunction init_lang($langCode)
335d868eb89SAndreas Gohr{
3366d06b26aSDominik Eckelmann    //prepare language array
337dd7a6159SGerrit Uitslag    global $lang, $config_cascade;
33824870174SAndreas Gohr    $lang = [];
3396d06b26aSDominik Eckelmann
3406d06b26aSDominik Eckelmann    //load the language files
3411d82c8d3SChristopher Smith    require(DOKU_INC . 'inc/lang/en/lang.php');
342dd7a6159SGerrit Uitslag    foreach ($config_cascade['lang']['core'] as $config_file) {
34379e79377SAndreas Gohr        if (file_exists($config_file . 'en/lang.php')) {
344dd7a6159SGerrit Uitslag            include($config_file . 'en/lang.php');
345dd7a6159SGerrit Uitslag        }
346dd7a6159SGerrit Uitslag    }
347dd7a6159SGerrit Uitslag
3486d06b26aSDominik Eckelmann    if ($langCode && $langCode != 'en') {
3496d06b26aSDominik Eckelmann        if (file_exists(DOKU_INC . "inc/lang/$langCode/lang.php")) {
3501d82c8d3SChristopher Smith            require(DOKU_INC . "inc/lang/$langCode/lang.php");
3516d06b26aSDominik Eckelmann        }
352dd7a6159SGerrit Uitslag        foreach ($config_cascade['lang']['core'] as $config_file) {
35379e79377SAndreas Gohr            if (file_exists($config_file . "$langCode/lang.php")) {
354dd7a6159SGerrit Uitslag                include($config_file . "$langCode/lang.php");
3556d06b26aSDominik Eckelmann            }
356dd7a6159SGerrit Uitslag        }
3576d06b26aSDominik Eckelmann    }
3586d06b26aSDominik Eckelmann}
3596d06b26aSDominik Eckelmann
36098407a7aSandi/**
3616b9c156cSAnika Henke * Checks the existence of certain files and creates them if missing.
3627367b368SAndreas Gohr */
363d868eb89SAndreas Gohrfunction init_files()
364d868eb89SAndreas Gohr{
3657367b368SAndreas Gohr    global $conf;
3660d8850c4SAndreas Gohr
36724870174SAndreas Gohr    $files = [$conf['indexdir'] . '/page.idx'];
3687367b368SAndreas Gohr
3697367b368SAndreas Gohr    foreach ($files as $file) {
37079e79377SAndreas Gohr        if (!file_exists($file)) {
3710d8850c4SAndreas Gohr            $fh = @fopen($file, 'a');
3720d8850c4SAndreas Gohr            if ($fh) {
3737367b368SAndreas Gohr                fclose($fh);
3743aa75874Smovatica                if ($conf['fperm']) chmod($file, $conf['fperm']);
3750d8850c4SAndreas Gohr            } else {
3763816dcbcSAndreas Gohr                nice_die("$file is not writable. Check your permissions settings!");
3770d8850c4SAndreas Gohr            }
3787367b368SAndreas Gohr        }
3797367b368SAndreas Gohr    }
3807367b368SAndreas Gohr}
3817367b368SAndreas Gohr
3827367b368SAndreas Gohr/**
3830d8850c4SAndreas Gohr * Returns absolute path
384f62ea8a1Sandi *
3850d8850c4SAndreas Gohr * This tries the given path first, then checks in DOKU_INC.
3867f086b67SAnika Henke * Check for accessibility on directories as well.
3870d8850c4SAndreas Gohr *
3880d8850c4SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
389f50a239bSTakamura *
390f50a239bSTakamura * @param string $path
391f50a239bSTakamura *
392f50a239bSTakamura * @return bool|string
393f62ea8a1Sandi */
394d868eb89SAndreas Gohrfunction init_path($path)
395d868eb89SAndreas Gohr{
3966b9c156cSAnika Henke    // check existence
39700976812SAndreas Gohr    $p = fullpath($path);
39879e79377SAndreas Gohr    if (!file_exists($p)) {
39900976812SAndreas Gohr        $p = fullpath(DOKU_INC . $path);
40079e79377SAndreas Gohr        if (!file_exists($p)) {
4018fc4e739Sandi            return '';
402f62ea8a1Sandi        }
4030d8850c4SAndreas Gohr    }
4040d8850c4SAndreas Gohr
4050d8850c4SAndreas Gohr    // check writability
4060d8850c4SAndreas Gohr    if (!@is_writable($p)) {
4070d8850c4SAndreas Gohr        return '';
4080d8850c4SAndreas Gohr    }
4090d8850c4SAndreas Gohr
4100d8850c4SAndreas Gohr    // check accessability (execute bit) for directories
41179e79377SAndreas Gohr    if (@is_dir($p) && !file_exists("$p/.")) {
4120d8850c4SAndreas Gohr        return '';
4130d8850c4SAndreas Gohr    }
4140d8850c4SAndreas Gohr
4150d8850c4SAndreas Gohr    return $p;
4160d8850c4SAndreas Gohr}
4178c4f28e8Sjan
418ed7b5f09Sandi/**
4191ca31cfeSAndreas Gohr * Sets the internal config values fperm and dperm which, when set,
4201ca31cfeSAndreas Gohr * will be used to change the permission of a newly created dir or
4211ca31cfeSAndreas Gohr * file with chmod. Considers the influence of the system's umask
4221ca31cfeSAndreas Gohr * setting the values only if needed.
4231ca31cfeSAndreas Gohr */
424d868eb89SAndreas Gohrfunction init_creationmodes()
425d868eb89SAndreas Gohr{
4261ca31cfeSAndreas Gohr    global $conf;
4271ca31cfeSAndreas Gohr
4281ca31cfeSAndreas Gohr    // Legacy support for old umask/dmask scheme
4291ca31cfeSAndreas Gohr    unset($conf['dmask']);
4301ca31cfeSAndreas Gohr    unset($conf['fmask']);
4311ca31cfeSAndreas Gohr    unset($conf['umask']);
43223420346SDamien Regad
43323420346SDamien Regad    $conf['fperm'] = false;
43423420346SDamien Regad    $conf['dperm'] = false;
4351ca31cfeSAndreas Gohr
4369f3cdec3SAndreas Gohr    // get system umask, fallback to 0 if none available
4379f3cdec3SAndreas Gohr    $umask = @umask();
4389f3cdec3SAndreas Gohr    if (!$umask) $umask = 0000;
4391ca31cfeSAndreas Gohr
4401ca31cfeSAndreas Gohr    // check what is set automatically by the system on file creation
4411ca31cfeSAndreas Gohr    // and set the fperm param if it's not what we want
442bd539124SAndreas Gohr    $auto_fmode = 0666 & ~$umask;
4431ca31cfeSAndreas Gohr    if ($auto_fmode != $conf['fmode']) $conf['fperm'] = $conf['fmode'];
4441ca31cfeSAndreas Gohr
445bd539124SAndreas Gohr    // check what is set automatically by the system on directory creation
446bd539124SAndreas Gohr    // and set the dperm param if it's not what we want.
447bd539124SAndreas Gohr    $auto_dmode = 0777 & ~$umask;
4481ca31cfeSAndreas Gohr    if ($auto_dmode != $conf['dmode']) $conf['dperm'] = $conf['dmode'];
4491ca31cfeSAndreas Gohr}
4501ca31cfeSAndreas Gohr
4511ca31cfeSAndreas Gohr/**
452ed7b5f09Sandi * Returns the full absolute URL to the directory where
453ed7b5f09Sandi * DokuWiki is installed in (includes a trailing slash)
454ed7b5f09Sandi *
455585bf44eSChristopher Smith * !! Can not access $_SERVER values through $INPUT
456585bf44eSChristopher Smith * !! here as this function is called before $INPUT is
457585bf44eSChristopher Smith * !! initialized.
458585bf44eSChristopher Smith *
459ed7b5f09Sandi * @author Andreas Gohr <andi@splitbrain.org>
460f50a239bSTakamura *
4613bfb10aeSAndreas Gohr * @param null|bool $abs Return an absolute URL? (null defaults to $conf['canonical'])
462f50a239bSTakamura *
463f50a239bSTakamura * @return string
464ed7b5f09Sandi */
465d868eb89SAndreas Gohrfunction getBaseURL($abs = null)
466d868eb89SAndreas Gohr{
467ed7b5f09Sandi    global $conf;
4683bfb10aeSAndreas Gohr
4693bfb10aeSAndreas Gohr    $abs ??= $conf['canonical'];
470ed7b5f09Sandi
4711858e4d7SGerry Weißbach    if (!empty($conf['basedir'])) {
47246c73e01SChris Smith        $dir = $conf['basedir'];
47389aa05dbSAndreas Gohr    } elseif (substr($_SERVER['SCRIPT_NAME'], -4) == '.php') {
47446c73e01SChris Smith        $dir = dirname($_SERVER['SCRIPT_NAME']);
47589aa05dbSAndreas Gohr    } elseif (substr($_SERVER['PHP_SELF'], -4) == '.php') {
47646c73e01SChris Smith        $dir = dirname($_SERVER['PHP_SELF']);
477093ec9e4Sandi    } elseif ($_SERVER['DOCUMENT_ROOT'] && $_SERVER['SCRIPT_FILENAME']) {
478dccd6b2bSAndreas Gohr        $dir = preg_replace(
479dccd6b2bSAndreas Gohr            '/^' . preg_quote($_SERVER['DOCUMENT_ROOT'], '/') . '/',
480dccd6b2bSAndreas Gohr            '',
481dccd6b2bSAndreas Gohr            $_SERVER['SCRIPT_FILENAME']
482dccd6b2bSAndreas Gohr        );
48346c73e01SChris Smith        $dir = dirname('/' . $dir);
48492b83b77Sandi    } else {
485ac56bec8SAndreas Gohr        $dir = ''; //probably wrong, but we assume it's in the root
48692b83b77Sandi    }
487ed7b5f09Sandi
48846c73e01SChris Smith    $dir = str_replace('\\', '/', $dir);             // bugfix for weird WIN behaviour
48946c73e01SChris Smith    $dir = preg_replace('#//+#', '/', "/$dir/");     // ensure leading and trailing slashes
490ed7b5f09Sandi
491f62ea8a1Sandi    //handle script in lib/exe dir
492f62ea8a1Sandi    $dir = preg_replace('!lib/exe/$!', '', $dir);
493f62ea8a1Sandi
494488d5fa0SMichael Klier chi@chimeric.de    //handle script in lib/plugins dir
495488d5fa0SMichael Klier chi@chimeric.de    $dir = preg_replace('!lib/plugins/.*$!', '', $dir);
496488d5fa0SMichael Klier chi@chimeric.de
497ed7b5f09Sandi    //finish here for relative URLs
498ed7b5f09Sandi    if (!$abs) return $dir;
499ed7b5f09Sandi
50064159a61SAndreas Gohr    //use config if available, trim any slash from end of baseurl to avoid multiple consecutive slashes in the path
5011858e4d7SGerry Weißbach    if (!empty($conf['baseurl'])) return rtrim($conf['baseurl'], '/') . $dir;
502ef7b3ecdSAndreas Gohr
503e82e3526SAndreas Gohr    //split hostheader into host and port
50433cb4e01SAndreas Gohr    $hostname = \dokuwiki\Ip::hostName();
50533cb4e01SAndreas Gohr    $parsed_host = parse_url('http://' . $hostname);
5063bfb10aeSAndreas Gohr    $host = $parsed_host['host'] ?? '';
5073bfb10aeSAndreas Gohr    $port = $parsed_host['port'] ?? '';
5085627186cSAndreas Gohr
50933cb4e01SAndreas Gohr    if (!\dokuwiki\Ip::isSsl()) {
510ed7b5f09Sandi        $proto = 'http://';
511e82e3526SAndreas Gohr        if ($port == '80') {
512ed7b5f09Sandi            $port = '';
513ed7b5f09Sandi        }
514ed7b5f09Sandi    } else {
515ed7b5f09Sandi        $proto = 'https://';
516e82e3526SAndreas Gohr        if ($port == '443') {
517ed7b5f09Sandi            $port = '';
518ed7b5f09Sandi        }
519ed7b5f09Sandi    }
520ed7b5f09Sandi
521c66972f2SAdrian Lang    if ($port !== '') $port = ':' . $port;
522e82e3526SAndreas Gohr
523ed7b5f09Sandi    return $proto . $host . $port . $dir;
524ed7b5f09Sandi}
525ed7b5f09Sandi
526b000c6d4Sandi/**
52733cb4e01SAndreas Gohr * @deprecated 2025-06-03
528f5c6743cSAndreas Gohr */
529d868eb89SAndreas Gohrfunction is_ssl()
530d868eb89SAndreas Gohr{
53133cb4e01SAndreas Gohr    dbg_deprecated('Ip::isSsl()');
53233cb4e01SAndreas Gohr    return \dokuwiki\Ip::isSsl();
533f5c6743cSAndreas Gohr}
534f5c6743cSAndreas Gohr
535f5c6743cSAndreas Gohr/**
53626714386SAndreas Gohr * checks it is windows OS
53726714386SAndreas Gohr * @return bool
53826714386SAndreas Gohr */
539d868eb89SAndreas Gohrfunction isWindows()
540d868eb89SAndreas Gohr{
54194c7e51fSfiwswe    return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
54226714386SAndreas Gohr}
54326714386SAndreas Gohr
54426714386SAndreas Gohr/**
5453816dcbcSAndreas Gohr * print a nice message even if no styles are loaded yet.
546f50a239bSTakamura *
547f50a239bSTakamura * @param integer|string $msg
5483816dcbcSAndreas Gohr */
549d868eb89SAndreas Gohrfunction nice_die($msg)
550d868eb89SAndreas Gohr{
5513816dcbcSAndreas Gohr    echo<<<EOT
552c8839c22SAnika Henke<!DOCTYPE html>
5533816dcbcSAndreas Gohr<html>
5543816dcbcSAndreas Gohr<head><title>DokuWiki Setup Error</title></head>
5553816dcbcSAndreas Gohr<body style="font-family: Arial, sans-serif">
5563816dcbcSAndreas Gohr    <div style="width:60%; margin: auto; background-color: #fcc;
5573816dcbcSAndreas Gohr                border: 1px solid #faa; padding: 0.5em 1em;">
5583816dcbcSAndreas Gohr        <h1 style="font-size: 120%">DokuWiki Setup Error</h1>
5593816dcbcSAndreas Gohr        <p>$msg</p>
5603816dcbcSAndreas Gohr    </div>
5613816dcbcSAndreas Gohr</body>
5623816dcbcSAndreas Gohr</html>
5633816dcbcSAndreas GohrEOT;
5643862da0eSAndreas Gohr    if (defined('DOKU_UNITTEST')) {
5653862da0eSAndreas Gohr        throw new RuntimeException('nice_die: ' . $msg);
5663862da0eSAndreas Gohr    }
5670a4266d4SElan Ruusamäe    exit(1);
5683816dcbcSAndreas Gohr}
5693816dcbcSAndreas Gohr
57000976812SAndreas Gohr/**
57100976812SAndreas Gohr * A realpath() replacement
57200976812SAndreas Gohr *
57300976812SAndreas Gohr * This function behaves similar to PHP's realpath() but does not resolve
57400976812SAndreas Gohr * symlinks or accesses upper directories
57500976812SAndreas Gohr *
5764761d30cSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
57700976812SAndreas Gohr * @author <richpageau at yahoo dot co dot uk>
57859752844SAnders Sandblad * @link   http://php.net/manual/en/function.realpath.php#75992
579f50a239bSTakamura *
580f50a239bSTakamura * @param string $path
581f50a239bSTakamura * @param bool $exists
582f50a239bSTakamura *
583f50a239bSTakamura * @return bool|string
58400976812SAndreas Gohr */
585d868eb89SAndreas Gohrfunction fullpath($path, $exists = false)
586d868eb89SAndreas Gohr{
5874761d30cSAndreas Gohr    static $run = 0;
5884761d30cSAndreas Gohr    $root  = '';
5896c16a3a9Sfiwswe    $iswin = (isWindows() || !empty($GLOBALS['DOKU_UNITTEST_ASSUME_WINDOWS']));
59000976812SAndreas Gohr
5914761d30cSAndreas Gohr    // find the (indestructable) root of the path - keeps windows stuff intact
5922401f18dSSyntaxseed    if ($path[0] == '/') {
5934761d30cSAndreas Gohr        $root = '/';
5944761d30cSAndreas Gohr    } elseif ($iswin) {
5954761d30cSAndreas Gohr        // match drive letter and UNC paths
5964761d30cSAndreas Gohr        if (preg_match('!^([a-zA-z]:)(.*)!', $path, $match)) {
597b9c4302bSAndreas Gohr            $root = $match[1] . '/';
5984761d30cSAndreas Gohr            $path = $match[2];
5994761d30cSAndreas Gohr        } elseif (preg_match('!^(\\\\\\\\[^\\\\/]+\\\\[^\\\\/]+[\\\\/])(.*)!', $path, $match)) {
6004761d30cSAndreas Gohr            $root = $match[1];
6014761d30cSAndreas Gohr            $path = $match[2];
60200976812SAndreas Gohr        }
6034761d30cSAndreas Gohr    }
6044761d30cSAndreas Gohr    $path = str_replace('\\', '/', $path);
6054761d30cSAndreas Gohr
6064761d30cSAndreas Gohr    // if the given path wasn't absolute already, prepend the script path and retry
6074761d30cSAndreas Gohr    if (!$root) {
6084761d30cSAndreas Gohr        $base = dirname($_SERVER['SCRIPT_FILENAME']);
6094761d30cSAndreas Gohr        $path = $base . '/' . $path;
6104761d30cSAndreas Gohr        if ($run == 0) { // avoid endless recursion when base isn't absolute for some reason
6114761d30cSAndreas Gohr            $run++;
612b328697dSAndreas Gohr            return fullpath($path, $exists);
6134761d30cSAndreas Gohr        }
6144761d30cSAndreas Gohr    }
6154761d30cSAndreas Gohr    $run = 0;
61600976812SAndreas Gohr
61700976812SAndreas Gohr    // canonicalize
61800976812SAndreas Gohr    $path = explode('/', $path);
61924870174SAndreas Gohr    $newpath = [];
620ef38bfe8SAndreas Gohr    foreach ($path as $p) {
621ef38bfe8SAndreas Gohr        if ($p === '' || $p === '.') continue;
622ef38bfe8SAndreas Gohr        if ($p === '..') {
62300976812SAndreas Gohr            array_pop($newpath);
62400976812SAndreas Gohr            continue;
62500976812SAndreas Gohr        }
62624870174SAndreas Gohr        $newpath[] = $p;
62700976812SAndreas Gohr    }
6284761d30cSAndreas Gohr    $finalpath = $root . implode('/', $newpath);
62900976812SAndreas Gohr
6306b9c156cSAnika Henke    // check for existence when needed (except when unit testing)
63179e79377SAndreas Gohr    if ($exists && !defined('DOKU_UNITTEST') && !file_exists($finalpath)) {
6324761d30cSAndreas Gohr        return false;
63300976812SAndreas Gohr    }
6344761d30cSAndreas Gohr    return $finalpath;
63500976812SAndreas Gohr}
636