PageRenderTime 68ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/setup.php

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