PageRenderTime 44ms CodeModel.GetById 8ms app.highlight 26ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/setup.php

https://github.com/gwamgerald/moodle-1
PHP | 1018 lines | 588 code | 117 blank | 313 comment | 188 complexity | df63c1bd003a1e771d1c418cf05568e7 MD5 | raw file
   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->tempdir  - Path to moodle's temp file directory on server's filesystem.
  40 *  - $CFG->cachedir - Path to moodle's cache directory on server's filesystem (shared by cluster nodes).
  41 *  - $CFG->localcachedir - Path to moodle's local cache directory (not shared by cluster nodes).
  42 *
  43 * @global object $CFG
  44 * @name $CFG
  45 */
  46global $CFG; // this should be done much earlier in config.php before creating new $CFG instance
  47
  48if (!isset($CFG)) {
  49    if (defined('PHPUNIT_TEST') and PHPUNIT_TEST) {
  50        echo('There is a missing "global $CFG;" at the beginning of the config.php file.'."\n");
  51        exit(1);
  52    } else {
  53        // this should never happen, maybe somebody is accessing this file directly...
  54        exit(1);
  55    }
  56}
  57
  58// We can detect real dirroot path reliably since PHP 4.0.2,
  59// it can not be anything else, there is no point in having this in config.php
  60$CFG->dirroot = dirname(dirname(__FILE__));
  61
  62// File permissions on created directories in the $CFG->dataroot
  63if (!isset($CFG->directorypermissions)) {
  64    $CFG->directorypermissions = 02777;      // Must be octal (that's why it's here)
  65}
  66if (!isset($CFG->filepermissions)) {
  67    $CFG->filepermissions = ($CFG->directorypermissions & 0666); // strip execute flags
  68}
  69// Better also set default umask because developers often forget to include directory
  70// permissions in mkdir() and chmod() after creating new files.
  71if (!isset($CFG->umaskpermissions)) {
  72    $CFG->umaskpermissions = (($CFG->directorypermissions & 0777) ^ 0777);
  73}
  74umask($CFG->umaskpermissions);
  75
  76if (defined('BEHAT_SITE_RUNNING')) {
  77    // We already switched to behat test site previously.
  78
  79} else if (!empty($CFG->behat_wwwroot) or !empty($CFG->behat_dataroot) or !empty($CFG->behat_prefix)) {
  80    // The behat is configured on this server, we need to find out if this is the behat test
  81    // site based on the URL used for access.
  82    require_once(__DIR__ . '/../lib/behat/lib.php');
  83    if (behat_is_test_site()) {
  84        // Checking the integrity of the provided $CFG->behat_* vars and the
  85        // selected wwwroot to prevent conflicts with production and phpunit environments.
  86        behat_check_config_vars();
  87
  88        // Check that the directory does not contains other things.
  89        if (!file_exists("$CFG->behat_dataroot/behattestdir.txt")) {
  90            if ($dh = opendir($CFG->behat_dataroot)) {
  91                while (($file = readdir($dh)) !== false) {
  92                    if ($file === 'behat' or $file === '.' or $file === '..' or $file === '.DS_Store') {
  93                        continue;
  94                    }
  95                    behat_error(BEHAT_EXITCODE_CONFIG, '$CFG->behat_dataroot directory is not empty, ensure this is the directory where you want to install behat test dataroot');
  96                }
  97                closedir($dh);
  98                unset($dh);
  99                unset($file);
 100            }
 101
 102            if (defined('BEHAT_UTIL')) {
 103                // Now we create dataroot directory structure for behat tests.
 104                testing_initdataroot($CFG->behat_dataroot, 'behat');
 105            } else {
 106                behat_error(BEHAT_EXITCODE_INSTALL);
 107            }
 108        }
 109
 110        if (!defined('BEHAT_UTIL') and !defined('BEHAT_TEST')) {
 111            // Somebody tries to access test site directly, tell them if not enabled.
 112            if (!file_exists($CFG->behat_dataroot . '/behat/test_environment_enabled.txt')) {
 113                behat_error(BEHAT_EXITCODE_CONFIG, 'Behat is configured but not enabled on this test site.');
 114            }
 115        }
 116
 117        // Constant used to inform that the behat test site is being used,
 118        // this includes all the processes executed by the behat CLI command like
 119        // the site reset, the steps executed by the browser drivers when simulating
 120        // a user session and a real session when browsing manually to $CFG->behat_wwwroot
 121        // like the browser driver does automatically.
 122        // Different from BEHAT_TEST as only this last one can perform CLI
 123        // actions like reset the site or use data generators.
 124        define('BEHAT_SITE_RUNNING', true);
 125
 126        // Clean extra config.php settings.
 127        behat_clean_init_config();
 128
 129        // Now we can begin switching $CFG->X for $CFG->behat_X.
 130        $CFG->wwwroot = $CFG->behat_wwwroot;
 131        $CFG->prefix = $CFG->behat_prefix;
 132        $CFG->dataroot = $CFG->behat_dataroot;
 133    }
 134}
 135
 136// Normalise dataroot - we do not want any symbolic links, trailing / or any other weirdness there
 137if (!isset($CFG->dataroot)) {
 138    if (isset($_SERVER['REMOTE_ADDR'])) {
 139        header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
 140    }
 141    echo('Fatal error: $CFG->dataroot is not specified in config.php! Exiting.'."\n");
 142    exit(1);
 143}
 144$CFG->dataroot = realpath($CFG->dataroot);
 145if ($CFG->dataroot === false) {
 146    if (isset($_SERVER['REMOTE_ADDR'])) {
 147        header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
 148    }
 149    echo('Fatal error: $CFG->dataroot is not configured properly, directory does not exist or is not accessible! Exiting.'."\n");
 150    exit(1);
 151} else if (!is_writable($CFG->dataroot)) {
 152    if (isset($_SERVER['REMOTE_ADDR'])) {
 153        header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
 154    }
 155    echo('Fatal error: $CFG->dataroot is not writable, admin has to fix directory permissions! Exiting.'."\n");
 156    exit(1);
 157}
 158
 159// wwwroot is mandatory
 160if (!isset($CFG->wwwroot) or $CFG->wwwroot === 'http://example.com/moodle') {
 161    if (isset($_SERVER['REMOTE_ADDR'])) {
 162        header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
 163    }
 164    echo('Fatal error: $CFG->wwwroot is not configured! Exiting.'."\n");
 165    exit(1);
 166}
 167
 168// Make sure there is some database table prefix.
 169if (!isset($CFG->prefix)) {
 170    $CFG->prefix = '';
 171}
 172
 173// Define admin directory
 174if (!isset($CFG->admin)) {   // Just in case it isn't defined in config.php
 175    $CFG->admin = 'admin';   // This is relative to the wwwroot and dirroot
 176}
 177
 178// Set up some paths.
 179$CFG->libdir = $CFG->dirroot .'/lib';
 180
 181// Allow overriding of tempdir but be backwards compatible
 182if (!isset($CFG->tempdir)) {
 183    $CFG->tempdir = "$CFG->dataroot/temp";
 184}
 185
 186// Allow overriding of cachedir but be backwards compatible
 187if (!isset($CFG->cachedir)) {
 188    $CFG->cachedir = "$CFG->dataroot/cache";
 189}
 190
 191// Allow overriding of localcachedir.
 192if (!isset($CFG->localcachedir)) {
 193    $CFG->localcachedir = "$CFG->dataroot/localcache";
 194}
 195
 196// Location of all languages except core English pack.
 197if (!isset($CFG->langotherroot)) {
 198    $CFG->langotherroot = $CFG->dataroot.'/lang';
 199}
 200
 201// Location of local lang pack customisations (dirs with _local suffix).
 202if (!isset($CFG->langlocalroot)) {
 203    $CFG->langlocalroot = $CFG->dataroot.'/lang';
 204}
 205
 206// The current directory in PHP version 4.3.0 and above isn't necessarily the
 207// directory of the script when run from the command line. The require_once()
 208// would fail, so we'll have to chdir()
 209if (!isset($_SERVER['REMOTE_ADDR']) && isset($_SERVER['argv'][0])) {
 210    // do it only once - skip the second time when continuing after prevous abort
 211    if (!defined('ABORT_AFTER_CONFIG') and !defined('ABORT_AFTER_CONFIG_CANCEL')) {
 212        chdir(dirname($_SERVER['argv'][0]));
 213    }
 214}
 215
 216// sometimes default PHP settings are borked on shared hosting servers, I wonder why they have to do that??
 217ini_set('precision', 14); // needed for upgrades and gradebook
 218ini_set('serialize_precision', 17); // Make float serialization consistent on all systems.
 219
 220// Scripts may request no debug and error messages in output
 221// please note it must be defined before including the config.php script
 222// and in some cases you also need to set custom default exception handler
 223if (!defined('NO_DEBUG_DISPLAY')) {
 224    if (defined('AJAX_SCRIPT') and AJAX_SCRIPT) {
 225        // Moodle AJAX scripts are expected to return json data, any PHP notices or errors break it badly,
 226        // developers simply must learn to watch error log.
 227        define('NO_DEBUG_DISPLAY', true);
 228    } else {
 229        define('NO_DEBUG_DISPLAY', false);
 230    }
 231}
 232
 233// Some scripts such as upgrade may want to prevent output buffering
 234if (!defined('NO_OUTPUT_BUFFERING')) {
 235    define('NO_OUTPUT_BUFFERING', false);
 236}
 237
 238// PHPUnit tests need custom init
 239if (!defined('PHPUNIT_TEST')) {
 240    define('PHPUNIT_TEST', false);
 241}
 242
 243// Performance tests needs to always display performance info, even in redirections.
 244if (!defined('MDL_PERF_TEST')) {
 245    define('MDL_PERF_TEST', false);
 246} else {
 247    // We force the ones we need.
 248    if (!defined('MDL_PERF')) {
 249        define('MDL_PERF', true);
 250    }
 251    if (!defined('MDL_PERFDB')) {
 252        define('MDL_PERFDB', true);
 253    }
 254    if (!defined('MDL_PERFTOFOOT')) {
 255        define('MDL_PERFTOFOOT', true);
 256    }
 257}
 258
 259// When set to true MUC (Moodle caching) will be disabled as much as possible.
 260// A special cache factory will be used to handle this situation and will use special "disabled" equivalents objects.
 261// This ensure we don't attempt to read or create the config file, don't use stores, don't provide persistence or
 262// storage of any kind.
 263if (!defined('CACHE_DISABLE_ALL')) {
 264    define('CACHE_DISABLE_ALL', false);
 265}
 266
 267// When set to true MUC (Moodle caching) will not use any of the defined or default stores.
 268// The Cache API will continue to function however this will force the use of the cachestore_dummy so all requests
 269// will be interacting with a static property and will never go to the proper cache stores.
 270// Useful if you need to avoid the stores for one reason or another.
 271if (!defined('CACHE_DISABLE_STORES')) {
 272    define('CACHE_DISABLE_STORES', false);
 273}
 274
 275// Servers should define a default timezone in php.ini, but if they don't then make sure something is defined.
 276// This is a quick hack.  Ideally we should ask the admin for a value.  See MDL-22625 for more on this.
 277if (function_exists('date_default_timezone_set') and function_exists('date_default_timezone_get')) {
 278    $olddebug = error_reporting(0);
 279    date_default_timezone_set(date_default_timezone_get());
 280    error_reporting($olddebug);
 281    unset($olddebug);
 282}
 283
 284// Detect CLI scripts - CLI scripts are executed from command line, do not have session and we do not want HTML in output
 285// In your new CLI scripts just add "define('CLI_SCRIPT', true);" before requiring config.php.
 286// Please note that one script can not be accessed from both CLI and web interface.
 287if (!defined('CLI_SCRIPT')) {
 288    define('CLI_SCRIPT', false);
 289}
 290if (defined('WEB_CRON_EMULATED_CLI')) {
 291    if (!isset($_SERVER['REMOTE_ADDR'])) {
 292        echo('Web cron can not be executed as CLI script any more, please use admin/cli/cron.php instead'."\n");
 293        exit(1);
 294    }
 295} else if (isset($_SERVER['REMOTE_ADDR'])) {
 296    if (CLI_SCRIPT) {
 297        echo('Command line scripts can not be executed from the web interface');
 298        exit(1);
 299    }
 300} else {
 301    if (!CLI_SCRIPT) {
 302        echo('Command line scripts must define CLI_SCRIPT before requiring config.php'."\n");
 303        exit(1);
 304    }
 305}
 306
 307// All web service requests have WS_SERVER == true.
 308if (!defined('WS_SERVER')) {
 309    define('WS_SERVER', false);
 310}
 311
 312// Detect CLI maintenance mode - this is useful when you need to mess with database, such as during upgrades
 313if (file_exists("$CFG->dataroot/climaintenance.html")) {
 314    if (!CLI_SCRIPT) {
 315        header('Content-type: text/html; charset=utf-8');
 316        header('X-UA-Compatible: IE=edge');
 317        /// Headers to make it not cacheable and json
 318        header('Cache-Control: no-store, no-cache, must-revalidate');
 319        header('Cache-Control: post-check=0, pre-check=0', false);
 320        header('Pragma: no-cache');
 321        header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
 322        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
 323        header('Accept-Ranges: none');
 324        readfile("$CFG->dataroot/climaintenance.html");
 325        die;
 326    } else {
 327        if (!defined('CLI_MAINTENANCE')) {
 328            define('CLI_MAINTENANCE', true);
 329        }
 330    }
 331} else {
 332    if (!defined('CLI_MAINTENANCE')) {
 333        define('CLI_MAINTENANCE', false);
 334    }
 335}
 336
 337if (CLI_SCRIPT) {
 338    // sometimes people use different PHP binary for web and CLI, make 100% sure they have the supported PHP version
 339    if (version_compare(phpversion(), '5.4.4') < 0) {
 340        $phpversion = phpversion();
 341        // do NOT localise - lang strings would not work here and we CAN NOT move it to later place
 342        echo "Moodle 2.7 or later requires at least PHP 5.4.4 (currently using version $phpversion).\n";
 343        echo "Some servers may have multiple PHP versions installed, are you using the correct executable?\n";
 344        exit(1);
 345    }
 346}
 347
 348// Detect ajax scripts - they are similar to CLI because we can not redirect, output html, etc.
 349if (!defined('AJAX_SCRIPT')) {
 350    define('AJAX_SCRIPT', false);
 351}
 352
 353// Exact version of currently used yui2 and 3 library.
 354$CFG->yui2version = '2.9.0';
 355$CFG->yui3version = '3.17.2';
 356
 357// Patching the upstream YUI release.
 358// For important information on patching YUI modules, please see http://docs.moodle.org/dev/YUI/Patching.
 359// If we need to patch a YUI modules between official YUI releases, the yuipatchlevel will need to be manually
 360// incremented here. The module will also need to be listed in the yuipatchedmodules.
 361// When upgrading to a subsequent version of YUI, these should be reset back to 0 and an empty array.
 362$CFG->yuipatchlevel = 0;
 363$CFG->yuipatchedmodules = array(
 364);
 365
 366// Store settings from config.php in array in $CFG - we can use it later to detect problems and overrides.
 367if (!isset($CFG->config_php_settings)) {
 368    $CFG->config_php_settings = (array)$CFG;
 369    // Forced plugin settings override values from config_plugins table.
 370    unset($CFG->config_php_settings['forced_plugin_settings']);
 371    if (!isset($CFG->forced_plugin_settings)) {
 372        $CFG->forced_plugin_settings = array();
 373    }
 374}
 375
 376if (isset($CFG->debug)) {
 377    $CFG->debug = (int)$CFG->debug;
 378} else {
 379    $CFG->debug = 0;
 380}
 381$CFG->debugdeveloper = (($CFG->debug & (E_ALL | E_STRICT)) === (E_ALL | E_STRICT)); // DEBUG_DEVELOPER is not available yet.
 382
 383if (!defined('MOODLE_INTERNAL')) { // Necessary because cli installer has to define it earlier.
 384    /** Used by library scripts to check they are being called by Moodle. */
 385    define('MOODLE_INTERNAL', true);
 386}
 387
 388// core_component can be used in any scripts, it does not need anything else.
 389require_once($CFG->libdir .'/classes/component.php');
 390
 391// special support for highly optimised scripts that do not need libraries and DB connection
 392if (defined('ABORT_AFTER_CONFIG')) {
 393    if (!defined('ABORT_AFTER_CONFIG_CANCEL')) {
 394        // hide debugging if not enabled in config.php - we do not want to disclose sensitive info
 395        error_reporting($CFG->debug);
 396        if (NO_DEBUG_DISPLAY) {
 397            // Some parts of Moodle cannot display errors and debug at all.
 398            ini_set('display_errors', '0');
 399            ini_set('log_errors', '1');
 400        } else if (empty($CFG->debugdisplay)) {
 401            ini_set('display_errors', '0');
 402            ini_set('log_errors', '1');
 403        } else {
 404            ini_set('display_errors', '1');
 405        }
 406        require_once("$CFG->dirroot/lib/configonlylib.php");
 407        return;
 408    }
 409}
 410
 411// Early profiling start, based exclusively on config.php $CFG settings
 412if (!empty($CFG->earlyprofilingenabled)) {
 413    require_once($CFG->libdir . '/xhprof/xhprof_moodle.php');
 414    profiling_start();
 415}
 416
 417/**
 418 * Database connection. Used for all access to the database.
 419 * @global moodle_database $DB
 420 * @name $DB
 421 */
 422global $DB;
 423
 424/**
 425 * Moodle's wrapper round PHP's $_SESSION.
 426 *
 427 * @global object $SESSION
 428 * @name $SESSION
 429 */
 430global $SESSION;
 431
 432/**
 433 * Holds the user table record for the current user. Will be the 'guest'
 434 * user record for people who are not logged in.
 435 *
 436 * $USER is stored in the session.
 437 *
 438 * Items found in the user record:
 439 *  - $USER->email - The user's email address.
 440 *  - $USER->id - The unique integer identified of this user in the 'user' table.
 441 *  - $USER->email - The user's email address.
 442 *  - $USER->firstname - The user's first name.
 443 *  - $USER->lastname - The user's last name.
 444 *  - $USER->username - The user's login username.
 445 *  - $USER->secret - The user's ?.
 446 *  - $USER->lang - The user's language choice.
 447 *
 448 * @global object $USER
 449 * @name $USER
 450 */
 451global $USER;
 452
 453/**
 454 * Frontpage course record
 455 */
 456global $SITE;
 457
 458/**
 459 * A central store of information about the current page we are
 460 * generating in response to the user's request.
 461 *
 462 * @global moodle_page $PAGE
 463 * @name $PAGE
 464 */
 465global $PAGE;
 466
 467/**
 468 * The current course. An alias for $PAGE->course.
 469 * @global object $COURSE
 470 * @name $COURSE
 471 */
 472global $COURSE;
 473
 474/**
 475 * $OUTPUT is an instance of core_renderer or one of its subclasses. Use
 476 * it to generate HTML for output.
 477 *
 478 * $OUTPUT is initialised the first time it is used. See {@link bootstrap_renderer}
 479 * for the magic that does that. After $OUTPUT has been initialised, any attempt
 480 * to change something that affects the current theme ($PAGE->course, logged in use,
 481 * httpsrequried ... will result in an exception.)
 482 *
 483 * Please note the $OUTPUT is replacing the old global $THEME object.
 484 *
 485 * @global object $OUTPUT
 486 * @name $OUTPUT
 487 */
 488global $OUTPUT;
 489
 490/**
 491 * Full script path including all params, slash arguments, scheme and host.
 492 *
 493 * Note: Do NOT use for getting of current page URL or detection of https,
 494 * instead use $PAGE->url or strpos($CFG->httpswwwroot, 'https:') === 0
 495 *
 496 * @global string $FULLME
 497 * @name $FULLME
 498 */
 499global $FULLME;
 500
 501/**
 502 * Script path including query string and slash arguments without host.
 503 * @global string $ME
 504 * @name $ME
 505 */
 506global $ME;
 507
 508/**
 509 * $FULLME without slasharguments and query string.
 510 * @global string $FULLSCRIPT
 511 * @name $FULLSCRIPT
 512 */
 513global $FULLSCRIPT;
 514
 515/**
 516 * Relative moodle script path '/course/view.php'
 517 * @global string $SCRIPT
 518 * @name $SCRIPT
 519 */
 520global $SCRIPT;
 521
 522// Set httpswwwroot default value (this variable will replace $CFG->wwwroot
 523// inside some URLs used in HTTPSPAGEREQUIRED pages.
 524$CFG->httpswwwroot = $CFG->wwwroot;
 525
 526require_once($CFG->libdir .'/setuplib.php');        // Functions that MUST be loaded first
 527
 528if (NO_OUTPUT_BUFFERING) {
 529    // we have to call this always before starting session because it discards headers!
 530    disable_output_buffering();
 531}
 532
 533// Increase memory limits if possible
 534raise_memory_limit(MEMORY_STANDARD);
 535
 536// Time to start counting
 537init_performance_info();
 538
 539// Put $OUTPUT in place, so errors can be displayed.
 540$OUTPUT = new bootstrap_renderer();
 541
 542// set handler for uncaught exceptions - equivalent to print_error() call
 543if (!PHPUNIT_TEST or PHPUNIT_UTIL) {
 544    set_exception_handler('default_exception_handler');
 545    set_error_handler('default_error_handler', E_ALL | E_STRICT);
 546}
 547
 548// Acceptance tests needs special output to capture the errors,
 549// but not necessary for behat CLI command.
 550if (defined('BEHAT_SITE_RUNNING') && !defined('BEHAT_TEST')) {
 551    require_once(__DIR__ . '/behat/lib.php');
 552    set_error_handler('behat_error_handler', E_ALL | E_STRICT);
 553}
 554
 555// If there are any errors in the standard libraries we want to know!
 556error_reporting(E_ALL | E_STRICT);
 557
 558// Just say no to link prefetching (Moz prefetching, Google Web Accelerator, others)
 559// http://www.google.com/webmasters/faq.html#prefetchblock
 560if (!empty($_SERVER['HTTP_X_moz']) && $_SERVER['HTTP_X_moz'] === 'prefetch'){
 561    header($_SERVER['SERVER_PROTOCOL'] . ' 404 Prefetch Forbidden');
 562    echo('Prefetch request forbidden.');
 563    exit(1);
 564}
 565
 566//point pear include path to moodles lib/pear so that includes and requires will search there for files before anywhere else
 567//the problem is that we need specific version of quickforms and hacked excel files :-(
 568ini_set('include_path', $CFG->libdir.'/pear' . PATH_SEPARATOR . ini_get('include_path'));
 569//point zend include path to moodles lib/zend so that includes and requires will search there for files before anywhere else
 570//please note zend library is supposed to be used only from web service protocol classes, it may be removed in future
 571ini_set('include_path', $CFG->libdir.'/zend' . PATH_SEPARATOR . ini_get('include_path'));
 572
 573// Register our classloader, in theory somebody might want to replace it to load other hacked core classes.
 574if (defined('COMPONENT_CLASSLOADER')) {
 575    spl_autoload_register(COMPONENT_CLASSLOADER);
 576} else {
 577    spl_autoload_register('core_component::classloader');
 578}
 579
 580// Load up standard libraries
 581require_once($CFG->libdir .'/filterlib.php');       // Functions for filtering test as it is output
 582require_once($CFG->libdir .'/ajax/ajaxlib.php');    // Functions for managing our use of JavaScript and YUI
 583require_once($CFG->libdir .'/weblib.php');          // Functions relating to HTTP and content
 584require_once($CFG->libdir .'/outputlib.php');       // Functions for generating output
 585require_once($CFG->libdir .'/navigationlib.php');   // Class for generating Navigation structure
 586require_once($CFG->libdir .'/dmllib.php');          // Database access
 587require_once($CFG->libdir .'/datalib.php');         // Legacy lib with a big-mix of functions.
 588require_once($CFG->libdir .'/accesslib.php');       // Access control functions
 589require_once($CFG->libdir .'/deprecatedlib.php');   // Deprecated functions included for backward compatibility
 590require_once($CFG->libdir .'/moodlelib.php');       // Other general-purpose functions
 591require_once($CFG->libdir .'/enrollib.php');        // Enrolment related functions
 592require_once($CFG->libdir .'/pagelib.php');         // Library that defines the moodle_page class, used for $PAGE
 593require_once($CFG->libdir .'/blocklib.php');        // Library for controlling blocks
 594require_once($CFG->libdir .'/eventslib.php');       // Events functions
 595require_once($CFG->libdir .'/grouplib.php');        // Groups functions
 596require_once($CFG->libdir .'/sessionlib.php');      // All session and cookie related stuff
 597require_once($CFG->libdir .'/editorlib.php');       // All text editor related functions and classes
 598require_once($CFG->libdir .'/messagelib.php');      // Messagelib functions
 599require_once($CFG->libdir .'/modinfolib.php');      // Cached information on course-module instances
 600require_once($CFG->dirroot.'/cache/lib.php');       // Cache API
 601
 602// make sure PHP is not severly misconfigured
 603setup_validate_php_configuration();
 604
 605// Connect to the database
 606setup_DB();
 607
 608if (PHPUNIT_TEST and !PHPUNIT_UTIL) {
 609    // make sure tests do not run in parallel
 610    test_lock::acquire('phpunit');
 611    $dbhash = null;
 612    try {
 613        if ($dbhash = $DB->get_field('config', 'value', array('name'=>'phpunittest'))) {
 614            // reset DB tables
 615            phpunit_util::reset_database();
 616        }
 617    } catch (Exception $e) {
 618        if ($dbhash) {
 619            // we ned to reinit if reset fails
 620            $DB->set_field('config', 'value', 'na', array('name'=>'phpunittest'));
 621        }
 622    }
 623    unset($dbhash);
 624}
 625
 626// Load up any configuration from the config table or MUC cache.
 627if (PHPUNIT_TEST) {
 628    phpunit_util::initialise_cfg();
 629} else {
 630    initialise_cfg();
 631}
 632
 633if (isset($CFG->debug)) {
 634    $CFG->debug = (int)$CFG->debug;
 635    error_reporting($CFG->debug);
 636}  else {
 637    $CFG->debug = 0;
 638}
 639$CFG->debugdeveloper = (($CFG->debug & DEBUG_DEVELOPER) === DEBUG_DEVELOPER);
 640
 641// Find out if PHP configured to display warnings,
 642// this is a security problem because some moodle scripts may
 643// disclose sensitive information.
 644if (ini_get_bool('display_errors')) {
 645    define('WARN_DISPLAY_ERRORS_ENABLED', true);
 646}
 647// If we want to display Moodle errors, then try and set PHP errors to match.
 648if (!isset($CFG->debugdisplay)) {
 649    // Keep it "as is" during installation.
 650} else if (NO_DEBUG_DISPLAY) {
 651    // Some parts of Moodle cannot display errors and debug at all.
 652    ini_set('display_errors', '0');
 653    ini_set('log_errors', '1');
 654} else if (empty($CFG->debugdisplay)) {
 655    ini_set('display_errors', '0');
 656    ini_set('log_errors', '1');
 657} else {
 658    // This is very problematic in XHTML strict mode!
 659    ini_set('display_errors', '1');
 660}
 661
 662// Register our shutdown manager, do NOT use register_shutdown_function().
 663core_shutdown_manager::initialize();
 664
 665// Verify upgrade is not running unless we are in a script that needs to execute in any case
 666if (!defined('NO_UPGRADE_CHECK') and isset($CFG->upgraderunning)) {
 667    if ($CFG->upgraderunning < time()) {
 668        unset_config('upgraderunning');
 669    } else {
 670        print_error('upgraderunning');
 671    }
 672}
 673
 674// Turn on SQL logging if required
 675if (!empty($CFG->logsql)) {
 676    $DB->set_logging(true);
 677}
 678
 679// enable circular reference collector in PHP 5.3,
 680// it helps a lot when using large complex OOP structures such as in amos or gradebook
 681if (function_exists('gc_enable')) {
 682    gc_enable();
 683}
 684
 685// detect unsupported upgrade jump as soon as possible - do not change anything, do not use system functions
 686if (!empty($CFG->version) and $CFG->version < 2007101509) {
 687    print_error('upgraderequires19', 'error');
 688    die;
 689}
 690
 691// Calculate and set $CFG->ostype to be used everywhere. Possible values are:
 692// - WINDOWS: for any Windows flavour.
 693// - UNIX: for the rest
 694// Also, $CFG->os can continue being used if more specialization is required
 695if (stristr(PHP_OS, 'win') && !stristr(PHP_OS, 'darwin')) {
 696    $CFG->ostype = 'WINDOWS';
 697} else {
 698    $CFG->ostype = 'UNIX';
 699}
 700$CFG->os = PHP_OS;
 701
 702// Configure ampersands in URLs
 703ini_set('arg_separator.output', '&amp;');
 704
 705// Work around for a PHP bug   see MDL-11237
 706ini_set('pcre.backtrack_limit', 20971520);  // 20 MB
 707
 708// Location of standard files
 709$CFG->wordlist = $CFG->libdir .'/wordlist.txt';
 710$CFG->moddata  = 'moddata';
 711
 712// neutralise nasty chars in PHP_SELF
 713if (isset($_SERVER['PHP_SELF'])) {
 714    $phppos = strpos($_SERVER['PHP_SELF'], '.php');
 715    if ($phppos !== false) {
 716        $_SERVER['PHP_SELF'] = substr($_SERVER['PHP_SELF'], 0, $phppos+4);
 717    }
 718    unset($phppos);
 719}
 720
 721// initialise ME's - this must be done BEFORE starting of session!
 722initialise_fullme();
 723
 724// define SYSCONTEXTID in config.php if you want to save some queries,
 725// after install it must match the system context record id.
 726if (!defined('SYSCONTEXTID')) {
 727    context_system::instance();
 728}
 729
 730// Defining the site - aka frontpage course
 731try {
 732    $SITE = get_site();
 733} catch (moodle_exception $e) {
 734    $SITE = null;
 735    if (empty($CFG->version)) {
 736        $SITE = new stdClass();
 737        $SITE->id = 1;
 738        $SITE->shortname = null;
 739    } else {
 740        throw $e;
 741    }
 742}
 743// And the 'default' course - this will usually get reset later in require_login() etc.
 744$COURSE = clone($SITE);
 745// Id of the frontpage course.
 746define('SITEID', $SITE->id);
 747
 748// init session prevention flag - this is defined on pages that do not want session
 749if (CLI_SCRIPT) {
 750    // no sessions in CLI scripts possible
 751    define('NO_MOODLE_COOKIES', true);
 752
 753} else if (WS_SERVER) {
 754    // No sessions possible in web services.
 755    define('NO_MOODLE_COOKIES', true);
 756
 757} else if (!defined('NO_MOODLE_COOKIES')) {
 758    if (empty($CFG->version) or $CFG->version < 2009011900) {
 759        // no session before sessions table gets created
 760        define('NO_MOODLE_COOKIES', true);
 761    } else if (CLI_SCRIPT) {
 762        // CLI scripts can not have session
 763        define('NO_MOODLE_COOKIES', true);
 764    } else {
 765        define('NO_MOODLE_COOKIES', false);
 766    }
 767}
 768
 769// Start session and prepare global $SESSION, $USER.
 770if (empty($CFG->sessiontimeout)) {
 771    $CFG->sessiontimeout = 7200;
 772}
 773\core\session\manager::start();
 774if (!PHPUNIT_TEST and !defined('BEHAT_TEST')) {
 775    $SESSION =& $_SESSION['SESSION'];
 776    $USER    =& $_SESSION['USER'];
 777}
 778
 779// Initialise some variables that are supposed to be set in config.php only.
 780if (!isset($CFG->filelifetime)) {
 781    $CFG->filelifetime = 60*60*6;
 782}
 783
 784// Late profiling, only happening if early one wasn't started
 785if (!empty($CFG->profilingenabled)) {
 786    require_once($CFG->libdir . '/xhprof/xhprof_moodle.php');
 787    profiling_start();
 788}
 789
 790// Hack to get around max_input_vars restrictions,
 791// we need to do this after session init to have some basic DDoS protection.
 792workaround_max_input_vars();
 793
 794// Process theme change in the URL.
 795if (!empty($CFG->allowthemechangeonurl) and !empty($_GET['theme'])) {
 796    // we have to use _GET directly because we do not want this to interfere with _POST
 797    $urlthemename = optional_param('theme', '', PARAM_PLUGIN);
 798    try {
 799        $themeconfig = theme_config::load($urlthemename);
 800        // Makes sure the theme can be loaded without errors.
 801        if ($themeconfig->name === $urlthemename) {
 802            $SESSION->theme = $urlthemename;
 803        } else {
 804            unset($SESSION->theme);
 805        }
 806        unset($themeconfig);
 807        unset($urlthemename);
 808    } catch (Exception $e) {
 809        debugging('Failed to set the theme from the URL.', DEBUG_DEVELOPER, $e->getTrace());
 810    }
 811}
 812unset($urlthemename);
 813
 814// Ensure a valid theme is set.
 815if (!isset($CFG->theme)) {
 816    $CFG->theme = 'clean';
 817}
 818
 819// Set language/locale of printed times.  If user has chosen a language that
 820// that is different from the site language, then use the locale specified
 821// in the language file.  Otherwise, if the admin hasn't specified a locale
 822// then use the one from the default language.  Otherwise (and this is the
 823// majority of cases), use the stored locale specified by admin.
 824// note: do not accept lang parameter from POST
 825if (isset($_GET['lang']) and ($lang = optional_param('lang', '', PARAM_SAFEDIR))) {
 826    if (get_string_manager()->translation_exists($lang, false)) {
 827        $SESSION->lang = $lang;
 828    }
 829}
 830unset($lang);
 831
 832// PARAM_SAFEDIR used instead of PARAM_LANG because using PARAM_LANG results
 833// in an empty string being returned when a non-existant language is specified,
 834// which would make it necessary to log out to undo the forcelang setting.
 835// With PARAM_SAFEDIR, it's possible to specify ?forcelang=none to drop the forcelang effect.
 836if ($forcelang = optional_param('forcelang', '', PARAM_SAFEDIR)) {
 837    if (isloggedin()
 838        && get_string_manager()->translation_exists($forcelang, false)
 839        && has_capability('moodle/site:forcelanguage', context_system::instance())) {
 840        $SESSION->forcelang = $forcelang;
 841    } else if (isset($SESSION->forcelang)) {
 842        unset($SESSION->forcelang);
 843    }
 844}
 845unset($forcelang);
 846
 847setup_lang_from_browser();
 848
 849if (empty($CFG->lang)) {
 850    if (empty($SESSION->lang)) {
 851        $CFG->lang = 'en';
 852    } else {
 853        $CFG->lang = $SESSION->lang;
 854    }
 855}
 856
 857// Set the default site locale, a lot of the stuff may depend on this
 858// it is definitely too late to call this first in require_login()!
 859moodle_setlocale();
 860
 861// Create the $PAGE global - this marks the PAGE and OUTPUT fully initialised, this MUST be done at the end of setup!
 862if (!empty($CFG->moodlepageclass)) {
 863    if (!empty($CFG->moodlepageclassfile)) {
 864        require_once($CFG->moodlepageclassfile);
 865    }
 866    $classname = $CFG->moodlepageclass;
 867} else {
 868    $classname = 'moodle_page';
 869}
 870$PAGE = new $classname();
 871unset($classname);
 872
 873
 874if (!empty($CFG->debugvalidators) and !empty($CFG->guestloginbutton)) {
 875    if ($CFG->theme == 'standard') {    // Temporary measure to help with XHTML validation
 876        if (isset($_SERVER['HTTP_USER_AGENT']) and empty($USER->id)) {      // Allow W3CValidator in as user called w3cvalidator (or guest)
 877            if ((strpos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') !== false) or
 878                (strpos($_SERVER['HTTP_USER_AGENT'], 'Cynthia') !== false )) {
 879                if ($user = get_complete_user_data("username", "w3cvalidator")) {
 880                    $user->ignoresesskey = true;
 881                } else {
 882                    $user = guest_user();
 883                }
 884                \core\session\manager::set_user($user);
 885            }
 886        }
 887    }
 888}
 889
 890// Apache log integration. In apache conf file one can use ${MOODULEUSER}n in
 891// LogFormat to get the current logged in username in moodle.
 892if ($USER && function_exists('apache_note')
 893    && !empty($CFG->apacheloguser) && isset($USER->username)) {
 894    $apachelog_userid = $USER->id;
 895    $apachelog_username = clean_filename($USER->username);
 896    $apachelog_name = '';
 897    if (isset($USER->firstname)) {
 898        // We can assume both will be set
 899        // - even if to empty.
 900        $apachelog_name = clean_filename($USER->firstname . " " .
 901                                         $USER->lastname);
 902    }
 903    if (\core\session\manager::is_loggedinas()) {
 904        $realuser = \core\session\manager::get_realuser();
 905        $apachelog_username = clean_filename($realuser->username." as ".$apachelog_username);
 906        $apachelog_name = clean_filename($realuser->firstname." ".$realuser->lastname ." as ".$apachelog_name);
 907        $apachelog_userid = clean_filename($realuser->id." as ".$apachelog_userid);
 908    }
 909    switch ($CFG->apacheloguser) {
 910        case 3:
 911            $logname = $apachelog_username;
 912            break;
 913        case 2:
 914            $logname = $apachelog_name;
 915            break;
 916        case 1:
 917        default:
 918            $logname = $apachelog_userid;
 919            break;
 920    }
 921    apache_note('MOODLEUSER', $logname);
 922}
 923
 924// Use a custom script replacement if one exists
 925if (!empty($CFG->customscripts)) {
 926    if (($customscript = custom_script_path()) !== false) {
 927        require ($customscript);
 928    }
 929}
 930
 931if (PHPUNIT_TEST) {
 932    // no ip blocking, these are CLI only
 933} else if (CLI_SCRIPT and !defined('WEB_CRON_EMULATED_CLI')) {
 934    // no ip blocking
 935} else if (!empty($CFG->allowbeforeblock)) { // allowed list processed before blocked list?
 936    // in this case, ip in allowed list will be performed first
 937    // for example, client IP is 192.168.1.1
 938    // 192.168 subnet is an entry in allowed list
 939    // 192.168.1.1 is banned in blocked list
 940    // This ip will be banned finally
 941    if (!empty($CFG->allowedip)) {
 942        if (!remoteip_in_list($CFG->allowedip)) {
 943            die(get_string('ipblocked', 'admin'));
 944        }
 945    }
 946    // need further check, client ip may a part of
 947    // allowed subnet, but a IP address are listed
 948    // in blocked list.
 949    if (!empty($CFG->blockedip)) {
 950        if (remoteip_in_list($CFG->blockedip)) {
 951            die(get_string('ipblocked', 'admin'));
 952        }
 953    }
 954
 955} else {
 956    // in this case, IPs in blocked list will be performed first
 957    // for example, client IP is 192.168.1.1
 958    // 192.168 subnet is an entry in blocked list
 959    // 192.168.1.1 is allowed in allowed list
 960    // This ip will be allowed finally
 961    if (!empty($CFG->blockedip)) {
 962        if (remoteip_in_list($CFG->blockedip)) {
 963            // if the allowed ip list is not empty
 964            // IPs are not included in the allowed list will be
 965            // blocked too
 966            if (!empty($CFG->allowedip)) {
 967                if (!remoteip_in_list($CFG->allowedip)) {
 968                    die(get_string('ipblocked', 'admin'));
 969                }
 970            } else {
 971                die(get_string('ipblocked', 'admin'));
 972            }
 973        }
 974    }
 975    // if blocked list is null
 976    // allowed list should be tested
 977    if(!empty($CFG->allowedip)) {
 978        if (!remoteip_in_list($CFG->allowedip)) {
 979            die(get_string('ipblocked', 'admin'));
 980        }
 981    }
 982
 983}
 984
 985// // try to detect IE6 and prevent gzip because it is extremely buggy browser
 986if (!empty($_SERVER['HTTP_USER_AGENT']) and strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6') !== false) {
 987    ini_set('zlib.output_compression', 'Off');
 988    if (function_exists('apache_setenv')) {
 989        apache_setenv('no-gzip', 1);
 990    }
 991}
 992
 993// Switch to CLI maintenance mode if required, we need to do it here after all the settings are initialised.
 994if (isset($CFG->maintenance_later) and $CFG->maintenance_later <= time()) {
 995    if (!file_exists("$CFG->dataroot/climaintenance.html")) {
 996        require_once("$CFG->libdir/adminlib.php");
 997        enable_cli_maintenance_mode();
 998    }
 999    unset_config('maintenance_later');
1000    if (AJAX_SCRIPT) {
1001        die;
1002    } else if (!CLI_SCRIPT) {
1003        redirect(new moodle_url('/'));
1004    }
1005}
1006
1007// note: we can not block non utf-8 installations here, because empty mysql database
1008// might be converted to utf-8 in admin/index.php during installation
1009
1010
1011
1012// this is a funny trick to make Eclipse believe that $OUTPUT and other globals
1013// contains an instance of core_renderer, etc. which in turn fixes autocompletion ;-)
1014if (false) {
1015    $DB = new moodle_database();
1016    $OUTPUT = new core_renderer(null, null);
1017    $PAGE = new moodle_page();
1018}