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