Proyectos de Subversion Moodle

Rev

Rev 11 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
 
3
// This file is part of Moodle - http://moodle.org/
4
//
5
// Moodle is free software: you can redistribute it and/or modify
6
// it under the terms of the GNU General Public License as published by
7
// the Free Software Foundation, either version 3 of the License, or
8
// (at your option) any later version.
9
//
10
// Moodle is distributed in the hope that it will be useful,
11
// but WITHOUT ANY WARRANTY; without even the implied warranty of
12
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
// GNU General Public License for more details.
14
//
15
// You should have received a copy of the GNU General Public License
16
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17
 
18
/**
19
 * setup.php - Sets up sessions, connects to databases and so on
20
 *
21
 * Normally this is only called by the main config.php file
22
 * Normally this file does not need to be edited.
23
 *
24
 * @package    core
25
 * @subpackage lib
26
 * @copyright  1999 onwards Martin Dougiamas  {@link http://moodle.com}
27
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28
 */
29
 
30
/**
31
 * Holds the core settings that affect how Moodle works. Some of its fields
32
 * are set in config.php, and the rest are loaded from the config table.
33
 *
34
 * Some typical settings in the $CFG global:
35
 *  - $CFG->wwwroot  - Path to moodle index directory in url format.
36
 *  - $CFG->dataroot - Path to moodle data files directory on server's filesystem.
37
 *  - $CFG->dirroot  - Path to moodle's library folder on server's filesystem.
38
 *  - $CFG->libdir   - Path to moodle's library folder on server's filesystem.
39
 *  - $CFG->backuptempdir  - Path to moodle's backup temp file directory on server's filesystem.
40
 *  - $CFG->tempdir  - Path to moodle's temp file directory on server's filesystem.
41
 *  - $CFG->cachedir - Path to moodle's cache directory on server's filesystem (shared by cluster nodes).
42
 *  - $CFG->localcachedir - Path to moodle's local cache directory (not shared by cluster nodes).
43
 *  - $CFG->localrequestdir - Path to moodle's local temp request directory (not shared by cluster nodes).
44
 *
45
 * @global object $CFG
46
 * @name $CFG
47
 */
48
global $CFG; // this should be done much earlier in config.php before creating new $CFG instance
49
 
50
if (!isset($CFG)) {
51
    if (defined('PHPUNIT_TEST') and PHPUNIT_TEST) {
52
        echo('There is a missing "global $CFG;" at the beginning of the config.php file.'."\n");
53
        exit(1);
54
    } else {
55
        // this should never happen, maybe somebody is accessing this file directly...
56
        exit(1);
57
    }
58
}
59
 
60
// We can detect real dirroot path reliably since PHP 4.0.2,
61
// it can not be anything else, there is no point in having this in config.php
62
$CFG->dirroot = dirname(__DIR__);
63
 
64
// File permissions on created directories in the $CFG->dataroot
65
if (!isset($CFG->directorypermissions)) {
66
    $CFG->directorypermissions = 02777;      // Must be octal (that's why it's here)
67
}
68
if (!isset($CFG->filepermissions)) {
69
    $CFG->filepermissions = ($CFG->directorypermissions & 0666); // strip execute flags
70
}
71
// Better also set default umask because developers often forget to include directory
72
// permissions in mkdir() and chmod() after creating new files.
73
if (!isset($CFG->umaskpermissions)) {
74
    $CFG->umaskpermissions = (($CFG->directorypermissions & 0777) ^ 0777);
75
}
76
umask($CFG->umaskpermissions);
77
 
78
if (defined('BEHAT_SITE_RUNNING')) {
79
    // We already switched to behat test site previously.
80
 
81
} else if (!empty($CFG->behat_wwwroot) or !empty($CFG->behat_dataroot) or !empty($CFG->behat_prefix)) {
82
    // The behat is configured on this server, we need to find out if this is the behat test
83
    // site based on the URL used for access.
84
    require_once(__DIR__ . '/../lib/behat/lib.php');
85
 
86
    // Update config variables for parallel behat runs.
87
    behat_update_vars_for_process();
88
 
89
    // If behat is being installed for parallel run, then we modify params for parallel run only.
90
    if (behat_is_test_site() && !(defined('BEHAT_PARALLEL_UTIL') && empty($CFG->behatrunprocess))) {
91
        clearstatcache();
92
 
93
        // Checking the integrity of the provided $CFG->behat_* vars and the
94
        // selected wwwroot to prevent conflicts with production and phpunit environments.
95
        behat_check_config_vars();
96
 
97
        // Check that the directory does not contains other things.
98
        if (!file_exists("$CFG->behat_dataroot/behattestdir.txt")) {
99
            if ($dh = opendir($CFG->behat_dataroot)) {
100
                while (($file = readdir($dh)) !== false) {
101
                    if ($file === 'behat' or $file === '.' or $file === '..' or $file === '.DS_Store' or is_numeric($file)) {
102
                        continue;
103
                    }
104
                    behat_error(BEHAT_EXITCODE_CONFIG, "$CFG->behat_dataroot directory is not empty, ensure this is the " .
105
                        "directory where you want to install behat test dataroot");
106
                }
107
                closedir($dh);
108
                unset($dh);
109
                unset($file);
110
            }
111
 
112
            if (defined('BEHAT_UTIL')) {
113
                // Now we create dataroot directory structure for behat tests.
114
                testing_initdataroot($CFG->behat_dataroot, 'behat');
115
            } else {
116
                behat_error(BEHAT_EXITCODE_INSTALL);
117
            }
118
        }
119
 
120
        if (!defined('BEHAT_UTIL') and !defined('BEHAT_TEST')) {
121
            // Somebody tries to access test site directly, tell them if not enabled.
122
            $behatdir = preg_replace("#[/|\\\]" . BEHAT_PARALLEL_SITE_NAME . "\d{0,}$#", '', $CFG->behat_dataroot);
123
            if (!file_exists($behatdir . '/test_environment_enabled.txt')) {
124
                behat_error(BEHAT_EXITCODE_CONFIG, 'Behat is configured but not enabled on this test site.');
125
            }
126
        }
127
 
128
        // Constant used to inform that the behat test site is being used,
129
        // this includes all the processes executed by the behat CLI command like
130
        // the site reset, the steps executed by the browser drivers when simulating
131
        // a user session and a real session when browsing manually to $CFG->behat_wwwroot
132
        // like the browser driver does automatically.
133
        // Different from BEHAT_TEST as only this last one can perform CLI
134
        // actions like reset the site or use data generators.
135
        define('BEHAT_SITE_RUNNING', true);
136
 
137
        // Clean extra config.php settings.
138
        behat_clean_init_config();
139
 
140
        // Now we can begin switching $CFG->X for $CFG->behat_X.
141
        $CFG->wwwroot = $CFG->behat_wwwroot;
142
        $CFG->prefix = $CFG->behat_prefix;
143
        $CFG->dataroot = $CFG->behat_dataroot;
144
 
145
        // And we do the same with the optional ones.
146
        $allowedconfigoverride = ['dbname', 'dbuser', 'dbpass', 'dbhost'];
147
        foreach ($allowedconfigoverride as $config) {
148
            $behatconfig = 'behat_' . $config;
149
            if (!isset($CFG->$behatconfig)) {
150
                continue;
151
            }
152
            $CFG->$config = $CFG->$behatconfig;
153
        }
154
    }
155
}
156
 
