init.php 18.3 KB
Newer Older
Penny Leach's avatar
Penny Leach committed
1
2
<?php
/**
3
4
5
 *
 * @package    mahara
 * @subpackage core
6
 * @author     Catalyst IT Ltd
7
8
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later
 * @copyright  For copyright information on Mahara, please see the README file distributed with this software.
9
 *
Penny Leach's avatar
Penny Leach committed
10
11
 */

12
13
defined('INTERNAL') || die();

14
15
16
17
if (defined('CLI') && php_sapi_name() != 'cli') {
    die();
}

Penny Leach's avatar
Penny Leach committed
18
$CFG = new StdClass;
Son Nguyen's avatar
Son Nguyen committed
19
$CFG->docroot = dirname(__FILE__) . DIRECTORY_SEPARATOR;
20
21
22
//array containing site options from database that are overrided by $CFG
$OVERRIDDEN = array();

Nigel McNie's avatar
Nigel McNie committed
23
24
// Figure out our include path
if (!empty($_SERVER['MAHARA_LIBDIR'])) {
25
    $CFG->libroot = $_SERVER['MAHARA_LIBDIR'];
Penny Leach's avatar
Penny Leach committed
26
}
Nigel McNie's avatar
Nigel McNie committed
27
else {
Son Nguyen's avatar
Son Nguyen committed
28
    $CFG->libroot = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR;
Nigel McNie's avatar
Nigel McNie committed
29
}
30
set_include_path($CFG->libroot . PATH_SEPARATOR . $CFG->libroot . 'pear/' . PATH_SEPARATOR . get_include_path());
Penny Leach's avatar
Penny Leach committed
31

32
// Set up error handling
Nigel McNie's avatar
Nigel McNie committed
33
require('errors.php');
34

35
if (!is_readable($CFG->docroot . 'config.php')) {
36
37
38
39
    // @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
40
41
}

42
43
init_performance_info();

44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// 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
61
62
63
64
if (function_exists('libxml_disable_entity_loader')) {
    libxml_disable_entity_loader(true);
}

65
require($CFG->docroot . 'config.php');
Nigel McNie's avatar
Nigel McNie committed
66
$CFG = (object)array_merge((array)$cfg, (array)$CFG);
67
68
require_once('config-defaults.php');
$CFG = (object)array_merge((array)$cfg, (array)$CFG);
Penny Leach's avatar
Penny Leach committed
69

70
71
72
73
// xmldb stuff
$CFG->xmldbdisablenextprevchecking = true;
$CFG->xmldbdisablecommentchecking = true;

74
75
76
77
// ensure directorypermissions is set
if (empty($CFG->directorypermissions)) {
    $CFG->directorypermissions = 0700;
}
Hugh Davenport's avatar
Hugh Davenport committed
78
$CFG->filepermissions = $CFG->directorypermissions & 0666;
79

Son Nguyen's avatar
Son Nguyen committed
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
if (defined('BEHAT_SITE_RUNNING')) {
    // We already switched to behat test site previously.

}
else if (!empty($CFG->behat_wwwroot) ||empty($CFG->behat_dataroot) || !empty($CFG->behat_dbprefix)) {
    // The behat is configured on this server, we need to find out if this is the behat test
    // site based on the URL used for access.
    require_once($CFG->docroot . '/testing/frameworks/behat/lib.php');
    if (behat_is_test_site()) {
        // Checking the integrity of the provided $CFG->behat_* vars and the
        // selected wwwroot to prevent conflicts with production and phpunit environments.
        behat_check_config_vars();

        // Check that the directory does not contains other things.
        if (!file_exists("$CFG->behat_dataroot/behattestdir.txt")) {
            if ($dh = opendir($CFG->behat_dataroot)) {
                while (($file = readdir($dh)) !== false) {
                    if ($file === 'behat' || $file === '.' || $file === '..' || $file === '.DS_Store') {
                        continue;
                    }
                    behat_error(BEHAT_EXITCODE_CONFIG, '$CFG->behat_dataroot directory is not empty, ensure this is the directory where you want to install behat test dataroot');
                }
                closedir($dh);
                unset($dh);
                unset($file);
            }

            if (defined('BEHAT_UTIL')) {
                // Now we create dataroot directory structure for behat tests.
                testing_initdataroot($CFG->behat_dataroot, 'behat');
            } else {
                behat_error(BEHAT_EXITCODE_INSTALL);
            }
        }

        if (!defined('BEHAT_UTIL') && !defined('BEHAT_TEST')) {
            // Somebody tries to access test site directly, tell them if not enabled.
            if (!file_exists($CFG->behat_dataroot . '/behat/test_environment_enabled.txt')) {
                behat_error(BEHAT_EXITCODE_CONFIG, 'Behat is configured but not enabled on this test site.');
            }
        }

        // Constant used to inform that the behat test site is being used,
        // this includes all the processes executed by the behat CLI command like
        // the site reset, the steps executed by the browser drivers when simulating
        // a user session and a real session when browsing manually to $CFG->behat_wwwroot
        // like the browser driver does automatically.
        // Different from BEHAT_TEST as only this last one can perform CLI
        // actions like reset the site or use data generators.
        define('BEHAT_SITE_RUNNING', true);

        // Clean extra config.php settings.
        //behat_clean_init_config();

        // Now we can begin switching $CFG->X for $CFG->behat_X.
        $CFG->wwwroot = $CFG->behat_wwwroot;
        $CFG->dbprefix = $CFG->behat_dbprefix;
        $CFG->dataroot = $CFG->behat_dataroot;
    }
}

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

