Skip to content
Snippets Groups Projects
init.php 16.6 KiB
Newer Older
<?php
/**
 * Initialize some defaults needed for DokuWiki
 */

/**
 * timing Dokuwiki execution
 */
Andreas Gohr's avatar
Andreas Gohr committed
function delta_time($start=0) {
    return microtime(true)-((float)$start);
Andreas Gohr's avatar
Andreas Gohr committed
}
define('DOKU_START_TIME', delta_time());
Andreas Gohr's avatar
Andreas Gohr committed
global $config_cascade;
$config_cascade = array();
Andreas Gohr's avatar
Andreas Gohr committed
// if available load a preload config file
$preload = fullpath(dirname(__FILE__)).'/preload.php';
if (@file_exists($preload)) include($preload);
Andreas Gohr's avatar
Andreas Gohr committed
// define the include path
if(!defined('DOKU_INC')) define('DOKU_INC',fullpath(dirname(__FILE__).'/../').'/');
andi's avatar
andi committed

Andreas Gohr's avatar
Andreas Gohr committed
// define Plugin dir
if(!defined('DOKU_PLUGIN'))  define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');

Andreas Gohr's avatar
Andreas Gohr committed
// define config path (packagers may want to change this to /etc/dokuwiki/)
if(!defined('DOKU_CONF')) define('DOKU_CONF',DOKU_INC.'conf/');
Andreas Gohr's avatar
Andreas Gohr committed
// check for error reporting override or set error reporting to sane values
if (!defined('DOKU_E_LEVEL') && @file_exists(DOKU_CONF.'report_e_all')) {
Ben Coburn's avatar
Ben Coburn committed
    define('DOKU_E_LEVEL', E_ALL);
Andreas Gohr's avatar
Andreas Gohr committed
}
if (!defined('DOKU_E_LEVEL')) {
    if(defined('E_DEPRECATED')){ // since php 5.3, since php 5.4 E_STRICT is part of E_ALL
        error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT);
Andreas Gohr's avatar
Andreas Gohr committed
        error_reporting(E_ALL ^ E_NOTICE);
Andreas Gohr's avatar
Andreas Gohr committed
} else {
    error_reporting(DOKU_E_LEVEL);
Andreas Gohr's avatar
Andreas Gohr committed
}
Andreas Gohr's avatar
Andreas Gohr committed
// init memory caches
global $cache_revinfo;
       $cache_revinfo = array();
global $cache_wikifn;
       $cache_wikifn = array();
global $cache_cleanid;
       $cache_cleanid = array();
global $cache_authname;
       $cache_authname = array();
global $cache_metadata;
       $cache_metadata = array();

// always include 'inc/config_cascade.php'
// previously in preload.php set fields of $config_cascade will be merged with the defaults
include(DOKU_INC.'inc/config_cascade.php');
Andreas Gohr's avatar
Andreas Gohr committed

//prepare config array()
global $conf;
$conf = array();