157
// Set default warn runtime.
158
if (!isset($CFG->taskruntimewarn)) {
159
    $CFG->taskruntimewarn = 12 * 60 * 60;
160
}
161
 
162
// Set default error runtime.
163
if (!isset($CFG->taskruntimeerror)) {
164
    $CFG->taskruntimeerror = 24 * 60 * 60;
165
}
166
 
167
// Normalise dataroot - we do not want any symbolic links, trailing / or any other weirdness there
168
if (!isset($CFG->dataroot)) {
169
    if (isset($_SERVER['REMOTE_ADDR'])) {
170
        header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error ');
171
    }
172
    echo('Fatal error: $CFG->dataroot is not specified in config.php! Exiting.'."\n");
173
    exit(1);
174
}
175
$CFG->dataroot = realpath($CFG->dataroot);
176
if ($CFG->dataroot === false) {
177
    if (isset($_SERVER['REMOTE_ADDR'])) {
178
        header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error ');
179
    }
180
    echo('Fatal error: $CFG->dataroot is not configured properly, directory does not exist or is not accessible! Exiting.'."\n");
181
    exit(1);
182
} else if (!is_writable($CFG->dataroot)) {
183
    if (isset($_SERVER['REMOTE_ADDR'])) {
184
        header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error ');
185
    }
186
    echo('Fatal error: $CFG->dataroot is not writable, admin has to fix directory permissions! Exiting.'."\n");
187
    exit(1);
188
}
189
 
190
// wwwroot is mandatory
191
if (!isset($CFG->wwwroot) or $CFG->wwwroot === 'http://example.com/moodle') {
192
    if (isset($_SERVER['REMOTE_ADDR'])) {
193
        header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error ');
194
    }
195
    echo('Fatal error: $CFG->wwwroot is not configured! Exiting.'."\n");
196
    exit(1);
197
}
198
 
1441 ariadna 199
// The router configuration is mandatory.
200
$CFG->routerconfigured = !empty($CFG->routerconfigured);
201
 
1 efrain 202
// Make sure there is some database table prefix.
203
if (!isset($CFG->prefix)) {
204
    $CFG->prefix = '';
205
}
206
 
207
// Define admin directory
208
if (!isset($CFG->admin)) {   // Just in case it isn't defined in config.php
209
    $CFG->admin = 'admin';   // This is relative to the wwwroot and dirroot
210
}
211
 
212
// Set up some paths.
213
$CFG->libdir = $CFG->dirroot .'/lib';
214
 
215
// Allow overriding of tempdir but be backwards compatible
216
if (!isset($CFG->tempdir)) {
217
    $CFG->tempdir = $CFG->dataroot . DIRECTORY_SEPARATOR . "temp";
218
}
219
 
220
// Allow overriding of backuptempdir but be backwards compatible
221
if (!isset($CFG->backuptempdir)) {
222
    $CFG->backuptempdir = "$CFG->tempdir/backup";
223
}
224
 
225
// Allow overriding of cachedir but be backwards compatible
226
if (!isset($CFG->cachedir)) {
227
    $CFG->cachedir = "$CFG->dataroot/cache";
228
}
229
 
230
// Allow overriding of localcachedir.
231
if (!isset($CFG->localcachedir)) {
232
    $CFG->localcachedir = "$CFG->dataroot/localcache";
233
}
234
 
235
// Allow overriding of localrequestdir.
236
if (!isset($CFG->localrequestdir)) {
237
    $CFG->localrequestdir = sys_get_temp_dir() . '/requestdir';
238
}
239
 
240
// Location of all languages except core English pack.
241
if (!isset($CFG->langotherroot)) {
242
    $CFG->langotherroot = $CFG->dataroot.'/lang';
243
}
244
 
245
// Location of local lang pack customisations (dirs with _local suffix).
246
if (!isset($CFG->langlocalroot)) {
247
    $CFG->langlocalroot = $CFG->dataroot.'/lang';
248
}
249
 
250
// The current directory in PHP version 4.3.0 and above isn't necessarily the
251
// directory of the script when run from the command line. The require_once()
252
// would fail, so we'll have to chdir()
253
if (!isset($_SERVER['REMOTE_ADDR']) && isset($_SERVER['argv'][0])) {
254
    // do it only once - skip the second time when continuing after prevous abort
255
    if (!defined('ABORT_AFTER_CONFIG') and !defined('ABORT_AFTER_CONFIG_CANCEL')) {
256
        chdir(dirname($_SERVER['argv'][0]));
257
    }
258
}
259
 
260
// sometimes default PHP settings are borked on shared hosting servers, I wonder why they have to do that??
261
ini_set('precision', 14); // needed for upgrades and gradebook
11 efrain 262
ini_set('serialize_precision', -1); // Make float serialization consistent on all systems.
1 efrain 263
 
264
// Scripts may request no debug and error messages in output
265
// please note it must be defined before including the config.php script
266
// and in some cases you also need to set custom default exception handler
267
if (!defined('NO_DEBUG_DISPLAY')) {
268
    if (defined('AJAX_SCRIPT') and AJAX_SCRIPT) {
269
        // Moodle AJAX scripts are expected to return json data, any PHP notices or errors break it badly,
270
        // developers simply must learn to watch error log.
271
        define('NO_DEBUG_DISPLAY', true);
272
    } else {
273
        define('NO_DEBUG_DISPLAY', false);
274
    }
275
}
276
 
277
// Some scripts such as upgrade may want to prevent output buffering
278
if (!defined('NO_OUTPUT_BUFFERING')) {
279
    define('NO_OUTPUT_BUFFERING', false);
280
}
281
 
282
// PHPUnit tests need custom init
283
if (!defined('PHPUNIT_TEST')) {
284
    define('PHPUNIT_TEST', false);
285
}
286
 