// Set default configs that are dependent on the docroot and dataroot
if (empty($CFG->sessionpath)) {
    $CFG->sessionpath = $CFG->dataroot . 'sessions';
}

Aaron Wells's avatar
Aaron Wells committed
151
152
153
154
155
// Now that we've loaded the configs, we can override the default error settings
// from errors.php
$errorlevel = $CFG->error_reporting;
error_reporting($errorlevel);
set_error_handler('error', $errorlevel);
156
// core libraries
157
require('mahara.php');
158
ensure_sanity();
159
require('dml.php');
160
require('web.php');
Penny Leach's avatar
Penny Leach committed
161
require('user.php');
162
163
164
165
166
// Optional local/lib.php file
$locallib = get_config('docroot') . 'local/lib.php';
if (file_exists($locallib)) {
    require($locallib);
}
167

Nigel McNie's avatar
Nigel McNie committed
168
// Database access functions
169
170
require('adodb/adodb-exceptions.inc.php');
require('adodb/adodb.inc.php');
171

Nigel McNie's avatar
Nigel McNie committed
172
173
174
175
176
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();
177

178
    // Transform $CFG->dbtype into the name of the ADODB driver we will use
179
    if (is_postgres()) {
180
        $CFG->dbtype = 'postgres';
181
182
    }
    else if (is_mysql()) {
183
184
185
186
187
188
189
        // 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';
        }
190
    }
191

192
    $db = ADONewConnection($CFG->dbtype);
193
194
195
    if (empty($CFG->dbhost)) {
        $CFG->dbhost = '';
    }
196
    // The ADODB connection function doesn't have a separate port argument, but the
197
    // postgres, mysql, and mysqli drivers all support a $this->dbport field.
198
199
    if (!empty($CFG->dbport)) {
        $db->port = $CFG->dbport;
Nigel McNie's avatar
Nigel McNie committed
200
201
202
    }
    if (!empty($CFG->dbpersist)) {    // Use persistent connection (default)
        $dbconnected = $db->PConnect($CFG->dbhost,$CFG->dbuser,$CFG->dbpass,$CFG->dbname);
Aaron Wells's avatar
Aaron Wells committed
203
    }
204
    else {                                                     // Use single connection
Nigel McNie's avatar
Nigel McNie committed
205
206
        $dbconnected = $db->Connect($CFG->dbhost,$CFG->dbuser,$CFG->dbpass,$CFG->dbname);
    }
207

208
209
210
    // Now we have a connection, verify the server is a new enough version
    $dbversion = $db->ServerInfo();
    if (is_postgres()) {
211
        $okversion = '8.3';
212
213
214
215
216
217
218
219
220
221
        $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));
    }

222
223
    $db->SetFetchMode(ADODB_FETCH_ASSOC);
    configure_dbconnection();
224
    ensure_internal_plugins_exist();
225

Nigel McNie's avatar
Nigel McNie committed
226
    ob_end_clean();
227
}
Nigel McNie's avatar
Nigel McNie committed
228
catch (Exception $e) {
229
230
231
    if ($e instanceof ConfigSanityException) {
        throw $e;
    }
232
    $errormessage = ob_get_contents();
233
234
235
    if (!$errormessage) {
        $errormessage = $e->getMessage();
    }
236
    ob_end_clean();
237
238
    $errormessage = get_string('dbconnfailed', 'error') . $errormessage;
    throw new ConfigSanityException($errormessage);
239
}
240
try {
241
    db_ignore_sql_exceptions(true);
242
    load_config();
243
    db_ignore_sql_exceptions(false);
Aaron Wells's avatar
Aaron Wells committed
244
}
245
catch (SQLException $e) {
246
    db_ignore_sql_exceptions(false);
247
}
248

