xref: /dokuwiki/inc/init.php (revision 042b9feccd0e2d859641e309ec62796db9416cb4)
1ed7b5f09Sandi<?php
2ed7b5f09Sandi/**
3ed7b5f09Sandi * Initialize some defaults needed for DokuWiki
4ed7b5f09Sandi */
5ed7b5f09Sandi
6cbb44eabSAndreas Gohruse dokuwiki\Extension\Event;
7e1d9dcc8SAndreas Gohruse dokuwiki\Extension\EventHandler;
8e1d9dcc8SAndreas Gohr
93272d797SAndreas Gohr/**
103272d797SAndreas Gohr * timing Dokuwiki execution
11f50a239bSTakamura *
12f50a239bSTakamura * @param integer $start
13f50a239bSTakamura *
14f50a239bSTakamura * @return mixed
153272d797SAndreas Gohr */
16a609a9ccSBen Coburnfunction delta_time($start=0) {
17ac4be4d7SPiyush Mishra    return microtime(true)-((float)$start);
18a609a9ccSBen Coburn}
19a609a9ccSBen Coburndefine('DOKU_START_TIME', delta_time());
20a609a9ccSBen Coburn
21ccaeaa85SAndreas Gohrglobal $config_cascade;
22cca94fbcSRoland Hager$config_cascade = array();
23ccaeaa85SAndreas Gohr
2448beefecSAndreas Gohr// if available load a preload config file
25e6266454SChris Smith$preload = fullpath(dirname(__FILE__)).'/preload.php';
2679e79377SAndreas Gohrif (file_exists($preload)) include($preload);
2748beefecSAndreas Gohr
28ed7b5f09Sandi// define the include path
2900976812SAndreas Gohrif(!defined('DOKU_INC')) define('DOKU_INC',fullpath(dirname(__FILE__).'/../').'/');
30ad15db82Sandi
31c2a6d816SAndreas Gohr// define Plugin dir
32c2a6d816SAndreas Gohrif(!defined('DOKU_PLUGIN'))  define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
33c2a6d816SAndreas Gohr
34e7cb32dcSAndreas Gohr// define config path (packagers may want to change this to /etc/dokuwiki/)
35b7551a6dSEsther Brunnerif(!defined('DOKU_CONF')) define('DOKU_CONF',DOKU_INC.'conf/');
36e7cb32dcSAndreas Gohr
37bad905f1SBen Coburn// check for error reporting override or set error reporting to sane values
3879e79377SAndreas Gohrif (!defined('DOKU_E_LEVEL') && file_exists(DOKU_CONF.'report_e_all')) {
39bad905f1SBen Coburn    define('DOKU_E_LEVEL', E_ALL);
40bad905f1SBen Coburn}
41fc80ed59SAndreas Gohrif (!defined('DOKU_E_LEVEL')) {
424fcd684aSMichael Hamann    error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT);
43fc80ed59SAndreas Gohr} else {
44fc80ed59SAndreas Gohr    error_reporting(DOKU_E_LEVEL);
45fc80ed59SAndreas Gohr}
46c53ea5f2Sandi
47a69722b3SAndreas Gohr// avoid caching issues #1594
48a69722b3SAndreas Gohrheader('Vary: Cookie');
49a69722b3SAndreas Gohr
5050602150SBen Coburn// init memory caches
51db959ae3SAndreas Gohrglobal $cache_revinfo;
52db959ae3SAndreas Gohr       $cache_revinfo = array();
53db959ae3SAndreas Gohrglobal $cache_wikifn;
54db959ae3SAndreas Gohr       $cache_wikifn = array();
55db959ae3SAndreas Gohrglobal $cache_cleanid;
56db959ae3SAndreas Gohr       $cache_cleanid = array();
57db959ae3SAndreas Gohrglobal $cache_authname;
58db959ae3SAndreas Gohr       $cache_authname = array();
59db959ae3SAndreas Gohrglobal $cache_metadata;
60db959ae3SAndreas Gohr       $cache_metadata = array();
6150602150SBen Coburn
62cca94fbcSRoland Hager// always include 'inc/config_cascade.php'
63cca94fbcSRoland Hager// previously in preload.php set fields of $config_cascade will be merged with the defaults
64e6a6dbfeSAndreas Gohrinclude(DOKU_INC.'inc/config_cascade.php');
65cb043f52SChris Smith
664724a577Sandi//prepare config array()
67ee20e7d1Sandiglobal $conf;
684724a577Sandi$conf = array();
694724a577Sandi
70cb043f52SChris Smith// load the global config file(s)
71b303b92cSChris Smithforeach (array('default','local','protected') as $config_group) {
72f8121585SChris Smith    if (empty($config_cascade['main'][$config_group])) continue;
73b303b92cSChris Smith    foreach ($config_cascade['main'][$config_group] as $config_file) {
7479e79377SAndreas Gohr        if (file_exists($config_file)) {
75f8121585SChris Smith            include($config_file);
76f8121585SChris Smith        }
77cb043f52SChris Smith    }
780a6ead41SAndreas Gohr}
79ad15db82Sandi
80066fee30SAndreas Gohr//prepare license array()
81066fee30SAndreas Gohrglobal $license;
82066fee30SAndreas Gohr$license = array();
83066fee30SAndreas Gohr
84066fee30SAndreas Gohr// load the license file(s)
85f8121585SChris Smithforeach (array('default','local') as $config_group) {
86f8121585SChris Smith    if (empty($config_cascade['license'][$config_group])) continue;
87f8121585SChris Smith    foreach ($config_cascade['license'][$config_group] as $config_file) {
8879e79377SAndreas Gohr        if(file_exists($config_file)){
89f8121585SChris Smith            include($config_file);
90f8121585SChris Smith        }
91f8121585SChris Smith    }
92066fee30SAndreas Gohr}
93066fee30SAndreas Gohr
941f8eb24fSAndreas Gohr// set timezone (as in pre 5.3.0 days)
951f8eb24fSAndreas Gohrdate_default_timezone_set(@date_default_timezone_get());
961f8eb24fSAndreas Gohr
97ed7b5f09Sandi// define baseURL
984b1a4e04SAndreas Gohrif(!defined('DOKU_REL')) define('DOKU_REL',getBaseURL(false));
99ed7b5f09Sandiif(!defined('DOKU_URL')) define('DOKU_URL',getBaseURL(true));
1004b1a4e04SAndreas Gohrif(!defined('DOKU_BASE')){
1014b1a4e04SAndreas Gohr    if($conf['canonical']){
1024b1a4e04SAndreas Gohr        define('DOKU_BASE',DOKU_URL);
1034b1a4e04SAndreas Gohr    }else{
1044b1a4e04SAndreas Gohr        define('DOKU_BASE',DOKU_REL);
1054b1a4e04SAndreas Gohr    }
1064b1a4e04SAndreas Gohr}
1074b1a4e04SAndreas Gohr
108b8595a66SAndreas Gohr// define whitespace
109b4f2363aSAndreas Gohrif(!defined('NL')) define ('NL',"\n");
110b8595a66SAndreas Gohrif(!defined('DOKU_LF')) define ('DOKU_LF',"\n");
111b8595a66SAndreas Gohrif(!defined('DOKU_TAB')) define ('DOKU_TAB',"\t");
112ed7b5f09Sandi
113656c8fb3SAndreas Gohr// define cookie and session id, append server port when securecookie is configured FS#1664
114fb97a12aSMichael Großeif (!defined('DOKU_COOKIE')) {
115fb97a12aSMichael Große    $serverPort = isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : '';
116fb97a12aSMichael Große    define('DOKU_COOKIE', 'DW' . md5(DOKU_REL . (($conf['securecookie']) ? $serverPort : '')));
117abc9c0d2SAndreas Gohr    unset($serverPort);
118fb97a12aSMichael Große}
119ee20e7d1Sandi
120ed7b5f09Sandi// define main script
121ed7b5f09Sandiif(!defined('DOKU_SCRIPT')) define('DOKU_SCRIPT','doku.php');
122ed7b5f09Sandi
123c163dbefSMichael Großeif(!defined('DOKU_TPL')) {
124c163dbefSMichael Große    /**
125c163dbefSMichael Große     * @deprecated 2012-10-13 replaced by more dynamic method
126c163dbefSMichael Große     * @see tpl_basedir()
127c163dbefSMichael Große     */
128c163dbefSMichael Große    define('DOKU_TPL', DOKU_BASE.'lib/tpl/'.$conf['template'].'/');
129c163dbefSMichael Große}
1306b13307fSandi
131c163dbefSMichael Großeif(!defined('DOKU_TPLINC')) {
132c163dbefSMichael Große    /**
133c163dbefSMichael Große     * @deprecated 2012-10-13 replaced by more dynamic method
134c163dbefSMichael Große     * @see tpl_incdir()
135c163dbefSMichael Große     */
136c163dbefSMichael Große    define('DOKU_TPLINC', DOKU_INC.'lib/tpl/'.$conf['template'].'/');
137c163dbefSMichael Große}
13878a6aeb1SAndreas Gohr
139ed7b5f09Sandi// make session rewrites XHTML compliant
1403fc74836Sandi@ini_set('arg_separator.output', '&amp;');
141ed7b5f09Sandi
142d7e6bba9SAndreas Gohr// make sure global zlib does not interfere FS#1132
143d7e6bba9SAndreas Gohr@ini_set('zlib.output_compression', 'off');
144d7e6bba9SAndreas Gohr
1456deb5405SAndreas Gohr// increase PCRE backtrack limit
1466deb5405SAndreas Gohr@ini_set('pcre.backtrack_limit', '20971520');
1476deb5405SAndreas Gohr
14898bda4fdSAndreas Gohr// enable gzip compression if supported
149fb97a12aSMichael Große$httpAcceptEncoding = isset($_SERVER['HTTP_ACCEPT_ENCODING']) ? $_SERVER['HTTP_ACCEPT_ENCODING'] : '';
150fb97a12aSMichael Große$conf['gzip_output'] &= (strpos($httpAcceptEncoding, 'gzip') !== false);
15165f6e7d6SMichael Hamannglobal $ACT;
1523138b5c7SAndreas Gohrif ($conf['gzip_output'] &&
1533138b5c7SAndreas Gohr        !defined('DOKU_DISABLE_GZIP_OUTPUT') &&
15465f6e7d6SMichael Hamann        function_exists('ob_gzhandler') &&
15599e10b7fSMichael Hamann        // Disable compression when a (compressed) sitemap might be delivered
15665f6e7d6SMichael Hamann        // See https://bugs.dokuwiki.org/index.php?do=details&task_id=2576
15799e10b7fSMichael Hamann        $ACT != 'sitemap') {
1583138b5c7SAndreas Gohr    ob_start('ob_gzhandler');
1593138b5c7SAndreas Gohr}
1603138b5c7SAndreas Gohr
161ed7b5f09Sandi// init session
1626534245aSAndreas Gohrif(!headers_sent() && !defined('NOSESSION')) {
163c09f0eb1SGerrit Uitslag    if(!defined('DOKU_SESSION_NAME'))     define ('DOKU_SESSION_NAME', "DokuWiki");
164c09f0eb1SGerrit Uitslag    if(!defined('DOKU_SESSION_LIFETIME')) define ('DOKU_SESSION_LIFETIME', 0);
16555a71a16SGerrit Uitslag    if(!defined('DOKU_SESSION_PATH')) {
16673ab87deSGabriel Birke        $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
16755a71a16SGerrit Uitslag        define ('DOKU_SESSION_PATH', $cookieDir);
168f5c6743cSAndreas Gohr    }
169c09f0eb1SGerrit Uitslag    if(!defined('DOKU_SESSION_DOMAIN'))   define ('DOKU_SESSION_DOMAIN', '');
170c09f0eb1SGerrit Uitslag
1716eb3cdf6SAndreas Gohr    // start the session
1726eb3cdf6SAndreas Gohr    init_session();
17314a122deSAndreas Gohr
17414a122deSAndreas Gohr    // load left over messages
17514a122deSAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['msg'])) {
17614a122deSAndreas Gohr        $MSG = $_SESSION[DOKU_COOKIE]['msg'];
17714a122deSAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['msg']);
17814a122deSAndreas Gohr    }
179bad31ae9SAndreas Gohr}
180ed7b5f09Sandi
181a1637ffdSAndreas Gohr// don't let cookies ever interfere with request vars
182a1637ffdSAndreas Gohr$_REQUEST = array_merge($_GET,$_POST);
183a1637ffdSAndreas Gohr
1843dea4ebcSAndreas Gohr// we don't want a purge URL to be digged
1850e80bb5eSChristopher Smithif(isset($_REQUEST['purge']) && !empty($_SERVER['HTTP_REFERER'])) unset($_REQUEST['purge']);
1863dea4ebcSAndreas Gohr
1871ca31cfeSAndreas Gohr// precalculate file creation modes
1881ca31cfeSAndreas Gohrinit_creationmodes();
189ed7b5f09Sandi
1903dc3a5f1Sandi// make real paths and check them
19198407a7aSandiinit_paths();
1927367b368SAndreas Gohrinit_files();
193ed7b5f09Sandi
194f1986589SMichael Klier// setup plugin controller class (can be overwritten in preload.php)
195f1986589SMichael Klierglobal $plugin_controller_class, $plugin_controller;
1963a7140a1SAndreas Gohrif (empty($plugin_controller_class)) $plugin_controller_class = dokuwiki\Extension\PluginController::class;
197f1986589SMichael Klier
198c7cb395cSAdrian Lang// load libraries
199605f8e8dSAndreas Gohrrequire_once(DOKU_INC.'vendor/autoload.php');
200c7cb395cSAdrian Langrequire_once(DOKU_INC.'inc/load.php');
201c7cb395cSAdrian Lang
202642e976cSAndreas Gohr// from now on everything is an exception
203642e976cSAndreas Gohr\dokuwiki\ErrorHandler::register();
204642e976cSAndreas Gohr
2050f8f7aaaSDanny Lin// disable gzip if not available
20613c37900SAndreas Gohrdefine('DOKU_HAS_BZIP', function_exists('bzopen'));
20713c37900SAndreas Gohrdefine('DOKU_HAS_GZIP', function_exists('gzopen'));
20813c37900SAndreas Gohrif($conf['compression'] == 'bz2' && !DOKU_HAS_BZIP) {
2090f8f7aaaSDanny Lin    $conf['compression'] = 'gz';
2100f8f7aaaSDanny Lin}
21113c37900SAndreas Gohrif($conf['compression'] == 'gz' && !DOKU_HAS_GZIP) {
2120f8f7aaaSDanny Lin    $conf['compression'] = 0;
2130f8f7aaaSDanny Lin}
2140f8f7aaaSDanny Lin
21589177306SAndreas Gohr// input handle class
21689177306SAndreas Gohrglobal $INPUT;
217ccc4c71cSAndreas Gohr$INPUT = new \dokuwiki\Input\Input();
21889177306SAndreas Gohr
219f1986589SMichael Klier// initialize plugin controller
220f1986589SMichael Klier$plugin_controller = new $plugin_controller_class();
221f1986589SMichael Klier
222f1986589SMichael Klier// initialize the event handler
223f1986589SMichael Klierglobal $EVENT_HANDLER;
224e1d9dcc8SAndreas Gohr$EVENT_HANDLER = new EventHandler();
225f1986589SMichael Klier
2266d06b26aSDominik Eckelmann$local = $conf['lang'];
227cbb44eabSAndreas GohrEvent::createAndTrigger('INIT_LANG_LOAD', $local, 'init_lang', true);
2286d06b26aSDominik Eckelmann
2296d06b26aSDominik Eckelmann
23016905344SAndreas Gohr// setup authentication system
231c7cb395cSAdrian Langif (!defined('NOSESSION')) {
23216905344SAndreas Gohr    auth_setup();
233c7cb395cSAdrian Lang}
234f62ea8a1Sandi
2355ec3fefcSAndreas Gohr// setup mail system
2365ec3fefcSAndreas Gohrmail_setup();
2375ec3fefcSAndreas Gohr
238*042b9fecSAndreas Gohr$nil = null;
239*042b9fecSAndreas GohrEvent::createAndTrigger('DOKUWIKI_INIT_DONE', $nil, null, false);
240*042b9fecSAndreas Gohr
241f62ea8a1Sandi/**
2426eb3cdf6SAndreas Gohr * Initializes the session
2436eb3cdf6SAndreas Gohr *
2446eb3cdf6SAndreas Gohr * Makes sure the passed session cookie is valid, invalid ones are ignored an a new session ID is issued
2456eb3cdf6SAndreas Gohr *
2466eb3cdf6SAndreas Gohr * @link http://stackoverflow.com/a/33024310/172068
247924e477eSAndreas Gohr * @link http://php.net/manual/en/session.configuration.php#ini.session.sid-length
2486eb3cdf6SAndreas Gohr */
2496eb3cdf6SAndreas Gohrfunction init_session() {
2506eb3cdf6SAndreas Gohr    global $conf;
2516eb3cdf6SAndreas Gohr    session_name(DOKU_SESSION_NAME);
25264159a61SAndreas Gohr    session_set_cookie_params(
25364159a61SAndreas Gohr        DOKU_SESSION_LIFETIME,
25464159a61SAndreas Gohr        DOKU_SESSION_PATH,
25564159a61SAndreas Gohr        DOKU_SESSION_DOMAIN,
25664159a61SAndreas Gohr        ($conf['securecookie'] && is_ssl()),
25764159a61SAndreas Gohr        true
25864159a61SAndreas Gohr    );
2596eb3cdf6SAndreas Gohr
2606eb3cdf6SAndreas Gohr    // make sure the session cookie contains a valid session ID
261924e477eSAndreas Gohr    if(isset($_COOKIE[DOKU_SESSION_NAME]) && !preg_match('/^[-,a-zA-Z0-9]{22,256}$/', $_COOKIE[DOKU_SESSION_NAME])) {
2626eb3cdf6SAndreas Gohr        unset($_COOKIE[DOKU_SESSION_NAME]);
2636eb3cdf6SAndreas Gohr    }
2646eb3cdf6SAndreas Gohr
2656eb3cdf6SAndreas Gohr    session_start();
2666eb3cdf6SAndreas Gohr}
2676eb3cdf6SAndreas Gohr
2686eb3cdf6SAndreas Gohr
2696eb3cdf6SAndreas Gohr/**
27098407a7aSandi * Checks paths from config file
27198407a7aSandi */
27298407a7aSandifunction init_paths(){
27398407a7aSandi    global $conf;
27498407a7aSandi
2750ecde6ceSAndreas Gohr    $paths = [
2760ecde6ceSAndreas Gohr        'datadir'   => 'pages',
27798407a7aSandi        'olddir'    => 'attic',
27898407a7aSandi        'mediadir'  => 'media',
279e4f389efSKate Arzamastseva        'mediaolddir' => 'media_attic',
28098407a7aSandi        'metadir'   => 'meta',
281e4f389efSKate Arzamastseva        'mediametadir' => 'media_meta',
28298407a7aSandi        'cachedir'  => 'cache',
283579b0f7eSTNHarris        'indexdir'  => 'index',
284de33a58fSMichael Klier        'lockdir'   => 'locks',
2850ecde6ceSAndreas Gohr        'tmpdir'    => 'tmp',
2860ecde6ceSAndreas Gohr        'logdir'    => 'log',
2870ecde6ceSAndreas Gohr    ];
28898407a7aSandi
28998407a7aSandi    foreach($paths as $c => $p) {
2907f086b67SAnika Henke        $path = empty($conf[$c]) ? $conf['savedir'].'/'.$p : $conf[$c];
2916b9c156cSAnika Henke        $conf[$c] = init_path($path);
2926b9c156cSAnika Henke        if(empty($conf[$c]))
2936b9c156cSAnika Henke            nice_die("The $c ('$p') at $path is not found, isn't accessible or writable.
29469dc3177SAndreas Gohr                You should check your config and permission settings.
29569dc3177SAndreas Gohr                Or maybe you want to <a href=\"install.php\">run the
29669dc3177SAndreas Gohr                installer</a>?");
29798407a7aSandi    }
29871726d78SBen Coburn
29971726d78SBen Coburn    // path to old changelog only needed for upgrading
30064159a61SAndreas Gohr    $conf['changelog_old'] = init_path(
30164159a61SAndreas Gohr        (isset($conf['changelog'])) ? ($conf['changelog']) : ($conf['savedir'] . '/changes.log')
30264159a61SAndreas Gohr    );
30371726d78SBen Coburn    if ($conf['changelog_old']=='') { unset($conf['changelog_old']); }
30471726d78SBen Coburn    // hardcoded changelog because it is now a cache that lives in meta
30571726d78SBen Coburn    $conf['changelog'] = $conf['metadir'].'/_dokuwiki.changes';
30699c8d7f2Smichael    $conf['media_changelog'] = $conf['metadir'].'/_media.changes';
30798407a7aSandi}
30898407a7aSandi
30938fb1fc7SGerrit Uitslag/**
31038fb1fc7SGerrit Uitslag * Load the language strings
31138fb1fc7SGerrit Uitslag *
31238fb1fc7SGerrit Uitslag * @param string $langCode language code, as passed by event handler
31338fb1fc7SGerrit Uitslag */
3146d06b26aSDominik Eckelmannfunction init_lang($langCode) {
3156d06b26aSDominik Eckelmann    //prepare language array
316dd7a6159SGerrit Uitslag    global $lang, $config_cascade;
3176d06b26aSDominik Eckelmann    $lang = array();
3186d06b26aSDominik Eckelmann
3196d06b26aSDominik Eckelmann    //load the language files
3201d82c8d3SChristopher Smith    require(DOKU_INC.'inc/lang/en/lang.php');
321dd7a6159SGerrit Uitslag    foreach ($config_cascade['lang']['core'] as $config_file) {
32279e79377SAndreas Gohr        if (file_exists($config_file . 'en/lang.php')) {
323dd7a6159SGerrit Uitslag            include($config_file . 'en/lang.php');
324dd7a6159SGerrit Uitslag        }
325dd7a6159SGerrit Uitslag    }
326dd7a6159SGerrit Uitslag
3276d06b26aSDominik Eckelmann    if ($langCode && $langCode != 'en') {
3286d06b26aSDominik Eckelmann        if (file_exists(DOKU_INC."inc/lang/$langCode/lang.php")) {
3291d82c8d3SChristopher Smith            require(DOKU_INC."inc/lang/$langCode/lang.php");
3306d06b26aSDominik Eckelmann        }
331dd7a6159SGerrit Uitslag        foreach ($config_cascade['lang']['core'] as $config_file) {
33279e79377SAndreas Gohr            if (file_exists($config_file . "$langCode/lang.php")) {
333dd7a6159SGerrit Uitslag                include($config_file . "$langCode/lang.php");
3346d06b26aSDominik Eckelmann            }
335dd7a6159SGerrit Uitslag        }
3366d06b26aSDominik Eckelmann    }
3376d06b26aSDominik Eckelmann}
3386d06b26aSDominik Eckelmann
33998407a7aSandi/**
3406b9c156cSAnika Henke * Checks the existence of certain files and creates them if missing.
3417367b368SAndreas Gohr */
3427367b368SAndreas Gohrfunction init_files(){
3437367b368SAndreas Gohr    global $conf;
3440d8850c4SAndreas Gohr
345345b1674SAndreas Gohr    $files = array($conf['indexdir'].'/page.idx');
3467367b368SAndreas Gohr
3477367b368SAndreas Gohr    foreach($files as $file){
34879e79377SAndreas Gohr        if(!file_exists($file)){
3490d8850c4SAndreas Gohr            $fh = @fopen($file,'a');
3500d8850c4SAndreas Gohr            if($fh){
3517367b368SAndreas Gohr                fclose($fh);
3523aa75874Smovatica                if($conf['fperm']) chmod($file, $conf['fperm']);
3530d8850c4SAndreas Gohr            }else{
3543816dcbcSAndreas Gohr                nice_die("$file is not writable. Check your permissions settings!");
3550d8850c4SAndreas Gohr            }
3567367b368SAndreas Gohr        }
3577367b368SAndreas Gohr    }
3587367b368SAndreas Gohr}
3597367b368SAndreas Gohr
3607367b368SAndreas Gohr/**
3610d8850c4SAndreas Gohr * Returns absolute path
362f62ea8a1Sandi *
3630d8850c4SAndreas Gohr * This tries the given path first, then checks in DOKU_INC.
3647f086b67SAnika Henke * Check for accessibility on directories as well.
3650d8850c4SAndreas Gohr *
3660d8850c4SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
367f50a239bSTakamura *
368f50a239bSTakamura * @param string $path
369f50a239bSTakamura *
370f50a239bSTakamura * @return bool|string
371f62ea8a1Sandi */
372f62ea8a1Sandifunction init_path($path){
3736b9c156cSAnika Henke    // check existence
37400976812SAndreas Gohr    $p = fullpath($path);
37579e79377SAndreas Gohr    if(!file_exists($p)){
37600976812SAndreas Gohr        $p = fullpath(DOKU_INC.$path);
37779e79377SAndreas Gohr        if(!file_exists($p)){
3788fc4e739Sandi            return '';
379f62ea8a1Sandi        }
3800d8850c4SAndreas Gohr    }
3810d8850c4SAndreas Gohr
3820d8850c4SAndreas Gohr    // check writability
3830d8850c4SAndreas Gohr    if(!@is_writable($p)){
3840d8850c4SAndreas Gohr        return '';
3850d8850c4SAndreas Gohr    }
3860d8850c4SAndreas Gohr
3870d8850c4SAndreas Gohr    // check accessability (execute bit) for directories
38879e79377SAndreas Gohr    if(@is_dir($p) && !file_exists("$p/.")){
3890d8850c4SAndreas Gohr        return '';
3900d8850c4SAndreas Gohr    }
3910d8850c4SAndreas Gohr
3920d8850c4SAndreas Gohr    return $p;
3930d8850c4SAndreas Gohr}
3948c4f28e8Sjan
395ed7b5f09Sandi/**
3961ca31cfeSAndreas Gohr * Sets the internal config values fperm and dperm which, when set,
3971ca31cfeSAndreas Gohr * will be used to change the permission of a newly created dir or
3981ca31cfeSAndreas Gohr * file with chmod. Considers the influence of the system's umask
3991ca31cfeSAndreas Gohr * setting the values only if needed.
4001ca31cfeSAndreas Gohr */
4011ca31cfeSAndreas Gohrfunction init_creationmodes(){
4021ca31cfeSAndreas Gohr    global $conf;
4031ca31cfeSAndreas Gohr
4041ca31cfeSAndreas Gohr    // Legacy support for old umask/dmask scheme
4051ca31cfeSAndreas Gohr    unset($conf['dmask']);
4061ca31cfeSAndreas Gohr    unset($conf['fmask']);
4071ca31cfeSAndreas Gohr    unset($conf['umask']);
40823420346SDamien Regad
40923420346SDamien Regad    $conf['fperm'] = false;
41023420346SDamien Regad    $conf['dperm'] = false;
4111ca31cfeSAndreas Gohr
4129f3cdec3SAndreas Gohr    // get system umask, fallback to 0 if none available
4139f3cdec3SAndreas Gohr    $umask = @umask();
4149f3cdec3SAndreas Gohr    if(!$umask) $umask = 0000;
4151ca31cfeSAndreas Gohr
4161ca31cfeSAndreas Gohr    // check what is set automatically by the system on file creation
4171ca31cfeSAndreas Gohr    // and set the fperm param if it's not what we want
418bd539124SAndreas Gohr    $auto_fmode = 0666 & ~$umask;
4191ca31cfeSAndreas Gohr    if($auto_fmode != $conf['fmode']) $conf['fperm'] = $conf['fmode'];
4201ca31cfeSAndreas Gohr
421bd539124SAndreas Gohr    // check what is set automatically by the system on directory creation
422bd539124SAndreas Gohr    // and set the dperm param if it's not what we want.
423bd539124SAndreas Gohr    $auto_dmode = 0777 & ~$umask;
4241ca31cfeSAndreas Gohr    if($auto_dmode != $conf['dmode']) $conf['dperm'] = $conf['dmode'];
4251ca31cfeSAndreas Gohr}
4261ca31cfeSAndreas Gohr
4271ca31cfeSAndreas Gohr/**
428ed7b5f09Sandi * Returns the full absolute URL to the directory where
429ed7b5f09Sandi * DokuWiki is installed in (includes a trailing slash)
430ed7b5f09Sandi *
431585bf44eSChristopher Smith * !! Can not access $_SERVER values through $INPUT
432585bf44eSChristopher Smith * !! here as this function is called before $INPUT is
433585bf44eSChristopher Smith * !! initialized.
434585bf44eSChristopher Smith *
435ed7b5f09Sandi * @author Andreas Gohr <andi@splitbrain.org>
436f50a239bSTakamura *
437f50a239bSTakamura * @param null|string $abs
438f50a239bSTakamura *
439f50a239bSTakamura * @return string
440ed7b5f09Sandi */
4414b1a4e04SAndreas Gohrfunction getBaseURL($abs=null){
442ed7b5f09Sandi    global $conf;
443ed7b5f09Sandi    //if canonical url enabled always return absolute
4444b1a4e04SAndreas Gohr    if(is_null($abs)) $abs = $conf['canonical'];
445ed7b5f09Sandi
4461858e4d7SGerry Weißbach    if(!empty($conf['basedir'])){
44746c73e01SChris Smith        $dir = $conf['basedir'];
44889aa05dbSAndreas Gohr    }elseif(substr($_SERVER['SCRIPT_NAME'],-4) == '.php'){
44946c73e01SChris Smith        $dir = dirname($_SERVER['SCRIPT_NAME']);
45089aa05dbSAndreas Gohr    }elseif(substr($_SERVER['PHP_SELF'],-4) == '.php'){
45146c73e01SChris Smith        $dir = dirname($_SERVER['PHP_SELF']);
452093ec9e4Sandi    }elseif($_SERVER['DOCUMENT_ROOT'] && $_SERVER['SCRIPT_FILENAME']){
453093ec9e4Sandi        $dir = preg_replace ('/^'.preg_quote($_SERVER['DOCUMENT_ROOT'],'/').'/','',
454093ec9e4Sandi                $_SERVER['SCRIPT_FILENAME']);
45546c73e01SChris Smith        $dir = dirname('/'.$dir);
45692b83b77Sandi    }else{
45746c73e01SChris Smith        $dir = '.'; //probably wrong
45892b83b77Sandi    }
459ed7b5f09Sandi
46046c73e01SChris Smith    $dir = str_replace('\\','/',$dir);             // bugfix for weird WIN behaviour
46146c73e01SChris Smith    $dir = preg_replace('#//+#','/',"/$dir/");     // ensure leading and trailing slashes
462ed7b5f09Sandi
463f62ea8a1Sandi    //handle script in lib/exe dir
464f62ea8a1Sandi    $dir = preg_replace('!lib/exe/$!','',$dir);
465f62ea8a1Sandi
466488d5fa0SMichael Klier chi@chimeric.de    //handle script in lib/plugins dir
467488d5fa0SMichael Klier chi@chimeric.de    $dir = preg_replace('!lib/plugins/.*$!','',$dir);
468488d5fa0SMichael Klier chi@chimeric.de
469ed7b5f09Sandi    //finish here for relative URLs
470ed7b5f09Sandi    if(!$abs) return $dir;
471ed7b5f09Sandi
47264159a61SAndreas Gohr    //use config if available, trim any slash from end of baseurl to avoid multiple consecutive slashes in the path
4731858e4d7SGerry Weißbach    if(!empty($conf['baseurl'])) return rtrim($conf['baseurl'],'/').$dir;
474ef7b3ecdSAndreas Gohr
475e82e3526SAndreas Gohr    //split hostheader into host and port
4765627186cSAndreas Gohr    if(isset($_SERVER['HTTP_HOST'])){
477204b27c8SMichael Hamann        $parsed_host = parse_url('http://'.$_SERVER['HTTP_HOST']);
478f87b5dbbSChristopher Smith        $host = isset($parsed_host['host']) ? $parsed_host['host'] : null;
479f87b5dbbSChristopher Smith        $port = isset($parsed_host['port']) ? $parsed_host['port'] : null;
4805627186cSAndreas Gohr    }elseif(isset($_SERVER['SERVER_NAME'])){
481204b27c8SMichael Hamann        $parsed_host = parse_url('http://'.$_SERVER['SERVER_NAME']);
482f87b5dbbSChristopher Smith        $host = isset($parsed_host['host']) ? $parsed_host['host'] : null;
483f87b5dbbSChristopher Smith        $port = isset($parsed_host['port']) ? $parsed_host['port'] : null;
4845627186cSAndreas Gohr    }else{
4855627186cSAndreas Gohr        $host = php_uname('n');
486c66972f2SAdrian Lang        $port = '';
4875627186cSAndreas Gohr    }
4885627186cSAndreas Gohr
489204b27c8SMichael Hamann    if(is_null($port)){
490204b27c8SMichael Hamann        $port = '';
491204b27c8SMichael Hamann    }
492204b27c8SMichael Hamann
493f5c6743cSAndreas Gohr    if(!is_ssl()){
494ed7b5f09Sandi        $proto = 'http://';
495e82e3526SAndreas Gohr        if ($port == '80') {
496ed7b5f09Sandi            $port = '';
497ed7b5f09Sandi        }
498ed7b5f09Sandi    }else{
499ed7b5f09Sandi        $proto = 'https://';
500e82e3526SAndreas Gohr        if ($port == '443') {
501ed7b5f09Sandi            $port = '';
502ed7b5f09Sandi        }
503ed7b5f09Sandi    }
504ed7b5f09Sandi
505c66972f2SAdrian Lang    if($port !== '') $port = ':'.$port;
506e82e3526SAndreas Gohr
507ed7b5f09Sandi    return $proto.$host.$port.$dir;
508ed7b5f09Sandi}
509ed7b5f09Sandi
510b000c6d4Sandi/**
511f5c6743cSAndreas Gohr * Check if accessed via HTTPS
512f5c6743cSAndreas Gohr *
513f5c6743cSAndreas Gohr * Apache leaves ,$_SERVER['HTTPS'] empty when not available, IIS sets it to 'off'.
514f5c6743cSAndreas Gohr * 'false' and 'disabled' are just guessing
515f5c6743cSAndreas Gohr *
516f5c6743cSAndreas Gohr * @returns bool true when SSL is active
517f5c6743cSAndreas Gohr */
518f5c6743cSAndreas Gohrfunction is_ssl() {
51919738e65SEnrico Tagliavini    // check if we are behind a reverse proxy
52019738e65SEnrico Tagliavini    if(isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
52119738e65SEnrico Tagliavini        if($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
52219738e65SEnrico Tagliavini            return true;
52319738e65SEnrico Tagliavini        } else {
52419738e65SEnrico Tagliavini            return false;
52519738e65SEnrico Tagliavini        }
52619738e65SEnrico Tagliavini    }
527c66972f2SAdrian Lang    if(!isset($_SERVER['HTTPS']) ||
528c66972f2SAdrian Lang        preg_match('/^(|off|false|disabled)$/i', $_SERVER['HTTPS'])) {
529f5c6743cSAndreas Gohr        return false;
530f5c6743cSAndreas Gohr    } else {
531f5c6743cSAndreas Gohr        return true;
532f5c6743cSAndreas Gohr    }
533f5c6743cSAndreas Gohr}
534f5c6743cSAndreas Gohr
535f5c6743cSAndreas Gohr/**
53626714386SAndreas Gohr * checks it is windows OS
53726714386SAndreas Gohr * @return bool
53826714386SAndreas Gohr */
53926714386SAndreas Gohrfunction isWindows() {
54026714386SAndreas Gohr    return (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? true : false;
54126714386SAndreas Gohr}
54226714386SAndreas Gohr
54326714386SAndreas Gohr/**
5443816dcbcSAndreas Gohr * print a nice message even if no styles are loaded yet.
545f50a239bSTakamura *
546f50a239bSTakamura * @param integer|string $msg
5473816dcbcSAndreas Gohr */
5483816dcbcSAndreas Gohrfunction nice_die($msg){
5493816dcbcSAndreas Gohr    echo<<<EOT
550c8839c22SAnika Henke<!DOCTYPE html>
5513816dcbcSAndreas Gohr<html>
5523816dcbcSAndreas Gohr<head><title>DokuWiki Setup Error</title></head>
5533816dcbcSAndreas Gohr<body style="font-family: Arial, sans-serif">
5543816dcbcSAndreas Gohr    <div style="width:60%; margin: auto; background-color: #fcc;
5553816dcbcSAndreas Gohr                border: 1px solid #faa; padding: 0.5em 1em;">
5563816dcbcSAndreas Gohr        <h1 style="font-size: 120%">DokuWiki Setup Error</h1>
5573816dcbcSAndreas Gohr        <p>$msg</p>
5583816dcbcSAndreas Gohr    </div>
5593816dcbcSAndreas Gohr</body>
5603816dcbcSAndreas Gohr</html>
5613816dcbcSAndreas GohrEOT;
5623862da0eSAndreas Gohr    if(defined('DOKU_UNITTEST')) {
5633862da0eSAndreas Gohr        throw new RuntimeException('nice_die: '.$msg);
5643862da0eSAndreas Gohr    }
5650a4266d4SElan Ruusamäe    exit(1);
5663816dcbcSAndreas Gohr}
5673816dcbcSAndreas Gohr
56800976812SAndreas Gohr/**
56900976812SAndreas Gohr * A realpath() replacement
57000976812SAndreas Gohr *
57100976812SAndreas Gohr * This function behaves similar to PHP's realpath() but does not resolve
57200976812SAndreas Gohr * symlinks or accesses upper directories
57300976812SAndreas Gohr *
5744761d30cSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
57500976812SAndreas Gohr * @author <richpageau at yahoo dot co dot uk>
57659752844SAnders Sandblad * @link   http://php.net/manual/en/function.realpath.php#75992
577f50a239bSTakamura *
578f50a239bSTakamura * @param string $path
579f50a239bSTakamura * @param bool $exists
580f50a239bSTakamura *
581f50a239bSTakamura * @return bool|string
58200976812SAndreas Gohr */
583b328697dSAndreas Gohrfunction fullpath($path,$exists=false){
5844761d30cSAndreas Gohr    static $run = 0;
5854761d30cSAndreas Gohr    $root  = '';
586724970e6SAndreas Gohr    $iswin = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' || !empty($GLOBALS['DOKU_UNITTEST_ASSUME_WINDOWS']));
58700976812SAndreas Gohr
5884761d30cSAndreas Gohr    // find the (indestructable) root of the path - keeps windows stuff intact
5892401f18dSSyntaxseed    if($path[0] == '/'){
5904761d30cSAndreas Gohr        $root = '/';
5914761d30cSAndreas Gohr    }elseif($iswin){
5924761d30cSAndreas Gohr        // match drive letter and UNC paths
5934761d30cSAndreas Gohr        if(preg_match('!^([a-zA-z]:)(.*)!',$path,$match)){
594b9c4302bSAndreas Gohr            $root = $match[1].'/';
5954761d30cSAndreas Gohr            $path = $match[2];
5964761d30cSAndreas Gohr        }else if(preg_match('!^(\\\\\\\\[^\\\\/]+\\\\[^\\\\/]+[\\\\/])(.*)!',$path,$match)){
5974761d30cSAndreas Gohr            $root = $match[1];
5984761d30cSAndreas Gohr            $path = $match[2];
59900976812SAndreas Gohr        }
6004761d30cSAndreas Gohr    }
6014761d30cSAndreas Gohr    $path = str_replace('\\','/',$path);
6024761d30cSAndreas Gohr
6034761d30cSAndreas Gohr    // if the given path wasn't absolute already, prepend the script path and retry
6044761d30cSAndreas Gohr    if(!$root){
6054761d30cSAndreas Gohr        $base = dirname($_SERVER['SCRIPT_FILENAME']);
6064761d30cSAndreas Gohr        $path = $base.'/'.$path;
6074761d30cSAndreas Gohr        if($run == 0){ // avoid endless recursion when base isn't absolute for some reason
6084761d30cSAndreas Gohr            $run++;
609b328697dSAndreas Gohr            return fullpath($path,$exists);
6104761d30cSAndreas Gohr        }
6114761d30cSAndreas Gohr    }
6124761d30cSAndreas Gohr    $run = 0;
61300976812SAndreas Gohr
61400976812SAndreas Gohr    // canonicalize
61500976812SAndreas Gohr    $path=explode('/', $path);
61600976812SAndreas Gohr    $newpath=array();
617ef38bfe8SAndreas Gohr    foreach($path as $p) {
618ef38bfe8SAndreas Gohr        if ($p === '' || $p === '.') continue;
619ef38bfe8SAndreas Gohr        if ($p==='..') {
62000976812SAndreas Gohr            array_pop($newpath);
62100976812SAndreas Gohr            continue;
62200976812SAndreas Gohr        }
623ef38bfe8SAndreas Gohr        array_push($newpath, $p);
62400976812SAndreas Gohr    }
6254761d30cSAndreas Gohr    $finalpath = $root.implode('/', $newpath);
62600976812SAndreas Gohr
6276b9c156cSAnika Henke    // check for existence when needed (except when unit testing)
62879e79377SAndreas Gohr    if($exists && !defined('DOKU_UNITTEST') && !file_exists($finalpath)) {
6294761d30cSAndreas Gohr        return false;
63000976812SAndreas Gohr    }
6314761d30cSAndreas Gohr    return $finalpath;
63200976812SAndreas Gohr}
63300976812SAndreas Gohr
634