287
// Performance tests needs to always display performance info, even in redirections;
288
// MDL_PERF_TEST is used in https://github.com/moodlehq/moodle-performance-comparison scripts.
289
if (!defined('MDL_PERF_TEST')) {
290
    define('MDL_PERF_TEST', false);
291
}
292
// Make sure all MDL_PERF* constants are always defined.
293
if (!defined('MDL_PERF')) {
294
    define('MDL_PERF', MDL_PERF_TEST);
295
}
296
if (!defined('MDL_PERFTOFOOT')) {
297
    define('MDL_PERFTOFOOT', MDL_PERF_TEST);
298
}
299
if (!defined('MDL_PERFTOLOG')) {
300
    define('MDL_PERFTOLOG', false);
301
}
302
if (!defined('MDL_PERFINC')) {
303
    define('MDL_PERFINC', false);
304
}
305
// Note that PHPUnit and Behat tests should pass with both MDL_PERF true and false.
306
 
307
// When set to true MUC (Moodle caching) will be disabled as much as possible.
308
// A special cache factory will be used to handle this situation and will use special "disabled" equivalents objects.
309
// This ensure we don't attempt to read or create the config file, don't use stores, don't provide persistence or
310
// storage of any kind.
311
if (!defined('CACHE_DISABLE_ALL')) {
312
    define('CACHE_DISABLE_ALL', false);
313
}
314
 
315
// When set to true MUC (Moodle caching) will not use any of the defined or default stores.
1441 ariadna 316
// The Cache API will continue to function however this will force the use of the dummy_cachestore so all requests
1 efrain 317
// will be interacting with a static property and will never go to the proper cache stores.
318
// Useful if you need to avoid the stores for one reason or another.
319
if (!defined('CACHE_DISABLE_STORES')) {
320
    define('CACHE_DISABLE_STORES', false);
321
}
322
 
323
// Servers should define a default timezone in php.ini, but if they don't then make sure no errors are shown.
324
date_default_timezone_set(@date_default_timezone_get());
325
 
326
// Detect CLI scripts - CLI scripts are executed from command line, do not have session and we do not want HTML in output
327
// In your new CLI scripts just add "define('CLI_SCRIPT', true);" before requiring config.php.
328
// Please note that one script can not be accessed from both CLI and web interface.
329
if (!defined('CLI_SCRIPT')) {
330
    define('CLI_SCRIPT', false);
331
}
332
if (defined('WEB_CRON_EMULATED_CLI')) {
333
    if (!isset($_SERVER['REMOTE_ADDR'])) {
334
        echo('Web cron can not be executed as CLI script any more, please use admin/cli/cron.php instead'."\n");
335
        exit(1);
336
    }
337
} else if (isset($_SERVER['REMOTE_ADDR'])) {
338
    if (CLI_SCRIPT) {
339
        echo('Command line scripts can not be executed from the web interface');
340
        exit(1);
341
    }
342
} else {
343
    if (!CLI_SCRIPT) {
344
        echo('Command line scripts must define CLI_SCRIPT before requiring config.php'."\n");
345
        exit(1);
346
    }
347
}
348
 
349
// All web service requests have WS_SERVER == true.
350
if (!defined('WS_SERVER')) {
351
    define('WS_SERVER', false);
352
}
353
 
354
// Detect CLI maintenance mode - this is useful when you need to mess with database, such as during upgrades
355
if (file_exists("$CFG->dataroot/climaintenance.html")) {
356
    if (!CLI_SCRIPT) {
357
        header($_SERVER['SERVER_PROTOCOL'] . ' 503 Moodle under maintenance');
358
        header('Status: 503 Moodle under maintenance');
359
        header('Retry-After: 300');
360
        header('Content-type: text/html; charset=utf-8');
361
        header('X-UA-Compatible: IE=edge');
362
        /// Headers to make it not cacheable and json
363
        header('Cache-Control: no-store, no-cache, must-revalidate');
364
        header('Cache-Control: post-check=0, pre-check=0', false);
365
        header('Pragma: no-cache');
366
        header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
367
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
368
        header('Accept-Ranges: none');
369
        readfile("$CFG->dataroot/climaintenance.html");
370
        die;
371
    } else {
372
        if (!defined('CLI_MAINTENANCE')) {
373
            define('CLI_MAINTENANCE', true);
374
        }
375
    }
376
} else {
377
    if (!defined('CLI_MAINTENANCE')) {
378
        define('CLI_MAINTENANCE', false);
379
    }
380
}
381
 
382
// Some core parts of Moodle may make use of language features not available in older PHP versions.s
383
// When this happens as part of our core bootstrap, we can end up having confusing and spurious error
384
// messages which are hard to diagnose.
385
// This check allows us to insert a very basic check for the absolute minimum version of PHP for the
386
// Moodle core to be able to load the environment and error pages.
387
// It should only be updated in these circumstances, not with every PHP version.
388
if (version_compare(PHP_VERSION, '8.1.0') < 0) {
389
    $phpversion = PHP_VERSION;
390
    // Do NOT localise - lang strings would not work here and we CAN NOT move it to later place.
391
    echo "Moodle 4.4 or later requires at least PHP 8.1 (currently using version $phpversion).\n";
392
    echo "Some servers may have multiple PHP versions installed, are you using the correct executable?\n";
393
    exit(1);
394
}
395
 
396
// Detect ajax scripts - they are similar to CLI because we can not redirect, output html, etc.
397
if (!defined('AJAX_SCRIPT')) {
398
    define('AJAX_SCRIPT', false);
399
}
400
 
401
// Exact version of currently used yui2 and 3 library.
402
$CFG->yui2version = '2.9.0';
403
$CFG->yui3version = '3.18.1';
404
 
405
// Patching the upstream YUI release.
406
// If we need to patch a YUI modules between official YUI releases, the yuipatchlevel will need to be manually
407
// incremented here. The module will also need to be listed in the yuipatchedmodules.
408
// When upgrading to a subsequent version of YUI, these should be reset back to 0 and an empty array.
409
$CFG->yuipatchlevel = 0;
410
$CFG->yuipatchedmodules = array(
411
);
412
 
413
if (!empty($CFG->disableonclickaddoninstall)) {
414
    // This config.php flag has been merged into another one.
415
    $CFG->disableupdateautodeploy = true;
416
}
417
 
418
// Store settings from config.php in array in $CFG - we can use it later to detect problems and overrides.
419
if (!isset($CFG->config_php_settings)) {
420
    $CFG->config_php_settings = (array)$CFG;
421
    // Forced plugin settings override values from config_plugins table.
422
    unset($CFG->config_php_settings['forced_plugin_settings']);
423
    if (!isset($CFG->forced_plugin_settings)) {
424
        $CFG->forced_plugin_settings = array();
425
    }
426
}
427
 
428
if (isset($CFG->debug)) {
429
    $CFG->debug = (int)$CFG->debug;
430
} else {
431
    $CFG->debug = 0;
432
}
1441 ariadna 433
$CFG->debugdeveloper = (($CFG->debug & E_ALL) === E_ALL); // DEBUG_DEVELOPER is not available yet.
1 efrain 434
 