249
250
// Make sure wwwroot is set and available, either in the database or in the
// config file. Cron requires it when sending out forums emails.
251
if (!isset($CFG->wwwroot) && isset($_SERVER['HTTP_HOST'])) {
252
    $proto = (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) != 'off') ? 'https://' : 'http://';
253
    $host  =  (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : $_SERVER['HTTP_HOST'];
254
255
256
257
    if (false !== strpos($host, ',')) {
        list($host) = explode(',', $host);
        $host = trim($host);
    }
258
259
260
261
    $path = '';
    if (strpos(dirname(__FILE__), strlen($_SERVER['DOCUMENT_ROOT'])) === 0) {
        $path  = substr(dirname(__FILE__), strlen($_SERVER['DOCUMENT_ROOT']));
    }
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
    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 ++;
        }
    }
279
    if ($path) {
280
        $path = str_replace('\\', '/', $path);  // windows
281
282
283
        if (substr($path, 0, 1) != '/') {
            $path = '/' . $path;
        }
284
        $path .= '/';
285
286
    } else {
        $path = '/';
287
    }
288
289
290
291
292
293
294
295
    $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;
    }
296
}
297
298
299
300
301
if (isset($CFG->wwwroot)) {
    if (substr($CFG->wwwroot, -1, 1) != '/') {
        $CFG->wwwroot .= '/';
    }
}
302

303
304
305
306
307
308
309
// 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'];
}

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

315
// Make sure that we are using ssl if wwwroot expects us to do so
316
317
if ($CFG->sslproxy === false && isset($_SERVER['REMOTE_ADDR']) && (!isset($_SERVER['HTTPS']) || strtolower($_SERVER['HTTPS']) == 'off') &&
    parse_url($CFG->wwwroot, PHP_URL_SCHEME) === 'https'){
318
319
    redirect(get_relative_script_path());
}
320
if (!isset($CFG->noreplyaddress) && isset($_SERVER['HTTP_HOST'])) {
321
322
323
324
325
326
327
    $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;
328
329
330
331
332
333
334
335
336
    try {
        set_config('noreplyaddress', $noreplyaddress);
    }
    catch (Exception $e) {
        // Do nothing again, same reason as above
        $CFG->noreplyaddress = $noreplyaddress;
    }
}

Aaron Wells's avatar
Aaron Wells committed
337
338
if (!get_config('theme')) {
    // if it's not set, we're probably not installed,
Penny Leach's avatar
Penny Leach committed
339
    // so set it in $CFG directly rather than the db which doesn't yet exist
Aaron Wells's avatar
Aaron Wells committed
340
    $CFG->theme = 'default';
Penny Leach's avatar
Penny Leach committed
341
342
}

Aaron Wells's avatar
Aaron Wells committed
343
if (defined('INSTALLER')) {
344
345
346
347
    // Custom themes sometimes cause upgrades to fail.
    $CFG->theme = 'default';
}

348
349
350
351
352
353
354
355
356
// Make sure the search plugin is configured
if (!get_config('searchplugin')) {
    try {
        set_config('searchplugin', 'internal');
    }
    catch (Exception $e) {
        $CFG->searchplugin = 'internal';
    }
}
357
358
359
360
361
362
363
364
365
$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);

366
367
368
369
370
371
372
373
374
375
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;
}

376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
if (get_config('installed')) {
    // Check whether core upgrades need to be done. If so, "close" the site
    // from logins
    require(get_config('libroot') . 'version.php');
    $upgradeavailable = $config->version > get_config('version');
    $disablelogin  = $config->disablelogin;
    $cfgsiteclosed = get_config('siteclosed');
    if ($upgradeavailable != $cfgsiteclosed) {
        set_config('siteclosed', $upgradeavailable);
        set_config('disablelogin', $disablelogin);
    }
}

// If we're in the middle of an upgrade, quit the cron now.
$siteclosedforupgrade = get_config('siteclosed');
if ($siteclosedforupgrade && defined('CRON')) {
    exit("Site closed for upgrade.\n");
}

Son Nguyen's avatar
Son Nguyen committed
395
396
397
398
399
400
401
402
403
404
if (!defined('CLI')) {
    header('Content-type: text/html; charset=UTF-8');
    // 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');

    // Prevent clickjacking through iframe tags
    header('X-Frame-Options: SAMEORIGIN');
}
405

