PageRenderTime 51ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/trunk/MoodleWebRole/lib/setup.php

#
PHP | 786 lines | 497 code | 105 blank | 184 comment | 173 complexity | 88da9247ec83902aef06fe65c060a678 MD5 | raw file
Possible License(s): LGPL-2.1, BSD-3-Clause, LGPL-2.0, GPL-2.0
  1. <?php
  2. /**
  3. * setup.php - Sets up sessions, connects to databases and so on
  4. *
  5. * Normally this is only called by the main config.php file
  6. * Normally this file does not need to be edited.
  7. * @author Martin Dougiamas
  8. * @version $Id: setup.php,v 1.212.2.30 2010/05/21 11:39:44 skodak Exp $
  9. * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
  10. * @package moodlecore
  11. */
  12. ////// DOCUMENTATION IN PHPDOC FORMAT FOR MOODLE GLOBALS AND COMMON OBJECT TYPES /////////////
  13. /**
  14. * $USER is a global instance of a typical $user record.
  15. *
  16. * Items found in the user record:
  17. * - $USER->emailstop - Does the user want email sent to them?
  18. * - $USER->email - The user's email address.
  19. * - $USER->id - The unique integer identified of this user in the 'user' table.
  20. * - $USER->email - The user's email address.
  21. * - $USER->firstname - The user's first name.
  22. * - $USER->lastname - The user's last name.
  23. * - $USER->username - The user's login username.
  24. * - $USER->secret - The user's ?.
  25. * - $USER->lang - The user's language choice.
  26. *
  27. * @global object(user) $USER
  28. */
  29. global $USER;
  30. /**
  31. * This global variable is read in from the 'config' table.
  32. *
  33. * Some typical settings in the $CFG global:
  34. * - $CFG->wwwroot - Path to moodle index directory in url format.
  35. * - $CFG->dataroot - Path to moodle index directory on server's filesystem.
  36. * - $CFG->libdir - Path to moodle's library folder on server's filesystem.
  37. *
  38. * @global object(cfg) $CFG
  39. */
  40. global $CFG;
  41. /**
  42. * Definition of session type
  43. * @global object(session) $SESSION
  44. */
  45. global $SESSION;
  46. /**
  47. * Definition of shared memory cache
  48. */
  49. global $MCACHE;
  50. /**
  51. * Definition of course type
  52. * @global object(course) $COURSE
  53. */
  54. global $COURSE;
  55. /**
  56. * Definition of db type
  57. * @global object(db) $db
  58. */
  59. global $db;
  60. /**
  61. * $THEME is a global that defines the site theme.
  62. *
  63. * Items found in the theme record:
  64. * - $THEME->cellheading - Cell colors.
  65. * - $THEME->cellheading2 - Alternate cell colors.
  66. *
  67. * @global object(theme) $THEME
  68. */
  69. global $THEME;
  70. /**
  71. * HTTPSPAGEREQUIRED is a global to define if the page being displayed must run under HTTPS.
  72. *
  73. * It's primary goal is to allow 100% HTTPS pages when $CFG->loginhttps is enabled. Default to false.
  74. * It's enabled only by the httpsrequired() function and used in some pages to update some URLs
  75. */
  76. global $HTTPSPAGEREQUIRED;
  77. /// First try to detect some attacks on older buggy PHP versions
  78. if (isset($_REQUEST['GLOBALS']) || isset($_COOKIE['GLOBALS']) || isset($_FILES['GLOBALS'])) {
  79. die('Fatal: Illegal GLOBALS overwrite attempt detected!');
  80. }
  81. if (!isset($CFG->wwwroot)) {
  82. trigger_error('Fatal: $CFG->wwwroot is not configured! Exiting.');
  83. die;
  84. }
  85. /// sometimes default PHP settings are borked on shared hosting servers, I wonder why they have to do that??
  86. @ini_set('precision', 14); // needed for upgrades and gradebook
  87. /// New versions of HTML Purifier are not compatible with PHP 4
  88. if (version_compare(phpversion(), "5.0.5") < 0) {
  89. $CFG->enablehtmlpurifier = 0;
  90. }
  91. /// store settings from config.php in array in $CFG - we can use it later to detect problems and overrides
  92. $CFG->config_php_settings = (array)$CFG;
  93. /// Set httpswwwroot default value (this variable will replace $CFG->wwwroot
  94. /// inside some URLs used in HTTPSPAGEREQUIRED pages.
  95. $CFG->httpswwwroot = $CFG->wwwroot;
  96. $CFG->libdir = $CFG->dirroot .'/lib';
  97. require_once($CFG->libdir .'/setuplib.php'); // Functions that MUST be loaded first
  98. /// Time to start counting
  99. init_performance_info();
  100. /// If there are any errors in the standard libraries we want to know!
  101. error_reporting(E_ALL);
  102. /// Just say no to link prefetching (Moz prefetching, Google Web Accelerator, others)
  103. /// http://www.google.com/webmasters/faq.html#prefetchblock
  104. if (!empty($_SERVER['HTTP_X_moz']) && $_SERVER['HTTP_X_moz'] === 'prefetch'){
  105. header($_SERVER['SERVER_PROTOCOL'] . ' 404 Prefetch Forbidden');
  106. trigger_error('Prefetch request forbidden.');
  107. exit;
  108. }
  109. /// Connect to the database using adodb
  110. /// Set $CFG->dbfamily global
  111. /// and configure some other specific variables for each db BEFORE attempting the connection
  112. preconfigure_dbconnection();
  113. require_once($CFG->libdir .'/adodb/adodb.inc.php'); // Database access functions
  114. $db = &ADONewConnection($CFG->dbtype);
  115. // See MDL-6760 for why this is necessary. In Moodle 1.8, once we start using NULLs properly,
  116. // we probably want to change this value to ''.
  117. $db->null2null = 'A long random string that will never, ever match something we want to insert into the database, I hope. \'';
  118. error_reporting(0); // Hide errors
  119. if (!isset($CFG->dbpersist) or !empty($CFG->dbpersist)) { // Use persistent connection (default)
  120. $dbconnected = $db->PConnect($CFG->dbhost,$CFG->dbuser,$CFG->dbpass,$CFG->dbname);
  121. } else { // Use single connection
  122. $dbconnected = $db->Connect($CFG->dbhost,$CFG->dbuser,$CFG->dbpass,$CFG->dbname);
  123. }
  124. if (! $dbconnected) {
  125. // In the name of protocol correctness, monitoring and performance
  126. // profiling, set the appropriate error headers for machine comsumption
  127. if (isset($_SERVER['SERVER_PROTOCOL'])) {
  128. // Avoid it with cron.php. Note that we assume it's HTTP/1.x
  129. header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
  130. }
  131. // and then for human consumption...
  132. echo '<html><body>';
  133. echo '<table align="center"><tr>';
  134. echo '<td style="color:#990000; text-align:center; font-size:large; border-width:1px; '.
  135. ' border-color:#000000; border-style:solid; border-radius: 20px; border-collapse: collapse; '.
  136. ' -moz-border-radius: 20px; padding: 15px">';
  137. echo '<p>Error: Database connection failed.</p>';
  138. echo '<p>It is possible that the database is overloaded or otherwise not running properly.</p>';
  139. echo '<p>The site administrator should also check that the database details have been correctly specified in config.php</p>';
  140. echo '</td></tr></table>';
  141. echo '</body></html>';
  142. error_log('ADODB Error: '.$db->ErrorMsg()); // see MDL-14628
  143. if (empty($CFG->noemailever) and !empty($CFG->emailconnectionerrorsto)) {
  144. if (file_exists($CFG->dataroot.'/emailcount')){
  145. $fp = fopen($CFG->dataroot.'/emailcount', 'r');
  146. $content = fread($fp, 24);
  147. fclose($fp);
  148. if((time() - (int)$content) > 600){
  149. mail($CFG->emailconnectionerrorsto,
  150. 'WARNING: Database connection error: '.$CFG->wwwroot,
  151. 'Connection error: '.$CFG->wwwroot);
  152. $fp = fopen($CFG->dataroot.'/emailcount', 'w');
  153. fwrite($fp, time());
  154. }
  155. } else {
  156. mail($CFG->emailconnectionerrorsto,
  157. 'WARNING: Database connection error: '.$CFG->wwwroot,
  158. 'Connection error: '.$CFG->wwwroot);
  159. $fp = fopen($CFG->dataroot.'/emailcount', 'w');
  160. fwrite($fp, time());
  161. }
  162. }
  163. die;
  164. }
  165. /// Forcing ASSOC mode for ADOdb (some DBs default to FETCH_BOTH)
  166. $db->SetFetchMode(ADODB_FETCH_ASSOC);
  167. /// Starting here we have a correct DB conection but me must avoid
  168. /// to execute any DB transaction until "set names" has been executed
  169. /// some lines below!
  170. error_reporting(E_ALL); // Show errors from now on.
  171. if (!isset($CFG->prefix)) { // Just in case it isn't defined in config.php
  172. $CFG->prefix = '';
  173. }
  174. /// Define admin directory
  175. if (!isset($CFG->admin)) { // Just in case it isn't defined in config.php
  176. $CFG->admin = 'admin'; // This is relative to the wwwroot and dirroot
  177. }
  178. /// Increase memory limits if possible
  179. raise_memory_limit('96M'); // We should never NEED this much but just in case...
  180. /// Load up standard libraries
  181. require_once($CFG->libdir .'/textlib.class.php'); // Functions to handle multibyte strings
  182. require_once($CFG->libdir .'/weblib.php'); // Functions for producing HTML
  183. require_once($CFG->libdir .'/dmllib.php'); // Functions to handle DB data (DML)
  184. require_once($CFG->libdir .'/datalib.php'); // Legacy lib with a big-mix of functions.
  185. require_once($CFG->libdir .'/accesslib.php'); // Access control functions
  186. require_once($CFG->libdir .'/deprecatedlib.php'); // Deprecated functions included for backward compatibility
  187. require_once($CFG->libdir .'/moodlelib.php'); // Other general-purpose functions
  188. require_once($CFG->libdir .'/eventslib.php'); // Events functions
  189. require_once($CFG->libdir .'/grouplib.php'); // Groups functions
  190. //point pear include path to moodles lib/pear so that includes and requires will search there for files before anywhere else
  191. //the problem is that we need specific version of quickforms and hacked excel files :-(
  192. ini_set('include_path', $CFG->libdir.'/pear' . PATH_SEPARATOR . ini_get('include_path'));
  193. /// Disable errors for now - needed for installation when debug enabled in config.php
  194. if (isset($CFG->debug)) {
  195. $originalconfigdebug = $CFG->debug;
  196. unset($CFG->debug);
  197. } else {
  198. $originalconfigdebug = -1;
  199. }
  200. /// Set the client/server and connection to utf8
  201. /// and configure some other specific variables for each db
  202. configure_dbconnection();
  203. /// Load up any configuration from the config table
  204. $CFG = get_config();
  205. /// Turn on SQL logging if required
  206. if (!empty($CFG->logsql)) {
  207. $db->LogSQL();
  208. // And override ADODB's default logging time
  209. if (isset($CFG->logsqlmintime)) {
  210. global $ADODB_PERF_MIN;
  211. $ADODB_PERF_MIN = $CFG->logsqlmintime;
  212. }
  213. }
  214. /// Prevent warnings from roles when upgrading with debug on
  215. if (isset($CFG->debug)) {
  216. $originaldatabasedebug = $CFG->debug;
  217. unset($CFG->debug);
  218. } else {
  219. $originaldatabasedebug = -1;
  220. }
  221. /// For now, only needed under apache (and probably unstable in other contexts)
  222. if (function_exists('register_shutdown_function')) {
  223. register_shutdown_function('moodle_request_shutdown');
  224. }
  225. /// Defining the site
  226. if ($SITE = get_site()) {
  227. /**
  228. * If $SITE global from {@link get_site()} is set then SITEID to $SITE->id, otherwise set to 1.
  229. */
  230. define('SITEID', $SITE->id);
  231. /// And the 'default' course
  232. $COURSE = clone($SITE); // For now. This will usually get reset later in require_login() etc.
  233. } else {
  234. /**
  235. * @ignore
  236. */
  237. define('SITEID', 1);
  238. /// And the 'default' course
  239. $COURSE = new object; // no site created yet
  240. $COURSE->id = 1;
  241. }
  242. // define SYSCONTEXTID in config.php if you want to save some queries (after install or upgrade!)
  243. if (!defined('SYSCONTEXTID')) {
  244. get_system_context();
  245. }
  246. /// Set error reporting back to normal
  247. if ($originaldatabasedebug == -1) {
  248. $CFG->debug = DEBUG_MINIMAL;
  249. } else {
  250. $CFG->debug = $originaldatabasedebug;
  251. }
  252. if ($originalconfigdebug !== -1) {
  253. $CFG->debug = $originalconfigdebug;
  254. }
  255. unset($originalconfigdebug);
  256. unset($originaldatabasedebug);
  257. error_reporting($CFG->debug);
  258. /// find out if PHP cofigured to display warnings
  259. if (ini_get_bool('display_errors')) {
  260. define('WARN_DISPLAY_ERRORS_ENABLED', true);
  261. }
  262. /// If we want to display Moodle errors, then try and set PHP errors to match
  263. if (!isset($CFG->debugdisplay)) {
  264. //keep it as is during installation
  265. } else if (empty($CFG->debugdisplay)) {
  266. @ini_set('display_errors', '0');
  267. @ini_set('log_errors', '1');
  268. } else {
  269. @ini_set('display_errors', '1');
  270. }
  271. // Even when users want to see errors in the output,
  272. // some parts of Moodle cannot display them at all.
  273. // (Once we are XHTML strict compliant, debugdisplay
  274. // _must_ go away).
  275. if (defined('MOODLE_SANE_OUTPUT')) {
  276. @ini_set('display_errors', '0');
  277. @ini_set('log_errors', '1');
  278. }
  279. /// Shared-Memory cache init -- will set $MCACHE
  280. /// $MCACHE is a global object that offers at least add(), set() and delete()
  281. /// with similar semantics to the memcached PHP API http://php.net/memcache
  282. /// Ensure we define rcache - so we can later check for it
  283. /// with a really fast and unambiguous $CFG->rcache === false
  284. if (!empty($CFG->cachetype)) {
  285. if (empty($CFG->rcache)) {
  286. $CFG->rcache = false;
  287. } else {
  288. $CFG->rcache = true;
  289. }
  290. // do not try to initialize if cache disabled
  291. if (!$CFG->rcache) {
  292. $CFG->cachetype = '';
  293. }
  294. if ($CFG->cachetype === 'memcached' && !empty($CFG->memcachedhosts)) {
  295. if (!init_memcached()) {
  296. debugging("Error initialising memcached");
  297. $CFG->cachetype = '';
  298. $CFG->rcache = false;
  299. }
  300. } else if ($CFG->cachetype === 'eaccelerator') {
  301. if (!init_eaccelerator()) {
  302. debugging("Error initialising eaccelerator cache");
  303. $CFG->cachetype = '';
  304. $CFG->rcache = false;
  305. }
  306. }
  307. } else { // just make sure it is defined
  308. $CFG->cachetype = '';
  309. $CFG->rcache = false;
  310. }
  311. /// Set a default enrolment configuration (see bug 1598)
  312. if (!isset($CFG->enrol)) {
  313. $CFG->enrol = 'manual';
  314. }
  315. /// Set default enabled enrolment plugins
  316. if (!isset($CFG->enrol_plugins_enabled)) {
  317. $CFG->enrol_plugins_enabled = 'manual';
  318. }
  319. /// File permissions on created directories in the $CFG->dataroot
  320. if (empty($CFG->directorypermissions)) {
  321. $CFG->directorypermissions = 0777; // Must be octal (that's why it's here)
  322. }
  323. /// Calculate and set $CFG->ostype to be used everywhere. Possible values are:
  324. /// - WINDOWS: for any Windows flavour.
  325. /// - UNIX: for the rest
  326. /// Also, $CFG->os can continue being used if more specialization is required
  327. if (stristr(PHP_OS, 'win') && !stristr(PHP_OS, 'darwin')) {
  328. $CFG->ostype = 'WINDOWS';
  329. } else {
  330. $CFG->ostype = 'UNIX';
  331. }
  332. $CFG->os = PHP_OS;
  333. /// Set up default frame target string, based on $CFG->framename
  334. $CFG->frametarget = frametarget();
  335. /// Setup cache dir for Smarty and others
  336. if (!file_exists($CFG->dataroot .'/cache')) {
  337. make_upload_directory('cache');
  338. }
  339. /// Set up smarty template system
  340. //require_once($CFG->libdir .'/smarty/Smarty.class.php');
  341. //$smarty = new Smarty;
  342. //$smarty->template_dir = $CFG->dirroot .'/templates/'. $CFG->template;
  343. //if (!file_exists($CFG->dataroot .'/cache/smarty')) {
  344. // make_upload_directory('cache/smarty');
  345. //}
  346. //$smarty->compile_dir = $CFG->dataroot .'/cache/smarty';
  347. /// Set up session handling
  348. if(empty($CFG->respectsessionsettings)) {
  349. if (empty($CFG->dbsessions)) { /// File-based sessions
  350. // Some distros disable GC by setting probability to 0
  351. // overriding the PHP default of 1
  352. // (gc_probability is divided by gc_divisor, which defaults to 1000)
  353. if (ini_get('session.gc_probability') == 0) {
  354. ini_set('session.gc_probability', 1);
  355. }
  356. if (!empty($CFG->sessiontimeout)) {
  357. ini_set('session.gc_maxlifetime', $CFG->sessiontimeout);
  358. }
  359. if (!file_exists($CFG->dataroot .'/sessions')) {
  360. make_upload_directory('sessions');
  361. }
  362. ini_set('session.save_path', $CFG->dataroot .'/sessions');
  363. } else { /// Database sessions
  364. ini_set('session.save_handler', 'user');
  365. $ADODB_SESSION_DRIVER = $CFG->dbtype;
  366. $ADODB_SESSION_CONNECT = $CFG->dbhost;
  367. $ADODB_SESSION_USER = $CFG->dbuser;
  368. $ADODB_SESSION_PWD = $CFG->dbpass;
  369. $ADODB_SESSION_DB = $CFG->dbname;
  370. $ADODB_SESSION_TBL = $CFG->prefix.'sessions2';
  371. if (!empty($CFG->sessiontimeout)) {
  372. $ADODB_SESS_LIFE = $CFG->sessiontimeout;
  373. }
  374. require_once($CFG->libdir. '/adodb/session/adodb-session2.php');
  375. }
  376. }
  377. /// Set sessioncookie and sessioncookiepath variable if it isn't already
  378. if (!isset($CFG->sessioncookie)) {
  379. $CFG->sessioncookie = '';
  380. }
  381. if (!isset($CFG->sessioncookiedomain)) {
  382. $CFG->sessioncookiedomain = '';
  383. }
  384. if (!isset($CFG->sessioncookiepath)) {
  385. $CFG->sessioncookiepath = '/';
  386. }
  387. /// Configure ampersands in URLs
  388. @ini_set('arg_separator.output', '&amp;');
  389. /// Work around for a PHP bug see MDL-11237
  390. @ini_set('pcre.backtrack_limit', 20971520); // 20 MB
  391. /// Location of standard files
  392. $CFG->wordlist = $CFG->libdir .'/wordlist.txt';
  393. $CFG->javascript = $CFG->libdir .'/javascript.php';
  394. $CFG->moddata = 'moddata';
  395. // Alas, in some cases we cannot deal with magic_quotes.
  396. if (defined('MOODLE_SANE_INPUT') && ini_get_bool('magic_quotes_gpc')) {
  397. mdie("Facilities that require MOODLE_SANE_INPUT "
  398. . "cannot work with magic_quotes_gpc. Please disable "
  399. . "magic_quotes_gpc.");
  400. }
  401. /// A hack to get around magic_quotes_gpc being turned off
  402. /// It is strongly recommended to enable "magic_quotes_gpc"!
  403. if (!ini_get_bool('magic_quotes_gpc') && !defined('MOODLE_SANE_INPUT') ) {
  404. function addslashes_deep($value) {
  405. $value = is_array($value) ?
  406. array_map('addslashes_deep', $value) :
  407. addslashes($value);
  408. return $value;
  409. }
  410. $_POST = array_map('addslashes_deep', $_POST);
  411. $_GET = array_map('addslashes_deep', $_GET);
  412. $_COOKIE = array_map('addslashes_deep', $_COOKIE);
  413. $_REQUEST = array_map('addslashes_deep', $_REQUEST);
  414. if (!empty($_SERVER['REQUEST_URI'])) {
  415. $_SERVER['REQUEST_URI'] = addslashes($_SERVER['REQUEST_URI']);
  416. }
  417. if (!empty($_SERVER['QUERY_STRING'])) {
  418. $_SERVER['QUERY_STRING'] = addslashes($_SERVER['QUERY_STRING']);
  419. }
  420. if (!empty($_SERVER['HTTP_REFERER'])) {
  421. $_SERVER['HTTP_REFERER'] = addslashes($_SERVER['HTTP_REFERER']);
  422. }
  423. if (!empty($_SERVER['PATH_INFO'])) {
  424. $_SERVER['PATH_INFO'] = addslashes($_SERVER['PATH_INFO']);
  425. }
  426. if (!empty($_SERVER['PHP_SELF'])) {
  427. $_SERVER['PHP_SELF'] = addslashes($_SERVER['PHP_SELF']);
  428. }
  429. if (!empty($_SERVER['PATH_TRANSLATED'])) {
  430. $_SERVER['PATH_TRANSLATED'] = addslashes($_SERVER['PATH_TRANSLATED']);
  431. }
  432. }
  433. /// neutralise nasty chars in PHP_SELF
  434. if (isset($_SERVER['PHP_SELF'])) {
  435. $phppos = strpos($_SERVER['PHP_SELF'], '.php');
  436. if ($phppos !== false) {
  437. $_SERVER['PHP_SELF'] = substr($_SERVER['PHP_SELF'], 0, $phppos+4);
  438. }
  439. unset($phppos);
  440. }
  441. /// The following code can emulate "register globals" if required.
  442. /// This hack is no longer being applied as of Moodle 1.6 unless you really
  443. /// really want to use it (by defining $CFG->enableglobalshack = true)
  444. if (!empty($CFG->enableglobalshack) && !defined('MOODLE_SANE_INPUT')) {
  445. if (!empty($CFG->detect_unchecked_vars)) {
  446. global $UNCHECKED_VARS;
  447. $UNCHECKED_VARS->url = $_SERVER['PHP_SELF'];
  448. $UNCHECKED_VARS->vars = array();
  449. }
  450. if (isset($_GET)) {
  451. extract($_GET, EXTR_SKIP); // Skip existing variables, ie CFG
  452. if (!empty($CFG->detect_unchecked_vars)) {
  453. foreach ($_GET as $key => $val) {
  454. $UNCHECKED_VARS->vars[$key]=$val;
  455. }
  456. }
  457. }
  458. if (isset($_POST)) {
  459. extract($_POST, EXTR_SKIP); // Skip existing variables, ie CFG
  460. if (!empty($CFG->detect_unchecked_vars)) {
  461. foreach ($_POST as $key => $val) {
  462. $UNCHECKED_VARS->vars[$key]=$val;
  463. }
  464. }
  465. }
  466. if (isset($_SERVER)) {
  467. extract($_SERVER);
  468. }
  469. }
  470. /// Load up global environment variables
  471. if (!isset($CFG->cookiesecure) or strpos($CFG->wwwroot, 'https://') !== 0) {
  472. $CFG->cookiesecure = false;
  473. }
  474. if (!isset($CFG->cookiehttponly)) {
  475. $CFG->cookiehttponly = false;
  476. }
  477. //discard session ID from POST, GET and globals to tighten security,
  478. //this session fixation prevention can not be used in cookieless mode
  479. if (empty($CFG->usesid) && !defined('MOODLE_SANE_INPUT')) {
  480. unset(${'MoodleSession'.$CFG->sessioncookie});
  481. unset($_GET['MoodleSession'.$CFG->sessioncookie]);
  482. unset($_POST['MoodleSession'.$CFG->sessioncookie]);
  483. }
  484. //compatibility hack for Moodle Cron, cookies not deleted, but set to "deleted" - should not be needed with $nomoodlecookie in cron.php now
  485. if (!empty($_COOKIE['MoodleSession'.$CFG->sessioncookie]) && $_COOKIE['MoodleSession'.$CFG->sessioncookie] == "deleted") {
  486. unset($_COOKIE['MoodleSession'.$CFG->sessioncookie]);
  487. }
  488. if (!empty($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie]) && $_COOKIE['MoodleSessionTest'.$CFG->sessioncookie] == "deleted") {
  489. unset($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie]);
  490. }
  491. if (empty($nomoodlecookie)) {
  492. session_name('MoodleSession'.$CFG->sessioncookie);
  493. if (check_php_version('5.2.0')) {
  494. session_set_cookie_params(0, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $CFG->cookiesecure, $CFG->cookiehttponly);
  495. } else {
  496. session_set_cookie_params(0, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $CFG->cookiesecure);
  497. }
  498. @session_start();
  499. if (! isset($_SESSION['SESSION'])) {
  500. $_SESSION['SESSION'] = new object;
  501. $_SESSION['SESSION']->session_test = random_string(10);
  502. if (!empty($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie])) {
  503. $_SESSION['SESSION']->has_timed_out = true;
  504. }
  505. if (check_php_version('5.2.0')) {
  506. setcookie('MoodleSessionTest'.$CFG->sessioncookie, $_SESSION['SESSION']->session_test, 0, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $CFG->cookiesecure, $CFG->cookiehttponly);
  507. } else {
  508. setcookie('MoodleSessionTest'.$CFG->sessioncookie, $_SESSION['SESSION']->session_test, 0, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $CFG->cookiesecure);
  509. }
  510. $_COOKIE['MoodleSessionTest'.$CFG->sessioncookie] = $_SESSION['SESSION']->session_test;
  511. }
  512. if (! isset($_SESSION['USER'])) {
  513. $_SESSION['USER'] = new object;
  514. }
  515. $SESSION = &$_SESSION['SESSION']; // Makes them easier to reference
  516. $USER = &$_SESSION['USER'];
  517. if (!isset($USER->id)) {
  518. $USER->id = 0; // to enable proper function of $CFG->notloggedinroleid hack
  519. }
  520. }
  521. else {
  522. $SESSION = NULL;
  523. $USER = new object();
  524. $USER->id = 0; // user not logged in when session disabled
  525. if (isset($CFG->mnet_localhost_id)) {
  526. $USER->mnethostid = $CFG->mnet_localhost_id;
  527. }
  528. }
  529. if (defined('FULLME')) { // Usually in command-line scripts like admin/cron.php
  530. $FULLME = FULLME;
  531. $ME = FULLME;
  532. } else {
  533. $FULLME = qualified_me();
  534. $ME = strip_querystring($FULLME);
  535. }
  536. if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
  537. require_once("$CFG->dirroot/lib/cookieless.php");
  538. }
  539. /// In VERY rare cases old PHP server bugs (it has been found on PHP 4.1.2 running
  540. /// as a CGI under IIS on Windows) may require that you uncomment the following:
  541. // session_register("USER");
  542. // session_register("SESSION");
  543. /// Load up theme variables (colours etc)
  544. if (!isset($CFG->themedir)) {
  545. $CFG->themedir = $CFG->dirroot.'/theme';
  546. $CFG->themewww = $CFG->wwwroot.'/theme';
  547. }
  548. $CFG->httpsthemewww = $CFG->themewww;
  549. if (isset($_GET['theme'])) {
  550. if ($CFG->allowthemechangeonurl || confirm_sesskey()) {
  551. $themename = clean_param($_GET['theme'], PARAM_SAFEDIR);
  552. if (($themename != '') and file_exists($CFG->themedir.'/'.$themename)) {
  553. $SESSION->theme = $themename;
  554. }
  555. unset($themename);
  556. }
  557. }
  558. if (!isset($CFG->theme)) {
  559. $CFG->theme = 'standardwhite';
  560. }
  561. /// now do a session test to prevent random user switching - observed on some PHP/Apache combinations,
  562. /// disable checks when working in cookieless mode
  563. if (empty($CFG->usesid) || !empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
  564. if ($SESSION != NULL) {
  565. if (empty($_COOKIE['MoodleSessionTest'.$CFG->sessioncookie])) {
  566. report_session_error();
  567. } else if (isset($SESSION->session_test) && $_COOKIE['MoodleSessionTest'.$CFG->sessioncookie] != $SESSION->session_test) {
  568. report_session_error();
  569. }
  570. }
  571. }
  572. /// Set language/locale of printed times. If user has chosen a language that
  573. /// that is different from the site language, then use the locale specified
  574. /// in the language file. Otherwise, if the admin hasn't specified a locale
  575. /// then use the one from the default language. Otherwise (and this is the
  576. /// majority of cases), use the stored locale specified by admin.
  577. if ($SESSION !== NULL && isset($_GET['lang']) && ($lang = clean_param($_GET['lang'], PARAM_SAFEDIR))) {
  578. if (file_exists($CFG->dataroot .'/lang/'. $lang) or file_exists($CFG->dirroot .'/lang/'. $lang)) {
  579. $SESSION->lang = $lang;
  580. } else if (file_exists($CFG->dataroot.'/lang/'.$lang.'_utf8') or
  581. file_exists($CFG->dirroot .'/lang/'.$lang.'_utf8')) {
  582. $SESSION->lang = $lang.'_utf8';
  583. }
  584. }
  585. setup_lang_from_browser();
  586. unset($lang);
  587. if (empty($CFG->lang)) {
  588. if (empty($SESSION->lang)) {
  589. $CFG->lang = 'en_utf8';
  590. } else {
  591. $CFG->lang = $SESSION->lang;
  592. }
  593. }
  594. // set default locale and themes - might be changed again later from require_login()
  595. course_setup();
  596. if (!empty($CFG->opentogoogle)) {
  597. if (empty($USER->id)) { // Ignore anyone logged in
  598. if (!empty($_SERVER['HTTP_USER_AGENT'])) {
  599. if (strpos($_SERVER['HTTP_USER_AGENT'], 'Googlebot') !== false ) {
  600. $USER = guest_user();
  601. } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'google.com') !== false ) { // Google
  602. $USER = guest_user();
  603. } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Yahoo! Slurp') !== false ) { // Yahoo
  604. $USER = guest_user();
  605. } else if (strpos($_SERVER['HTTP_USER_AGENT'], '[ZSEBOT]') !== false ) { // Zoomspider
  606. $USER = guest_user();
  607. } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSNBOT') !== false ) { // MSN Search
  608. $USER = guest_user();
  609. }
  610. }
  611. if (!empty($CFG->guestloginbutton) && empty($USER) && !empty($_SERVER['HTTP_REFERER'])) {
  612. if (strpos($_SERVER['HTTP_REFERER'], 'google') !== false ) {
  613. $USER = guest_user();
  614. } else if (strpos($_SERVER['HTTP_REFERER'], 'altavista') !== false ) {
  615. $USER = guest_user();
  616. }
  617. }
  618. if (!empty($USER)) {
  619. load_all_capabilities();
  620. }
  621. }
  622. }
  623. if (!empty($CFG->guestloginbutton)) {
  624. if ($CFG->theme == 'standard' or $CFG->theme == 'standardwhite') { // Temporary measure to help with XHTML validation
  625. if (isset($_SERVER['HTTP_USER_AGENT']) and empty($_SESSION['USER']->id)) { // Allow W3CValidator in as user called w3cvalidator (or guest)
  626. if ((strpos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') !== false) or
  627. (strpos($_SERVER['HTTP_USER_AGENT'], 'Cynthia') !== false )) {
  628. if ($USER = get_complete_user_data("username", "w3cvalidator")) {
  629. $USER->ignoresesskey = true;
  630. } else {
  631. $USER = guest_user();
  632. }
  633. }
  634. }
  635. }
  636. }
  637. /// Apache log intergration. In apache conf file one can use ${MOODULEUSER}n in
  638. /// LogFormat to get the current logged in username in moodle.
  639. if ($USER && function_exists('apache_note')
  640. && !empty($CFG->apacheloguser) && isset($USER->username)) {
  641. $apachelog_userid = $USER->id;
  642. $apachelog_username = clean_filename($USER->username);
  643. $apachelog_name = '';
  644. if (isset($USER->firstname)) {
  645. // We can assume both will be set
  646. // - even if to empty.
  647. $apachelog_name = clean_filename($USER->firstname . " " .
  648. $USER->lastname);
  649. }
  650. if (isset($USER->realuser)) {
  651. if ($realuser = get_record('user', 'id', $USER->realuser)) {
  652. $apachelog_username = clean_filename($realuser->username." as ".$apachelog_username);
  653. $apachelog_name = clean_filename($realuser->firstname." ".$realuser->lastname ." as ".$apachelog_name);
  654. $apachelog_userid = clean_filename($realuser->id." as ".$apachelog_userid);
  655. }
  656. }
  657. switch ($CFG->apacheloguser) {
  658. case 3:
  659. $logname = $apachelog_username;
  660. break;
  661. case 2:
  662. $logname = $apachelog_name;
  663. break;
  664. case 1:
  665. default:
  666. $logname = $apachelog_userid;
  667. break;
  668. }
  669. apache_note('MOODLEUSER', $logname);
  670. }
  671. /// Adjust ALLOWED_TAGS
  672. adjust_allowed_tags();
  673. /// Use a custom script replacement if one exists
  674. if (!empty($CFG->customscripts)) {
  675. if (($customscript = custom_script_path()) !== false) {
  676. require ($customscript);
  677. }
  678. }
  679. /// note: we can not block non utf-8 installatrions here, because empty mysql database
  680. /// might be converted to utf-8 in admin/index.php during installation
  681. ?>