435
if (!defined('MOODLE_INTERNAL')) { // Necessary because cli installer has to define it earlier.
436
    /** Used by library scripts to check they are being called by Moodle. */
437
    define('MOODLE_INTERNAL', true);
438
}
439
 
1441 ariadna 440
// The core_component class can be used in any scripts, it does not need anything else.
1 efrain 441
require_once($CFG->libdir .'/classes/component.php');
442
 
443
/**
444
 * Database connection. Used for all access to the database.
445
 * @global moodle_database $DB
446
 * @name $DB
447
 */
448
global $DB;
449
 
450
/**
451
 * Moodle's wrapper round PHP's $_SESSION.
452
 *
453
 * @global object $SESSION
454
 * @name $SESSION
455
 */
456
global $SESSION;
457
 
458
/**
459
 * Holds the user table record for the current user. Will be the 'guest'
460
 * user record for people who are not logged in.
461
 *
462
 * $USER is stored in the session.
463
 *
464
 * Items found in the user record:
465
 *  - $USER->email - The user's email address.
466
 *  - $USER->id - The unique integer identified of this user in the 'user' table.
467
 *  - $USER->email - The user's email address.
468
 *  - $USER->firstname - The user's first name.
469
 *  - $USER->lastname - The user's last name.
470
 *  - $USER->username - The user's login username.
471
 *  - $USER->secret - The user's ?.
472
 *  - $USER->lang - The user's language choice.
473
 *
474
 * @global object $USER
475
 * @name $USER
476
 */
477
global $USER;
478
 
479
/**
480
 * Frontpage course record
481
 */
482
global $SITE;
483
 
484
/**
485
 * A central store of information about the current page we are
486
 * generating in response to the user's request.
487
 *
488
 * @global moodle_page $PAGE
489
 * @name $PAGE
490
 */
491
global $PAGE;
492
 
493
/**
494
 * The current course. An alias for $PAGE->course.
495
 * @global object $COURSE
496
 * @name $COURSE
497
 */
498
global $COURSE;
499
 
500
/**
501
 * $OUTPUT is an instance of core_renderer or one of its subclasses. Use
502
 * it to generate HTML for output.
503
 *
504
 * $OUTPUT is initialised the first time it is used. See {@link bootstrap_renderer}
505
 * for the magic that does that. After $OUTPUT has been initialised, any attempt
506
 * to change something that affects the current theme ($PAGE->course, logged in use,
507
 * httpsrequried ... will result in an exception.)
508
 *
509
 * Please note the $OUTPUT is replacing the old global $THEME object.
510
 *
511
 * @global object $OUTPUT
512
 * @name $OUTPUT
513
 */
514
global $OUTPUT;
515
 
516
/**
517
 * Full script path including all params, slash arguments, scheme and host.
518
 *
519
 * Note: Do NOT use for getting of current page URL or detection of https,
520
 * instead use $PAGE->url or is_https().
521
 *
522
 * @global string $FULLME
523
 * @name $FULLME
524
 */
525
global $FULLME;
526
 
527
/**
528
 * Script path including query string and slash arguments without host.
529
 * @global string $ME
530
 * @name $ME
531
 */
532
global $ME;
533
 
534
/**
535
 * $FULLME without slasharguments and query string.
536
 * @global string $FULLSCRIPT
537
 * @name $FULLSCRIPT
538
 */
539
global $FULLSCRIPT;
540
 
541
/**
542
 * Relative moodle script path '/course/view.php'
543
 * @global string $SCRIPT
544
 * @name $SCRIPT
545
 */
546
global $SCRIPT;
547
 
548
// The httpswwwroot has been deprecated, we keep it as an alias for backwards compatibility with plugins only.
549
$CFG->httpswwwroot = $CFG->wwwroot;
550
 
1441 ariadna 551
// We have to call this always before starting session because it discards headers!
552
if (NO_OUTPUT_BUFFERING) {
553
    // Try to disable all output buffering and purge all headers.
554
    $olddebug = error_reporting(0);
1 efrain 555
 
1441 ariadna 556
    // Disable compression, it would prevent closing of buffers.
557
    if ($outputcompression = ini_get('zlib.output_compression')) {
558
        switch(strtolower($outputcompression)) {
559
            case 'on':
560
            case '1':
561
                ini_set('zlib.output_compression', 'Off');
562
                break;
563
        }
564
    }
565
 
566
    // Try to flush everything all the time.
567
    ob_implicit_flush(true);
568
 
569
    // Close all buffers if possible and discard any existing output.
570
    // This can actually work around some whitespace problems in config.php.
571
    while (ob_get_level()) {
572
        if (!ob_end_clean()) {
573
            // Prevent infinite loop when buffer can not be closed.
574
            break;
575
        }
576
    }
577
 
578
    // Disable any other output handlers.
579
    ini_set('output_handler', '');
580
 
581
    error_reporting($olddebug);
582
 
583
    // Disable buffering in nginx.
584
    header('X-Accel-Buffering: no');
1 efrain 585
}
586
 
1441 ariadna 587
// Point pear include path to moodles lib/pear so that includes and requires will search there for files before anywhere else
588
// the problem is that we need specific version of quickforms and hacked excel files :-(.
589
ini_set('include_path', $CFG->libdir . '/pear' . PATH_SEPARATOR . ini_get('include_path'));
590
 
591
// Register our classloader.
592
\core\component::register_autoloader();
593
 
594
// Early profiling start, based exclusively on config.php $CFG settings
595
if (!empty($CFG->earlyprofilingenabled) && !defined('ABORT_AFTER_CONFIG_CANCEL')) {
596
    require_once($CFG->libdir . '/xhprof/xhprof_moodle.php');
597
    profiling_start();
598
}
599
 
600
// Special support for highly optimised scripts that do not need libraries and DB connection.
601
if (defined('ABORT_AFTER_CONFIG')) {
602
    if (!defined('ABORT_AFTER_CONFIG_CANCEL')) {
603
        // Hide debugging if not enabled in config.php - we do not want to disclose sensitive info.
604
        error_reporting($CFG->debug);
605
        if (NO_DEBUG_DISPLAY) {
606
            // Some parts of Moodle cannot display errors and debug at all.
607
            ini_set('display_errors', '0');
608
            ini_set('log_errors', '1');
609
        } else if (empty($CFG->debugdisplay)) {
610
            ini_set('display_errors', '0');
611
            ini_set('log_errors', '1');
612
        } else {
613
            ini_set('display_errors', '1');
614
        }
615
        require_once("$CFG->dirroot/lib/configonlylib.php");
616
        return;
617
    }
618
}
619
 
620
require_once($CFG->libdir .'/setuplib.php');        // Functions that MUST be loaded first.
621
 
