/** * Returns system context instance. * * @static * @param int $instanceid * @param int $strictness * @param bool $cache * @return context_system context instance */ public static function instance($instanceid = 0, $strictness = MUST_EXIST, $cache = true) { global $DB; if ($instanceid != 0) { debugging('context_system::instance(): invalid $id parameter detected, should be 0'); } if (defined('SYSCONTEXTID') and $cache) { // dangerous: define this in config.php to eliminate 1 query/page if (!isset(context::$systemcontext)) { $record = new stdClass(); $record->id = SYSCONTEXTID; $record->contextlevel = CONTEXT_SYSTEM; $record->instanceid = 0; $record->path = '/' . SYSCONTEXTID; $record->depth = 1; context::$systemcontext = new context_system($record); } return context::$systemcontext; } try { // we ignore the strictness completely because system context must except except during install $record = $DB->get_record('context', array('contextlevel' => CONTEXT_SYSTEM), '*', MUST_EXIST); } catch (dml_exception $e) { //table or record does not exist if (!during_initial_install()) { // do not mess with system context after install, it simply must exist throw $e; } $record = null; } if (!$record) { $record = new stdClass(); $record->contextlevel = CONTEXT_SYSTEM; $record->instanceid = 0; $record->depth = 1; $record->path = null; //not known before insert try { if ($DB->count_records('context')) { // contexts already exist, this is very weird, system must be first!!! return null; } if (defined('SYSCONTEXTID')) { // this would happen only in unittest on sites that went through weird 1.7 upgrade $record->id = SYSCONTEXTID; $DB->import_record('context', $record); $DB->get_manager()->reset_sequence('context'); } else { $record->id = $DB->insert_record('context', $record); } } catch (dml_exception $e) { // can not create context - table does not exist yet, sorry return null; } } if ($record->instanceid != 0) { // this is very weird, somebody must be messing with context table debugging('Invalid system context detected'); } if ($record->depth != 1 or $record->path != '/' . $record->id) { // fix path if necessary, initial install or path reset $record->depth = 1; $record->path = '/' . $record->id; $DB->update_record('context', $record); } if (!defined('SYSCONTEXTID')) { define('SYSCONTEXTID', $record->id); } context::$systemcontext = new context_system($record); return context::$systemcontext; }