// load the global config file(s)
foreach (array('default','local','protected') as $config_group) {
    if (empty($config_cascade['main'][$config_group])) continue;
    foreach ($config_cascade['main'][$config_group] as $config_file) {
Andreas Gohr's avatar
Andreas Gohr committed
        if (@file_exists($config_file)) {
            include($config_file);
        }
Andreas Gohr's avatar
Andreas Gohr committed
}
andi's avatar
andi committed

Andreas Gohr's avatar
Andreas Gohr committed
//prepare license array()
global $license;
$license = array();
Andreas Gohr's avatar
Andreas Gohr committed
// load the license file(s)
foreach (array('default','local') as $config_group) {
    if (empty($config_cascade['license'][$config_group])) continue;
    foreach ($config_cascade['license'][$config_group] as $config_file) {
Andreas Gohr's avatar
Andreas Gohr committed
        if(@file_exists($config_file)){
            include($config_file);
        }
Andreas Gohr's avatar
Andreas Gohr committed
}
// set timezone (as in pre 5.3.0 days)
date_default_timezone_set(@date_default_timezone_get());

Andreas Gohr's avatar
Andreas Gohr committed
// define baseURL
if(!defined('DOKU_REL')) define('DOKU_REL',getBaseURL(false));
if(!defined('DOKU_URL')) define('DOKU_URL',getBaseURL(true));
if(!defined('DOKU_BASE')){
    if($conf['canonical']){
Andreas Gohr's avatar
Andreas Gohr committed
        define('DOKU_BASE',DOKU_URL);
Andreas Gohr's avatar
Andreas Gohr committed
        define('DOKU_BASE',DOKU_REL);
Andreas Gohr's avatar
Andreas Gohr committed
}
Andreas Gohr's avatar
Andreas Gohr committed
// define whitespace
if(!defined('DOKU_LF')) define ('DOKU_LF',"\n");
if(!defined('DOKU_TAB')) define ('DOKU_TAB',"\t");
Andreas Gohr's avatar
Andreas Gohr committed
// define cookie and session id, append server port when securecookie is configured FS#1664
if (!defined('DOKU_COOKIE')) define('DOKU_COOKIE', 'DW'.md5(DOKU_REL.(($conf['securecookie'])?$_SERVER['SERVER_PORT']:'')));
Andreas Gohr's avatar
Andreas Gohr committed
// define main script
if(!defined('DOKU_SCRIPT')) define('DOKU_SCRIPT','doku.php');
// DEPRECATED, use tpl_basedir() instead
Andreas Gohr's avatar
Andreas Gohr committed
if(!defined('DOKU_TPL')) define('DOKU_TPL',
        DOKU_BASE.'lib/tpl/'.$conf['template'].'/');
// DEPRECATED, use tpl_incdir() instead
Andreas Gohr's avatar
Andreas Gohr committed
if(!defined('DOKU_TPLINC')) define('DOKU_TPLINC',
        DOKU_INC.'lib/tpl/'.$conf['template'].'/');
Andreas Gohr's avatar
Andreas Gohr committed
// make session rewrites XHTML compliant
@ini_set('arg_separator.output', '&amp;');
Andreas Gohr's avatar
Andreas Gohr committed
// make sure global zlib does not interfere FS#1132
@ini_set('zlib.output_compression', 'off');
Andreas Gohr's avatar
Andreas Gohr committed
// increase PCRE backtrack limit
@ini_set('pcre.backtrack_limit', '20971520');
Andreas Gohr's avatar
Andreas Gohr committed
// enable gzip compression if supported
$conf['gzip_output'] &= (strpos($_SERVER['HTTP_ACCEPT_ENCODING'],'gzip') !== false);
if ($conf['gzip_output'] &&
        !defined('DOKU_DISABLE_GZIP_OUTPUT') &&
        function_exists('ob_gzhandler')) {
    ob_start('ob_gzhandler');
Andreas Gohr's avatar
Andreas Gohr committed
}
Andreas Gohr's avatar
Andreas Gohr committed
// init session
if (!headers_sent() && !defined('NOSESSION')){
Andreas Gohr's avatar
Andreas Gohr committed
    session_name("DokuWiki");
    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
    if (version_compare(PHP_VERSION, '5.2.0', '>')) {
        session_set_cookie_params(0,$cookieDir,'',($conf['securecookie'] && is_ssl()),true);
    }else{
        session_set_cookie_params(0,$cookieDir,'',($conf['securecookie'] && is_ssl()));
Andreas Gohr's avatar
Andreas Gohr committed
    session_start();

    // load left over messages
    if(isset($_SESSION[DOKU_COOKIE]['msg'])){
Andreas Gohr's avatar
Andreas Gohr committed
        $MSG = $_SESSION[DOKU_COOKIE]['msg'];
        unset($_SESSION[DOKU_COOKIE]['msg']);
Andreas Gohr's avatar
Andreas Gohr committed
}
Andreas Gohr's avatar
Andreas Gohr committed
// kill magic quotes
if (get_magic_quotes_gpc() && !defined('MAGIC_QUOTES_STRIPPED')) {
    if (!empty($_GET))    remove_magic_quotes($_GET);
    if (!empty($_POST))   remove_magic_quotes($_POST);
    if (!empty($_COOKIE)) remove_magic_quotes($_COOKIE);
    if (!empty($_REQUEST)) remove_magic_quotes($_REQUEST);
    @ini_set('magic_quotes_gpc', 0);
    define('MAGIC_QUOTES_STRIPPED',1);
Andreas Gohr's avatar
Andreas Gohr committed
}
@set_magic_quotes_runtime(0);
@ini_set('magic_quotes_sybase',0);
Andreas Gohr's avatar
Andreas Gohr committed
// don't let cookies ever interfere with request vars
$_REQUEST = array_merge($_GET,$_POST);
Andreas Gohr's avatar
Andreas Gohr committed
// we don't want a purge URL to be digged
if(isset($_REQUEST['purge']) && $_SERVER['HTTP_REFERER']) unset($_REQUEST['purge']);
Andreas Gohr's avatar
Andreas Gohr committed
// disable gzip if not available
if($conf['compression'] == 'bz2' && !function_exists('bzopen')){
    $conf['compression'] = 'gz';
Andreas Gohr's avatar
Andreas Gohr committed
}
if($conf['compression'] == 'gz' && !function_exists('gzopen')){
Andreas Gohr's avatar
Andreas Gohr committed
    $conf['compression'] = 0;
Andreas Gohr's avatar
Andreas Gohr committed
}
Andreas Gohr's avatar
Andreas Gohr committed
// fix dateformat for upgraders
if(strpos($conf['dformat'],'%') === false){
    $conf['dformat'] = '%Y/%m/%d %H:%M';
Andreas Gohr's avatar
Andreas Gohr committed
}
Andreas Gohr's avatar
Andreas Gohr committed
// precalculate file creation modes
init_creationmodes();
Andreas Gohr's avatar
Andreas Gohr committed
// make real paths and check them
init_paths();
init_files();
// setup plugin controller class (can be overwritten in preload.php)
$plugin_types = array('admin','syntax','action','renderer', 'helper','remote');
global $plugin_controller_class, $plugin_controller;
if (empty($plugin_controller_class)) $plugin_controller_class = 'Doku_Plugin_Controller';

Adrian Lang's avatar
Adrian Lang committed
// load libraries
require_once(DOKU_INC.'inc/load.php');

// input handle class
global $INPUT;
$INPUT = new Input();

// initialize plugin controller
$plugin_controller = new $plugin_controller_class();

// initialize the event handler
global $EVENT_HANDLER;
$EVENT_HANDLER = new Doku_Event_Handler();

$local = $conf['lang'];
trigger_event('INIT_LANG_LOAD', $local, 'init_lang', true);


// setup authentication system
Adrian Lang's avatar
Adrian Lang committed
if (!defined('NOSESSION')) {
    auth_setup();
}
// setup mail system
mail_setup();

andi's avatar
andi committed
/**
 * Checks paths from config file
 */
function init_paths(){
Andreas Gohr's avatar
Andreas Gohr committed
    global $conf;

    $paths = array('datadir'   => 'pages',
            'olddir'    => 'attic',
            'mediadir'  => 'media',
Kate Arzamastseva's avatar
Kate Arzamastseva committed
            'mediaolddir' => 'media_attic',
Andreas Gohr's avatar
Andreas Gohr committed
            'metadir'   => 'meta',
Kate Arzamastseva's avatar
Kate Arzamastseva committed
            'mediametadir' => 'media_meta',
Andreas Gohr's avatar
Andreas Gohr committed
            'cachedir'  => 'cache',
            'indexdir'  => 'index',
            'lockdir'   => 'locks',
            'tmpdir'    => 'tmp');

    foreach($paths as $c => $p) {
        $path = empty($conf[$c]) ? $conf['savedir'].'/'.$p : $conf[$c];
        $conf[$c] = init_path($path);
        if(empty($conf[$c]))
            nice_die("The $c ('$p') at $path is not found, isn't accessible or writable.
Andreas Gohr's avatar
Andreas Gohr committed
                You should check your config and permission settings.
                Or maybe you want to <a href=\"install.php\">run the
                installer</a>?");
    }

    // path to old changelog only needed for upgrading
    $conf['changelog_old'] = init_path((isset($conf['changelog']))?($conf['changelog']):($conf['savedir'].'/changes.log'));
    if ($conf['changelog_old']=='') { unset($conf['changelog_old']); }
    // hardcoded changelog because it is now a cache that lives in meta
    $conf['changelog'] = $conf['metadir'].'/_dokuwiki.changes';
    $conf['media_changelog'] = $conf['metadir'].'/_media.changes';
andi's avatar
andi committed
}

function init_lang($langCode) {
    //prepare language array
    global $lang;
    $lang = array();

    //load the language files
    require_once(DOKU_INC.'inc/lang/en/lang.php');
    if ($langCode && $langCode != 'en') {
        if (file_exists(DOKU_INC."inc/lang/$langCode/lang.php")) {
            require_once(DOKU_INC."inc/lang/$langCode/lang.php");
        }
    }
}

 * Checks the existence of certain files and creates them if missing.
Andreas Gohr's avatar
Andreas Gohr committed
    global $conf;

    $files = array($conf['indexdir'].'/page.idx');
Andreas Gohr's avatar
Andreas Gohr committed

    foreach($files as $file){
        if(!@file_exists($file)){
            $fh = @fopen($file,'a');
            if($fh){
                fclose($fh);
                if($conf['fperm']) chmod($file, $conf['fperm']);
            }else{
                nice_die("$file is not writable. Check your permissions settings!");
            }
        }

    # create title index (needs to have same length as page.idx)
    $file = $conf['indexdir'].'/title.idx';
    if(!@file_exists($file)){
        $pages = file($conf['indexdir'].'/page.idx');
        $pages = count($pages);
        $fh = @fopen($file,'a');
        if($fh){
            for($i=0; $i<$pages; $i++){
                fwrite($fh,"\n");
            }
            fclose($fh);
        }else{
            nice_die("$file is not writable. Check your permissions settings!");
        }
    }
Andreas Gohr's avatar
Andreas Gohr committed
 * Returns absolute path
 *
 * This tries the given path first, then checks in DOKU_INC.
 * Check for accessibility on directories as well.
Andreas Gohr's avatar
Andreas Gohr committed
 * @author Andreas Gohr <andi@splitbrain.org>
 */
function init_path($path){
Andreas Gohr's avatar
Andreas Gohr committed
    $p = fullpath($path);
Andreas Gohr's avatar
Andreas Gohr committed
    if(!@file_exists($p)){
Andreas Gohr's avatar
Andreas Gohr committed
        $p = fullpath(DOKU_INC.$path);
        if(!@file_exists($p)){
            return '';
        }
Andreas Gohr's avatar
Andreas Gohr committed
    // check writability
    if(!@is_writable($p)){
        return '';
    }
Andreas Gohr's avatar
Andreas Gohr committed
    // check accessability (execute bit) for directories
    if(@is_dir($p) && !@file_exists("$p/.")){
        return '';
    }
Andreas Gohr's avatar
Andreas Gohr committed
    return $p;
/**
 * Sets the internal config values fperm and dperm which, when set,
 * will be used to change the permission of a newly created dir or
 * file with chmod. Considers the influence of the system's umask
 * setting the values only if needed.
 */
function init_creationmodes(){
Andreas Gohr's avatar
Andreas Gohr committed
    global $conf;

    // Legacy support for old umask/dmask scheme
    unset($conf['dmask']);
    unset($conf['fmask']);
    unset($conf['umask']);
    unset($conf['fperm']);
    unset($conf['dperm']);

    // get system umask, fallback to 0 if none available
    $umask = @umask();
    if(!$umask) $umask = 0000;

    // check what is set automatically by the system on file creation
    // and set the fperm param if it's not what we want
    $auto_fmode = 0666 & ~$umask;
    if($auto_fmode != $conf['fmode']) $conf['fperm'] = $conf['fmode'];

    // check what is set automatically by the system on file creation
    // and set the dperm param if it's not what we want
    $auto_dmode = $conf['dmode'] & ~$umask;
    if($auto_dmode != $conf['dmode']) $conf['dperm'] = $conf['dmode'];
/**
 * remove magic quotes recursivly
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 */
function remove_magic_quotes(&$array) {
Andreas Gohr's avatar
Andreas Gohr committed
    foreach (array_keys($array) as $key) {
        // handle magic quotes in keynames (breaks order)
        $sk = stripslashes($key);
        if($sk != $key){
            $array[$sk] = $array[$key];
            unset($array[$key]);
            $key = $sk;
        }

        // do recursion if needed
        if (is_array($array[$key])) {
            remove_magic_quotes($array[$key]);
        }else {
            $array[$key] = stripslashes($array[$key]);
        }
    }
}

/**
 * Returns the full absolute URL to the directory where
 * DokuWiki is installed in (includes a trailing slash)
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 */
function getBaseURL($abs=null){
Andreas Gohr's avatar
Andreas Gohr committed
    global $conf;
    //if canonical url enabled always return absolute
    if(is_null($abs)) $abs = $conf['canonical'];

    if($conf['basedir']){
        $dir = $conf['basedir'];
    }elseif(substr($_SERVER['SCRIPT_NAME'],-4) == '.php'){
        $dir = dirname($_SERVER['SCRIPT_NAME']);
    }elseif(substr($_SERVER['PHP_SELF'],-4) == '.php'){
        $dir = dirname($_SERVER['PHP_SELF']);
    }elseif($_SERVER['DOCUMENT_ROOT'] && $_SERVER['SCRIPT_FILENAME']){
        $dir = preg_replace ('/^'.preg_quote($_SERVER['DOCUMENT_ROOT'],'/').'/','',
                $_SERVER['SCRIPT_FILENAME']);
        $dir = dirname('/'.$dir);
    }else{
        $dir = '.'; //probably wrong
Andreas Gohr's avatar
Andreas Gohr committed

    $dir = str_replace('\\','/',$dir);             // bugfix for weird WIN behaviour
    $dir = preg_replace('#//+#','/',"/$dir/");     // ensure leading and trailing slashes

    //handle script in lib/exe dir
    $dir = preg_replace('!lib/exe/$!','',$dir);
Andreas Gohr's avatar
Andreas Gohr committed

    //handle script in lib/plugins dir
    $dir = preg_replace('!lib/plugins/.*$!','',$dir);

    //finish here for relative URLs
    if(!$abs) return $dir;

    //use config option if available, trim any slash from end of baseurl to avoid multiple consecutive slashes in the path
    if($conf['baseurl']) return rtrim($conf['baseurl'],'/').$dir;

    //split hostheader into host and port
    if(isset($_SERVER['HTTP_HOST'])){
        $parsed_host = parse_url('http://'.$_SERVER['HTTP_HOST']);
        $host = $parsed_host['host'];
        $port = $parsed_host['port'];
    }elseif(isset($_SERVER['SERVER_NAME'])){
        $parsed_host = parse_url('http://'.$_SERVER['SERVER_NAME']);
        $host = $parsed_host['host'];
        $port = $parsed_host['port'];
    }else{
        $host = php_uname('n');
        $port = '';
    }

    if(!$port && isset($_SERVER['SERVER_PORT'])) {
        $port = $_SERVER['SERVER_PORT'];
    }
Andreas Gohr's avatar
Andreas Gohr committed
    if(!is_ssl()){
        $proto = 'http://';
        if ($port == '80') {
            $port = '';
Andreas Gohr's avatar
Andreas Gohr committed
        }
    }else{
        $proto = 'https://';
        if ($port == '443') {
            $port = '';
Andreas Gohr's avatar
Andreas Gohr committed
        }
    if($port !== '') $port = ':'.$port;
Andreas Gohr's avatar
Andreas Gohr committed
    return $proto.$host.$port.$dir;
/**
 * Check if accessed via HTTPS
 *
 * Apache leaves ,$_SERVER['HTTPS'] empty when not available, IIS sets it to 'off'.
 * 'false' and 'disabled' are just guessing
 *
 * @returns bool true when SSL is active
 */
function is_ssl(){
    if (!isset($_SERVER['HTTPS']) ||
        preg_match('/^(|off|false|disabled)$/i',$_SERVER['HTTPS'])){
        return false;
    }else{
        return true;
    }
}

/**
 * print a nice message even if no styles are loaded yet.
 */
function nice_die($msg){
Andreas Gohr's avatar
Andreas Gohr committed
    echo<<<EOT
<!DOCTYPE html>
Andreas Gohr's avatar
Andreas Gohr committed
<html>
<head><title>DokuWiki Setup Error</title></head>
<body style="font-family: Arial, sans-serif">
    <div style="width:60%; margin: auto; background-color: #fcc;
                border: 1px solid #faa; padding: 0.5em 1em;">
        <h1 style="font-size: 120%">DokuWiki Setup Error</h1>
        <p>$msg</p>
    </div>
</body>
</html>
Andreas Gohr's avatar
Andreas Gohr committed
    exit;
/**
 * A realpath() replacement
 *
 * This function behaves similar to PHP's realpath() but does not resolve
 * symlinks or accesses upper directories
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 * @author <richpageau at yahoo dot co dot uk>
 * @link   http://de3.php.net/manual/en/function.realpath.php#75992
 */
function fullpath($path,$exists=false){
furun's avatar
furun committed
    static $run = 0;
    $root  = '';
    $iswin = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' || @$GLOBALS['DOKU_UNITTEST_ASSUME_WINDOWS']);

    // find the (indestructable) root of the path - keeps windows stuff intact
    if($path{0} == '/'){
        $root = '/';
    }elseif($iswin){
        // match drive letter and UNC paths
        if(preg_match('!^([a-zA-z]:)(.*)!',$path,$match)){
            $root = $match[1].'/';
            $path = $match[2];
        }else if(preg_match('!^(\\\\\\\\[^\\\\/]+\\\\[^\\\\/]+[\\\\/])(.*)!',$path,$match)){
            $root = $match[1];
            $path = $match[2];
        }
    $path = str_replace('\\','/',$path);

    // if the given path wasn't absolute already, prepend the script path and retry
    if(!$root){
        $base = dirname($_SERVER['SCRIPT_FILENAME']);
        $path = $base.'/'.$path;
        if($run == 0){ // avoid endless recursion when base isn't absolute for some reason
            $run++;
            return fullpath($path,$exists);

    // canonicalize
    $path=explode('/', $path);
    $newpath=array();
Andreas Gohr's avatar
Andreas Gohr committed
    foreach($path as $p) {
        if ($p === '' || $p === '.') continue;
Andreas Gohr's avatar
Andreas Gohr committed
        if ($p==='..') {
            array_pop($newpath);
            continue;
Andreas Gohr's avatar
Andreas Gohr committed
        array_push($newpath, $p);
    $finalpath = $root.implode('/', $newpath);
    // check for existence when needed (except when unit testing)
    if($exists && !defined('DOKU_UNITTEST') && !@file_exists($finalpath)) {
        return false;
    return $finalpath;