622
// Load up standard libraries.
623
require_once($CFG->libdir .'/filterlib.php');       // Functions for filtering test as it is output.
624
require_once($CFG->libdir .'/ajax/ajaxlib.php');    // Functions for managing our use of JavaScript and YUI.
625
require_once($CFG->libdir .'/weblib.php');          // Functions relating to HTTP and content.
626
require_once($CFG->libdir .'/outputlib.php');       // Functions for generating output.
627
require_once($CFG->libdir .'/navigationlib.php');   // Class for generating Navigation structure.
628
require_once($CFG->libdir .'/dmllib.php');          // Database access.
629
require_once($CFG->libdir .'/datalib.php');         // Legacy lib with a big-mix of functions..
630
require_once($CFG->libdir .'/accesslib.php');       // Access control functions.
631
require_once($CFG->libdir .'/deprecatedlib.php');   // Deprecated functions included for backward compatibility.
632
require_once($CFG->libdir .'/moodlelib.php');       // Other general-purpose functions.
633
require_once($CFG->libdir .'/enrollib.php');        // Enrolment related functions.
634
require_once($CFG->libdir .'/pagelib.php');         // Library that defines the moodle_page class, used for $PAGE.
635
require_once($CFG->libdir .'/blocklib.php');        // Library for controlling blocks.
636
require_once($CFG->libdir .'/grouplib.php');        // Groups functions.
637
require_once($CFG->libdir .'/sessionlib.php');      // All session and cookie related stuff.
638
require_once($CFG->libdir .'/editorlib.php');       // All text editor related functions and classes.
639
require_once($CFG->libdir .'/messagelib.php');      // Messagelib functions.
640
require_once($CFG->libdir .'/modinfolib.php');      // Cached information on course-module instances.
641
 
642
// Increase memory limits if possible.
1 efrain 643
raise_memory_limit(MEMORY_STANDARD);
644
 
645
// Time to start counting
646
init_performance_info();
647
 
648
// Put $OUTPUT in place, so errors can be displayed.
649
$OUTPUT = new bootstrap_renderer();
650
 
651
// Set handler for uncaught exceptions - equivalent to throw new \moodle_exception() call.
652
if (!PHPUNIT_TEST or PHPUNIT_UTIL) {
653
    set_exception_handler('default_exception_handler');
1441 ariadna 654
    set_error_handler('default_error_handler', E_ALL);
1 efrain 655
}
656
 
657
// Acceptance tests needs special output to capture the errors,
658
// but not necessary for behat CLI command and init script.
659
if (defined('BEHAT_SITE_RUNNING') && !defined('BEHAT_TEST') && !defined('BEHAT_UTIL')) {
660
    require_once(__DIR__ . '/behat/lib.php');
1441 ariadna 661
    set_error_handler('behat_error_handler', E_ALL);
1 efrain 662
}
663
 
664
if (defined('WS_SERVER') && WS_SERVER) {
665
    require_once($CFG->dirroot . '/webservice/lib.php');
666
    set_exception_handler('early_ws_exception_handler');
667
}
668
 
669
// If there are any errors in the standard libraries we want to know!
1441 ariadna 670
error_reporting(E_ALL);
1 efrain 671
 
672
// Just say no to link prefetching (Moz prefetching, Google Web Accelerator, others)
673
// http://www.google.com/webmasters/faq.html#prefetchblock
674
if (!empty($_SERVER['HTTP_X_moz']) && $_SERVER['HTTP_X_moz'] === 'prefetch'){
675
    header($_SERVER['SERVER_PROTOCOL'] . ' 404 Prefetch Forbidden');
676
    echo('Prefetch request forbidden.');
677
    exit(1);
678
}
679
 
680
// Remember the default PHP timezone, we will need it later.
681
core_date::store_default_php_timezone();
682
 
683
// make sure PHP is not severly misconfigured
684
setup_validate_php_configuration();
685
 
686
// Connect to the database
687
setup_DB();
688
 
689
if (PHPUNIT_TEST and !PHPUNIT_UTIL) {
690
    // Make sure tests do not run in parallel.
691
    $suffix = '';
692
    if (phpunit_util::is_in_isolated_process()) {
693
        $suffix = '.isolated';
694
    }
695
    test_lock::acquire('phpunit', $suffix);
696
    $dbhash = null;
697
    try {
698
        if ($dbhash = $DB->get_field('config', 'value', array('name'=>'phpunittest'))) {
699
            // reset DB tables
700
            phpunit_util::reset_database();
701
        }
702
    } catch (Exception $e) {
703
        if ($dbhash) {
704
            // we ned to reinit if reset fails
705
            $DB->set_field('config', 'value', 'na', array('name'=>'phpunittest'));
706
        }
707
    }
708
    unset($dbhash);
709
}
710
 
711
// Load any immutable bootstrap config from local cache.
11 efrain 712
$bootstraplocalfile = $CFG->localcachedir . '/bootstrap.php';
713
$bootstrapsharedfile = $CFG->cachedir . '/bootstrap.php';
714
 
715
if (!is_readable($bootstraplocalfile) && is_readable($bootstrapsharedfile)) {
716
    // If we don't have a local cache but do have a shared cache then clone it,
717
    // for example when scaling up new front ends.
718
    make_localcache_directory('', true);
719
    copy($bootstrapsharedfile, $bootstraplocalfile);
720
}
721
if (is_readable($bootstraplocalfile)) {
1 efrain 722
    try {
11 efrain 723
        require_once($bootstraplocalfile);
1 efrain 724
        // Verify the file is not stale.
725
        if (!isset($CFG->bootstraphash) || $CFG->bootstraphash !== hash_local_config_cache()) {
726
            // Something has changed, the bootstrap.php file is stale.
727
            unset($CFG->siteidentifier);
11 efrain 728
            @unlink($bootstraplocalfile);
729
            @unlink($bootstrapsharedfile);
1 efrain 730
        }
731
    } catch (Throwable $e) {
732
        // If it is corrupted then attempt to delete it and it will be rebuilt.
11 efrain 733
        @unlink($bootstraplocalfile);
734
        @unlink($bootstrapsharedfile);
1 efrain 735
    }
736
}
737
 
738
// Load up any configuration from the config table or MUC cache.
739
if (PHPUNIT_TEST) {
740
    phpunit_util::initialise_cfg();
741
} else {
742
    initialise_cfg();
743
}
744
 
745
if (isset($CFG->debug)) {
746
    $CFG->debug = (int)$CFG->debug;
747
    error_reporting($CFG->debug);
748
}  else {
749
    $CFG->debug = 0;
750
}
751
$CFG->debugdeveloper = (($CFG->debug & DEBUG_DEVELOPER) === DEBUG_DEVELOPER);
752
 
753
// Set a default value for whether to show exceptions in a pretty format.
754
if (!property_exists($CFG, 'debug_developer_use_pretty_exceptions')) {
755
    $CFG->debug_developer_use_pretty_exceptions = true;
756
 
757
}
758
 
