init.php 14.1 KB
Newer Older
Penny Leach's avatar
Penny Leach committed
1 2
<?php
/**
Francois Marier's avatar
Francois Marier committed
3
 * Mahara: Electronic portfolio, weblog, resume builder and social networking
4 5
 * Copyright (C) 2006-2009 Catalyst IT Ltd and others; see:
 *                         http://wiki.mahara.org/Contributors
Penny Leach's avatar
Penny Leach committed
6
 *
Francois Marier's avatar
Francois Marier committed
7 8 9 10
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
11
 *
Francois Marier's avatar
Francois Marier committed
12 13 14 15
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
16
 *
Francois Marier's avatar
Francois Marier committed
17 18
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 20 21
 *
 * @package    mahara
 * @subpackage core
22
 * @author     Catalyst IT Ltd
23
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
24
 * @copyright  (C) 2006-2009 Catalyst IT Ltd http://catalyst.net.nz
25
 *
Penny Leach's avatar
Penny Leach committed
26 27
 */

28 29
defined('INTERNAL') || die();

Penny Leach's avatar
Penny Leach committed
30
$CFG = new StdClass;
31
$CFG->docroot = dirname(__FILE__) . '/';
32 33 34
//array containing site options from database that are overrided by $CFG
$OVERRIDDEN = array();

Nigel McNie's avatar
Nigel McNie committed
35 36
// Figure out our include path
if (!empty($_SERVER['MAHARA_LIBDIR'])) {
37
    $CFG->libroot = $_SERVER['MAHARA_LIBDIR'];
Penny Leach's avatar
Penny Leach committed
38
}
Nigel McNie's avatar
Nigel McNie committed
39
else {
40
    $CFG->libroot = dirname(__FILE__) . '/lib/';
Nigel McNie's avatar
Nigel McNie committed
41
}
42
set_include_path($CFG->libroot . PATH_SEPARATOR . $CFG->libroot . 'pear/' . PATH_SEPARATOR . get_include_path());
Penny Leach's avatar
Penny Leach committed
43

44 45 46 47 48
// Ensure that, by default, the response is not cached
header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
header('Expires: '. gmdate('D, d M Y H:i:s', 507686400) .' GMT');
header('Pragma: no-cache');

49 50 51
// Prevent clickjacking through iframe tags
header('X-Frame-Options: SAMEORIGIN');

52
// Set up error handling
Nigel McNie's avatar
Nigel McNie committed
53
require('errors.php');
54

55
if (!is_readable($CFG->docroot . 'config.php')) {
56 57 58 59
    // @todo Later, this will redirect to the installer script. For now, we
    // just log and exit.
    log_environ('Not installed! Please create config.php from config-dist.php');
    exit;
Penny Leach's avatar
Penny Leach committed
60 61
}

62 63
init_performance_info();

64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
// Because the default XML loader is vulnerable to XEE attacks, we're disabling it by default.
// If you need to use it, you can re-enable the function, call it while passing in the
// LIBXML_NONET parameter, and then disable the function again, like this:
//
// EXAMPLE
//     if (function_exists('libxml_disable_entity_loader')) {
//         libxml_disable_entity_loader(false);
//     }
//     $options =
//         LIBXML_COMPACT |    // Reported to greatly speed XML parsing
//         LIBXML_NONET        // Disable network access - security check
//     ;
//     $xml = simplexml_load_file($filename, 'SimpleXMLElement', $options);
//     if (function_exists('libxml_disable_entity_loader')) {
//         libxml_disable_entity_loader(true);
//     }
// END EXAMPLE
Hugh Davenport's avatar
Hugh Davenport committed
81 82 83 84
if (function_exists('libxml_disable_entity_loader')) {
    libxml_disable_entity_loader(true);
}

85
require($CFG->docroot . 'config.php');
Nigel McNie's avatar
Nigel McNie committed
86
$CFG = (object)array_merge((array)$cfg, (array)$CFG);
87 88
require_once('config-defaults.php');
$CFG = (object)array_merge((array)$cfg, (array)$CFG);
Penny Leach's avatar
Penny Leach committed
89

90 91
// Fix up paths in $CFG
foreach (array('docroot', 'dataroot') as $path) {
92
    $CFG->{$path} = (substr($CFG->{$path}, -1) != '/') ? $CFG->{$path} . '/' : $CFG->{$path};
93 94
}

95 96 97 98
// xmldb stuff
$CFG->xmldbdisablenextprevchecking = true;
$CFG->xmldbdisablecommentchecking = true;

99 100 101 102
// ensure directorypermissions is set
if (empty($CFG->directorypermissions)) {
    $CFG->directorypermissions = 0700;
}
Hugh Davenport's avatar
Hugh Davenport committed
103
$CFG->filepermissions = $CFG->directorypermissions & 0666;
104

