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