759
// Find out if PHP configured to display warnings,
760
// this is a security problem because some moodle scripts may
761
// disclose sensitive information.
762
if (ini_get_bool('display_errors')) {
763
    define('WARN_DISPLAY_ERRORS_ENABLED', true);
764
}
765
// If we want to display Moodle errors, then try and set PHP errors to match.
766
if (!isset($CFG->debugdisplay)) {
767
    // Keep it "as is" during installation.
768
} else if (NO_DEBUG_DISPLAY) {
769
    // Some parts of Moodle cannot display errors and debug at all.
770
    ini_set('display_errors', '0');
771
    ini_set('log_errors', '1');
1441 ariadna 772
    ini_set('zend.exception_ignore_args', '1');
1 efrain 773
} else if (empty($CFG->debugdisplay)) {
774
    ini_set('display_errors', '0');
775
    ini_set('log_errors', '1');
1441 ariadna 776
    ini_set('zend.exception_ignore_args', '1');
1 efrain 777
} else {
778
    // This is very problematic in XHTML strict mode!
779
    ini_set('display_errors', '1');
780
}
781
 
782
// Register our shutdown manager, do NOT use register_shutdown_function().
783
core_shutdown_manager::initialize();
784
 
785
// Verify upgrade is not running unless we are in a script that needs to execute in any case
786
if (!defined('NO_UPGRADE_CHECK') and isset($CFG->upgraderunning)) {
787
    if ($CFG->upgraderunning < time()) {
788
        unset_config('upgraderunning');
789
    } else {
790
        throw new \moodle_exception('upgraderunning');
791
    }
792
}
793
 
794
// enable circular reference collector in PHP 5.3,
795
// it helps a lot when using large complex OOP structures such as in amos or gradebook
796
if (function_exists('gc_enable')) {
797
    gc_enable();
798
}
799
 
800
// detect unsupported upgrade jump as soon as possible - do not change anything, do not use system functions
801
if (!empty($CFG->version) and $CFG->version < 2007101509) {
802
    throw new \moodle_exception('upgraderequires19', 'error');
803
    die;
804
}
805
 
806
// Calculate and set $CFG->ostype to be used everywhere. Possible values are:
807
// - WINDOWS: for any Windows flavour.
808
// - UNIX: for the rest
809
// Also, $CFG->os can continue being used if more specialization is required
810
if (stristr(PHP_OS, 'win') && !stristr(PHP_OS, 'darwin')) {
811
    $CFG->ostype = 'WINDOWS';
812
} else {
813
    $CFG->ostype = 'UNIX';
814
}
815
$CFG->os = PHP_OS;
816
 
817
// Configure ampersands in URLs
818
ini_set('arg_separator.output', '&amp;');
819
 
820
// Work around for a PHP bug   see MDL-11237
821
ini_set('pcre.backtrack_limit', 20971520);  // 20 MB
822
 
823
// Set PHP default timezone to server timezone.
824
core_date::set_default_server_timezone();
825
 
826
// Location of standard files
827
$CFG->wordlist = $CFG->libdir .'/wordlist.txt';
828
$CFG->moddata  = 'moddata';
829
 
830
// neutralise nasty chars in PHP_SELF
831
if (isset($_SERVER['PHP_SELF'])) {
832
    $phppos = strpos($_SERVER['PHP_SELF'], '.php');
833
    if ($phppos !== false) {
834
        $_SERVER['PHP_SELF'] = substr($_SERVER['PHP_SELF'], 0, $phppos+4);
835
    }
836
    unset($phppos);
837
}
838
 
839
// initialise ME's - this must be done BEFORE starting of session!
840
initialise_fullme();
841
 
842
// SYSCONTEXTID is cached in local cache to eliminate 1 query per page.
843
if (!defined('SYSCONTEXTID')) {
844
    context_system::instance();
845
}
846
 
847
// Defining the site - aka frontpage course
848
try {
849
    $SITE = get_site();
850
} catch (moodle_exception $e) {
851
    $SITE = null;
852
    if (empty($CFG->version)) {
853
        $SITE = new stdClass();
854
        $SITE->id = 1;
855
        $SITE->shortname = null;
856
    } else {
857
        throw $e;
858
    }
859
}
860
// And the 'default' course - this will usually get reset later in require_login() etc.
861
$COURSE = clone($SITE);
862
// Id of the frontpage course.
863
define('SITEID', $SITE->id);
864
 
865
// init session prevention flag - this is defined on pages that do not want session
866
if (CLI_SCRIPT) {
867
    // no sessions in CLI scripts possible
868
    define('NO_MOODLE_COOKIES', true);
869
 
870
} else if (WS_SERVER) {
871
    // No sessions possible in web services.
872
    define('NO_MOODLE_COOKIES', true);
873
 
874
} else if (!defined('NO_MOODLE_COOKIES')) {
875
    if (empty($CFG->version) or $CFG->version < 2009011900) {
876
        // no session before sessions table gets created
877
        define('NO_MOODLE_COOKIES', true);
878
    } else if (CLI_SCRIPT) {
879
        // CLI scripts can not have session
880
        define('NO_MOODLE_COOKIES', true);
881
    } else {
882
        define('NO_MOODLE_COOKIES', false);
883
    }
884
}
885
 
886
// Start session and prepare global $SESSION, $USER.
887
if (empty($CFG->sessiontimeout)) {
888
    $CFG->sessiontimeout = 8 * 60 * 60;
889
}
890
// Set sessiontimeoutwarning 20 minutes.
891
if (empty($CFG->sessiontimeoutwarning)) {
892
    $CFG->sessiontimeoutwarning = 20 * 60;
893
}
894
 
895
// Allow plugins to callback just before the session is started.
896
$pluginswithfunction = get_plugins_with_function('before_session_start', 'lib.php');
897
foreach ($pluginswithfunction as $plugins) {
898
    foreach ($plugins as $function) {
899
        try {
900
            $function();
901
        } catch (Throwable $e) {
902
            debugging("Exception calling '$function'", DEBUG_DEVELOPER, $e->getTrace());
903
        }
904
    }
905
}
906
 
907
\core\session\manager::start();
908
// Prevent ignoresesskey hack from getting carried over to a next page.
909
unset($USER->ignoresesskey);
910
 