105
// core libraries
106
require('mahara.php');
107
ensure_sanity();
108
require('dml.php');
109
require('web.php');
Penny Leach's avatar
Penny Leach committed
110
require('user.php');
111
require(get_config('docroot') . 'local/lib.php');
112

Nigel McNie's avatar
Nigel McNie committed
113
// Database access functions
114 115
require('adodb/adodb-exceptions.inc.php');
require('adodb/adodb.inc.php');
116

Nigel McNie's avatar
Nigel McNie committed
117 118 119 120 121
try {
    // ADODB does not provide the raw driver error message if the connection
    // fails for some reason, so we use output buffering to catch whatever
    // the error is instead.
    ob_start();
122

123
    // Transform $CFG->dbtype into the name of the ADODB driver we will use
124 125 126 127
    if (is_postgres()) {
        $CFG->dbtype = 'postgres7';
    }
    else if (is_mysql()) {
128 129 130 131 132 133 134
        // If they have mysqli, use it. Otherwise, fall back to the older "mysql" extension.
        if (extension_loaded('mysqli')) {
            $CFG->dbtype = 'mysqli';
        }
        else {
            $CFG->dbtype = 'mysql';
        }
135
    }
136

Nigel McNie's avatar
Nigel McNie committed
137
    $db = &ADONewConnection($CFG->dbtype);
138 139 140 141
    if (empty($CFG->dbhost)) {
        $CFG->dbhost = '';
    }
    else if (!empty($CFG->dbport)) {
Nigel McNie's avatar
Nigel McNie committed
142 143 144 145
        $CFG->dbhost .= ':'.$CFG->dbport;
    }
    if (!empty($CFG->dbpersist)) {    // Use persistent connection (default)
        $dbconnected = $db->PConnect($CFG->dbhost,$CFG->dbuser,$CFG->dbpass,$CFG->dbname);
146 147
    } 
    else {                                                     // Use single connection
Nigel McNie's avatar
Nigel McNie committed
148 149
        $dbconnected = $db->Connect($CFG->dbhost,$CFG->dbuser,$CFG->dbpass,$CFG->dbname);
    }
150

151 152 153
    // Now we have a connection, verify the server is a new enough version
    $dbversion = $db->ServerInfo();
    if (is_postgres()) {
154
        $okversion = '8.3';
155 156 157 158 159 160 161 162 163 164
        $dbfriendlyname = 'PostgreSQL';
    }
    else if (is_mysql()) {
        $okversion = '5.0.25';
        $dbfriendlyname = 'MySQL';
    }
    if ($dbversion['version'] < $okversion) {
        throw new ConfigSanityException(get_string('dbversioncheckfailed', 'error', $dbfriendlyname, $dbversion['version'], $okversion));
    }

165 166
    $db->SetFetchMode(ADODB_FETCH_ASSOC);
    configure_dbconnection();
167
    ensure_internal_plugins_exist();
168

Nigel McNie's avatar
Nigel McNie committed
169
    ob_end_clean();
170
}
Nigel McNie's avatar
Nigel McNie committed
171
catch (Exception $e) {
172 173 174
    if ($e instanceof ConfigSanityException) {
        throw $e;
    }
175
    $errormessage = ob_get_contents();
176 177 178
    if (!$errormessage) {
        $errormessage = $e->getMessage();
    }
179
    ob_end_clean();
180 181
    $errormessage = get_string('dbconnfailed', 'error') . $errormessage;
    throw new ConfigSanityException($errormessage);
182
}
183
try {
184
    db_ignore_sql_exceptions(true);
185
    load_config();
186
    db_ignore_sql_exceptions(false);
187
} 
188
catch (SQLException $e) {
189
    db_ignore_sql_exceptions(false);
190
}
191

192 193
// Make sure wwwroot is set and available, either in the database or in the
// config file. Cron requires it when sending out forums emails.
194
if (!isset($CFG->wwwroot) && isset($_SERVER['HTTP_HOST'])) {
195
    $proto = (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) != 'off') ? 'https://' : 'http://';
