xref: /dokuwiki/inc/init.php (revision c163dbef86cf8fa975012c52ca572a24f01b85fb)
1ed7b5f09Sandi<?php
2ed7b5f09Sandi/**
3ed7b5f09Sandi * Initialize some defaults needed for DokuWiki
4ed7b5f09Sandi */
5ed7b5f09Sandi
630085ef3SYurii K
73272d797SAndreas Gohr/**
83272d797SAndreas Gohr * timing Dokuwiki execution
9f50a239bSTakamura *
10f50a239bSTakamura * @param integer $start
11f50a239bSTakamura *
12f50a239bSTakamura * @return mixed
133272d797SAndreas Gohr */
14a609a9ccSBen Coburnfunction delta_time($start=0) {
15ac4be4d7SPiyush Mishra    return microtime(true)-((float)$start);
16a609a9ccSBen Coburn}
17a609a9ccSBen Coburndefine('DOKU_START_TIME', delta_time());
18a609a9ccSBen Coburn
19ccaeaa85SAndreas Gohrglobal $config_cascade;
20cca94fbcSRoland Hager$config_cascade = array();
21ccaeaa85SAndreas Gohr
2248beefecSAndreas Gohr// if available load a preload config file
23e6266454SChris Smith$preload = fullpath(dirname(__FILE__)).'/preload.php';
2479e79377SAndreas Gohrif (file_exists($preload)) include($preload);
2548beefecSAndreas Gohr
26ed7b5f09Sandi// define the include path
2700976812SAndreas Gohrif(!defined('DOKU_INC')) define('DOKU_INC',fullpath(dirname(__FILE__).'/../').'/');
28ad15db82Sandi
29c2a6d816SAndreas Gohr// define Plugin dir
30c2a6d816SAndreas Gohrif(!defined('DOKU_PLUGIN'))  define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
31c2a6d816SAndreas Gohr
32e7cb32dcSAndreas Gohr// define config path (packagers may want to change this to /etc/dokuwiki/)
33b7551a6dSEsther Brunnerif(!defined('DOKU_CONF')) define('DOKU_CONF',DOKU_INC.'conf/');
34e7cb32dcSAndreas Gohr
35bad905f1SBen Coburn// check for error reporting override or set error reporting to sane values
3679e79377SAndreas Gohrif (!defined('DOKU_E_LEVEL') && file_exists(DOKU_CONF.'report_e_all')) {
37bad905f1SBen Coburn    define('DOKU_E_LEVEL', E_ALL);
38bad905f1SBen Coburn}
39fc80ed59SAndreas Gohrif (!defined('DOKU_E_LEVEL')) {
404fcd684aSMichael Hamann    error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT);
41fc80ed59SAndreas Gohr} else {
42fc80ed59SAndreas Gohr    error_reporting(DOKU_E_LEVEL);
43fc80ed59SAndreas Gohr}
44c53ea5f2Sandi
45a69722b3SAndreas Gohr// avoid caching issues #1594
46a69722b3SAndreas Gohrheader('Vary: Cookie');
47a69722b3SAndreas Gohr
4850602150SBen Coburn// init memory caches
49db959ae3SAndreas Gohrglobal $cache_revinfo;
50db959ae3SAndreas Gohr       $cache_revinfo = array();
51db959ae3SAndreas Gohrglobal $cache_wikifn;
52db959ae3SAndreas Gohr       $cache_wikifn = array();
53db959ae3SAndreas Gohrglobal $cache_cleanid;
54db959ae3SAndreas Gohr       $cache_cleanid = array();
55db959ae3SAndreas Gohrglobal $cache_authname;
56db959ae3SAndreas Gohr       $cache_authname = array();
57db959ae3SAndreas Gohrglobal $cache_metadata;
58db959ae3SAndreas Gohr       $cache_metadata = array();
5950602150SBen Coburn
60cca94fbcSRoland Hager// always include 'inc/config_cascade.php'
61cca94fbcSRoland Hager// previously in preload.php set fields of $config_cascade will be merged with the defaults
62e6a6dbfeSAndreas Gohrinclude(DOKU_INC.'inc/config_cascade.php');
63cb043f52SChris Smith
644724a577Sandi//prepare config array()
65ee20e7d1Sandiglobal $conf;
664724a577Sandi$conf = array();
674724a577Sandi
68cb043f52SChris Smith// load the global config file(s)
69b303b92cSChris Smithforeach (array('default','local','protected') as $config_group) {
70f8121585SChris Smith    if (empty($config_cascade['main'][$config_group])) continue;
71b303b92cSChris Smith    foreach ($config_cascade['main'][$config_group] as $config_file) {
7279e79377SAndreas Gohr        if (file_exists($config_file)) {
73f8121585SChris Smith            include($config_file);
74f8121585SChris Smith        }
75cb043f52SChris Smith    }
760a6ead41SAndreas Gohr}
77ad15db82Sandi
78066fee30SAndreas Gohr//prepare license array()
79066fee30SAndreas Gohrglobal $license;
80066fee30SAndreas Gohr$license = array();
81066fee30SAndreas Gohr
82066fee30SAndreas Gohr// load the license file(s)
83f8121585SChris Smithforeach (array('default','local') as $config_group) {
84f8121585SChris Smith    if (empty($config_cascade['license'][$config_group])) continue;
85f8121585SChris Smith    foreach ($config_cascade['license'][$config_group] as $config_file) {
8679e79377SAndreas Gohr        if(file_exists($config_file)){
87f8121585SChris Smith            include($config_file);
88f8121585SChris Smith        }
89f8121585SChris Smith    }
90066fee30SAndreas Gohr}
91066fee30SAndreas Gohr
921f8eb24fSAndreas Gohr// set timezone (as in pre 5.3.0 days)
931f8eb24fSAndreas Gohrdate_default_timezone_set(@date_default_timezone_get());
941f8eb24fSAndreas Gohr
95ed7b5f09Sandi// define baseURL
964b1a4e04SAndreas Gohrif(!defined('DOKU_REL')) define('DOKU_REL',getBaseURL(false));
97ed7b5f09Sandiif(!defined('DOKU_URL')) define('DOKU_URL',getBaseURL(true));
984b1a4e04SAndreas Gohrif(!defined('DOKU_BASE')){
994b1a4e04SAndreas Gohr    if($conf['canonical']){
1004b1a4e04SAndreas Gohr        define('DOKU_BASE',DOKU_URL);
1014b1a4e04SAndreas Gohr    }else{
1024b1a4e04SAndreas Gohr        define('DOKU_BASE',DOKU_REL);
1034b1a4e04SAndreas Gohr    }
1044b1a4e04SAndreas Gohr}
1054b1a4e04SAndreas Gohr
106b8595a66SAndreas Gohr// define whitespace
107b8595a66SAndreas Gohrif(!defined('DOKU_LF')) define ('DOKU_LF',"\n");
108b8595a66SAndreas Gohrif(!defined('DOKU_TAB')) define ('DOKU_TAB',"\t");
109ed7b5f09Sandi
110656c8fb3SAndreas Gohr// define cookie and session id, append server port when securecookie is configured FS#1664
111656c8fb3SAndreas Gohrif (!defined('DOKU_COOKIE')) define('DOKU_COOKIE', 'DW'.md5(DOKU_REL.(($conf['securecookie'])?$_SERVER['SERVER_PORT']:'')));
112e71ce681SAndreas Gohr
113ee20e7d1Sandi
114ed7b5f09Sandi// define main script
115ed7b5f09Sandiif(!defined('DOKU_SCRIPT')) define('DOKU_SCRIPT','doku.php');
116ed7b5f09Sandi
117*c163dbefSMichael Großeif(!defined('DOKU_TPL')) {
118*c163dbefSMichael Große    /**
119*c163dbefSMichael Große     * @deprecated 2012-10-13 replaced by more dynamic method
120*c163dbefSMichael Große     * @see tpl_basedir()
121*c163dbefSMichael Große     */
122*c163dbefSMichael Große    define('DOKU_TPL', DOKU_BASE.'lib/tpl/'.$conf['template'].'/');
123*c163dbefSMichael Große}
1246b13307fSandi
125*c163dbefSMichael Großeif(!defined('DOKU_TPLINC')) {
126*c163dbefSMichael Große    /**
127*c163dbefSMichael Große     * @deprecated 2012-10-13 replaced by more dynamic method
128*c163dbefSMichael Große     * @see tpl_incdir()
129*c163dbefSMichael Große     */
130*c163dbefSMichael Große    define('DOKU_TPLINC', DOKU_INC.'lib/tpl/'.$conf['template'].'/');
131*c163dbefSMichael Große}
13278a6aeb1SAndreas Gohr
133ed7b5f09Sandi// make session rewrites XHTML compliant
1343fc74836Sandi@ini_set('arg_separator.output', '&amp;');
135ed7b5f09Sandi
136d7e6bba9SAndreas Gohr// make sure global zlib does not interfere FS#1132
137d7e6bba9SAndreas Gohr@ini_set('zlib.output_compression', 'off');
138d7e6bba9SAndreas Gohr
1396deb5405SAndreas Gohr// increase PCRE backtrack limit
1406deb5405SAndreas Gohr@ini_set('pcre.backtrack_limit', '20971520');
1416deb5405SAndreas Gohr
14298bda4fdSAndreas Gohr// enable gzip compression if supported
14398bda4fdSAndreas Gohr$conf['gzip_output'] &= (strpos($_SERVER['HTTP_ACCEPT_ENCODING'],'gzip') !== false);
14465f6e7d6SMichael Hamannglobal $ACT;
1453138b5c7SAndreas Gohrif ($conf['gzip_output'] &&
1463138b5c7SAndreas Gohr        !defined('DOKU_DISABLE_GZIP_OUTPUT') &&
14765f6e7d6SMichael Hamann        function_exists('ob_gzhandler') &&
14899e10b7fSMichael Hamann        // Disable compression when a (compressed) sitemap might be delivered
14965f6e7d6SMichael Hamann        // See https://bugs.dokuwiki.org/index.php?do=details&task_id=2576
15099e10b7fSMichael Hamann        $ACT != 'sitemap') {
1513138b5c7SAndreas Gohr    ob_start('ob_gzhandler');
1523138b5c7SAndreas Gohr}
1533138b5c7SAndreas Gohr
154ed7b5f09Sandi// init session
1556534245aSAndreas Gohrif(!headers_sent() && !defined('NOSESSION')) {
156c09f0eb1SGerrit Uitslag    if(!defined('DOKU_SESSION_NAME'))     define ('DOKU_SESSION_NAME', "DokuWiki");
157c09f0eb1SGerrit Uitslag    if(!defined('DOKU_SESSION_LIFETIME')) define ('DOKU_SESSION_LIFETIME', 0);
15855a71a16SGerrit Uitslag    if(!defined('DOKU_SESSION_PATH')) {
15973ab87deSGabriel Birke        $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
16055a71a16SGerrit Uitslag        define ('DOKU_SESSION_PATH', $cookieDir);
161f5c6743cSAndreas Gohr    }
162c09f0eb1SGerrit Uitslag    if(!defined('DOKU_SESSION_DOMAIN'))   define ('DOKU_SESSION_DOMAIN', '');
163c09f0eb1SGerrit Uitslag
1646eb3cdf6SAndreas Gohr    // start the session
1656eb3cdf6SAndreas Gohr    init_session();
16614a122deSAndreas Gohr
16714a122deSAndreas Gohr    // load left over messages
16814a122deSAndreas Gohr    if(isset($_SESSION[DOKU_COOKIE]['msg'])) {
16914a122deSAndreas Gohr        $MSG = $_SESSION[DOKU_COOKIE]['msg'];
17014a122deSAndreas Gohr        unset($_SESSION[DOKU_COOKIE]['msg']);
17114a122deSAndreas Gohr    }
172bad31ae9SAndreas Gohr}
173ed7b5f09Sandi
174a1637ffdSAndreas Gohr// don't let cookies ever interfere with request vars
175a1637ffdSAndreas Gohr$_REQUEST = array_merge($_GET,$_POST);
176a1637ffdSAndreas Gohr
1773dea4ebcSAndreas Gohr// we don't want a purge URL to be digged
1780e80bb5eSChristopher Smithif(isset($_REQUEST['purge']) && !empty($_SERVER['HTTP_REFERER'])) unset($_REQUEST['purge']);
1793dea4ebcSAndreas Gohr
1801ca31cfeSAndreas Gohr// precalculate file creation modes
1811ca31cfeSAndreas Gohrinit_creationmodes();
182ed7b5f09Sandi
1833dc3a5f1Sandi// make real paths and check them
18498407a7aSandiinit_paths();
1857367b368SAndreas Gohrinit_files();
186ed7b5f09Sandi
187f1986589SMichael Klier// setup plugin controller class (can be overwritten in preload.php)
18893a7873eSAndreas Gohr$plugin_types = array('auth', 'admin','syntax','action','renderer', 'helper','remote');
189f1986589SMichael Klierglobal $plugin_controller_class, $plugin_controller;
190f1986589SMichael Klierif (empty($plugin_controller_class)) $plugin_controller_class = 'Doku_Plugin_Controller';
191f1986589SMichael Klier
192c7cb395cSAdrian Lang// load libraries
193605f8e8dSAndreas Gohrrequire_once(DOKU_INC.'vendor/autoload.php');
194c7cb395cSAdrian Langrequire_once(DOKU_INC.'inc/load.php');
195c7cb395cSAdrian Lang
1960f8f7aaaSDanny Lin// disable gzip if not available
19713c37900SAndreas Gohrdefine('DOKU_HAS_BZIP', function_exists('bzopen'));
19813c37900SAndreas Gohrdefine('DOKU_HAS_GZIP', function_exists('gzopen'));
19913c37900SAndreas Gohrif($conf['compression'] == 'bz2' && !DOKU_HAS_BZIP) {
2000f8f7aaaSDanny Lin    $conf['compression'] = 'gz';
2010f8f7aaaSDanny Lin}
20213c37900SAndreas Gohrif($conf['compression'] == 'gz' && !DOKU_HAS_GZIP) {
2030f8f7aaaSDanny Lin    $conf['compression'] = 0;
2040f8f7aaaSDanny Lin}
2050f8f7aaaSDanny Lin
20689177306SAndreas Gohr// input handle class
20789177306SAndreas Gohrglobal $INPUT;
20889177306SAndreas Gohr$INPUT = new Input();
20989177306SAndreas Gohr
210f1986589SMichael Klier// initialize plugin controller
211f1986589SMichael Klier$plugin_controller = new $plugin_controller_class();
212f1986589SMichael Klier
213f1986589SMichael Klier// initialize the event handler
214f1986589SMichael Klierglobal $EVENT_HANDLER;
215f1986589SMichael Klier$EVENT_HANDLER = new Doku_Event_Handler();
216f1986589SMichael Klier
2176d06b26aSDominik Eckelmann$local = $conf['lang'];
2186d06b26aSDominik Eckelmanntrigger_event('INIT_LANG_LOAD', $local, 'init_lang', true);
2196d06b26aSDominik Eckelmann
2206d06b26aSDominik Eckelmann
22116905344SAndreas Gohr// setup authentication system
222c7cb395cSAdrian Langif (!defined('NOSESSION')) {
22316905344SAndreas Gohr    auth_setup();
224c7cb395cSAdrian Lang}
225f62ea8a1Sandi
2265ec3fefcSAndreas Gohr// setup mail system
2275ec3fefcSAndreas Gohrmail_setup();
2285ec3fefcSAndreas Gohr
229f62ea8a1Sandi/**
2306eb3cdf6SAndreas Gohr * Initializes the session
2316eb3cdf6SAndreas Gohr *
2326eb3cdf6SAndreas Gohr * Makes sure the passed session cookie is valid, invalid ones are ignored an a new session ID is issued
2336eb3cdf6SAndreas Gohr *
2346eb3cdf6SAndreas Gohr * @link http://stackoverflow.com/a/33024310/172068
235924e477eSAndreas Gohr * @link http://php.net/manual/en/session.configuration.php#ini.session.sid-length
2366eb3cdf6SAndreas Gohr */
2376eb3cdf6SAndreas Gohrfunction init_session() {
2386eb3cdf6SAndreas Gohr    global $conf;
2396eb3cdf6SAndreas Gohr    session_name(DOKU_SESSION_NAME);
2406eb3cdf6SAndreas Gohr    session_set_cookie_params(DOKU_SESSION_LIFETIME, DOKU_SESSION_PATH, DOKU_SESSION_DOMAIN, ($conf['securecookie'] && is_ssl()), true);
2416eb3cdf6SAndreas Gohr
2426eb3cdf6SAndreas Gohr    // make sure the session cookie contains a valid session ID
243924e477eSAndreas Gohr    if(isset($_COOKIE[DOKU_SESSION_NAME]) && !preg_match('/^[-,a-zA-Z0-9]{22,256}$/', $_COOKIE[DOKU_SESSION_NAME])) {
2446eb3cdf6SAndreas Gohr        unset($_COOKIE[DOKU_SESSION_NAME]);
2456eb3cdf6SAndreas Gohr    }
2466eb3cdf6SAndreas Gohr
2476eb3cdf6SAndreas Gohr    session_start();
2486eb3cdf6SAndreas Gohr}
2496eb3cdf6SAndreas Gohr
2506eb3cdf6SAndreas Gohr
2516eb3cdf6SAndreas Gohr/**
25298407a7aSandi * Checks paths from config file
25398407a7aSandi */
25498407a7aSandifunction init_paths(){
25598407a7aSandi    global $conf;
25698407a7aSandi
25798407a7aSandi    $paths = array('datadir'   => 'pages',
25898407a7aSandi            'olddir'    => 'attic',
25998407a7aSandi            'mediadir'  => 'media',
260e4f389efSKate Arzamastseva            'mediaolddir' => 'media_attic',
26198407a7aSandi            'metadir'   => 'meta',
262e4f389efSKate Arzamastseva            'mediametadir' => 'media_meta',
26398407a7aSandi            'cachedir'  => 'cache',
264579b0f7eSTNHarris            'indexdir'  => 'index',
265de33a58fSMichael Klier            'lockdir'   => 'locks',
266de33a58fSMichael Klier            'tmpdir'    => 'tmp');
26798407a7aSandi
26898407a7aSandi    foreach($paths as $c => $p) {
2697f086b67SAnika Henke        $path = empty($conf[$c]) ? $conf['savedir'].'/'.$p : $conf[$c];
2706b9c156cSAnika Henke        $conf[$c] = init_path($path);
2716b9c156cSAnika Henke        if(empty($conf[$c]))
2726b9c156cSAnika Henke            nice_die("The $c ('$p') at $path is not found, isn't accessible or writable.
27369dc3177SAndreas Gohr                You should check your config and permission settings.
27469dc3177SAndreas Gohr                Or maybe you want to <a href=\"install.php\">run the
27569dc3177SAndreas Gohr                installer</a>?");
27698407a7aSandi    }
27771726d78SBen Coburn
27871726d78SBen Coburn    // path to old changelog only needed for upgrading
27971726d78SBen Coburn    $conf['changelog_old'] = init_path((isset($conf['changelog']))?($conf['changelog']):($conf['savedir'].'/changes.log'));
28071726d78SBen Coburn    if ($conf['changelog_old']=='') { unset($conf['changelog_old']); }
28171726d78SBen Coburn    // hardcoded changelog because it is now a cache that lives in meta
28271726d78SBen Coburn    $conf['changelog'] = $conf['metadir'].'/_dokuwiki.changes';
28399c8d7f2Smichael    $conf['media_changelog'] = $conf['metadir'].'/_media.changes';
28498407a7aSandi}
28598407a7aSandi
28638fb1fc7SGerrit Uitslag/**
28738fb1fc7SGerrit Uitslag * Load the language strings
28838fb1fc7SGerrit Uitslag *
28938fb1fc7SGerrit Uitslag * @param string $langCode language code, as passed by event handler
29038fb1fc7SGerrit Uitslag */
2916d06b26aSDominik Eckelmannfunction init_lang($langCode) {
2926d06b26aSDominik Eckelmann    //prepare language array
293dd7a6159SGerrit Uitslag    global $lang, $config_cascade;
2946d06b26aSDominik Eckelmann    $lang = array();
2956d06b26aSDominik Eckelmann
2966d06b26aSDominik Eckelmann    //load the language files
2971d82c8d3SChristopher Smith    require(DOKU_INC.'inc/lang/en/lang.php');
298dd7a6159SGerrit Uitslag    foreach ($config_cascade['lang']['core'] as $config_file) {
29979e79377SAndreas Gohr        if (file_exists($config_file . 'en/lang.php')) {
300dd7a6159SGerrit Uitslag            include($config_file . 'en/lang.php');
301dd7a6159SGerrit Uitslag        }
302dd7a6159SGerrit Uitslag    }
303dd7a6159SGerrit Uitslag
3046d06b26aSDominik Eckelmann    if ($langCode && $langCode != 'en') {
3056d06b26aSDominik Eckelmann        if (file_exists(DOKU_INC."inc/lang/$langCode/lang.php")) {
3061d82c8d3SChristopher Smith            require(DOKU_INC."inc/lang/$langCode/lang.php");
3076d06b26aSDominik Eckelmann        }
308dd7a6159SGerrit Uitslag        foreach ($config_cascade['lang']['core'] as $config_file) {
30979e79377SAndreas Gohr            if (file_exists($config_file . "$langCode/lang.php")) {
310dd7a6159SGerrit Uitslag                include($config_file . "$langCode/lang.php");
3116d06b26aSDominik Eckelmann            }
312dd7a6159SGerrit Uitslag        }
3136d06b26aSDominik Eckelmann    }
3146d06b26aSDominik Eckelmann}
3156d06b26aSDominik Eckelmann
31698407a7aSandi/**
3176b9c156cSAnika Henke * Checks the existence of certain files and creates them if missing.
3187367b368SAndreas Gohr */
3197367b368SAndreas Gohrfunction init_files(){
3207367b368SAndreas Gohr    global $conf;
3210d8850c4SAndreas Gohr
322345b1674SAndreas Gohr    $files = array($conf['indexdir'].'/page.idx');
3237367b368SAndreas Gohr
3247367b368SAndreas Gohr    foreach($files as $file){
32579e79377SAndreas Gohr        if(!file_exists($file)){
3260d8850c4SAndreas Gohr            $fh = @fopen($file,'a');
3270d8850c4SAndreas Gohr            if($fh){
3287367b368SAndreas Gohr                fclose($fh);
329443e135dSChristopher Smith                if(!empty($conf['fperm'])) chmod($file, $conf['fperm']);
3300d8850c4SAndreas Gohr            }else{
3313816dcbcSAndreas Gohr                nice_die("$file is not writable. Check your permissions settings!");
3320d8850c4SAndreas Gohr            }
3337367b368SAndreas Gohr        }
3347367b368SAndreas Gohr    }
3357367b368SAndreas Gohr}
3367367b368SAndreas Gohr
3377367b368SAndreas Gohr/**
3380d8850c4SAndreas Gohr * Returns absolute path
339f62ea8a1Sandi *
3400d8850c4SAndreas Gohr * This tries the given path first, then checks in DOKU_INC.
3417f086b67SAnika Henke * Check for accessibility on directories as well.
3420d8850c4SAndreas Gohr *
3430d8850c4SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
344f50a239bSTakamura *
345f50a239bSTakamura * @param string $path
346f50a239bSTakamura *
347f50a239bSTakamura * @return bool|string
348f62ea8a1Sandi */
349f62ea8a1Sandifunction init_path($path){
3506b9c156cSAnika Henke    // check existence
35100976812SAndreas Gohr    $p = fullpath($path);
35279e79377SAndreas Gohr    if(!file_exists($p)){
35300976812SAndreas Gohr        $p = fullpath(DOKU_INC.$path);
35479e79377SAndreas Gohr        if(!file_exists($p)){
3558fc4e739Sandi            return '';
356f62ea8a1Sandi        }
3570d8850c4SAndreas Gohr    }
3580d8850c4SAndreas Gohr
3590d8850c4SAndreas Gohr    // check writability
3600d8850c4SAndreas Gohr    if(!@is_writable($p)){
3610d8850c4SAndreas Gohr        return '';
3620d8850c4SAndreas Gohr    }
3630d8850c4SAndreas Gohr
3640d8850c4SAndreas Gohr    // check accessability (execute bit) for directories
36579e79377SAndreas Gohr    if(@is_dir($p) && !file_exists("$p/.")){
3660d8850c4SAndreas Gohr        return '';
3670d8850c4SAndreas Gohr    }
3680d8850c4SAndreas Gohr
3690d8850c4SAndreas Gohr    return $p;
3700d8850c4SAndreas Gohr}
3718c4f28e8Sjan
372ed7b5f09Sandi/**
3731ca31cfeSAndreas Gohr * Sets the internal config values fperm and dperm which, when set,
3741ca31cfeSAndreas Gohr * will be used to change the permission of a newly created dir or
3751ca31cfeSAndreas Gohr * file with chmod. Considers the influence of the system's umask
3761ca31cfeSAndreas Gohr * setting the values only if needed.
3771ca31cfeSAndreas Gohr */
3781ca31cfeSAndreas Gohrfunction init_creationmodes(){
3791ca31cfeSAndreas Gohr    global $conf;
3801ca31cfeSAndreas Gohr
3811ca31cfeSAndreas Gohr    // Legacy support for old umask/dmask scheme
3821ca31cfeSAndreas Gohr    unset($conf['dmask']);
3831ca31cfeSAndreas Gohr    unset($conf['fmask']);
3841ca31cfeSAndreas Gohr    unset($conf['umask']);
3851ca31cfeSAndreas Gohr    unset($conf['fperm']);
3861ca31cfeSAndreas Gohr    unset($conf['dperm']);
3871ca31cfeSAndreas Gohr
3889f3cdec3SAndreas Gohr    // get system umask, fallback to 0 if none available
3899f3cdec3SAndreas Gohr    $umask = @umask();
3909f3cdec3SAndreas Gohr    if(!$umask) $umask = 0000;
3911ca31cfeSAndreas Gohr
3921ca31cfeSAndreas Gohr    // check what is set automatically by the system on file creation
3931ca31cfeSAndreas Gohr    // and set the fperm param if it's not what we want
3941ca31cfeSAndreas Gohr    $auto_fmode = 0666 & ~$umask;
3951ca31cfeSAndreas Gohr    if($auto_fmode != $conf['fmode']) $conf['fperm'] = $conf['fmode'];
3961ca31cfeSAndreas Gohr
3971ca31cfeSAndreas Gohr    // check what is set automatically by the system on file creation
3981ca31cfeSAndreas Gohr    // and set the dperm param if it's not what we want
3991ca31cfeSAndreas Gohr    $auto_dmode = $conf['dmode'] & ~$umask;
4001ca31cfeSAndreas Gohr    if($auto_dmode != $conf['dmode']) $conf['dperm'] = $conf['dmode'];
4011ca31cfeSAndreas Gohr}
4021ca31cfeSAndreas Gohr
4031ca31cfeSAndreas Gohr/**
404ed7b5f09Sandi * Returns the full absolute URL to the directory where
405ed7b5f09Sandi * DokuWiki is installed in (includes a trailing slash)
406ed7b5f09Sandi *
407585bf44eSChristopher Smith * !! Can not access $_SERVER values through $INPUT
408585bf44eSChristopher Smith * !! here as this function is called before $INPUT is
409585bf44eSChristopher Smith * !! initialized.
410585bf44eSChristopher Smith *
411ed7b5f09Sandi * @author Andreas Gohr <andi@splitbrain.org>
412f50a239bSTakamura *
413f50a239bSTakamura * @param null|string $abs
414f50a239bSTakamura *
415f50a239bSTakamura * @return string
416ed7b5f09Sandi */
4174b1a4e04SAndreas Gohrfunction getBaseURL($abs=null){
418ed7b5f09Sandi    global $conf;
419ed7b5f09Sandi    //if canonical url enabled always return absolute
4204b1a4e04SAndreas Gohr    if(is_null($abs)) $abs = $conf['canonical'];
421ed7b5f09Sandi
4221858e4d7SGerry Weißbach    if(!empty($conf['basedir'])){
42346c73e01SChris Smith        $dir = $conf['basedir'];
42489aa05dbSAndreas Gohr    }elseif(substr($_SERVER['SCRIPT_NAME'],-4) == '.php'){
42546c73e01SChris Smith        $dir = dirname($_SERVER['SCRIPT_NAME']);
42689aa05dbSAndreas Gohr    }elseif(substr($_SERVER['PHP_SELF'],-4) == '.php'){
42746c73e01SChris Smith        $dir = dirname($_SERVER['PHP_SELF']);
428093ec9e4Sandi    }elseif($_SERVER['DOCUMENT_ROOT'] && $_SERVER['SCRIPT_FILENAME']){
429093ec9e4Sandi        $dir = preg_replace ('/^'.preg_quote($_SERVER['DOCUMENT_ROOT'],'/').'/','',
430093ec9e4Sandi                $_SERVER['SCRIPT_FILENAME']);
43146c73e01SChris Smith        $dir = dirname('/'.$dir);
43292b83b77Sandi    }else{
43346c73e01SChris Smith        $dir = '.'; //probably wrong
43492b83b77Sandi    }
435ed7b5f09Sandi
43646c73e01SChris Smith    $dir = str_replace('\\','/',$dir);             // bugfix for weird WIN behaviour
43746c73e01SChris Smith    $dir = preg_replace('#//+#','/',"/$dir/");     // ensure leading and trailing slashes
438ed7b5f09Sandi
439f62ea8a1Sandi    //handle script in lib/exe dir
440f62ea8a1Sandi    $dir = preg_replace('!lib/exe/$!','',$dir);
441f62ea8a1Sandi
442488d5fa0SMichael Klier chi@chimeric.de    //handle script in lib/plugins dir
443488d5fa0SMichael Klier chi@chimeric.de    $dir = preg_replace('!lib/plugins/.*$!','',$dir);
444488d5fa0SMichael Klier chi@chimeric.de
445ed7b5f09Sandi    //finish here for relative URLs
446ed7b5f09Sandi    if(!$abs) return $dir;
447ed7b5f09Sandi
44846c73e01SChris Smith    //use config option if available, trim any slash from end of baseurl to avoid multiple consecutive slashes in the path
4491858e4d7SGerry Weißbach    if(!empty($conf['baseurl'])) return rtrim($conf['baseurl'],'/').$dir;
450ef7b3ecdSAndreas Gohr
451e82e3526SAndreas Gohr    //split hostheader into host and port
4525627186cSAndreas Gohr    if(isset($_SERVER['HTTP_HOST'])){
453204b27c8SMichael Hamann        $parsed_host = parse_url('http://'.$_SERVER['HTTP_HOST']);
454f87b5dbbSChristopher Smith        $host = isset($parsed_host['host']) ? $parsed_host['host'] : null;
455f87b5dbbSChristopher Smith        $port = isset($parsed_host['port']) ? $parsed_host['port'] : null;
4565627186cSAndreas Gohr    }elseif(isset($_SERVER['SERVER_NAME'])){
457204b27c8SMichael Hamann        $parsed_host = parse_url('http://'.$_SERVER['SERVER_NAME']);
458f87b5dbbSChristopher Smith        $host = isset($parsed_host['host']) ? $parsed_host['host'] : null;
459f87b5dbbSChristopher Smith        $port = isset($parsed_host['port']) ? $parsed_host['port'] : null;
4605627186cSAndreas Gohr    }else{
4615627186cSAndreas Gohr        $host = php_uname('n');
462c66972f2SAdrian Lang        $port = '';
4635627186cSAndreas Gohr    }
4645627186cSAndreas Gohr
465204b27c8SMichael Hamann    if(is_null($port)){
466204b27c8SMichael Hamann        $port = '';
467204b27c8SMichael Hamann    }
468204b27c8SMichael Hamann
469f5c6743cSAndreas Gohr    if(!is_ssl()){
470ed7b5f09Sandi        $proto = 'http://';
471e82e3526SAndreas Gohr        if ($port == '80') {
472ed7b5f09Sandi            $port = '';
473ed7b5f09Sandi        }
474ed7b5f09Sandi    }else{
475ed7b5f09Sandi        $proto = 'https://';
476e82e3526SAndreas Gohr        if ($port == '443') {
477ed7b5f09Sandi            $port = '';
478ed7b5f09Sandi        }
479ed7b5f09Sandi    }
480ed7b5f09Sandi
481c66972f2SAdrian Lang    if($port !== '') $port = ':'.$port;
482e82e3526SAndreas Gohr
483ed7b5f09Sandi    return $proto.$host.$port.$dir;
484ed7b5f09Sandi}
485ed7b5f09Sandi
486b000c6d4Sandi/**
487f5c6743cSAndreas Gohr * Check if accessed via HTTPS
488f5c6743cSAndreas Gohr *
489f5c6743cSAndreas Gohr * Apache leaves ,$_SERVER['HTTPS'] empty when not available, IIS sets it to 'off'.
490f5c6743cSAndreas Gohr * 'false' and 'disabled' are just guessing
491f5c6743cSAndreas Gohr *
492f5c6743cSAndreas Gohr * @returns bool true when SSL is active
493f5c6743cSAndreas Gohr */
494f5c6743cSAndreas Gohrfunction is_ssl() {
49519738e65SEnrico Tagliavini    // check if we are behind a reverse proxy
49619738e65SEnrico Tagliavini    if(isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
49719738e65SEnrico Tagliavini        if($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
49819738e65SEnrico Tagliavini            return true;
49919738e65SEnrico Tagliavini        } else {
50019738e65SEnrico Tagliavini            return false;
50119738e65SEnrico Tagliavini        }
50219738e65SEnrico Tagliavini    }
503c66972f2SAdrian Lang    if(!isset($_SERVER['HTTPS']) ||
504c66972f2SAdrian Lang        preg_match('/^(|off|false|disabled)$/i', $_SERVER['HTTPS'])) {
505f5c6743cSAndreas Gohr        return false;
506f5c6743cSAndreas Gohr    } else {
507f5c6743cSAndreas Gohr        return true;
508f5c6743cSAndreas Gohr    }
509f5c6743cSAndreas Gohr}
510f5c6743cSAndreas Gohr
511f5c6743cSAndreas Gohr/**
51226714386SAndreas Gohr * checks it is windows OS
51326714386SAndreas Gohr * @return bool
51426714386SAndreas Gohr */
51526714386SAndreas Gohrfunction isWindows() {
51626714386SAndreas Gohr    return (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? true : false;
51726714386SAndreas Gohr}
51826714386SAndreas Gohr
51926714386SAndreas Gohr/**
5203816dcbcSAndreas Gohr * print a nice message even if no styles are loaded yet.
521f50a239bSTakamura *
522f50a239bSTakamura * @param integer|string $msg
5233816dcbcSAndreas Gohr */
5243816dcbcSAndreas Gohrfunction nice_die($msg){
5253816dcbcSAndreas Gohr    echo<<<EOT
526c8839c22SAnika Henke<!DOCTYPE html>
5273816dcbcSAndreas Gohr<html>
5283816dcbcSAndreas Gohr<head><title>DokuWiki Setup Error</title></head>
5293816dcbcSAndreas Gohr<body style="font-family: Arial, sans-serif">
5303816dcbcSAndreas Gohr    <div style="width:60%; margin: auto; background-color: #fcc;
5313816dcbcSAndreas Gohr                border: 1px solid #faa; padding: 0.5em 1em;">
5323816dcbcSAndreas Gohr        <h1 style="font-size: 120%">DokuWiki Setup Error</h1>
5333816dcbcSAndreas Gohr        <p>$msg</p>
5343816dcbcSAndreas Gohr    </div>
5353816dcbcSAndreas Gohr</body>
5363816dcbcSAndreas Gohr</html>
5373816dcbcSAndreas GohrEOT;
5383862da0eSAndreas Gohr    if(defined('DOKU_UNITTEST')) {
5393862da0eSAndreas Gohr        throw new RuntimeException('nice_die: '.$msg);
5403862da0eSAndreas Gohr    }
5410a4266d4SElan Ruusamäe    exit(1);
5423816dcbcSAndreas Gohr}
5433816dcbcSAndreas Gohr
54400976812SAndreas Gohr/**
54500976812SAndreas Gohr * A realpath() replacement
54600976812SAndreas Gohr *
54700976812SAndreas Gohr * This function behaves similar to PHP's realpath() but does not resolve
54800976812SAndreas Gohr * symlinks or accesses upper directories
54900976812SAndreas Gohr *
5504761d30cSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
55100976812SAndreas Gohr * @author <richpageau at yahoo dot co dot uk>
55259752844SAnders Sandblad * @link   http://php.net/manual/en/function.realpath.php#75992
553f50a239bSTakamura *
554f50a239bSTakamura * @param string $path
555f50a239bSTakamura * @param bool $exists
556f50a239bSTakamura *
557f50a239bSTakamura * @return bool|string
55800976812SAndreas Gohr */
559b328697dSAndreas Gohrfunction fullpath($path,$exists=false){
5604761d30cSAndreas Gohr    static $run = 0;
5614761d30cSAndreas Gohr    $root  = '';
562724970e6SAndreas Gohr    $iswin = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' || !empty($GLOBALS['DOKU_UNITTEST_ASSUME_WINDOWS']));
56300976812SAndreas Gohr
5644761d30cSAndreas Gohr    // find the (indestructable) root of the path - keeps windows stuff intact
5654761d30cSAndreas Gohr    if($path{0} == '/'){
5664761d30cSAndreas Gohr        $root = '/';
5674761d30cSAndreas Gohr    }elseif($iswin){
5684761d30cSAndreas Gohr        // match drive letter and UNC paths
5694761d30cSAndreas Gohr        if(preg_match('!^([a-zA-z]:)(.*)!',$path,$match)){
570b9c4302bSAndreas Gohr            $root = $match[1].'/';
5714761d30cSAndreas Gohr            $path = $match[2];
5724761d30cSAndreas Gohr        }else if(preg_match('!^(\\\\\\\\[^\\\\/]+\\\\[^\\\\/]+[\\\\/])(.*)!',$path,$match)){
5734761d30cSAndreas Gohr            $root = $match[1];
5744761d30cSAndreas Gohr            $path = $match[2];
57500976812SAndreas Gohr        }
5764761d30cSAndreas Gohr    }
5774761d30cSAndreas Gohr    $path = str_replace('\\','/',$path);
5784761d30cSAndreas Gohr
5794761d30cSAndreas Gohr    // if the given path wasn't absolute already, prepend the script path and retry
5804761d30cSAndreas Gohr    if(!$root){
5814761d30cSAndreas Gohr        $base = dirname($_SERVER['SCRIPT_FILENAME']);
5824761d30cSAndreas Gohr        $path = $base.'/'.$path;
5834761d30cSAndreas Gohr        if($run == 0){ // avoid endless recursion when base isn't absolute for some reason
5844761d30cSAndreas Gohr            $run++;
585b328697dSAndreas Gohr            return fullpath($path,$exists);
5864761d30cSAndreas Gohr        }
5874761d30cSAndreas Gohr    }
5884761d30cSAndreas Gohr    $run = 0;
58900976812SAndreas Gohr
59000976812SAndreas Gohr    // canonicalize
59100976812SAndreas Gohr    $path=explode('/', $path);
59200976812SAndreas Gohr    $newpath=array();
593ef38bfe8SAndreas Gohr    foreach($path as $p) {
594ef38bfe8SAndreas Gohr        if ($p === '' || $p === '.') continue;
595ef38bfe8SAndreas Gohr        if ($p==='..') {
59600976812SAndreas Gohr            array_pop($newpath);
59700976812SAndreas Gohr            continue;
59800976812SAndreas Gohr        }
599ef38bfe8SAndreas Gohr        array_push($newpath, $p);
60000976812SAndreas Gohr    }
6014761d30cSAndreas Gohr    $finalpath = $root.implode('/', $newpath);
60200976812SAndreas Gohr
6036b9c156cSAnika Henke    // check for existence when needed (except when unit testing)
60479e79377SAndreas Gohr    if($exists && !defined('DOKU_UNITTEST') && !file_exists($finalpath)) {
6054761d30cSAndreas Gohr        return false;
60600976812SAndreas Gohr    }
6074761d30cSAndreas Gohr    return $finalpath;
60800976812SAndreas Gohr}
60900976812SAndreas Gohr
610