911
if (!empty($CFG->proxylogunsafe) || !empty($CFG->proxyfixunsafe)) {
912
    if (!empty($CFG->proxyfixunsafe)) {
913
        require_once($CFG->libdir.'/filelib.php');
914
 
915
        $proxyurl = get_moodle_proxy_url();
916
        // This fixes stream handlers inside php.
917
        $defaults = stream_context_set_default([
918
            'http' => [
919
                'user_agent' => \core_useragent::get_moodlebot_useragent(),
920
                'proxy' => $proxyurl
921
            ],
922
        ]);
923
 
924
        // Attempt to tell other web clients to use the proxy too. This only
925
        // works for clients written in php in the same process, it will not
926
        // work for with requests done in another process from an exec call.
927
        putenv('http_proxy=' . $proxyurl);
928
        putenv('https_proxy=' . $proxyurl);
929
        putenv('HTTPS_PROXY=' . $proxyurl);
930
    } else {
931
        $defaults = stream_context_get_default();
932
    }
933
 
934
    if (!empty($CFG->proxylogunsafe)) {
935
        stream_context_set_params($defaults, ['notification' => 'proxy_log_callback']);
936
    }
937
 
938
}
939
 
940
// Set default content type and encoding, developers are still required to use
941
// echo $OUTPUT->header() everywhere, anything that gets set later should override these headers.
942
// This is intended to mitigate some security problems.
943
if (AJAX_SCRIPT) {
944
    if (!core_useragent::supports_json_contenttype()) {
945
        // Some bloody old IE.
946
        @header('Content-type: text/plain; charset=utf-8');
947
        @header('X-Content-Type-Options: nosniff');
948
    } else if (!empty($_FILES)) {
949
        // Some ajax code may have problems with json and file uploads.
950
        @header('Content-type: text/plain; charset=utf-8');
951
    } else {
952
        @header('Content-type: application/json; charset=utf-8');
953
    }
954
} else if (!CLI_SCRIPT) {
955
    @header('Content-type: text/html; charset=utf-8');
956
}
957
 
958
// Initialise some variables that are supposed to be set in config.php only.
959
if (!isset($CFG->filelifetime)) {
960
    $CFG->filelifetime = 60*60*6;
961
}
962
 
963
// Late profiling, only happening if early one wasn't started
964
if (!empty($CFG->profilingenabled)) {
965
    require_once($CFG->libdir . '/xhprof/xhprof_moodle.php');
966
    profiling_start();
967
}
968
 
969
// Hack to get around max_input_vars restrictions,
970
// we need to do this after session init to have some basic DDoS protection.
971
workaround_max_input_vars();
972
 
973
// Process theme change in the URL.
974
if (!empty($CFG->allowthemechangeonurl) and !empty($_GET['theme'])) {
975
    // we have to use _GET directly because we do not want this to interfere with _POST
976
    $urlthemename = optional_param('theme', '', PARAM_PLUGIN);
977
    try {
978
        $themeconfig = theme_config::load($urlthemename);
979
        // Makes sure the theme can be loaded without errors.
980
        if ($themeconfig->name === $urlthemename) {
981
            $SESSION->theme = $urlthemename;
982
        } else {
983
            unset($SESSION->theme);
984
        }
985
        unset($themeconfig);
986
        unset($urlthemename);
987
    } catch (Exception $e) {
988
        debugging('Failed to set the theme from the URL.', DEBUG_DEVELOPER, $e->getTrace());
989
    }
990
}
991
unset($urlthemename);
992
 
993
// Ensure a valid theme is set.
994
if (!isset($CFG->theme)) {
995
    $CFG->theme = 'boost';
996
}
997
 
998
// Set language/locale of printed times.  If user has chosen a language that
999
// that is different from the site language, then use the locale specified
1000
// in the language file.  Otherwise, if the admin hasn't specified a locale
1001
// then use the one from the default language.  Otherwise (and this is the
1002
// majority of cases), use the stored locale specified by admin.
1003
// note: do not accept lang parameter from POST
1004
if (isset($_GET['lang']) and ($lang = optional_param('lang', '', PARAM_SAFEDIR))) {
1005
    if (get_string_manager()->translation_exists($lang, false)) {
1006
        $SESSION->lang = $lang;
1007
        \core_courseformat\base::session_cache_reset_all();
1008
    }
1009
}
1010
unset($lang);
1011
 
1012
// PARAM_SAFEDIR used instead of PARAM_LANG because using PARAM_LANG results
1013
// in an empty string being returned when a non-existant language is specified,
1014
// which would make it necessary to log out to undo the forcelang setting.
1015
// With PARAM_SAFEDIR, it's possible to specify ?forcelang=none to drop the forcelang effect.
1016
if ($forcelang = optional_param('forcelang', '', PARAM_SAFEDIR)) {
1017
    if (isloggedin()
1018
        && get_string_manager()->translation_exists($forcelang, false)
1019
        && has_capability('moodle/site:forcelanguage', context_system::instance())) {
1020
        $SESSION->forcelang = $forcelang;
1021
    } else if (isset($SESSION->forcelang)) {
1022
        unset($SESSION->forcelang);
1023
    }
1024
}
1025
unset($forcelang);
1026
 
1027
setup_lang_from_browser();
1028
 
1029
if (empty($CFG->lang)) {
1030
    if (empty($SESSION->lang)) {
1031
        $CFG->lang = 'en';
1032
    } else {
1033
        $CFG->lang = $SESSION->lang;
1034
    }
1035
}
1036
 
1037
// Set the default site locale, a lot of the stuff may depend on this
1038
// it is definitely too late to call this first in require_login()!
1039
moodle_setlocale();
1040
 
1041
// Create the $PAGE global - this marks the PAGE and OUTPUT fully initialised, this MUST be done at the end of setup!
1042
if (!empty($CFG->moodlepageclass)) {
1043
    if (!empty($CFG->moodlepageclassfile)) {
1044
        require_once($CFG->moodlepageclassfile);
1045
    }
1046
    $classname = $CFG->moodlepageclass;
1047
} else {
1048
    $classname = 'moodle_page';
1049
}
1050
$PAGE = new $classname();
1051
unset($classname);
1052
 
1053
 