196
    $host  =  (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : $_SERVER['HTTP_HOST'];
197 198 199 200
    if (false !== strpos($host, ',')) {
        list($host) = explode(',', $host);
        $host = trim($host);
    }
201 202 203 204
    $path = '';
    if (strpos(dirname(__FILE__), strlen($_SERVER['DOCUMENT_ROOT'])) === 0) {
        $path  = substr(dirname(__FILE__), strlen($_SERVER['DOCUMENT_ROOT']));
    }
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
    else {
        $self = explode('/', $_SERVER['PHP_SELF']);
        $dir = dirname(__FILE__);
        $i = 0;
        while (realpath($_SERVER['DOCUMENT_ROOT'].$path) != $dir) {
            if ($i >= count($self) - 1) {
                $path = '';
                break;
            }
            if (empty($self[$i])) {
                $i ++;
                continue;
            }
            $path .= '/'.$self[$i];
            $i ++;
        }
    }
222
    if ($path) {
223
        $path = str_replace('\\', '/', $path);  // windows
224 225 226
        if (substr($path, 0, 1) != '/') {
            $path = '/' . $path;
        }
227
        $path .= '/';
228 229
    } else {
        $path = '/';
230
    }
231 232 233 234 235 236 237 238
    $wwwroot = $proto . $host . $path;
    try {
        set_config('wwwroot', $wwwroot);
    }
    catch (Exception $e) {
        // Just set it directly. The system will most likely not be installed, so we don't care
        $CFG->wwwroot = $wwwroot;
    }
239
}
240 241 242 243 244
if (isset($CFG->wwwroot)) {
    if (substr($CFG->wwwroot, -1, 1) != '/') {
        $CFG->wwwroot .= '/';
    }
}
245

246 247 248 249 250 251 252
// If we have cleanurl subdomains turned on, we need to set cookiedomain
// to ensure cookies are given back to us in all subdomains
if (isset($CFG->cleanurls) && isset($CFG->cleanurlusersubdomains) && !isset($CFG->cookiedomain)) {
    $url = parse_url(get_config('wwwroot'));
    $CFG->cookiedomain = '.' . $url['host'];
}

253
// If we're forcing an ssl proxy, make sure the wwwroot is correct
254
if ($CFG->sslproxy == true && parse_url($CFG->wwwroot, PHP_URL_SCHEME) !== 'https') {
255 256 257
    throw new ConfigSanityException(get_string('wwwrootnothttps', 'error', get_config('wwwroot')));
}

