xref: /dokuwiki/inc/init.php (revision 6bdc2fb913a5268649e45df2dc0ceb28ea15c324)
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
205c7cb395cSAdrian Lang// load libraries
206605f8e8dSAndreas Gohrrequire_once(DOKU_INC . 'vendor/autoload.php');
207c7cb395cSAdrian Langrequire_once(DOKU_INC . 'inc/load.php');
208c7cb395cSAdrian Lang
209642e976cSAndreas Gohr// from now on everything is an exception
21024870174SAndreas GohrErrorHandler::register();
211642e976cSAndreas Gohr
2120f8f7aaaSDanny Lin// disable gzip if not available
21313c37900SAndreas Gohrdefine('DOKU_HAS_BZIP', function_exists('bzopen'));
21413c37900SAndreas Gohrdefine('DOKU_HAS_GZIP', function_exists('gzopen'));
21513c37900SAndreas Gohrif ($conf['compression'] == 'bz2' && !DOKU_HAS_BZIP) {
2160f8f7aaaSDanny Lin    $conf['compression'] = 'gz';
2170f8f7aaaSDanny Lin}
21813c37900SAndreas Gohrif ($conf['compression'] == 'gz' && !DOKU_HAS_GZIP) {
2190f8f7aaaSDanny Lin    $conf['compression'] = 0;
2200f8f7aaaSDanny Lin}
2210f8f7aaaSDanny Lin
22289177306SAndreas Gohr// input handle class
22389177306SAndreas Gohrglobal $INPUT;
22424870174SAndreas Gohr$INPUT = new Input();
22589177306SAndreas Gohr
226f1986589SMichael Klier// initialize plugin controller
227f1986589SMichael Klier$plugin_controller = new $plugin_controller_class();
228f1986589SMichael Klier
229f1986589SMichael Klier// initialize the event handler
230f1986589SMichael Klierglobal $EVENT_HANDLER;
231e1d9dcc8SAndreas Gohr$EVENT_HANDLER = new EventHandler();
232f1986589SMichael Klier
2336d06b26aSDominik Eckelmann$local = $conf['lang'];
234cbb44eabSAndreas GohrEvent::createAndTrigger('INIT_LANG_LOAD', $local, 'init_lang', true);
2356d06b26aSDominik Eckelmann
2366d06b26aSDominik Eckelmann
23716905344SAndreas Gohr// setup authentication system
238c7cb395cSAdrian Langif (!defined('NOSESSION')) {
23916905344SAndreas Gohr    auth_setup();
240c7cb395cSAdrian Lang}
241f62ea8a1Sandi
2425ec3fefcSAndreas Gohr// setup mail system
2435ec3fefcSAndreas Gohrmail_setup();
2445ec3fefcSAndreas Gohr
245042b9fecSAndreas Gohr$nil = null;
246042b9fecSAndreas GohrEvent::createAndTrigger('DOKUWIKI_INIT_DONE', $nil, null, false);
247042b9fecSAndreas Gohr
248f62ea8a1Sandi/**
2496eb3cdf6SAndreas Gohr * Initializes the session
2506eb3cdf6SAndreas Gohr *
2516eb3cdf6SAndreas Gohr * Makes sure the passed session cookie is valid, invalid ones are ignored an a new session ID is issued
2526eb3cdf6SAndreas Gohr *
2536eb3cdf6SAndreas Gohr * @link http://stackoverflow.com/a/33024310/172068
254924e477eSAndreas Gohr * @link http://php.net/manual/en/session.configuration.php#ini.session.sid-length
2556eb3cdf6SAndreas Gohr */
256d868eb89SAndreas Gohrfunction init_session()
257d868eb89SAndreas Gohr{
2586eb3cdf6SAndreas Gohr    global $conf;
2596eb3cdf6SAndreas Gohr    session_name(DOKU_SESSION_NAME);
260bf8392ebSAndreas Gohr    session_set_cookie_params([
261bf8392ebSAndreas Gohr        'lifetime' => DOKU_SESSION_LIFETIME,
262bf8392ebSAndreas Gohr        'path' => DOKU_SESSION_PATH,
263bf8392ebSAndreas Gohr        'domain' => DOKU_SESSION_DOMAIN,
264bf8392ebSAndreas Gohr        'secure' => ($conf['securecookie'] && is_ssl()),
265bf8392ebSAndreas Gohr        'httponly' => true,
266bf8392ebSAndreas Gohr        'samesite' => 'Lax',
267bf8392ebSAndreas Gohr    ]);
2686eb3cdf6SAndreas Gohr
2696eb3cdf6SAndreas Gohr    // make sure the session cookie contains a valid session ID
270924e477eSAndreas Gohr    if (isset($_COOKIE[DOKU_SESSION_NAME]) && !preg_match('/^[-,a-zA-Z0-9]{22,256}$/', $_COOKIE[DOKU_SESSION_NAME])) {
2716eb3cdf6SAndreas Gohr        unset($_COOKIE[DOKU_SESSION_NAME]);
2726eb3cdf6SAndreas Gohr    }
2736eb3cdf6SAndreas Gohr
2746eb3cdf6SAndreas Gohr    session_start();
2756eb3cdf6SAndreas Gohr}
2766eb3cdf6SAndreas Gohr
2776eb3cdf6SAndreas Gohr
2786eb3cdf6SAndreas Gohr/**
27998407a7aSandi * Checks paths from config file
28098407a7aSandi */
281d868eb89SAndreas Gohrfunction init_paths()
282d868eb89SAndreas Gohr{
28398407a7aSandi    global $conf;
28498407a7aSandi
2850ecde6ceSAndreas Gohr    $paths = [
2860ecde6ceSAndreas Gohr        'datadir'   => 'pages',
28798407a7aSandi        'olddir'    => 'attic',
28898407a7aSandi        'mediadir'  => 'media',
289e4f389efSKate Arzamastseva        'mediaolddir' => 'media_attic',
29098407a7aSandi        'metadir'   => 'meta',
291e4f389efSKate Arzamastseva        'mediametadir' => 'media_meta',
29298407a7aSandi        'cachedir'  => 'cache',
293579b0f7eSTNHarris        'indexdir'  => 'index',
294de33a58fSMichael Klier        'lockdir'   => 'locks',
2950ecde6ceSAndreas Gohr        'tmpdir'    => 'tmp',
2960ecde6ceSAndreas Gohr        'logdir'    => 'log',
2970ecde6ceSAndreas Gohr    ];
29898407a7aSandi
29998407a7aSandi    foreach ($paths as $c => $p) {
3007f086b67SAnika Henke        $path = empty($conf[$c]) ? $conf['savedir'] . '/' . $p : $conf[$c];
3016b9c156cSAnika Henke        $conf[$c] = init_path($path);
302697a39aeSAndreas Gohr        if (empty($conf[$c])) {
303697a39aeSAndreas Gohr            $path = fullpath($path);
3046b9c156cSAnika Henke            nice_die("The $c ('$p') at $path is not found, isn't accessible or writable.
30569dc3177SAndreas Gohr                You should check your config and permission settings.
30669dc3177SAndreas Gohr                Or maybe you want to <a href=\"install.php\">run the
30769dc3177SAndreas Gohr                installer</a>?");
30898407a7aSandi        }
309697a39aeSAndreas Gohr    }
31071726d78SBen Coburn
31171726d78SBen Coburn    // path to old changelog only needed for upgrading
31264159a61SAndreas Gohr    $conf['changelog_old'] = init_path(
31324870174SAndreas Gohr        $conf['changelog'] ?? $conf['savedir'] . '/changes.log'
31464159a61SAndreas Gohr    );
315177d6836SAndreas Gohr    if ($conf['changelog_old'] == '') {
316d4f83172SAndreas Gohr        unset($conf['changelog_old']);
317d4f83172SAndreas Gohr    }
31871726d78SBen Coburn    // hardcoded changelog because it is now a cache that lives in meta
31971726d78SBen Coburn    $conf['changelog'] = $conf['metadir'] . '/_dokuwiki.changes';
32099c8d7f2Smichael    $conf['media_changelog'] = $conf['metadir'] . '/_media.changes';
32198407a7aSandi}
32298407a7aSandi
32338fb1fc7SGerrit Uitslag/**
32438fb1fc7SGerrit Uitslag * Load the language strings
32538fb1fc7SGerrit Uitslag *
32638fb1fc7SGerrit Uitslag * @param string $langCode language code, as passed by event handler
32738fb1fc7SGerrit Uitslag */
328d868eb89SAndreas Gohrfunction init_lang($langCode)
329d868eb89SAndreas Gohr{
3306d06b26aSDominik Eckelmann    //prepare language array
331dd7a6159SGerrit Uitslag    global $lang, $config_cascade;
33224870174SAndreas Gohr    $lang = [];
3336d06b26aSDominik Eckelmann
3346d06b26aSDominik Eckelmann    //load the language files
3351d82c8d3SChristopher Smith    require(DOKU_INC . 'inc/lang/en/lang.php');
336dd7a6159SGerrit Uitslag    foreach ($config_cascade['lang']['core'] as $config_file) {
33779e79377SAndreas Gohr        if (file_exists($config_file . 'en/lang.php')) {
338dd7a6159SGerrit Uitslag            include($config_file . 'en/lang.php');
339dd7a6159SGerrit Uitslag        }
340dd7a6159SGerrit Uitslag    }
341dd7a6159SGerrit Uitslag
3426d06b26aSDominik Eckelmann    if ($langCode && $langCode != 'en') {
3436d06b26aSDominik Eckelmann        if (file_exists(DOKU_INC . "inc/lang/$langCode/lang.php")) {
3441d82c8d3SChristopher Smith            require(DOKU_INC . "inc/lang/$langCode/lang.php");
3456d06b26aSDominik Eckelmann        }
346dd7a6159SGerrit Uitslag        foreach ($config_cascade['lang']['core'] as $config_file) {
34779e79377SAndreas Gohr            if (file_exists($config_file . "$langCode/lang.php")) {
348dd7a6159SGerrit Uitslag                include($config_file . "$langCode/lang.php");
3496d06b26aSDominik Eckelmann            }
350dd7a6159SGerrit Uitslag        }
3516d06b26aSDominik Eckelmann    }
3526d06b26aSDominik Eckelmann}
3536d06b26aSDominik Eckelmann
35498407a7aSandi/**
3556b9c156cSAnika Henke * Checks the existence of certain files and creates them if missing.
3567367b368SAndreas Gohr */
357d868eb89SAndreas Gohrfunction init_files()
358d868eb89SAndreas Gohr{
3597367b368SAndreas Gohr    global $conf;
3600d8850c4SAndreas Gohr
36124870174SAndreas Gohr    $files = [$conf['indexdir'] . '/page.idx'];
3627367b368SAndreas Gohr
3637367b368SAndreas Gohr    foreach ($files as $file) {
36479e79377SAndreas Gohr        if (!file_exists($file)) {
3650d8850c4SAndreas Gohr            $fh = @fopen($file, 'a');
3660d8850c4SAndreas Gohr            if ($fh) {
3677367b368SAndreas Gohr                fclose($fh);
3683aa75874Smovatica                if ($conf['fperm']) chmod($file, $conf['fperm']);
3690d8850c4SAndreas Gohr            } else {
3703816dcbcSAndreas Gohr                nice_die("$file is not writable. Check your permissions settings!");
3710d8850c4SAndreas Gohr            }
3727367b368SAndreas Gohr        }
3737367b368SAndreas Gohr    }
3747367b368SAndreas Gohr}
3757367b368SAndreas Gohr
3767367b368SAndreas Gohr/**
3770d8850c4SAndreas Gohr * Returns absolute path
378f62ea8a1Sandi *
3790d8850c4SAndreas Gohr * This tries the given path first, then checks in DOKU_INC.
3807f086b67SAnika Henke * Check for accessibility on directories as well.
3810d8850c4SAndreas Gohr *
3820d8850c4SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
383f50a239bSTakamura *
384f50a239bSTakamura * @param string $path
385f50a239bSTakamura *
386f50a239bSTakamura * @return bool|string
387f62ea8a1Sandi */
388d868eb89SAndreas Gohrfunction init_path($path)
389d868eb89SAndreas Gohr{
3906b9c156cSAnika Henke    // check existence
39100976812SAndreas Gohr    $p = fullpath($path);
39279e79377SAndreas Gohr    if (!file_exists($p)) {
39300976812SAndreas Gohr        $p = fullpath(DOKU_INC . $path);
39479e79377SAndreas Gohr        if (!file_exists($p)) {
3958fc4e739Sandi            return '';
396f62ea8a1Sandi        }
3970d8850c4SAndreas Gohr    }
3980d8850c4SAndreas Gohr
3990d8850c4SAndreas Gohr    // check writability
4000d8850c4SAndreas Gohr    if (!@is_writable($p)) {
4010d8850c4SAndreas Gohr        return '';
4020d8850c4SAndreas Gohr    }
4030d8850c4SAndreas Gohr
4040d8850c4SAndreas Gohr    // check accessability (execute bit) for directories
40579e79377SAndreas Gohr    if (@is_dir($p) && !file_exists("$p/.")) {
4060d8850c4SAndreas Gohr        return '';
4070d8850c4SAndreas Gohr    }
4080d8850c4SAndreas Gohr
4090d8850c4SAndreas Gohr    return $p;
4100d8850c4SAndreas Gohr}
4118c4f28e8Sjan
412ed7b5f09Sandi/**
4131ca31cfeSAndreas Gohr * Sets the internal config values fperm and dperm which, when set,
4141ca31cfeSAndreas Gohr * will be used to change the permission of a newly created dir or
4151ca31cfeSAndreas Gohr * file with chmod. Considers the influence of the system's umask
4161ca31cfeSAndreas Gohr * setting the values only if needed.
4171ca31cfeSAndreas Gohr */
418d868eb89SAndreas Gohrfunction init_creationmodes()
419d868eb89SAndreas Gohr{
4201ca31cfeSAndreas Gohr    global $conf;
4211ca31cfeSAndreas Gohr
4221ca31cfeSAndreas Gohr    // Legacy support for old umask/dmask scheme
4231ca31cfeSAndreas Gohr    unset($conf['dmask']);
4241ca31cfeSAndreas Gohr    unset($conf['fmask']);
4251ca31cfeSAndreas Gohr    unset($conf['umask']);
42623420346SDamien Regad
42723420346SDamien Regad    $conf['fperm'] = false;
42823420346SDamien Regad    $conf['dperm'] = false;
4291ca31cfeSAndreas Gohr
4309f3cdec3SAndreas Gohr    // get system umask, fallback to 0 if none available
4319f3cdec3SAndreas Gohr    $umask = @umask();
4329f3cdec3SAndreas Gohr    if (!$umask) $umask = 0000;
4331ca31cfeSAndreas Gohr
4341ca31cfeSAndreas Gohr    // check what is set automatically by the system on file creation
4351ca31cfeSAndreas Gohr    // and set the fperm param if it's not what we want
436bd539124SAndreas Gohr    $auto_fmode = 0666 & ~$umask;
4371ca31cfeSAndreas Gohr    if ($auto_fmode != $conf['fmode']) $conf['fperm'] = $conf['fmode'];
4381ca31cfeSAndreas Gohr
439bd539124SAndreas Gohr    // check what is set automatically by the system on directory creation
440bd539124SAndreas Gohr    // and set the dperm param if it's not what we want.
441bd539124SAndreas Gohr    $auto_dmode = 0777 & ~$umask;
4421ca31cfeSAndreas Gohr    if ($auto_dmode != $conf['dmode']) $conf['dperm'] = $conf['dmode'];
4431ca31cfeSAndreas Gohr}
4441ca31cfeSAndreas Gohr
4451ca31cfeSAndreas Gohr/**
446ed7b5f09Sandi * Returns the full absolute URL to the directory where
447ed7b5f09Sandi * DokuWiki is installed in (includes a trailing slash)
448ed7b5f09Sandi *
449585bf44eSChristopher Smith * !! Can not access $_SERVER values through $INPUT
450585bf44eSChristopher Smith * !! here as this function is called before $INPUT is
451585bf44eSChristopher Smith * !! initialized.
452585bf44eSChristopher Smith *
453ed7b5f09Sandi * @author Andreas Gohr <andi@splitbrain.org>
454f50a239bSTakamura *
4553bfb10aeSAndreas Gohr * @param null|bool $abs Return an absolute URL? (null defaults to $conf['canonical'])
456f50a239bSTakamura *
457f50a239bSTakamura * @return string
458ed7b5f09Sandi */
459d868eb89SAndreas Gohrfunction getBaseURL($abs = null)
460d868eb89SAndreas Gohr{
461ed7b5f09Sandi    global $conf;
4623bfb10aeSAndreas Gohr
4633bfb10aeSAndreas Gohr    $abs ??= $conf['canonical'];
464ed7b5f09Sandi
4651858e4d7SGerry Weißbach    if (!empty($conf['basedir'])) {
46646c73e01SChris Smith        $dir = $conf['basedir'];
46789aa05dbSAndreas Gohr    } elseif (substr($_SERVER['SCRIPT_NAME'], -4) == '.php') {
46846c73e01SChris Smith        $dir = dirname($_SERVER['SCRIPT_NAME']);
46989aa05dbSAndreas Gohr    } elseif (substr($_SERVER['PHP_SELF'], -4) == '.php') {
47046c73e01SChris Smith        $dir = dirname($_SERVER['PHP_SELF']);
471093ec9e4Sandi    } elseif ($_SERVER['DOCUMENT_ROOT'] && $_SERVER['SCRIPT_FILENAME']) {
472dccd6b2bSAndreas Gohr        $dir = preg_replace(
473dccd6b2bSAndreas Gohr            '/^' . preg_quote($_SERVER['DOCUMENT_ROOT'], '/') . '/',
474dccd6b2bSAndreas Gohr            '',
475dccd6b2bSAndreas Gohr            $_SERVER['SCRIPT_FILENAME']
476dccd6b2bSAndreas Gohr        );
47746c73e01SChris Smith        $dir = dirname('/' . $dir);
47892b83b77Sandi    } else {
47946c73e01SChris Smith        $dir = '.'; //probably wrong
48092b83b77Sandi    }
481ed7b5f09Sandi
48246c73e01SChris Smith    $dir = str_replace('\\', '/', $dir);             // bugfix for weird WIN behaviour
48346c73e01SChris Smith    $dir = preg_replace('#//+#', '/', "/$dir/");     // ensure leading and trailing slashes
484ed7b5f09Sandi
485f62ea8a1Sandi    //handle script in lib/exe dir
486f62ea8a1Sandi    $dir = preg_replace('!lib/exe/$!', '', $dir);
487f62ea8a1Sandi
488488d5fa0SMichael Klier chi@chimeric.de    //handle script in lib/plugins dir
489488d5fa0SMichael Klier chi@chimeric.de    $dir = preg_replace('!lib/plugins/.*$!', '', $dir);
490488d5fa0SMichael Klier chi@chimeric.de
491ed7b5f09Sandi    //finish here for relative URLs
492ed7b5f09Sandi    if (!$abs) return $dir;
493ed7b5f09Sandi
49464159a61SAndreas Gohr    //use config if available, trim any slash from end of baseurl to avoid multiple consecutive slashes in the path
4951858e4d7SGerry Weißbach    if (!empty($conf['baseurl'])) return rtrim($conf['baseurl'], '/') . $dir;
496ef7b3ecdSAndreas Gohr
497e82e3526SAndreas Gohr    //split hostheader into host and port
4985627186cSAndreas Gohr    if (isset($_SERVER['HTTP_HOST'])) {
499204b27c8SMichael Hamann        $parsed_host = parse_url('http://' . $_SERVER['HTTP_HOST']);
5003bfb10aeSAndreas Gohr        $host = $parsed_host['host'] ?? '';
5013bfb10aeSAndreas Gohr        $port = $parsed_host['port'] ?? '';
5025627186cSAndreas Gohr    } elseif (isset($_SERVER['SERVER_NAME'])) {
503204b27c8SMichael Hamann        $parsed_host = parse_url('http://' . $_SERVER['SERVER_NAME']);
5043bfb10aeSAndreas Gohr        $host = $parsed_host['host'] ?? '';
5053bfb10aeSAndreas Gohr        $port = $parsed_host['port'] ?? '';
5065627186cSAndreas Gohr    } else {
5075627186cSAndreas Gohr        $host = php_uname('n');
508c66972f2SAdrian Lang        $port = '';
5095627186cSAndreas Gohr    }
5105627186cSAndreas Gohr
511f5c6743cSAndreas Gohr    if (!is_ssl()) {
512ed7b5f09Sandi        $proto = 'http://';
513e82e3526SAndreas Gohr        if ($port == '80') {
514ed7b5f09Sandi            $port = '';
515ed7b5f09Sandi        }
516ed7b5f09Sandi    } else {
517ed7b5f09Sandi        $proto = 'https://';
518e82e3526SAndreas Gohr        if ($port == '443') {
519ed7b5f09Sandi            $port = '';
520ed7b5f09Sandi        }
521ed7b5f09Sandi    }
522ed7b5f09Sandi
523c66972f2SAdrian Lang    if ($port !== '') $port = ':' . $port;
524e82e3526SAndreas Gohr
525ed7b5f09Sandi    return $proto . $host . $port . $dir;
526ed7b5f09Sandi}
527ed7b5f09Sandi
528b000c6d4Sandi/**
529f5c6743cSAndreas Gohr * Check if accessed via HTTPS
530f5c6743cSAndreas Gohr *
531f5c6743cSAndreas Gohr * Apache leaves ,$_SERVER['HTTPS'] empty when not available, IIS sets it to 'off'.
532f5c6743cSAndreas Gohr * 'false' and 'disabled' are just guessing
533f5c6743cSAndreas Gohr *
534f5c6743cSAndreas Gohr * @returns bool true when SSL is active
535f5c6743cSAndreas Gohr */
536d868eb89SAndreas Gohrfunction is_ssl()
537d868eb89SAndreas Gohr{
53819738e65SEnrico Tagliavini    // check if we are behind a reverse proxy
539*6bdc2fb9SAndreas Gohr    if (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') == 'https') {
540f5c6743cSAndreas Gohr        return true;
541f5c6743cSAndreas Gohr    }
542*6bdc2fb9SAndreas Gohr
543*6bdc2fb9SAndreas Gohr    if (preg_match('/^(|off|false|disabled)$/i', $_SERVER['HTTPS'] ?? 'off')) {
544*6bdc2fb9SAndreas Gohr        return false;
545*6bdc2fb9SAndreas Gohr    }
546*6bdc2fb9SAndreas Gohr
547*6bdc2fb9SAndreas Gohr    return true;
548f5c6743cSAndreas Gohr}
549f5c6743cSAndreas Gohr
550f5c6743cSAndreas Gohr/**
55126714386SAndreas Gohr * checks it is windows OS
55226714386SAndreas Gohr * @return bool
55326714386SAndreas Gohr */
554d868eb89SAndreas Gohrfunction isWindows()
555d868eb89SAndreas Gohr{
55624870174SAndreas Gohr    return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
55726714386SAndreas Gohr}
55826714386SAndreas Gohr
55926714386SAndreas Gohr/**
5603816dcbcSAndreas Gohr * print a nice message even if no styles are loaded yet.
561f50a239bSTakamura *
562f50a239bSTakamura * @param integer|string $msg
5633816dcbcSAndreas Gohr */
564d868eb89SAndreas Gohrfunction nice_die($msg)
565d868eb89SAndreas Gohr{
5663816dcbcSAndreas Gohr    echo<<<EOT
567c8839c22SAnika Henke<!DOCTYPE html>
5683816dcbcSAndreas Gohr<html>
5693816dcbcSAndreas Gohr<head><title>DokuWiki Setup Error</title></head>
5703816dcbcSAndreas Gohr<body style="font-family: Arial, sans-serif">
5713816dcbcSAndreas Gohr    <div style="width:60%; margin: auto; background-color: #fcc;
5723816dcbcSAndreas Gohr                border: 1px solid #faa; padding: 0.5em 1em;">
5733816dcbcSAndreas Gohr        <h1 style="font-size: 120%">DokuWiki Setup Error</h1>
5743816dcbcSAndreas Gohr        <p>$msg</p>
5753816dcbcSAndreas Gohr    </div>
5763816dcbcSAndreas Gohr</body>
5773816dcbcSAndreas Gohr</html>
5783816dcbcSAndreas GohrEOT;
5793862da0eSAndreas Gohr    if (defined('DOKU_UNITTEST')) {
5803862da0eSAndreas Gohr        throw new RuntimeException('nice_die: ' . $msg);
5813862da0eSAndreas Gohr    }
5820a4266d4SElan Ruusamäe    exit(1);
5833816dcbcSAndreas Gohr}
5843816dcbcSAndreas Gohr
58500976812SAndreas Gohr/**
58600976812SAndreas Gohr * A realpath() replacement
58700976812SAndreas Gohr *
58800976812SAndreas Gohr * This function behaves similar to PHP's realpath() but does not resolve
58900976812SAndreas Gohr * symlinks or accesses upper directories
59000976812SAndreas Gohr *
5914761d30cSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
59200976812SAndreas Gohr * @author <richpageau at yahoo dot co dot uk>
59359752844SAnders Sandblad * @link   http://php.net/manual/en/function.realpath.php#75992
594f50a239bSTakamura *
595f50a239bSTakamura * @param string $path
596f50a239bSTakamura * @param bool $exists
597f50a239bSTakamura *
598f50a239bSTakamura * @return bool|string
59900976812SAndreas Gohr */
600d868eb89SAndreas Gohrfunction fullpath($path, $exists = false)
601d868eb89SAndreas Gohr{
6024761d30cSAndreas Gohr    static $run = 0;
6034761d30cSAndreas Gohr    $root  = '';
604724970e6SAndreas Gohr    $iswin = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' || !empty($GLOBALS['DOKU_UNITTEST_ASSUME_WINDOWS']));
60500976812SAndreas Gohr
6064761d30cSAndreas Gohr    // find the (indestructable) root of the path - keeps windows stuff intact
6072401f18dSSyntaxseed    if ($path[0] == '/') {
6084761d30cSAndreas Gohr        $root = '/';
6094761d30cSAndreas Gohr    } elseif ($iswin) {
6104761d30cSAndreas Gohr        // match drive letter and UNC paths
6114761d30cSAndreas Gohr        if (preg_match('!^([a-zA-z]:)(.*)!', $path, $match)) {
612b9c4302bSAndreas Gohr            $root = $match[1] . '/';
6134761d30cSAndreas Gohr            $path = $match[2];
6144761d30cSAndreas Gohr        } elseif (preg_match('!^(\\\\\\\\[^\\\\/]+\\\\[^\\\\/]+[\\\\/])(.*)!', $path, $match)) {
6154761d30cSAndreas Gohr            $root = $match[1];
6164761d30cSAndreas Gohr            $path = $match[2];
61700976812SAndreas Gohr        }
6184761d30cSAndreas Gohr    }
6194761d30cSAndreas Gohr    $path = str_replace('\\', '/', $path);
6204761d30cSAndreas Gohr
6214761d30cSAndreas Gohr    // if the given path wasn't absolute already, prepend the script path and retry
6224761d30cSAndreas Gohr    if (!$root) {
6234761d30cSAndreas Gohr        $base = dirname($_SERVER['SCRIPT_FILENAME']);
6244761d30cSAndreas Gohr        $path = $base . '/' . $path;
6254761d30cSAndreas Gohr        if ($run == 0) { // avoid endless recursion when base isn't absolute for some reason
6264761d30cSAndreas Gohr            $run++;
627b328697dSAndreas Gohr            return fullpath($path, $exists);
6284761d30cSAndreas Gohr        }
6294761d30cSAndreas Gohr    }
6304761d30cSAndreas Gohr    $run = 0;
63100976812SAndreas Gohr
63200976812SAndreas Gohr    // canonicalize
63300976812SAndreas Gohr    $path = explode('/', $path);
63424870174SAndreas Gohr    $newpath = [];
635ef38bfe8SAndreas Gohr    foreach ($path as $p) {
636ef38bfe8SAndreas Gohr        if ($p === '' || $p === '.') continue;
637ef38bfe8SAndreas Gohr        if ($p === '..') {
63800976812SAndreas Gohr            array_pop($newpath);
63900976812SAndreas Gohr            continue;
64000976812SAndreas Gohr        }
64124870174SAndreas Gohr        $newpath[] = $p;
64200976812SAndreas Gohr    }
6434761d30cSAndreas Gohr    $finalpath = $root . implode('/', $newpath);
64400976812SAndreas Gohr
6456b9c156cSAnika Henke    // check for existence when needed (except when unit testing)
64679e79377SAndreas Gohr    if ($exists && !defined('DOKU_UNITTEST') && !file_exists($finalpath)) {
6474761d30cSAndreas Gohr        return false;
64800976812SAndreas Gohr    }
6494761d30cSAndreas Gohr    return $finalpath;
65000976812SAndreas Gohr}
651