1054
if (!empty($CFG->debugvalidators) and !empty($CFG->guestloginbutton)) {
1055
    if ($CFG->theme == 'standard') {    // Temporary measure to help with XHTML validation
1056
        if (isset($_SERVER['HTTP_USER_AGENT']) and empty($USER->id)) {      // Allow W3CValidator in as user called w3cvalidator (or guest)
1057
            if ((strpos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') !== false) or
1058
                (strpos($_SERVER['HTTP_USER_AGENT'], 'Cynthia') !== false )) {
1059
                if ($user = get_complete_user_data("username", "w3cvalidator")) {
1060
                    $user->ignoresesskey = true;
1061
                } else {
1062
                    $user = guest_user();
1063
                }
1064
                \core\session\manager::set_user($user);
1065
            }
1066
        }
1067
    }
1068
}
1069
 
1070
// Apache log integration. In apache conf file one can use ${MOODULEUSER}n in
1071
// LogFormat to get the current logged in username in moodle.
1072
// Alternatvely for other web servers a header X-MOODLEUSER can be set which
1073
// can be using in the logfile and stripped out if needed.
1074
set_access_log_user();
1075
 
1076
if (CLI_SCRIPT && !empty($CFG->version)) {
1077
    // Allow auth plugins to optionally authenticate users on the CLI.
1078
    require_once($CFG->libdir. '/authlib.php');
1079
    auth_plugin_base::login_cli_admin_user();
1080
}
1081
 
1082
// Ensure the urlrewriteclass is setup correctly (to avoid crippling site).
1083
if (isset($CFG->urlrewriteclass)) {
1084
    if (!class_exists($CFG->urlrewriteclass)) {
1085
        debugging("urlrewriteclass {$CFG->urlrewriteclass} was not found, disabling.");
1086
        unset($CFG->urlrewriteclass);
1087
    } else if (!in_array('core\output\url_rewriter', class_implements($CFG->urlrewriteclass))) {
1088
        debugging("{$CFG->urlrewriteclass} does not implement core\output\url_rewriter, disabling.", DEBUG_DEVELOPER);
1089
        unset($CFG->urlrewriteclass);
1090
    }
1091
}
1092
 
1093
// Use a custom script replacement if one exists
1094
if (!empty($CFG->customscripts)) {
1095
    if (($customscript = custom_script_path()) !== false) {
1096
        require ($customscript);
1097
    }
1098
}
1099
 
1100
if (PHPUNIT_TEST) {
1101
    // no ip blocking, these are CLI only
1102
} else if (CLI_SCRIPT and !defined('WEB_CRON_EMULATED_CLI')) {
1103
    // no ip blocking
1104
} else if (!empty($CFG->allowbeforeblock)) { // allowed list processed before blocked list?
1105
    // in this case, ip in allowed list will be performed first
1106
    // for example, client IP is 192.168.1.1
1107
    // 192.168 subnet is an entry in allowed list
1108
    // 192.168.1.1 is banned in blocked list
1109
    // This ip will be banned finally
1110
    if (!empty($CFG->allowedip)) {
1111
        if (!remoteip_in_list($CFG->allowedip)) {
1112
            die(get_string('ipblocked', 'admin'));
1113
        }
1114
    }
1115
    // need further check, client ip may a part of
1116
    // allowed subnet, but a IP address are listed
1117
    // in blocked list.
1118
    if (!empty($CFG->blockedip)) {
1119
        if (remoteip_in_list($CFG->blockedip)) {
1120
            die(get_string('ipblocked', 'admin'));
1121
        }
1122
    }
1123
 
1124
} else {
1125
    // in this case, IPs in blocked list will be performed first
1126
    // for example, client IP is 192.168.1.1
1127
    // 192.168 subnet is an entry in blocked list
1128
    // 192.168.1.1 is allowed in allowed list
1129
    // This ip will be allowed finally
1130
    if (!empty($CFG->blockedip)) {
1131
        if (remoteip_in_list($CFG->blockedip)) {
1132
            // if the allowed ip list is not empty
1133
            // IPs are not included in the allowed list will be
1134
            // blocked too
1135
            if (!empty($CFG->allowedip)) {
1136
                if (!remoteip_in_list($CFG->allowedip)) {
1137
                    die(get_string('ipblocked', 'admin'));
1138
                }
1139
            } else {
1140
                die(get_string('ipblocked', 'admin'));
1141
            }
1142
        }
1143
    }
1144
    // if blocked list is null
1145
    // allowed list should be tested
1146
    if(!empty($CFG->allowedip)) {
1147
        if (!remoteip_in_list($CFG->allowedip)) {
1148
            die(get_string('ipblocked', 'admin'));
1149
        }
1150
    }
1151
 
1152
}
1153
 
1154
// // try to detect IE6 and prevent gzip because it is extremely buggy browser
1155
if (!empty($_SERVER['HTTP_USER_AGENT']) and strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6') !== false) {
1156
    ini_set('zlib.output_compression', 'Off');
1157
    if (function_exists('apache_setenv')) {
1158
        apache_setenv('no-gzip', 1);
1159
    }
1160
}
1161
 
1162
// Switch to CLI maintenance mode if required, we need to do it here after all the settings are initialised.
1163
if (isset($CFG->maintenance_later) and $CFG->maintenance_later <= time()) {
1441 ariadna 1164
 
1165
    // Because maintenance_later is triggered by any potentially real non admin user
1166
    // who just happened to be the first to load a page after the time is due, we do
1167
    // this simple workaround so add_to_config_log doesn't log it as them.
1168
    \core\session\manager::write_close();
1169
    $USER->id = 0;
1170
 
1 efrain 1171
    if (!file_exists("$CFG->dataroot/climaintenance.html")) {
1172
        require_once("$CFG->libdir/adminlib.php");
1441 ariadna 1173
        set_config('maintenance_enabled', 'cli mode', null, true);
1 efrain 1174
        enable_cli_maintenance_mode();
1175
    }
1441 ariadna 1176
    if (isset($CFG->maintenance_later)) {
1177
        unset_config('maintenance_later', null, true);
1178
    }
1 efrain 1179
    if (AJAX_SCRIPT) {
1180
        die;
1181
    } else if (!CLI_SCRIPT) {
1441 ariadna 1182
        // We redirect to ourselves to reload the page to get a fresh bootstrap
1183
        // so that we get the maintenance page which is earlier in setup.
1184
        redirect(new moodle_url($ME));
1 efrain 1185
    }
1186
}
1187
 
1188
// Add behat_shutdown_function to shutdown manager, so we can capture php errors,
1189
// but not necessary for behat CLI command as it's being captured by behat process.
1190
if (defined('BEHAT_SITE_RUNNING') && !defined('BEHAT_TEST')) {
1191
    core_shutdown_manager::register_function('behat_shutdown_function');
1192
}
1193
 
1194
// note: we can not block non utf-8 installations here, because empty mysql database
1195
// might be converted to utf-8 in admin/index.php during installation
1196
 
1197
 
1198
 
1199
// this is a funny trick to make Eclipse believe that $OUTPUT and other globals
1200
// contains an instance of core_renderer, etc. which in turn fixes autocompletion ;-)
1201
if (false) {
1202
    $DB = new moodle_database();
1203
    $OUTPUT = new core_renderer(null, null);
1204
    $PAGE = new moodle_page();
1205
}
1206
 
1207
// Cache any immutable config locally to avoid constant DB lookups.
1208
initialise_local_config_cache();
1209
 
1210
// Allow plugins to callback as soon possible after setup.php is loaded.
1441 ariadna 1211
$afterconfighook = new \core\hook\after_config();
1212
$afterconfighook->process_legacy_callbacks();
1213
\core\di::get(\core\hook\manager::class)->dispatch($afterconfighook);