406
407
// Only do authentication once we know the page theme, so that the login form
// can have the correct theming.
408
require_once('auth/lib.php');
409
410
$SESSION = Session::singleton();
$USER    = new LiveUser();
411

412
413
414
415
if (function_exists('local_init_user')) {
    local_init_user();
}

416
417
418
419
420
421
422
423
424
// 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());
}

425
426
427
if ($siteclosedforupgrade && $USER->admin) {
    if (get_config('disablelogin')) {
        $USER->logout();
428
    }
429
430
431
432
433
    else if (!defined('INSTALLER')) {
        redirect('/admin/upgrade.php');
    }
}

434
435
436
437
438
439
440
// The installer does its own auth_setup checking, because some upgrades may
// break logging in and so need to allow no logins.
// Command-line scripts obviously have no logged-in user.
if (!defined('INSTALLER') && !defined('CLI') && !defined('CRON')) {
    auth_setup();
}

441
442
443
444
445
446
447
$siteclosed = $siteclosedforupgrade || get_config('siteclosedbyadmin');
if ($siteclosed && !$USER->admin) {
    if ($USER->is_logged_in()) {
        $USER->logout();
    }
    if (!defined('HOME') && !defined('INSTALLER')) {
        redirect();
448
449
450
    }
}

451
// check to see if we're installed...
452
453
454
if (!get_config('installed')) {
    ensure_install_sanity();

455
    $scriptfilename = str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']);
Son Nguyen's avatar
Son Nguyen committed
456
457
    if (!defined('CLI')
    && false === strpos($scriptfilename, 'admin/index.php')
458
    && false === strpos($scriptfilename, 'admin/upgrade.php')
459
460
461
    && false === strpos($scriptfilename, 'admin/upgrade.json.php')
    && false === strpos($scriptfilename, 'admin/cli/install.php')
    && false === strpos($scriptfilename, 'admin/cli/upgrade.php')) {
462
        redirect('/admin/index.php');
463
    }
464
465
}

Clare Lenihan's avatar
Clare Lenihan committed
466
if (defined('JSON') && !defined('NOSESSKEY')) {
467
    $sesskey = param_variable('sesskey', null);
468
469
    global $USER;
    if ($sesskey === null || $USER->get('sesskey') != $sesskey) {
470
        $USER->logout();
471
        json_reply('global', get_string('invalidsesskey'), 1);
472
    }
473
}
474
$mobile_detection_done = $SESSION->get('mobile_detection');
475
// Device detection
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
if (!$mobile_detection_done) {
    if (get_config('installed') && get_account_preference($USER->get('id'), 'devicedetection')) {
        require_once(get_config('libroot') . 'mobile_detect/Mobile_Detect.php');
        $detect = new Mobile_Detect();
        $isMobile = $detect->isMobile();
        $isTablet = $detect->isTablet();
        $SESSION->set('handheld_device', $isMobile);
        $SESSION->set('mobile', $isTablet ? false : $isMobile);
        $SESSION->set('tablet', $isTablet);
    }
    else {
        $SESSION->set('handheld_device', false);
        $SESSION->set('mobile', false);
        $SESSION->set('tablet', false);
    }
    $SESSION->set('mobile_detection', true);
492
}
493

494
// Run modules bootstrap code.
495
496
497
498
499
500
501
502
503
if (!defined('INSTALLER')) {
    // make sure the table exists if upgrading from older version
    require_once('ddl.php');
    if (table_exists(new XMLDBTable('module_installed'))) {
        if ($plugins = plugins_installed('module')) {
            foreach ($plugins as &$plugin) {
                if (safe_require_plugin('module', $plugin->name)) {
                    call_static_method(generate_class_name('module', $plugin->name), 'bootstrap');
                }
504
505
506
507
            }
        }
    }
}
508
509
510
511
/*
 * Initializes our performance info early.
 *
 * Pairs up with get_performance_info() which is actually
Aaron Wells's avatar
Aaron Wells committed
512
513
 * in lib/mahara.php. This function is here so that we can
 * call it before all the libs are pulled in.
514
515
516
517
518
519
 *
 * @uses $PERF
 */
function init_performance_info() {

    global $PERF;
Aaron Wells's avatar
Aaron Wells committed
520

521
    $PERF = new StdClass;
522
    $PERF->dbreads = $PERF->dbwrites = $PERF->dbcached = 0;
523
524
525
526
527
528
529
530
    $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')) {
Aaron Wells's avatar
Aaron Wells committed
531
        $PERF->startposixtimes = posix_times();
532
533
    }
}