258
// Make sure that we are using ssl if wwwroot expects us to do so
259 260
if ($CFG->sslproxy === false && isset($_SERVER['REMOTE_ADDR']) && (!isset($_SERVER['HTTPS']) || strtolower($_SERVER['HTTPS']) == 'off') &&
    parse_url($CFG->wwwroot, PHP_URL_SCHEME) === 'https'){
261 262
    redirect(get_relative_script_path());
}
263
if (!isset($CFG->noreplyaddress) && isset($_SERVER['HTTP_HOST'])) {
264 265 266 267 268 269 270
    $noreplyaddress = 'noreply@';
    $host  =  (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : $_SERVER['HTTP_HOST'];
    if (false !== strpos($host, ',')) {
        list($host) = explode(',', $host);
        $host = trim($host);
    }
    $noreplyaddress .= $host;
271 272 273 274 275 276 277 278 279
    try {
        set_config('noreplyaddress', $noreplyaddress);
    }
    catch (Exception $e) {
        // Do nothing again, same reason as above
        $CFG->noreplyaddress = $noreplyaddress;
    }
}

Penny Leach's avatar
Penny Leach committed
280 281 282 283 284 285
if (!get_config('theme')) { 
    // if it's not set, we're probably not installed, 
    // so set it in $CFG directly rather than the db which doesn't yet exist
    $CFG->theme = 'default'; 
}

286 287 288 289 290
if (defined('INSTALLER')) { 
    // Custom themes sometimes cause upgrades to fail.
    $CFG->theme = 'default';
}

291 292 293 294 295 296 297 298 299
// Make sure the search plugin is configured
if (!get_config('searchplugin')) {
    try {
        set_config('searchplugin', 'internal');
    }
    catch (Exception $e) {
        $CFG->searchplugin = 'internal';
    }
}
300 301 302 303 304 305 306 307 308 309

$bcrypt_cost = get_config('bcrypt_cost');
// bcrypt_cost is the cost parameter passed as part of the bcrypt hash
// See http://php.net/manual/en/function.crypt.php
// The value is a 2 digit number in the range of 04-31
if (!$bcrypt_cost || !is_int($bcrypt_cost) || $bcrypt_cost < 4 || $bcrypt_cost > 31) {
    $bcrypt_cost = 12;
}
$CFG->bcrypt_cost = sprintf('%02d', $bcrypt_cost);

310 311 312 313 314 315 316 317 318 319
if (!get_config('productionmode')) {
    $CFG->log_dbg_targets     = LOG_TARGET_SCREEN | LOG_TARGET_ERRORLOG;
    $CFG->log_info_targets    = LOG_TARGET_SCREEN | LOG_TARGET_ERRORLOG;
    $CFG->log_warn_targets    = LOG_TARGET_SCREEN | LOG_TARGET_ERRORLOG;
    $CFG->log_environ_targets = LOG_TARGET_SCREEN | LOG_TARGET_ERRORLOG;
    $CFG->developermode       = DEVMODE_DEBUGJS | DEVMODE_DEBUGCSS | DEVMODE_UNPACKEDJS;
    $CFG->perftofoot          = true;
    $CFG->nocache             = true;
}

320 321
header('Content-type: text/html; charset=UTF-8');

322 323
// Only do authentication once we know the page theme, so that the login form
// can have the correct theming.
324
require_once('auth/lib.php');
325 326
$SESSION = Session::singleton();
$USER    = new LiveUser();
327

328 329 330 331
if (function_exists('local_init_user')) {
    local_init_user();
}

332 333 334 335 336 337 338 339 340
// try to set the theme, or catch the thrown exception (eg if the name is invalid)
try {
    $THEME   = new Theme($USER);
} catch (SystemException $exception) {
    // set the theme to 'default' and put up an error message
    $THEME = new Theme('default');
    $SESSION->add_error_msg($exception->getMessage());
}

341 342
// The installer does its own auth_setup checking, because some upgrades may
// break logging in and so need to allow no logins.
343 344
// Command-line scripts obviously have no logged-in user.
if (!defined('INSTALLER') && !defined('CLI')) {
345 346
    auth_setup();
}
347

348 349 350 351
$siteclosedforupgrade = get_config('siteclosed');
if ($siteclosedforupgrade && $USER->admin) {
    if (get_config('disablelogin')) {
        $USER->logout();
352
    }
353 354 355 356 357 358 359 360 361 362 363 364
    else if (!defined('INSTALLER')) {
        redirect('/admin/upgrade.php');
    }
}

$siteclosed = $siteclosedforupgrade || get_config('siteclosedbyadmin');
if ($siteclosed && !$USER->admin) {
    if ($USER->is_logged_in()) {
        $USER->logout();
    }
    if (!defined('HOME') && !defined('INSTALLER')) {
        redirect();
365 366 367
    }
}

368
// check to see if we're installed...
369 370 371
if (!get_config('installed')) {
    ensure_install_sanity();

372
    $scriptfilename = str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']);
373
    if (false === strpos($scriptfilename, 'admin/index.php')
374
    && false === strpos($scriptfilename, 'admin/upgrade.php')
375 376 377
    && false === strpos($scriptfilename, 'admin/upgrade.json.php')
    && false === strpos($scriptfilename, 'admin/cli/install.php')
    && false === strpos($scriptfilename, 'admin/cli/upgrade.php')) {
378
        redirect('/admin/index.php');
379
    }
380 381
}

Clare Lenihan's avatar
Clare Lenihan committed
382
if (defined('JSON') && !defined('NOSESSKEY')) {
383
    $sesskey = param_variable('sesskey', null);
384 385
    global $USER;
    if ($sesskey === null || $USER->get('sesskey') != $sesskey) {
386
        $USER->logout();
387
        json_reply('global', get_string('invalidsesskey'), 1);
388
    }
389 390
}

391
// Device detection
392
if (get_config('installed') && get_account_preference($USER->get('id'), 'devicedetection')) {
393 394 395 396 397 398 399 400 401 402 403
    require_once(get_config('libroot') . 'mobile_detect/Mobile_Detect.php');
    $detect = new Mobile_Detect();
    $SESSION->set('handheld_device', $detect->isMobile());
    $SESSION->set('mobile', $detect->isTablet() ? false : $detect->isMobile());
    $SESSION->set('tablet', $detect->isTablet());
}
else {
    $SESSION->set('handheld_device', false);
    $SESSION->set('mobile', false);
    $SESSION->set('tablet', false);
}
404

405 406 407 408 409 410 411 412 413 414 415 416 417 418
/*
 * Initializes our performance info early.
 *
 * Pairs up with get_performance_info() which is actually
 * in lib/mahara.php. This function is here so that we can 
 * call it before all the libs are pulled in. 
 *
 * @uses $PERF
 */
function init_performance_info() {

    global $PERF;
  
    $PERF = new StdClass;
419
    $PERF->dbreads = $PERF->dbwrites = $PERF->dbcached = 0;
420 421 422 423 424 425 426 427 428 429 430
    $PERF->logwrites = 0;
    if (function_exists('microtime')) {
        $PERF->starttime = microtime();
        }
    if (function_exists('memory_get_usage')) {
        $PERF->startmemory = memory_get_usage();
    }
    if (function_exists('posix_times')) {
        $PERF->startposixtimes = posix_times();  
    }
}