ÿØÿà JFIF    ÿÛ „  ( %!1"%)+...383-7(-.+  -%%--------+------------/----------------------------ÿÀ  ¶" ÿÄ     ÿÄ @    !1AQaq‘¡"±ÁÑð2’BRráS‚ñ3b¢CT²Ò #cÿÄ    ÿÄ '   1!AQ2a"‘±#ÿÚ   ? ò(/p‘—–¢·,M|¯G»R£üešT. ôŸEoCFñ‡ 4ÔkåóxR|µÁ¨ÓDà!Ç´µ˜‡p ÍQ‹§!þž^õWsŒy  åÁ§$á«%ºq˜™JyyË0y«^Ϗ -3ÃÏËÈ£Æ\P’ä„s&•‹Üs üô'àWt¹pñCp$bÚF`·7.^)¾!)ÒÙ˜–ÅÏš^h¾ø³·ìe±ŒaeÖ—Í,e=B}Jéߦ$$½—šÙÜCC¯¶è8β–Åkèwx LÉngT±æ¹£Ócœ¿Í/©Éÿ ‰ÚCÒ­mq;Tt¶–}0"zÖPcd1š­¤tˆ„ÐÓâqú[™öUCŠ2޿د­É(¸ßúçšmW,Ò ºf‹Ån™ÄLêÁ8üÁkÁ€L¥ÍuJ1œôrÂSŒÓöt!7EUíïb)AËi¬â-ÙHk8òÁiXYwÅ)O^"ÇØriÛô{»wRUKÙÏÚlÓ¬€‚’שT ] ªb—ÊîKC^×M“xùäñz¬zJ× {4[¹M'IÆeH1LCWÕ]œûº WDæà°OÅ‚¹c²ÞuA–rL`HšpCez‡V’— Ž‚Ë„–ñ­'µR0ÕÖ=À:±G»C\nÆÉ5*¢ †3šhQ4ýÒi$Õ1"Ü]¢p-q3zcQ$ªö¨¥æf›‘»´ÝÚHá„e²JÇ–iÊ:·à¬Øc5Åk»Laª*wi [0Ówk ¦a¦0Õ²ÅÅ‚T¸’³q:Æ<¹ú Ò˜Æ}2VE•Ѐp¡Ô3Úº …h³^LJºçì¥Ánó|˜ÖˆÎˆ+« ¦dø‘Mº–d\ªDðÛ„Ì×LÝ——Ð9Ç|•FèçVm™¨€™3õS–9Äå¢<̉Ìm¢±`·º˜&Z²ž Ë®D«¶»6™‰©­HÈ Àá«h­i³04æ’hxœi3ï¨(ÓL·†‹¶ËpŒ ƒÜÒ? :õdsÀ –3æÓ·Üjâ¬9—]8n¼&]I F£¼…ì–—Œ0v°LǐÅfÛ2TÖ’aµ˜N@ÖBSÏ^à´4-±°b×nÈÈœÆD=KdŒø…ÄÈK,›ÖR§fjü$^ÔÎ!„6^ s:Üun\ôkCÞò÷<—Lúl Í›G¹ÀPá¼Nc¡šÒ…ÙWͳœ±vÊáЄ×9‹P‰cEØ‘™›µŸP<×g1 º©Ø¬wiÁ^l5× I/';Ë+´Z‡ÓÄFÕp[Èð’ HÄ ó 9¬Dl4“é±Ï”V=^Hð;žLädÉa‚°Ë,#/Ž~²BÔÛ QãñQtIeórVB,ÏÂf‹4#Μc‹É3ZIÖ Œ¢¥·üxa‡Ãçè„jŠ[5 Ä!U?,3žÎ×…ðdÓ÷háŠA‰ìÄ4÷ÃÜZÃE{‰®+W\ZÍE[‰»µk»MÝ­`¢©†˜ÃV‹-f¢¡†¢a«eŠ%«Y¨©q%jâd,Ôq`) ¤¦…šˆ ¦E>0Ùb²t–Ÿ  ÷jsςҒKÈcø(é›;k(’#ôŒQ ™C> õ³M9óºÆµ¤çâ;uÀ)5>RÔ¸fÓ~Ȧ—’-$fe«"FâUˆÊwµPÏu w+"åÉó¨6s™Û9(À¨ù©hE°½†n`m~“@©›p!Vkhµ Á1šbEqqÊ@ºèl›2 –Yã%‘‚hÛ{a¶‡ÅÞM²¬çL34®Çl]®‹ŽØŒm'RÜe35æöˆ­Á­ cP9šeÁköo´L³Ì=p8]”‡B¶,šº|ɏdzXˆØk*ÇÚ{#ñ‰pã(€¶‡9ý'šÜ³½¯kƒ†Â’ëSOƒ•Å®H6+a¢µˆ‹Y¨b˜b+XˆÖ!°u!¢"µˆˆn2ˆ Å0Ä`Å Ô®c(ÓÜGº•Ä»Œ âWî%q.áÐÄ÷î%umÍ£+ÜQ,Vn¦-GphU¸¢X­&,Gt ·K¢ÅÅ·¥RÄÊÉbKn N­R2g$VµÕó Qr#–ÓZUÏð0ÎtÙÀœz ëöo“Îk¯n„T°"SÞ+³/…€½"ižãO%Í%&Δâ‘ËØ´IˆÓ°Ë‰ÞM3.™yçÁzit›`4C`k¢¼á!álÄï sÂ[×!¤l¾æo"ƒIÔ'@ªu)3›ô®“@Z à¾] üœ'‡4¸PÞkÁ-qÄH‰ÓÍBd´ÿ —¹°ÄA&ÊUC„öz‚‚RæŠtf¬>˜ÑidšEçÑL÷áý¡V±h§­c¿¥¨ƒ@g¼…Ýö^ÞËc.ž„æ“I[ ª+·zÐÒÚ,½Ð»¶€C›7jk$๖€Ž¾ÅÙpp¶ÍþéΤ ½ØÎŒq ñpæžÅ¥#Øâ49ÃÂK^MYV“,¶Éz_òæ:…;Õ«¦I3âJ£¤û5$7Èxün\â]Êe¯(Ÿ&Ž‹¶2<6Ćf× æ¢ƱqWı[(ÙÂŽç‚T7¨@ÈÉÍß‚ïÙ"&3TYlGށ†)†#5ŠA©^T2ÆÁ†)©†©†¤yGXÁ†©"†)©¼ÅV WS†#©]R–r‹q5ÕbâWþBh¯u+ªÅÄ×ü„nÑ^êkªÁj‰jeœWˆÕÕ`µDµ2Ì+Ä µDµµ5Ô{¤Þ0RF’H÷AÛ<ÊÁ§ ƈæ0Ñ£ê4 öÚµ[¬/1²€â<-¬šö²r×0o×w ´xÐÒË„ g01¬„åEM蛇Ã\6µE›‘fÙO k÷CºnÓ1`iîÒ² áÂ!ÑLÄÿ ³¬\õ*:M=Ç»c‹2[‰ØsÕLò\ŒK L^™üÄN\¶#» Ç\……ßïIœÉ$¸ÎñÍ®ÔHÇ Ûí/´>Li”„†g^$ 7NÍÑÑ2M2ªNg=k½Ð}Ÿl6‡ —JWˆ”ÞéT·+µ¦üÂFè¢Vs6ýÆ4»2+2IÝ9ô9®ÇGÙÇ1+Ä8;*Õ§ž½D*îÑWÚçá3Ma¤·ˆ¥t}š²Ü…Q+Æüµ8HíS”üxGéÁˆ¦Ël„éÈ 5 µÄƒ6äÜ(kIš¯S†fÖ&¸®×v|Äyˆ*禌Éù@7-®Ä[]ÎÖ¿ê`º…=:…žJVnݳvðÖKE¼‚ »mà ÷f®:Ë ™–4rð¡4` ܹçž~‹C=œ…¾Ïj|VDtK.ƒ"9 Ï ­–éXá³6WÒïIL-Ї Ç module.php000064400000027551152267212530006561 0ustar00. namespace core\context; use core\context; use stdClass; use coding_exception, moodle_url; /** * Course module context class * * @package core_access * @category access * @copyright Petr Skoda * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 4.2 */ class module extends context { /** @var int numeric context level value matching legacy CONTEXT_MODULE */ public const LEVEL = 70; /** * Please use \core\context\module::instance($cmid) if you need the instance of context. * Alternatively if you know only the context id use \core\context::instance_by_id($contextid) * * @param stdClass $record */ protected function __construct(stdClass $record) { parent::__construct($record); if ($record->contextlevel != self::LEVEL) { throw new coding_exception('Invalid $record->contextlevel in core\context\module constructor.'); } } /** * Returns short context name. * * @since Moodle 4.2 * * @return string */ public static function get_short_name(): string { return 'module'; } /** * Returns human readable context level name. * * @return string the human readable context level name. */ public static function get_level_name() { return get_string('activitymodule'); } /** * Returns human readable context identifier. * * @param boolean $withprefix whether to prefix the name of the context with the * module name, e.g. Forum, Glossary, etc. * @param boolean $short does not apply to module context * @param boolean $escape Whether the returned name of the context is to be HTML escaped or not. * @return string the human readable context name. */ public function get_context_name($withprefix = true, $short = false, $escape = true) { global $DB; $name = ''; if ($cm = $DB->get_record_sql("SELECT cm.*, md.name AS modname FROM {course_modules} cm JOIN {modules} md ON md.id = cm.module WHERE cm.id = ?", array($this->_instanceid))) { if ($mod = $DB->get_record($cm->modname, array('id' => $cm->instance))) { if ($withprefix) { $name = get_string('modulename', $cm->modname).': '; } if (!$escape) { $name .= format_string($mod->name, true, array('context' => $this, 'escape' => false)); } else { $name .= format_string($mod->name, true, array('context' => $this)); } } } return $name; } /** * Returns the most relevant URL for this context. * * @return moodle_url */ public function get_url() { global $DB; if ($modname = $DB->get_field_sql("SELECT md.name AS modname FROM {course_modules} cm JOIN {modules} md ON md.id = cm.module WHERE cm.id = ?", array($this->_instanceid))) { return new moodle_url('/mod/' . $modname . '/view.php', array('id' => $this->_instanceid)); } return new moodle_url('/'); } /** * Returns context instance database name. * * @return string|null table name for all levels except system. */ protected static function get_instance_table(): ?string { return 'course_modules'; } /** * Returns list of columns that can be used from behat * to look up context by reference. * * @return array list of column names from instance table */ protected static function get_behat_reference_columns(): array { return ['idnumber']; } /** * Returns list of all role archetypes that are compatible * with role assignments in context level. * @since Moodle 4.2 * * @return int[] */ protected static function get_compatible_role_archetypes(): array { return ['editingteacher', 'teacher', 'student']; } /** * Returns list of all possible parent context levels. * @since Moodle 4.2 * * @return int[] */ public static function get_possible_parent_levels(): array { return [course::LEVEL]; } /** * Returns array of relevant context capability records. * * @param string $sort * @return array */ public function get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT) { global $DB, $CFG; $cm = $DB->get_record('course_modules', array('id' => $this->_instanceid)); $module = $DB->get_record('modules', array('id' => $cm->module)); $subcaps = array(); $modulepath = "{$CFG->dirroot}/mod/{$module->name}"; $subplugins = \core\component::get_subplugins("mod_{$module->name}"); if (!empty($subplugins)) { foreach (array_keys($subplugins) as $subplugintype) { foreach (array_keys(\core_component::get_plugin_list($subplugintype)) as $subpluginname) { $subcaps = array_merge($subcaps, array_keys(load_capability_def($subplugintype.'_'.$subpluginname))); } } } $modfile = "{$modulepath}/lib.php"; $extracaps = array(); if (file_exists($modfile)) { include_once($modfile); $modfunction = $module->name.'_get_extra_capabilities'; if (function_exists($modfunction)) { $extracaps = $modfunction(); } } $extracaps = array_merge($subcaps, $extracaps); $extra = ''; list($extra, $params) = $DB->get_in_or_equal( $extracaps, SQL_PARAMS_NAMED, 'cap0', true, ''); if (!empty($extra)) { $extra = "OR name $extra"; } // Fetch the list of modules, and remove this one. $components = \core_component::get_component_list(); $componentnames = $components['mod']; unset($componentnames["mod_{$module->name}"]); $componentnames = array_keys($componentnames); // Exclude all other modules. list($notcompsql, $notcompparams) = $DB->get_in_or_equal($componentnames, SQL_PARAMS_NAMED, 'notcomp', false); $params = array_merge($params, $notcompparams); // Exclude other component submodules. $i = 0; $ignorecomponents = []; foreach ($componentnames as $mod) { if ($subplugins = \core_component::get_subplugins($mod)) { foreach (array_keys($subplugins) as $subplugintype) { $paramname = "notlike{$i}"; $ignorecomponents[] = $DB->sql_like('component', ":{$paramname}", true, true, true); $params[$paramname] = "{$subplugintype}_%"; $i++; } } } $notlikesql = "(" . implode(' AND ', $ignorecomponents) . ")"; $sql = "SELECT * FROM {capabilities} WHERE (contextlevel = ".self::LEVEL." AND component {$notcompsql} AND {$notlikesql}) $extra ORDER BY $sort"; return $DB->get_records_sql($sql, $params); } /** * Is this context part of any course? If yes return course context. * * @param bool $strict true means throw exception if not found, false means return false if not found * @return course|false context of the enclosing course, null if not found or exception */ public function get_course_context($strict = true) { return $this->get_parent_context(); } /** * Returns module context instance. * * @param int $cmid id of the record from {course_modules} table; pass cmid there, NOT id in the instance column * @param int $strictness * @return module|false context instance */ public static function instance($cmid, $strictness = MUST_EXIST) { global $DB; if ($context = context::cache_get(self::LEVEL, $cmid)) { return $context; } if (!$record = $DB->get_record('context', array('contextlevel' => self::LEVEL, 'instanceid' => $cmid))) { if ($cm = $DB->get_record('course_modules', array('id' => $cmid), 'id,course', $strictness)) { $parentcontext = course::instance($cm->course); $record = context::insert_context_record(self::LEVEL, $cm->id, $parentcontext->path); } } if ($record) { $context = new module($record); context::cache_add($context); return $context; } return false; } /** * Create missing context instances at module context level */ protected static function create_level_instances() { global $DB; $sql = "SELECT " . self::LEVEL . ", cm.id FROM {course_modules} cm WHERE NOT EXISTS (SELECT 'x' FROM {context} cx WHERE cm.id = cx.instanceid AND cx.contextlevel=" . self::LEVEL . ")"; $contextdata = $DB->get_recordset_sql($sql); foreach ($contextdata as $context) { context::insert_context_record(self::LEVEL, $context->id, null); } $contextdata->close(); } /** * Returns sql necessary for purging of stale context instances. * * @return string cleanup SQL */ protected static function get_cleanup_sql() { $sql = " SELECT c.* FROM {context} c LEFT OUTER JOIN {course_modules} cm ON c.instanceid = cm.id WHERE cm.id IS NULL AND c.contextlevel = " . self::LEVEL . " "; return $sql; } /** * Rebuild context paths and depths at module context level. * * @param bool $force */ protected static function build_paths($force) { global $DB; if ($force || $DB->record_exists_select('context', "contextlevel = " . self::LEVEL . " AND (depth = 0 OR path IS NULL)")) { if ($force) { $ctxemptyclause = ''; } else { $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)"; } $sql = "INSERT INTO {context_temp} (id, path, depth, locked) SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked FROM {context} ctx JOIN {course_modules} cm ON (cm.id = ctx.instanceid AND ctx.contextlevel = " . self::LEVEL . ") JOIN {context} pctx ON (pctx.instanceid = cm.course AND pctx.contextlevel = " . course::LEVEL . ") WHERE pctx.path IS NOT NULL AND pctx.depth > 0 $ctxemptyclause"; $trans = $DB->start_delegated_transaction(); $DB->delete_records('context_temp'); $DB->execute($sql); context::merge_context_temp_table(); $DB->delete_records('context_temp'); $trans->allow_commit(); } } } block.php000064400000021174152267212530006361 0ustar00. namespace core\context; use core\context; use stdClass; use coding_exception, moodle_url; /** * Block context class * * @package core_access * @category access * @copyright Petr Skoda * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 4.2 */ class block extends context { /** @var int numeric context level value matching legacy CONTEXT_BLOCK */ public const LEVEL = 80; /** * Please use \core\context\block::instance($blockinstanceid) if you need the instance of context. * Alternatively if you know only the context id use \core\context::instance_by_id($contextid) * * @param stdClass $record */ protected function __construct(stdClass $record) { parent::__construct($record); if ($record->contextlevel != self::LEVEL) { throw new coding_exception('Invalid $record->contextlevel in core\context\block constructor'); } } /** * Returns short context name. * * @since Moodle 4.2 * * @return string */ public static function get_short_name(): string { return 'block'; } /** * Returns human readable context level name. * * @return string the human readable context level name. */ public static function get_level_name() { return get_string('block'); } /** * Returns human readable context identifier. * * @param boolean $withprefix whether to prefix the name of the context with Block * @param boolean $short does not apply to block context * @param boolean $escape does not apply to block context * @return string the human readable context name. */ public function get_context_name($withprefix = true, $short = false, $escape = true) { global $DB; $name = ''; if ($blockinstance = $DB->get_record('block_instances', array('id' => $this->_instanceid))) { $blockobject = block_instance($blockinstance->blockname); if ($blockobject) { if ($withprefix) { $name = get_string('block').': '; } $name .= $blockobject->title; } } return $name; } /** * Returns the most relevant URL for this context. * * @return moodle_url */ public function get_url() { $parentcontexts = $this->get_parent_context(); return $parentcontexts->get_url(); } /** * Returns list of all possible parent context levels. * @since Moodle 4.2 * * @return int[] */ public static function get_possible_parent_levels(): array { // Blocks may be added to any other context instance. $alllevels = \core\context_helper::get_all_levels(); unset($alllevels[self::LEVEL]); return array_keys($alllevels); } /** * Returns array of relevant context capability records. * * @param string $sort * @return array */ public function get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT) { global $DB; $bi = $DB->get_record('block_instances', array('id' => $this->_instanceid)); $select = '(contextlevel = :level AND component = :component)'; $params = [ 'level' => self::LEVEL, 'component' => 'block_' . $bi->blockname, ]; $extracaps = block_method_result($bi->blockname, 'get_extra_capabilities'); if ($extracaps) { list($extra, $extraparams) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap'); $select .= " OR name $extra"; $params = array_merge($params, $extraparams); } return $DB->get_records_select('capabilities', $select, $params, $sort); } /** * Is this context part of any course? If yes return course context. * * @param bool $strict true means throw exception if not found, false means return false if not found * @return course context of the enclosing course, null if not found or exception */ public function get_course_context($strict = true) { $parentcontext = $this->get_parent_context(); return $parentcontext->get_course_context($strict); } /** * Returns block context instance. * * @param int $blockinstanceid id from {block_instances} table. * @param int $strictness * @return block|false context instance */ public static function instance($blockinstanceid, $strictness = MUST_EXIST) { global $DB; if ($context = context::cache_get(self::LEVEL, $blockinstanceid)) { return $context; } if (!$record = $DB->get_record('context', array('contextlevel' => self::LEVEL, 'instanceid' => $blockinstanceid))) { if ($bi = $DB->get_record('block_instances', array('id' => $blockinstanceid), 'id,parentcontextid', $strictness)) { $parentcontext = context::instance_by_id($bi->parentcontextid); $record = context::insert_context_record(self::LEVEL, $bi->id, $parentcontext->path); } } if ($record) { $context = new block($record); context::cache_add($context); return $context; } return false; } /** * Block do not have child contexts... * @return array */ public function get_child_contexts() { return array(); } /** * Create missing context instances at block context level */ protected static function create_level_instances() { global $DB; $sql = <<execute($sql, [ 'contextlevel' => self::LEVEL, 'existingcontextlevel' => self::LEVEL, ]); } /** * Returns sql necessary for purging of stale context instances. * * @return string cleanup SQL */ protected static function get_cleanup_sql() { $sql = " SELECT c.* FROM {context} c LEFT OUTER JOIN {block_instances} bi ON c.instanceid = bi.id WHERE bi.id IS NULL AND c.contextlevel = ".self::LEVEL." "; return $sql; } /** * Rebuild context paths and depths at block context level. * * @param bool $force */ protected static function build_paths($force) { global $DB; if ($force || $DB->record_exists_select('context', "contextlevel = ".self::LEVEL." AND (depth = 0 OR path IS NULL)")) { if ($force) { $ctxemptyclause = ''; } else { $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)"; } // The pctx.path IS NOT NULL prevents fatal problems with broken block instances that point to invalid context parent. $sql = "INSERT INTO {context_temp} (id, path, depth, locked) SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked FROM {context} ctx JOIN {block_instances} bi ON (bi.id = ctx.instanceid AND ctx.contextlevel = " . self::LEVEL . ") JOIN {context} pctx ON (pctx.id = bi.parentcontextid) WHERE (pctx.path IS NOT NULL AND pctx.depth > 0) $ctxemptyclause"; $trans = $DB->start_delegated_transaction(); $DB->delete_records('context_temp'); $DB->execute($sql); context::merge_context_temp_table(); $DB->delete_records('context_temp'); $trans->allow_commit(); } } } course.php000064400000024066152267212530006572 0ustar00. namespace core\context; use core\context; use stdClass; use coding_exception, moodle_url; /** * Course context class * * @package core_access * @category access * @copyright Petr Skoda * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 4.2 */ class course extends context { /** @var int numeric context level value matching legacy CONTEXT_COURSE */ public const LEVEL = 50; /** * Please use \core\context\course::instance($courseid) if you need the instance of context. * Alternatively if you know only the context id use \core\context::instance_by_id($contextid) * * @param stdClass $record */ protected function __construct(stdClass $record) { parent::__construct($record); if ($record->contextlevel != self::LEVEL) { throw new coding_exception('Invalid $record->contextlevel in core\context\course constructor.'); } } /** * Returns short context name. * * @since Moodle 4.2 * * @return string */ public static function get_short_name(): string { return 'course'; } /** * Returns human readable context level name. * * @return string the human readable context level name. */ public static function get_level_name() { return get_string('course'); } /** * Returns human readable context identifier. * * @param boolean $withprefix whether to prefix the name of the context with Course * @param boolean $short whether to use the short name of the thing. * @param bool $escape Whether the returned category name is to be HTML escaped or not. * @return string the human readable context name. */ public function get_context_name($withprefix = true, $short = false, $escape = true) { global $DB; $name = ''; if ($this->_instanceid == SITEID) { $name = get_string('frontpage', 'admin'); } else { if ($course = $DB->get_record('course', array('id' => $this->_instanceid))) { if ($withprefix) { $name = get_string('course').': '; } if ($short) { if (!$escape) { $name .= format_string($course->shortname, true, array('context' => $this, 'escape' => false)); } else { $name .= format_string($course->shortname, true, array('context' => $this)); } } else { if (!$escape) { $name .= format_string(get_course_display_name_for_list($course), true, array('context' => $this, 'escape' => false)); } else { $name .= format_string(get_course_display_name_for_list($course), true, array('context' => $this)); } } } } return $name; } /** * Returns the most relevant URL for this context. * * @return moodle_url */ public function get_url() { if ($this->_instanceid != SITEID) { return new moodle_url('/course/view.php', array('id' => $this->_instanceid)); } return new moodle_url('/'); } /** * Returns context instance database name. * * @return string|null table name for all levels except system. */ protected static function get_instance_table(): ?string { return 'course'; } /** * Returns list of columns that can be used from behat * to look up context by reference. * * @return array list of column names from instance table */ protected static function get_behat_reference_columns(): array { return ['shortname']; } /** * Returns list of all role archetypes that are compatible * with role assignments in context level. * @since Moodle 4.2 * * @return int[] */ protected static function get_compatible_role_archetypes(): array { return ['manager', 'editingteacher', 'teacher', 'student']; } /** * Returns list of all possible parent context levels. * @since Moodle 4.2 * * @return int[] */ public static function get_possible_parent_levels(): array { return [coursecat::LEVEL]; } /** * Returns array of relevant context capability records. * * @param string $sort * @return array */ public function get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT) { global $DB; $levels = \core\context_helper::get_child_levels(self::LEVEL); $levels[] = self::LEVEL; return $DB->get_records_list('capabilities', 'contextlevel', $levels, $sort); } /** * Is this context part of any course? If yes return course context. * * @param bool $strict true means throw exception if not found, false means return false if not found * @return course context of the enclosing course, null if not found or exception */ public function get_course_context($strict = true) { return $this; } /** * Returns course context instance. * * @param int $courseid id from {course} table * @param int $strictness * @return course|false context instance */ public static function instance($courseid, $strictness = MUST_EXIST) { global $DB; if ($context = context::cache_get(self::LEVEL, $courseid)) { return $context; } if (!$record = $DB->get_record('context', array('contextlevel' => self::LEVEL, 'instanceid' => $courseid))) { if ($course = $DB->get_record('course', array('id' => $courseid), 'id,category', $strictness)) { if ($course->category) { $parentcontext = coursecat::instance($course->category); $record = context::insert_context_record(self::LEVEL, $course->id, $parentcontext->path); } else { $record = context::insert_context_record(self::LEVEL, $course->id, '/'.SYSCONTEXTID, 0); } } } if ($record) { $context = new course($record); context::cache_add($context); return $context; } return false; } /** * Create missing context instances at course context level */ protected static function create_level_instances() { global $DB; $sql = "SELECT ".self::LEVEL.", c.id FROM {course} c WHERE NOT EXISTS (SELECT 'x' FROM {context} cx WHERE c.id = cx.instanceid AND cx.contextlevel=".self::LEVEL.")"; $contextdata = $DB->get_recordset_sql($sql); foreach ($contextdata as $context) { context::insert_context_record(self::LEVEL, $context->id, null); } $contextdata->close(); } /** * Returns sql necessary for purging of stale context instances. * * @return string cleanup SQL */ protected static function get_cleanup_sql() { $sql = " SELECT c.* FROM {context} c LEFT OUTER JOIN {course} co ON c.instanceid = co.id WHERE co.id IS NULL AND c.contextlevel = ".self::LEVEL." "; return $sql; } /** * Rebuild context paths and depths at course context level. * * @param bool $force */ protected static function build_paths($force) { global $DB; if ($force || $DB->record_exists_select('context', "contextlevel = ".self::LEVEL." AND (depth = 0 OR path IS NULL)")) { if ($force) { $ctxemptyclause = $emptyclause = ''; } else { $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)"; $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)"; } $base = '/'.SYSCONTEXTID; // Standard frontpage. $sql = "UPDATE {context} SET depth = 2, path = ".$DB->sql_concat("'$base/'", 'id')." WHERE contextlevel = ".self::LEVEL." AND EXISTS (SELECT 'x' FROM {course} c WHERE c.id = {context}.instanceid AND c.category = 0) $emptyclause"; $DB->execute($sql); // Standard courses. $sql = "INSERT INTO {context_temp} (id, path, depth, locked) SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked FROM {context} ctx JOIN {course} c ON (c.id = ctx.instanceid AND ctx.contextlevel = ".self::LEVEL." AND c.category <> 0) JOIN {context} pctx ON (pctx.instanceid = c.category AND pctx.contextlevel = ".coursecat::LEVEL.") WHERE pctx.path IS NOT NULL AND pctx.depth > 0 $ctxemptyclause"; $trans = $DB->start_delegated_transaction(); $DB->delete_records('context_temp'); $DB->execute($sql); context::merge_context_temp_table(); $DB->delete_records('context_temp'); $trans->allow_commit(); } } } system.php000064400000022673152267212530006620 0ustar00. namespace core\context; use core\context; use stdClass; use coding_exception, moodle_url; /** * System context class * * @package core_access * @category access * @copyright Petr Skoda * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 4.2 */ class system extends context { /** @var int numeric context level value matching legacy CONTEXT_SYSTEM */ public const LEVEL = 10; /** * Please use \core\context\system::instance() if you need the instance of context. * * @param stdClass $record */ protected function __construct(stdClass $record) { parent::__construct($record); if ($record->contextlevel != self::LEVEL) { throw new coding_exception('Invalid $record->contextlevel in core\context\system constructor.'); } } /** * Returns short context name. * * @since Moodle 4.2 * * @return string */ public static function get_short_name(): string { return 'system'; } /** * Returns human readable context level name. * * @return string the human readable context level name. */ public static function get_level_name() { return get_string('coresystem'); } /** * Returns human readable context identifier. * * @param boolean $withprefix does not apply to system context * @param boolean $short does not apply to system context * @param boolean $escape does not apply to system context * @return string the human readable context name. */ public function get_context_name($withprefix = true, $short = false, $escape = true) { return self::get_level_name(); } /** * Returns the most relevant URL for this context. * * @return moodle_url */ public function get_url() { return new moodle_url('/'); } /** * Returns list of all role archetypes that are compatible * with role assignments in context level. * @since Moodle 4.2 * * @return int[] */ protected static function get_compatible_role_archetypes(): array { return ['manager', 'coursecreator']; } /** * Returns list of all possible parent context levels. * @since Moodle 4.2 * * @return int[] */ public static function get_possible_parent_levels(): array { return []; } /** * Returns array of relevant context capability records. * * @param string $sort * @return array */ public function get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT) { global $DB; return $DB->get_records('capabilities', [], $sort); } /** * Create missing context instances at system context */ protected static function create_level_instances() { // Nothing to do here, the system context is created automatically in installer. self::instance(0); } /** * Returns system context instance. * * @param int $instanceid should be 0 * @param int $strictness * @param bool $cache * @return 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'); } // SYSCONTEXTID is cached in local cache to eliminate 1 query per page. if (defined('SYSCONTEXTID') && $cache) { if (!isset(context::$systemcontext)) { $record = new stdClass(); $record->id = SYSCONTEXTID; $record->contextlevel = self::LEVEL; $record->instanceid = 0; $record->path = '/'.SYSCONTEXTID; $record->depth = 1; $record->locked = 0; context::$systemcontext = new system($record); } return context::$systemcontext; } try { // We ignore the strictness completely because system context must exist except during install. $record = $DB->get_record('context', array('contextlevel' => self::LEVEL), '*', 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 = self::LEVEL; $record->instanceid = 0; $record->depth = 1; $record->path = null; // Not known before insert. $record->locked = 0; 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 || $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 (empty($record->locked)) { $record->locked = 0; } if (!defined('SYSCONTEXTID')) { define('SYSCONTEXTID', $record->id); } context::$systemcontext = new system($record); return context::$systemcontext; } /** * Returns all site contexts except the system context, DO NOT call on production servers!! * * Contexts are not cached. * * @return array */ public function get_child_contexts() { global $DB; debugging('Fetching of system context child courses is strongly discouraged' . ' on production servers (it may eat all available memory)!'); // Just get all the contexts except for system level // and hope we don't OOM in the process - don't cache. $sql = "SELECT c.* FROM {context} c WHERE contextlevel > " . self::LEVEL; $records = $DB->get_records_sql($sql); $result = array(); foreach ($records as $record) { $result[$record->id] = context::create_instance_from_record($record); } return $result; } /** * Returns sql necessary for purging of stale context instances. * * @return string cleanup SQL */ protected static function get_cleanup_sql() { $sql = " SELECT c.* FROM {context} c WHERE 1=2 "; return $sql; } /** * Rebuild context paths and depths at system context level. * * @param bool $force */ protected static function build_paths($force) { global $DB; /* note: ignore $force here, we always do full test of system context */ // Exactly one record must exist. $record = $DB->get_record('context', array('contextlevel' => self::LEVEL), '*', MUST_EXIST); if ($record->instanceid != 0) { debugging('Invalid system context detected'); } if (defined('SYSCONTEXTID') && $record->id != SYSCONTEXTID) { debugging('Invalid SYSCONTEXTID detected'); } if ($record->depth != 1 || $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); } } /** * Set whether this context has been locked or not. * * @param bool $locked * @return $this */ public function set_locked(bool $locked) { if ($locked) { throw new \coding_exception('It is not possible to lock the system context'); } return parent::set_locked($locked); } } coursecat.php000064400000024446152267212530007264 0ustar00. namespace core\context; use core\context; use stdClass; use coding_exception, moodle_url; /** * Course category context class * * @package core_access * @category access * @copyright Petr Skoda * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 4.2 */ class coursecat extends context { /** @var int numeric context level value matching legacy CONTEXT_COURSECAT */ public const LEVEL = 40; /** * Please use \core\context\coursecat::instance($coursecatid) if you need the instance of context. * Alternatively if you know only the context id use \core\context::instance_by_id($contextid) * * @param stdClass $record */ protected function __construct(stdClass $record) { parent::__construct($record); if ($record->contextlevel != self::LEVEL) { throw new coding_exception('Invalid $record->contextlevel in core\context\coursecat constructor.'); } } /** * Returns short context name. * * @since Moodle 4.2 * * @return string */ public static function get_short_name(): string { return 'coursecat'; } /** * Returns human readable context level name. * * @return string the human readable context level name. */ public static function get_level_name() { return get_string('category'); } /** * Returns human readable context identifier. * * @param boolean $withprefix whether to prefix the name of the context with Category * @param boolean $short does not apply to course categories * @param boolean $escape Whether the returned name of the context is to be HTML escaped or not. * @return string the human readable context name. */ public function get_context_name($withprefix = true, $short = false, $escape = true) { global $DB; $name = ''; if ($category = $DB->get_record('course_categories', array('id' => $this->_instanceid))) { if ($withprefix) { $name = get_string('category').': '; } if (!$escape) { $name .= format_string($category->name, true, array('context' => $this, 'escape' => false)); } else { $name .= format_string($category->name, true, array('context' => $this)); } } return $name; } /** * Returns the most relevant URL for this context. * * @return moodle_url */ public function get_url() { return new moodle_url('/course/index.php', array('categoryid' => $this->_instanceid)); } /** * Returns context instance database name. * * @return string|null table name for all levels except system. */ protected static function get_instance_table(): ?string { return 'course_categories'; } /** * Returns list of columns that can be used from behat * to look up context by reference. * * @return array list of column names from instance table */ protected static function get_behat_reference_columns(): array { return ['idnumber']; } /** * Returns list of all role archetypes that are compatible * with role assignments in context level. * @since Moodle 4.2 * * @return int[] */ protected static function get_compatible_role_archetypes(): array { return ['manager', 'coursecreator']; } /** * Returns list of all possible parent context levels. * @since Moodle 4.2 * * @return int[] */ public static function get_possible_parent_levels(): array { return [system::LEVEL, self::LEVEL]; } /** * Returns array of relevant context capability records. * * @param string $sort * @return array */ public function get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT) { global $DB; $levels = \core\context_helper::get_child_levels(self::LEVEL); $levels[] = self::LEVEL; return $DB->get_records_list('capabilities', 'contextlevel', $levels, $sort); } /** * Returns course category context instance. * * @param int $categoryid id from {course_categories} table * @param int $strictness * @return coursecat|false context instance */ public static function instance($categoryid, $strictness = MUST_EXIST) { global $DB; if ($context = context::cache_get(self::LEVEL, $categoryid)) { return $context; } if (!$record = $DB->get_record('context', array('contextlevel' => self::LEVEL, 'instanceid' => $categoryid))) { if ($category = $DB->get_record('course_categories', array('id' => $categoryid), 'id,parent', $strictness)) { if ($category->parent) { $parentcontext = self::instance($category->parent); $record = context::insert_context_record(self::LEVEL, $category->id, $parentcontext->path); } else { $record = context::insert_context_record(self::LEVEL, $category->id, '/'.SYSCONTEXTID, 0); } } } if ($record) { $context = new coursecat($record); context::cache_add($context); return $context; } return false; } /** * Returns immediate child contexts of category and all subcategories, * children of subcategories and courses are not returned. * * @return array */ public function get_child_contexts() { global $DB; if (empty($this->_path) || empty($this->_depth)) { debugging('Can not find child contexts of context '.$this->_id.' try rebuilding of context paths'); return array(); } $sql = "SELECT ctx.* FROM {context} ctx WHERE ctx.path LIKE ? AND (ctx.depth = ? OR ctx.contextlevel = ?)"; $params = array($this->_path.'/%', $this->depth + 1, self::LEVEL); $records = $DB->get_records_sql($sql, $params); $result = array(); foreach ($records as $record) { $result[$record->id] = context::create_instance_from_record($record); } return $result; } /** * Create missing context instances at course category context level */ protected static function create_level_instances() { global $DB; $sql = "SELECT ".self::LEVEL.", cc.id FROM {course_categories} cc WHERE NOT EXISTS (SELECT 'x' FROM {context} cx WHERE cc.id = cx.instanceid AND cx.contextlevel=".self::LEVEL.")"; $contextdata = $DB->get_recordset_sql($sql); foreach ($contextdata as $context) { context::insert_context_record(self::LEVEL, $context->id, null); } $contextdata->close(); } /** * Returns sql necessary for purging of stale context instances. * * @return string cleanup SQL */ protected static function get_cleanup_sql() { $sql = " SELECT c.* FROM {context} c LEFT OUTER JOIN {course_categories} cc ON c.instanceid = cc.id WHERE cc.id IS NULL AND c.contextlevel = ".self::LEVEL." "; return $sql; } /** * Rebuild context paths and depths at course category context level. * * @param bool $force */ protected static function build_paths($force) { global $DB; if ($force || $DB->record_exists_select('context', "contextlevel = ".self::LEVEL." AND (depth = 0 OR path IS NULL)")) { if ($force) { $ctxemptyclause = $emptyclause = ''; } else { $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)"; $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)"; } $base = '/'.SYSCONTEXTID; // Normal top level categories. $sql = "UPDATE {context} SET depth=2, path=".$DB->sql_concat("'$base/'", 'id')." WHERE contextlevel=".self::LEVEL." AND EXISTS (SELECT 'x' FROM {course_categories} cc WHERE cc.id = {context}.instanceid AND cc.depth=1) $emptyclause"; $DB->execute($sql); // Deeper categories - one query per depthlevel. $maxdepth = $DB->get_field_sql("SELECT MAX(depth) FROM {course_categories}"); for ($n = 2; $n <= $maxdepth; $n++) { $sql = "INSERT INTO {context_temp} (id, path, depth, locked) SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1, ctx.locked FROM {context} ctx JOIN {course_categories} cc ON (cc.id = ctx.instanceid AND ctx.contextlevel = ".self::LEVEL." AND cc.depth = $n) JOIN {context} pctx ON (pctx.instanceid = cc.parent AND pctx.contextlevel = ".self::LEVEL.") WHERE pctx.path IS NOT NULL AND pctx.depth > 0 $ctxemptyclause"; $trans = $DB->start_delegated_transaction(); $DB->delete_records('context_temp'); $DB->execute($sql); context::merge_context_temp_table(); $DB->delete_records('context_temp'); $trans->allow_commit(); } } } } user.php000064400000016413152267212530006245 0ustar00. namespace core\context; use core\context; use stdClass; use coding_exception, moodle_url; /** * User context class * * @package core_access * @category access * @copyright Petr Skoda * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 4.2 */ class user extends context { /** @var int numeric context level value matching legacy CONTEXT_USER */ public const LEVEL = 30; /** * Please use \core\context\user::instance($userid) if you need the instance of context. * Alternatively if you know only the context id use \core\context::instance_by_id($contextid) * * @param stdClass $record */ protected function __construct(stdClass $record) { parent::__construct($record); if ($record->contextlevel != self::LEVEL) { throw new coding_exception('Invalid $record->contextlevel in core\context\user constructor.'); } } /** * Returns short context name. * * @since Moodle 4.2 * * @return string */ public static function get_short_name(): string { return 'user'; } /** * Returns human readable context level name. * * @return string the human readable context level name. */ public static function get_level_name() { return get_string('user'); } /** * Returns human readable context identifier. * * @param boolean $withprefix whether to prefix the name of the context with User * @param boolean $short does not apply to user context * @param boolean $escape does not apply to user context * @return string the human readable context name. */ public function get_context_name($withprefix = true, $short = false, $escape = true) { global $DB; $name = ''; if ($user = $DB->get_record('user', array('id' => $this->_instanceid, 'deleted' => 0))) { if ($withprefix) { $name = get_string('user').': '; } $name .= fullname($user); } return $name; } /** * Returns the most relevant URL for this context. * * @return moodle_url */ public function get_url() { global $COURSE; if ($COURSE->id == SITEID) { $url = new moodle_url('/user/profile.php', array('id' => $this->_instanceid)); } else { $url = new moodle_url('/user/view.php', array('id' => $this->_instanceid, 'courseid' => $COURSE->id)); } return $url; } /** * Returns list of all possible parent context levels. * @since Moodle 4.2 * * @return int[] */ public static function get_possible_parent_levels(): array { return [system::LEVEL]; } /** * Returns context instance database name. * * @return string|null table name for all levels except system. */ protected static function get_instance_table(): ?string { return 'user'; } /** * Returns list of columns that can be used from behat * to look up context by reference. * * @return array list of column names from instance table */ protected static function get_behat_reference_columns(): array { return ['username']; } /** * Returns array of relevant context capability records. * * @param string $sort * @return array */ public function get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT) { global $DB; $extracaps = array('moodle/grade:viewall'); list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap'); return $DB->get_records_select('capabilities', "contextlevel = :level OR name {$extra}", $params + ['level' => self::LEVEL], $sort); } /** * Returns user context instance. * * @param int $userid id from {user} table * @param int $strictness * @return user|false context instance */ public static function instance($userid, $strictness = MUST_EXIST) { global $DB; if ($context = context::cache_get(self::LEVEL, $userid)) { return $context; } if (!$record = $DB->get_record('context', array('contextlevel' => self::LEVEL, 'instanceid' => $userid))) { if ($user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0), 'id', $strictness)) { $record = context::insert_context_record(self::LEVEL, $user->id, '/'.SYSCONTEXTID, 0); } } if ($record) { $context = new user($record); context::cache_add($context); return $context; } return false; } /** * Create missing context instances at user context level */ protected static function create_level_instances() { global $DB; $sql = "SELECT " . self::LEVEL . ", u.id FROM {user} u WHERE u.deleted = 0 AND NOT EXISTS (SELECT 'x' FROM {context} cx WHERE u.id = cx.instanceid AND cx.contextlevel=" . self::LEVEL . ")"; $contextdata = $DB->get_recordset_sql($sql); foreach ($contextdata as $context) { context::insert_context_record(self::LEVEL, $context->id, null); } $contextdata->close(); } /** * Returns sql necessary for purging of stale context instances. * * @return string cleanup SQL */ protected static function get_cleanup_sql() { $sql = " SELECT c.* FROM {context} c LEFT OUTER JOIN {user} u ON (c.instanceid = u.id AND u.deleted = 0) WHERE u.id IS NULL AND c.contextlevel = " . self::LEVEL . " "; return $sql; } /** * Rebuild context paths and depths at user context level. * * @param bool $force */ protected static function build_paths($force) { global $DB; // First update normal users. $path = $DB->sql_concat('?', 'id'); $pathstart = '/' . SYSCONTEXTID . '/'; $params = array($pathstart); if ($force) { $where = "depth <> 2 OR path IS NULL OR path <> ({$path})"; $params[] = $pathstart; } else { $where = "depth = 0 OR path IS NULL"; } $sql = "UPDATE {context} SET depth = 2, path = {$path} WHERE contextlevel = " . self::LEVEL . " AND ($where)"; $DB->execute($sql, $params); } } module_test.php000064400000026571152267723350007630 0ustar00. namespace core\context; use core\context, core\context_helper; /** * Unit tests for module context class. * * NOTE: more tests are in lib/tests/accesslib_test.php * * @package core * @copyright Petr Skoda * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @coversDefaultClass \core\context\module */ final class module_test extends \advanced_testcase { /** * Tests legacy class. * @coversNothing */ public function test_legacy_classname(): void { $this->resetAfterTest(); $course = $this->getDataGenerator()->create_course(); $page = $this->getDataGenerator()->create_module('page', ['course' => $course->id]); $context = module::instance($page->cmid); $this->assertInstanceOf(module::class, $context); $this->assertInstanceOf(\context_module::class, $context); } /** * Tests covered methods. * @covers ::instance * @covers \core\context::instance_by_id */ public function test_factory_methods(): void { $this->resetAfterTest(); $course = $this->getDataGenerator()->create_course(); $page = $this->getDataGenerator()->create_module('page', ['course' => $course->id]); $context = module::instance($page->cmid); $this->assertInstanceOf(module::class, $context); $this->assertSame((string)$page->cmid, $context->instanceid); $context = context::instance_by_id($context->id); $this->assertInstanceOf(module::class, $context); $this->assertSame((string)$page->cmid, $context->instanceid); } /** * Tests covered method. * @covers ::get_short_name */ public function test_get_short_name(): void { $this->assertSame('module', module::get_short_name()); } /** * Tests context level. * @coversNothing */ public function test_level(): void { $this->assertSame(70, module::LEVEL); $this->assertSame(CONTEXT_MODULE, module::LEVEL); } /** * Tests covered method. * @covers ::get_level_name */ public function test_get_level_name(): void { $this->assertSame('Activity module', module::get_level_name()); } /** * Tests covered method. * @covers ::get_context_name */ public function test_get_context_name(): void { $this->resetAfterTest(); $course = $this->getDataGenerator()->create_course(); $page = $this->getDataGenerator()->create_module('page', ['course' => $course->id, 'name' => 'Pokus']); $context = module::instance($page->cmid); $this->assertSame('Page: Pokus', $context->get_context_name()); $this->assertSame('Page: Pokus', $context->get_context_name(true)); $this->assertSame('Pokus', $context->get_context_name(false)); $this->assertSame('Pokus', $context->get_context_name(false, true)); $this->assertSame('Page: Pokus', $context->get_context_name(true, true, false)); } /** * Tests covered method. * @covers ::get_url */ public function test_get_url(): void { $this->resetAfterTest(); $course = $this->getDataGenerator()->create_course(); $page = $this->getDataGenerator()->create_module('page', ['course' => $course->id, 'name' => 'Pokus']); $context = module::instance($page->cmid); $expected = new \moodle_url('/mod/page/view.php', ['id' => $page->cmid]); $url = $context->get_url(); $this->assertInstanceOf(\moodle_url::class, $url); $this->assertSame($expected->out(), $url->out()); } /** * Tests covered methods. * @covers ::get_instance_table() * @covers ::get_behat_reference_columns() * @covers \core\context_helper::resolve_behat_reference */ public function test_resolve_behat_reference(): void { global $DB; $this->resetAfterTest(); $course = $this->getDataGenerator()->create_course(); $page = $this->getDataGenerator()->create_module('page', ['course' => $course->id, 'idnumber' => 'xyz']); $instance = $DB->get_record('course_modules', ['id' => $page->cmid], '*', MUST_EXIST); $context = module::instance($instance->id); $result = context_helper::resolve_behat_reference('Activity module', $instance->idnumber); $this->assertSame($context->id, $result->id); $result = context_helper::resolve_behat_reference('module', $instance->idnumber); $this->assertSame($context->id, $result->id); $result = context_helper::resolve_behat_reference('70', $instance->idnumber); $this->assertSame($context->id, $result->id); $result = context_helper::resolve_behat_reference('Activity module', 'dshjkdshjkhjsadjhdsa'); $this->assertNull($result); $result = context_helper::resolve_behat_reference('Activity module', ''); $this->assertNull($result); } /** * Tests covered method. * @covers ::get_compatible_role_archetypes */ public function test_get_compatible_role_archetypes(): void { global $DB; $allarchetypes = $DB->get_fieldset_select('role', 'DISTINCT archetype', 'archetype IS NOT NULL'); foreach ($allarchetypes as $allarchetype) { $levels = context_helper::get_compatible_levels($allarchetype); if ($allarchetype === 'editingteacher' || $allarchetype === 'teacher' || $allarchetype === 'student') { $this->assertContains(module::LEVEL, $levels, "$allarchetype is expected to be compatible with context"); } else { $this->assertNotContains(module::LEVEL, $levels, "$allarchetype is not expected to be compatible with context"); } } } /** * Tests covered method. * @covers ::get_possible_parent_levels */ public function test_get_possible_parent_levels(): void { $this->assertSame([course::LEVEL], module::get_possible_parent_levels()); } /** * Tests covered method. * @covers ::get_capabilities */ public function test_get_capabilities(): void { $this->resetAfterTest(); $course = $this->getDataGenerator()->create_course(); $mod = $this->getDataGenerator()->create_module('book', ['course' => $course->id, 'name' => 'Pokus']); $context = module::instance($mod->cmid); $capabilities = $context->get_capabilities(); $capabilities = convert_to_array($capabilities); $capabilities = array_column($capabilities, 'name'); $this->assertContains('mod/book:read', $capabilities); $this->assertContains('booktool/exportimscp:export', $capabilities); $this->assertContains('booktool/importhtml:import', $capabilities); $this->assertNotContains('mod/url:view', $capabilities); $this->assertNotContains('moodle/course:view', $capabilities); $this->assertNotContains('moodle/category:manage', $capabilities); $this->assertNotContains('moodle/user:viewalldetails', $capabilities); } /** * Tests covered method. * @covers ::create_level_instances */ public function test_create_level_instances(): void { global $DB; $this->resetAfterTest(); $course = $this->getDataGenerator()->create_course(); $page = $this->getDataGenerator()->create_module('page', ['course' => $course->id, 'name' => 'Pokus']); $context = module::instance($page->cmid); $DB->delete_records('context', ['id' => $context->id]); context_helper::create_instances(module::LEVEL); $record = $DB->get_record('context', ['contextlevel' => module::LEVEL, 'instanceid' => $page->cmid], '*', MUST_EXIST); } /** * Tests covered method. * @covers ::get_child_contexts */ public function test_get_child_contexts(): void { $this->resetAfterTest(); $course = $this->getDataGenerator()->create_course(); $page = $this->getDataGenerator()->create_module('page', ['course' => $course->id, 'name' => 'Pokus']); $context = module::instance($page->cmid); $children = $context->get_child_contexts(); $this->assertCount(0, $children); } /** * Tests covered method. * @covers ::get_cleanup_sql */ public function test_get_cleanup_sql(): void { global $DB; $this->resetAfterTest(); $course = $this->getDataGenerator()->create_course(); $page = $this->getDataGenerator()->create_module('page', ['course' => $course->id, 'name' => 'Pokus']); $context = module::instance($page->cmid); $DB->delete_records('course_modules', ['id' => $page->cmid]); $DB->delete_records('page', ['id' => $page->id]); context_helper::cleanup_instances(); $this->assertFalse($DB->record_exists('context', ['contextlevel' => module::LEVEL, 'instanceid' => $page->cmid])); } /** * Tests covered method. * @covers ::build_paths */ public function test_build_paths(): void { global $DB; $this->resetAfterTest(); $syscontext = system::instance(); $course = $this->getDataGenerator()->create_course(); $coursecontext = course::instance($course->id); $page = $this->getDataGenerator()->create_module('page', ['course' => $course->id, 'name' => 'Pokus']); $pagecontext = module::instance($page->cmid); $DB->set_field('context', 'depth', 1, ['id' => $pagecontext->id]); $DB->set_field('context', 'path', '/0', ['id' => $pagecontext->id]); context_helper::build_all_paths(true); $record = $DB->get_record('context', ['id' => $pagecontext->id]); $categorycontext = coursecat::instance($course->category); $this->assertSame('4', $record->depth); $this->assertSame('/' . $syscontext->id . '/' . $categorycontext->id . '/' . $coursecontext->id . '/' . $record->id, $record->path); } /** * Tests covered method. * @covers ::set_locked */ public function test_set_locked(): void { global $DB; $this->resetAfterTest(); $course = $this->getDataGenerator()->create_course(); $page = $this->getDataGenerator()->create_module('page', ['course' => $course->id, 'name' => 'Pokus']); $context = module::instance($page->cmid); $context->set_locked(true); $context = module::instance($page->cmid); $this->assertTrue($context->locked); $record = $DB->get_record('context', ['id' => $context->id]); $this->assertSame('1', $record->locked); $context->set_locked(false); $context = module::instance($page->cmid); $this->assertFalse($context->locked); $record = $DB->get_record('context', ['id' => $context->id]); $this->assertSame('0', $record->locked); } } user_test.php000064400000021450152267723350007310 0ustar00. namespace core\context; use core\context, core\context_helper; /** * Unit tests for user context class. * * NOTE: more tests are in lib/tests/accesslib_test.php * * @package core * @copyright Petr Skoda * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @coversDefaultClass \core\context\user */ final class user_test extends \advanced_testcase { /** * Tests legacy class. * @coversNothing */ public function test_legacy_classname(): void { $admin = get_admin(); $context = \context_user::instance($admin->id); $this->assertInstanceOf(user::class, $context); $this->assertInstanceOf(\context_user::class, $context); } /** * Tests covered methods. * @covers ::instance * @covers \core\context::instance_by_id */ public function test_factory_methods(): void { $admin = get_admin(); $context = user::instance($admin->id); $this->assertInstanceOf(user::class, $context); $this->assertSame($admin->id, $context->instanceid); $context = context::instance_by_id($context->id); $this->assertInstanceOf(user::class, $context); $this->assertSame($admin->id, $context->instanceid); } /** * Tests covered method. * @covers ::get_short_name */ public function test_get_short_name(): void { $this->assertSame('user', user::get_short_name()); } /** * Tests context level. * @coversNothing */ public function test_level(): void { $this->assertSame(30, user::LEVEL); $this->assertSame(CONTEXT_USER, user::LEVEL); } /** * Tests covered method. * @covers ::get_level_name */ public function test_get_level_name(): void { $this->assertSame('User', user::get_level_name()); } /** * Tests covered method. * @covers ::get_context_name */ public function test_get_context_name(): void { $admin = get_admin(); $context = user::instance($admin->id); $this->assertSame('User: Admin User', $context->get_context_name()); $this->assertSame('User: Admin User', $context->get_context_name(true)); $this->assertSame('Admin User', $context->get_context_name(false)); $this->assertSame('Admin User', $context->get_context_name(false, true)); $this->assertSame('User: Admin User', $context->get_context_name(true, true, false)); } /** * Tests covered method. * @covers ::get_url */ public function test_get_url(): void { $admin = get_admin(); $context = user::instance($admin->id); $expected = new \moodle_url('/user/profile.php', ['id' => $admin->id]); $url = $context->get_url(); $this->assertInstanceOf(\moodle_url::class, $url); $this->assertSame($expected->out(), $url->out()); } /** * Tests covered methods. * @covers ::get_instance_table() * @covers ::get_behat_reference_columns() * @covers \core\context_helper::resolve_behat_reference */ public function test_resolve_behat_reference(): void { $this->resetAfterTest(); $instance = $this->getDataGenerator()->create_user(); $context = context\user::instance($instance->id); $result = context_helper::resolve_behat_reference('User', $instance->username); $this->assertSame($context->id, $result->id); $result = context_helper::resolve_behat_reference('user', $instance->username); $this->assertSame($context->id, $result->id); $result = context_helper::resolve_behat_reference('30', $instance->username); $this->assertSame($context->id, $result->id); $result = context_helper::resolve_behat_reference('User', 'dshjkdshjkhjsadjhdsa'); $this->assertNull($result); $result = context_helper::resolve_behat_reference('User', ''); $this->assertNull($result); } /** * Tests covered method. * @covers ::get_compatible_role_archetypes */ public function test_get_compatible_role_archetypes(): void { global $DB; $allarchetypes = $DB->get_fieldset_select('role', 'DISTINCT archetype', 'archetype IS NOT NULL'); foreach ($allarchetypes as $allarchetype) { $levels = context_helper::get_compatible_levels($allarchetype); $this->assertNotContains(user::LEVEL, $levels, "$allarchetype is not expected to be compatible with context"); } } /** * Tests covered method. * @covers ::get_possible_parent_levels */ public function test_get_possible_parent_levels(): void { $this->assertSame([system::LEVEL], user::get_possible_parent_levels()); } /** * Tests covered method. * @covers ::get_capabilities */ public function test_get_capabilities(): void { $admin = get_admin(); $context = user::instance($admin->id); $capabilities = $context->get_capabilities(); $capabilities = convert_to_array($capabilities); $capabilities = array_column($capabilities, 'name'); $this->assertContains('moodle/user:viewalldetails', $capabilities); $this->assertContains('moodle/grade:viewall', $capabilities); $this->assertNotContains('moodle/course:view', $capabilities); $this->assertNotContains('moodle/site:config', $capabilities); } /** * Tests covered method. * @covers ::create_level_instances */ public function test_create_level_instances(): void { global $DB; $this->resetAfterTest(); $user = $this->getDataGenerator()->create_user(); $usercontext = user::instance($user->id); $DB->delete_records('context', ['id' => $usercontext->id]); context_helper::create_instances(user::LEVEL); $record = $DB->get_record('context', ['contextlevel' => user::LEVEL, 'instanceid' => $user->id], '*', MUST_EXIST); } /** * Tests covered method. * @covers ::get_child_contexts */ public function test_get_child_contexts(): void { $admin = get_admin(); $context = user::instance($admin->id); $children = $context->get_child_contexts(); $this->assertCount(0, $children); } /** * Tests covered method. * @covers ::get_cleanup_sql */ public function test_get_cleanup_sql(): void { global $DB; $this->resetAfterTest(); $user = $this->getDataGenerator()->create_user(); $usercontext = user::instance($user->id); $DB->set_field('user', 'deleted', 1, ['id' => $user->id]); context_helper::cleanup_instances(); $this->assertFalse($DB->record_exists('context', ['contextlevel' => user::LEVEL, 'instanceid' => $user->id])); } /** * Tests covered method. * @covers ::build_paths */ public function test_build_paths(): void { global $DB; $this->resetAfterTest(); $user = $this->getDataGenerator()->create_user(); $usercontext = user::instance($user->id); $syscontext = system::instance(); $DB->set_field('context', 'depth', 1, ['id' => $usercontext->id]); $DB->set_field('context', 'path', '/0', ['id' => $usercontext->id]); context_helper::build_all_paths(true); $record = $DB->get_record('context', ['id' => $usercontext->id]); $this->assertSame('2', $record->depth); $this->assertSame('/' . $syscontext->id . '/' . $record->id, $record->path); } /** * Tests covered method. * @covers ::set_locked */ public function test_set_locked(): void { global $DB; $this->resetAfterTest(); $admin = get_admin(); $context = user::instance($admin->id); $this->assertFalse($context->locked); $context->set_locked(true); $this->assertTrue($context->locked); $record = $DB->get_record('context', ['id' => $context->id]); $this->assertSame('1', $record->locked); $context->set_locked(false); $this->assertFalse($context->locked); $record = $DB->get_record('context', ['id' => $context->id]); $this->assertSame('0', $record->locked); } } block_test.php000064400000021727152267723350007433 0ustar00. namespace core\context; use core\context, core\context_helper; /** * Unit tests for block context class. * * NOTE: more tests are in lib/tests/accesslib_test.php * * @package core * @copyright Petr Skoda * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @coversDefaultClass \core\context\block */ final class block_test extends \advanced_testcase { /** * Tests legacy class name. * @covers \context_block */ public function test_legacy_classname(): void { $this->resetAfterTest(); $block = $this->getDataGenerator()->create_block('online_users'); $context = block::instance($block->id); $this->assertInstanceOf(block::class, $context); $this->assertInstanceOf(\context_block::class, $context); } /** * Tests covered methods. * @covers ::instance * @covers \core\context::instance_by_id */ public function test_factory_methods(): void { $this->resetAfterTest(); $block = $this->getDataGenerator()->create_block('online_users'); $context = block::instance($block->id); $this->assertInstanceOf(block::class, $context); $this->assertSame((string)$block->id, $context->instanceid); $context = context::instance_by_id($context->id); $this->assertInstanceOf(block::class, $context); $this->assertSame((string)$block->id, $context->instanceid); } /** * Tests covered method. * @covers ::get_short_name */ public function test_get_short_name(): void { $this->assertSame('block', block::get_short_name()); } /** * Tests levels. * @coversNothing */ public function test_level(): void { $this->assertSame(80, block::LEVEL); $this->assertSame(CONTEXT_BLOCK, block::LEVEL); } /** * Tests covered method. * @covers ::get_level_name */ public function test_get_level_name(): void { $this->assertSame('Block', block::get_level_name()); } /** * Tests covered method. * @covers ::get_context_name */ public function test_get_context_name(): void { $this->resetAfterTest(); $block = $this->getDataGenerator()->create_block('online_users'); $context = block::instance($block->id); $this->assertSame('Block: Online users', $context->get_context_name()); $this->assertSame('Block: Online users', $context->get_context_name(true)); $this->assertSame('Online users', $context->get_context_name(false)); $this->assertSame('Online users', $context->get_context_name(false, true)); $this->assertSame('Block: Online users', $context->get_context_name(true, true, false)); } /** * Tests covered method. * @covers ::get_url */ public function test_get_url(): void { $this->resetAfterTest(); $block = $this->getDataGenerator()->create_block('online_users'); $context = block::instance($block->id); $expected = new \moodle_url('/'); $url = $context->get_url(); $this->assertInstanceOf(\moodle_url::class, $url); $this->assertSame($expected->out(), $url->out()); } /** * Tests covered method. * @covers ::get_compatible_role_archetypes */ public function test_get_compatible_role_archetypes(): void { global $DB; $allarchetypes = $DB->get_fieldset_select('role', 'DISTINCT archetype', 'archetype IS NOT NULL'); foreach ($allarchetypes as $allarchetype) { $levels = context_helper::get_compatible_levels($allarchetype); $this->assertNotContains(block::LEVEL, $levels, "$allarchetype is not expected to be compatible with context"); } } /** * Tests covered method. * @covers ::get_possible_parent_levels */ public function test_get_possible_parent_levels(): void { $result = block::get_possible_parent_levels(); // All except itself. $this->assertContains(system::LEVEL, $result); $this->assertContains(user::LEVEL, $result); $this->assertContains(coursecat::LEVEL, $result); $this->assertContains(course::LEVEL, $result); $this->assertContains(module::LEVEL, $result); $this->assertNotContains(block::LEVEL, $result); // Make sure plugin contexts are covered too. $all = \core\context_helper::get_all_levels(); $this->assertCount(count($all) - 1, $result); } /** * Tests covered method. * @covers ::get_capabilities */ public function test_get_capabilities(): void { $this->resetAfterTest(); $block = $this->getDataGenerator()->create_block('online_users'); $context = block::instance($block->id); $capabilities = $context->get_capabilities(); $capabilities = convert_to_array($capabilities); $capabilities = array_column($capabilities, 'name'); $this->assertNotContains('moodle/site:config', $capabilities); $this->assertNotContains('moodle/course:view', $capabilities); $this->assertNotContains('moodle/category:manage', $capabilities); $this->assertNotContains('moodle/user:viewalldetails', $capabilities); $this->assertNotContains('mod/page:view', $capabilities); $this->assertNotContains('mod/url:view', $capabilities); } /** * Tests covered method. * @covers ::create_level_instances */ public function test_create_level_instances(): void { global $DB; $this->resetAfterTest(); $block = $this->getDataGenerator()->create_block('online_users'); $context = block::instance($block->id); $DB->delete_records('context', ['id' => $context->id]); context_helper::create_instances(block::LEVEL); $record = $DB->get_record('context', ['contextlevel' => block::LEVEL, 'instanceid' => $block->id], '*', MUST_EXIST); } /** * Tests covered method. * @covers ::get_child_contexts */ public function test_get_child_contexts(): void { $this->resetAfterTest(); $block = $this->getDataGenerator()->create_block('online_users'); $context = block::instance($block->id); $children = $context->get_child_contexts(); $this->assertCount(0, $children); } /** * Tests covered method. * @covers ::get_cleanup_sql */ public function test_get_cleanup_sql(): void { global $DB; $this->resetAfterTest(); $block = $this->getDataGenerator()->create_block('online_users'); $context = block::instance($block->id); $DB->delete_records('block_instances', ['id' => $block->id]); context_helper::cleanup_instances(); $this->assertFalse($DB->record_exists('context', ['contextlevel' => block::LEVEL, 'instanceid' => $block->id])); } /** * Tests covered method. * @covers ::build_paths */ public function test_build_paths(): void { global $DB; $this->resetAfterTest(); $syscontext = system::instance(); $block = $this->getDataGenerator()->create_block('online_users'); $context = block::instance($block->id); $DB->set_field('context', 'depth', 1, ['id' => $context->id]); $DB->set_field('context', 'path', '/0', ['id' => $context->id]); context_helper::build_all_paths(true); $record = $DB->get_record('context', ['id' => $context->id]); $this->assertSame('2', $record->depth); $this->assertSame('/' . $syscontext->id . '/' . $record->id, $record->path); } /** * Tests covered method. * @covers ::set_locked */ public function test_set_locked(): void { global $DB; $this->resetAfterTest(); $block = $this->getDataGenerator()->create_block('online_users'); $context = block::instance($block->id); $context->set_locked(true); $context = block::instance($block->id); $this->assertTrue($context->locked); $record = $DB->get_record('context', ['id' => $context->id]); $this->assertSame('1', $record->locked); $context->set_locked(false); $context = block::instance($block->id); $this->assertFalse($context->locked); $record = $DB->get_record('context', ['id' => $context->id]); $this->assertSame('0', $record->locked); } } course_test.php000064400000024144152267723350007635 0ustar00. namespace core\context; use core\context, core\context_helper; /** * Unit tests for course context class. * * NOTE: more tests are in lib/tests/accesslib_test.php * * @package core * @copyright Petr Skoda * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @coversDefaultClass \core\context\course */ final class course_test extends \advanced_testcase { /** * Tests legacy class. * @coversNothing */ public function test_legacy_classname(): void { global $SITE; $course = $SITE; $context = \context_course::instance($course->id); $this->assertInstanceOf(course::class, $context); $this->assertInstanceOf(\context_course::class, $context); } /** * Tests covered methods. * @covers ::instance * @covers \core\context::instance_by_id */ public function test_factory_methods(): void { global $SITE; $course = $SITE; $context = course::instance($course->id); $this->assertInstanceOf(course::class, $context); $this->assertSame($course->id, $context->instanceid); $context = context::instance_by_id($context->id); $this->assertInstanceOf(course::class, $context); $this->assertSame($course->id, $context->instanceid); } /** * Tests covered method. * @covers ::get_short_name */ public function test_get_short_name(): void { $this->assertSame('course', course::get_short_name()); } /** * Tests levels. * @coversNothing */ public function test_level(): void { $this->assertSame(50, course::LEVEL); $this->assertSame(CONTEXT_COURSE, course::LEVEL); } /** * Tests covered method. * @covers ::get_level_name */ public function test_get_level_name(): void { $this->assertSame('Course', course::get_level_name()); } /** * Tests covered method. * @covers ::get_context_name */ public function test_get_context_name(): void { $this->resetAfterTest(); $course = $this->getDataGenerator()->create_course(['fullname' => 'Test course', 'shortname' => 'TST']); $context = course::instance($course->id); $this->assertSame('Course: Test course', $context->get_context_name()); $this->assertSame('Course: Test course', $context->get_context_name(true)); $this->assertSame('Test course', $context->get_context_name(false)); $this->assertSame('TST', $context->get_context_name(false, true)); $this->assertSame('Course: TST', $context->get_context_name(true, true, false)); } /** * Tests covered method. * @covers ::get_url */ public function test_get_url(): void { $this->resetAfterTest(); $course = $this->getDataGenerator()->create_course(); $context = course::instance($course->id); $expected = new \moodle_url('/course/view.php', ['id' => $course->id]); $url = $context->get_url(); $this->assertInstanceOf(\moodle_url::class, $url); $this->assertSame($expected->out(), $url->out()); } /** * Tests covered methods. * @covers ::get_instance_table() * @covers ::get_behat_reference_columns() * @covers \core\context_helper::resolve_behat_reference */ public function test_resolve_behat_reference(): void { $this->resetAfterTest(); $instance = $this->getDataGenerator()->create_course(['shortname' => 'xyz']); $context = context\course::instance($instance->id); $result = context_helper::resolve_behat_reference('Course', $instance->shortname); $this->assertSame($context->id, $result->id); $result = context_helper::resolve_behat_reference('course', $instance->shortname); $this->assertSame($context->id, $result->id); $result = context_helper::resolve_behat_reference('50', $instance->shortname); $this->assertSame($context->id, $result->id); $result = context_helper::resolve_behat_reference('Course', 'dshjkdshjkhjsadjhdsa'); $this->assertNull($result); $result = context_helper::resolve_behat_reference('Course', ''); $this->assertNull($result); } /** * Tests covered method. * @covers ::get_compatible_role_archetypes */ public function test_get_compatible_role_archetypes(): void { global $DB; $allarchetypes = $DB->get_fieldset_select('role', 'DISTINCT archetype', 'archetype IS NOT NULL'); foreach ($allarchetypes as $allarchetype) { $levels = context_helper::get_compatible_levels($allarchetype); if ($allarchetype === 'editingteacher' || $allarchetype === 'teacher' || $allarchetype === 'student' || $allarchetype === 'manager') { $this->assertContains(course::LEVEL, $levels, "$allarchetype is expected to be compatible with context"); } else { $this->assertNotContains(course::LEVEL, $levels, "$allarchetype is not expected to be compatible with context"); } } } /** * Tests covered method. * @covers ::get_possible_parent_levels */ public function test_get_possible_parent_levels(): void { $this->assertSame([coursecat::LEVEL], course::get_possible_parent_levels()); } /** * Tests covered method. * @covers ::get_capabilities */ public function test_get_capabilities(): void { $this->resetAfterTest(); $course = $this->getDataGenerator()->create_course(); $context = course::instance($course->id); $capabilities = $context->get_capabilities(); $capabilities = convert_to_array($capabilities); $capabilities = array_column($capabilities, 'name'); $this->assertContains('moodle/course:view', $capabilities); $this->assertContains('mod/page:view', $capabilities); $this->assertContains('mod/url:view', $capabilities); $this->assertNotContains('moodle/category:manage', $capabilities); $this->assertNotContains('moodle/user:viewalldetails', $capabilities); } /** * Tests covered method. * @covers ::create_level_instances */ public function test_create_level_instances(): void { global $DB; $this->resetAfterTest(); $course = $this->getDataGenerator()->create_course(); $coursecontext = course::instance($course->id); $DB->delete_records('context', ['id' => $coursecontext->id]); context_helper::create_instances(course::LEVEL); $record = $DB->get_record('context', ['contextlevel' => course::LEVEL, 'instanceid' => $course->id], '*', MUST_EXIST); } /** * Tests covered method. * @covers ::get_child_contexts */ public function test_get_child_contexts(): void { $this->resetAfterTest(); $course = $this->getDataGenerator()->create_course(); $page = $this->getDataGenerator()->create_module('page', ['course' => $course->id, 'name' => 'Pokus']); $context = course::instance($course->id); $children = $context->get_child_contexts(); $this->assertCount(1, $children); $childcontext = reset($children); $this->assertInstanceOf(module::class, $childcontext); $this->assertEquals($page->cmid, $childcontext->instanceid); } /** * Tests covered method. * @covers ::get_cleanup_sql */ public function test_get_cleanup_sql(): void { global $DB; $this->resetAfterTest(); $course = $this->getDataGenerator()->create_course(); $coursecontext = course::instance($course->id); $DB->delete_records('course', ['id' => $course->id]); context_helper::cleanup_instances(); $this->assertFalse($DB->record_exists('context', ['contextlevel' => course::LEVEL, 'instanceid' => $course->id])); } /** * Tests covered method. * @covers ::build_paths */ public function test_build_paths(): void { global $DB; $this->resetAfterTest(); $course = $this->getDataGenerator()->create_course(); $coursecontext = course::instance($course->id); $syscontext = system::instance(); $DB->set_field('context', 'depth', 1, ['id' => $coursecontext->id]); $DB->set_field('context', 'path', '/0', ['id' => $coursecontext->id]); context_helper::build_all_paths(true); $record = $DB->get_record('context', ['id' => $coursecontext->id]); $categorycontext = coursecat::instance($course->category); $this->assertSame('3', $record->depth); $this->assertSame('/' . $syscontext->id . '/' . $categorycontext->id . '/' . $record->id, $record->path); } /** * Tests covered method. * @covers ::set_locked */ public function test_set_locked(): void { global $DB; $this->resetAfterTest(); $course1 = $this->getDataGenerator()->create_course(); $context1 = course::instance($course1->id); $context1->set_locked(true); $context1 = course::instance($course1->id); $this->assertTrue($context1->locked); $record = $DB->get_record('context', ['id' => $context1->id]); $this->assertSame('1', $record->locked); $context1->set_locked(false); $context1 = course::instance($course1->id); $this->assertFalse($context1->locked); $record = $DB->get_record('context', ['id' => $context1->id]); $this->assertSame('0', $record->locked); } } system_test.php000064400000016674152267723350007672 0ustar00. namespace core\context; use core\context, core\context_helper; /** * Unit tests for system context class. * * NOTE: more tests are in lib/tests/accesslib_test.php * * @package core * @copyright Petr Skoda * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @coversDefaultClass \core\context\system */ final class system_test extends \advanced_testcase { /** * Tests legacy class. * @coversNothing */ public function test_legacy_classname(): void { $context = \context_system::instance(); $this->assertInstanceOf(system::class, $context); $this->assertInstanceOf(\context_system::class, $context); } /** * Tests covered methods. * @covers ::instance * @covers \core\context::instance_by_id */ public function test_factory_methods(): void { $context = system::instance(); $this->assertInstanceOf(system::class, $context); $this->assertEquals(SYSCONTEXTID, $context->id); $context = context::instance_by_id($context->id); $this->assertInstanceOf(system::class, $context); $this->assertEquals(SYSCONTEXTID, $context->id); } /** * Tests covered method. * @covers ::get_short_name */ public function test_get_short_name(): void { $this->assertSame('system', system::get_short_name()); } /** * Tests context level. * @coversNothing */ public function test_level(): void { $this->assertSame(10, system::LEVEL); $this->assertSame(CONTEXT_SYSTEM, system::LEVEL); } /** * Tests covered method. * @covers ::get_level_name */ public function test_get_level_name(): void { $this->assertSame('System', system::get_level_name()); } /** * Tests covered method. * @covers ::get_context_name */ public function test_get_context_name(): void { $context = system::instance(); $this->assertSame('System', $context->get_context_name()); $this->assertSame('System', $context->get_context_name(true)); $this->assertSame('System', $context->get_context_name(false)); $this->assertSame('System', $context->get_context_name(false, true)); $this->assertSame('System', $context->get_context_name(true, true, false)); } /** * Tests covered method. * @covers ::get_url */ public function test_get_url(): void { $context = system::instance(); $expected = new \moodle_url('/'); $url = $context->get_url(); $this->assertInstanceOf(\moodle_url::class, $url); $this->assertSame($expected->out(), $url->out()); } /** * Tests covered method. * @covers \core\context_helper::resolve_behat_reference */ public function test_resolve_behat_reference(): void { $syscontext = context\system::instance(); $result = context_helper::resolve_behat_reference('System', ''); $this->assertSame($syscontext->id, $result->id); $result = context_helper::resolve_behat_reference('System', '44'); $this->assertSame($syscontext->id, $result->id); $result = context_helper::resolve_behat_reference('system', ''); $this->assertSame($syscontext->id, $result->id); $result = context_helper::resolve_behat_reference('10', ''); $this->assertSame($syscontext->id, $result->id); } /** * Tests covered method. * @covers ::get_compatible_role_archetypes */ public function test_get_compatible_role_archetypes(): void { global $DB; $allarchetypes = $DB->get_fieldset_select('role', 'DISTINCT archetype', 'archetype IS NOT NULL'); foreach ($allarchetypes as $allarchetype) { $levels = context_helper::get_compatible_levels($allarchetype); if ($allarchetype === 'manager' || $allarchetype === 'coursecreator') { $this->assertContains(system::LEVEL, $levels, "$allarchetype is expected to be compatible with context"); } else { $this->assertNotContains(system::LEVEL, $levels, "$allarchetype is not expected to be compatible with context"); } } } /** * Tests covered method. * @covers ::get_possible_parent_levels */ public function test_get_possible_parent_levels(): void { $this->assertSame([], system::get_possible_parent_levels()); } /** * Tests covered method. * @covers ::get_capabilities */ public function test_get_capabilities(): void { global $DB; $context = system::instance(); $capabilities = $context->get_capabilities(); $expected = $DB->count_records('capabilities', []); $this->assertCount($expected, $capabilities); } /** * Tests covered method. * @covers ::create_level_instances */ public function test_create_level_instances(): void { context_helper::create_instances(system::LEVEL); } /** * Tests covered method. * @covers ::get_child_contexts */ public function test_get_child_contexts(): void { global $DB; $context = system::instance(); $children = $context->get_child_contexts(); $expected = $DB->count_records('context', []) - 1; $this->assertCount($expected, $children); $this->assertDebuggingCalled('Fetching of system context child courses is strongly ' . 'discouraged on production servers (it may eat all available memory)!'); } /** * Tests covered method. * @covers ::get_cleanup_sql */ public function test_get_cleanup_sql(): void { // Nothing to clean up actually. context_helper::cleanup_instances(); } /** * Tests covered method. * @covers ::build_paths */ public function test_build_paths(): void { global $DB; $this->resetAfterTest(); $DB->set_field('context', 'depth', 2, ['id' => SYSCONTEXTID]); $DB->set_field('context', 'path', '/0', ['id' => SYSCONTEXTID]); context_helper::build_all_paths(true); $record = $DB->get_record('context', ['id' => SYSCONTEXTID]); $this->assertSame('1', $record->depth); $this->assertSame('/' . $record->id, $record->path); } /** * Tests covered method. * @covers ::set_locked */ public function test_set_locked(): void { $context = system::instance(); $context->set_locked(false); try { $context->set_locked(true); } catch (\moodle_exception $e) { $this->assertInstanceOf(\coding_exception::class, $e); $this->assertSame('Coding error detected, it must be fixed by a programmer: ' . 'It is not possible to lock the system context', $e->getMessage()); } } } coursecat_test.php000064400000024713152267723350010327 0ustar00. namespace core\context; use core\context, core\context_helper; /** * Unit tests for coursecat context class. * * NOTE: more tests are in lib/tests/accesslib_test.php * * @package core * @copyright Petr Skoda * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @coversDefaultClass \core\context\coursecat */ final class coursecat_test extends \advanced_testcase { /** * Tests legacy class name. * @coversNothing */ public function test_legacy_classname(): void { $category = \core_course_category::get_default(); $context = \context_coursecat::instance($category->id); $this->assertInstanceOf(coursecat::class, $context); $this->assertInstanceOf(\context_coursecat::class, $context); } /** * Tests covered methods. * @covers ::instance * @covers \core\context::instance_by_id */ public function test_factory_methods(): void { $category = \core_course_category::get_default(); $context = coursecat::instance($category->id); $this->assertInstanceOf(coursecat::class, $context); $this->assertSame($category->id, $context->instanceid); $context = context::instance_by_id($context->id); $this->assertInstanceOf(coursecat::class, $context); $this->assertSame($category->id, $context->instanceid); } /** * Tests covered method. * @covers ::get_short_name */ public function test_get_short_name(): void { $this->assertSame('coursecat', coursecat::get_short_name()); } /** * Tests levels. * @coversNothing */ public function test_level(): void { $this->assertSame(40, coursecat::LEVEL); $this->assertSame(CONTEXT_COURSECAT, coursecat::LEVEL); } /** * Tests covered method. * @covers ::get_level_name */ public function test_get_level_name(): void { $this->assertSame('Category', coursecat::get_level_name()); } /** * Tests covered method. * @covers ::get_context_name */ public function test_get_context_name(): void { $category = \core_course_category::get_default(); $context = coursecat::instance($category->id); $this->assertSame('Category: Category 1', $context->get_context_name()); $this->assertSame('Category: Category 1', $context->get_context_name(true)); $this->assertSame('Category 1', $context->get_context_name(false)); $this->assertSame('Category 1', $context->get_context_name(false, true)); $this->assertSame('Category: Category 1', $context->get_context_name(true, true, false)); } /** * Tests covered method. * @covers ::get_url */ public function test_get_url(): void { $category = \core_course_category::get_default(); $context = coursecat::instance($category->id); $expected = new \moodle_url('/course/index.php', ['categoryid' => $category->id]); $url = $context->get_url(); $this->assertInstanceOf(\moodle_url::class, $url); $this->assertSame($expected->out(), $url->out()); } /** * Tests covered methods. * @covers ::get_instance_table() * @covers ::get_behat_reference_columns() * @covers \core\context_helper::resolve_behat_reference */ public function test_resolve_behat_reference(): void { $this->resetAfterTest(); $instance = $this->getDataGenerator()->create_category(['idnumber' => 'xyz']); $context = context\coursecat::instance($instance->id); $result = context_helper::resolve_behat_reference('Category', $instance->idnumber); $this->assertSame($context->id, $result->id); $result = context_helper::resolve_behat_reference('coursecat', $instance->idnumber); $this->assertSame($context->id, $result->id); $result = context_helper::resolve_behat_reference('40', $instance->idnumber); $this->assertSame($context->id, $result->id); $result = context_helper::resolve_behat_reference('Category', 'dshjkdshjkhjsadjhdsa'); $this->assertNull($result); $result = context_helper::resolve_behat_reference('Category', ''); $this->assertNull($result); } /** * Tests covered method. * @covers ::get_compatible_role_archetypes */ public function test_get_compatible_role_archetypes(): void { global $DB; $allarchetypes = $DB->get_fieldset_select('role', 'DISTINCT archetype', 'archetype IS NOT NULL'); foreach ($allarchetypes as $allarchetype) { $levels = context_helper::get_compatible_levels($allarchetype); if ($allarchetype === 'manager' || $allarchetype === 'coursecreator') { $this->assertContains(coursecat::LEVEL, $levels, "$allarchetype is expected to be compatible with context"); } else { $this->assertNotContains(coursecat::LEVEL, $levels, "$allarchetype is not expected to be compatible with context"); } } } /** * Tests covered method. * @covers ::get_possible_parent_levels */ public function test_get_possible_parent_levels(): void { $this->assertSame([system::LEVEL, coursecat::LEVEL], coursecat::get_possible_parent_levels()); } /** * Tests covered method. * @covers ::get_capabilities */ public function test_get_capabilities(): void { $category = \core_course_category::get_default(); $context = coursecat::instance($category->id); $capabilities = $context->get_capabilities(); $capabilities = convert_to_array($capabilities); $capabilities = array_column($capabilities, 'name'); $this->assertContains('moodle/category:manage', $capabilities); $this->assertContains('moodle/course:view', $capabilities); $this->assertNotContains('moodle/user:viewalldetails', $capabilities); } /** * Tests covered method. * @covers ::create_level_instances */ public function test_create_level_instances(): void { global $DB; $this->resetAfterTest(); $coursecat = $this->getDataGenerator()->create_category(); $coursecatcontext = coursecat::instance($coursecat->id); $DB->delete_records('context', ['id' => $coursecatcontext->id]); context_helper::create_instances(coursecat::LEVEL); $record = $DB->get_record('context', ['contextlevel' => coursecat::LEVEL, 'instanceid' => $coursecat->id], '*', MUST_EXIST); } /** * Tests covered method. * @covers ::get_child_contexts */ public function test_get_child_contexts(): void { $this->resetAfterTest(); $category = \core_course_category::get_default(); $context = coursecat::instance($category->id); $children = $context->get_child_contexts(); $this->assertCount(0, $children); $course = $this->getDataGenerator()->create_course(['categoryid' => $category->id]); // This may fail if some plugin auto-creates activities. $children = $context->get_child_contexts(); $this->assertCount(1, $children); } /** * Tests covered method. * @covers ::get_cleanup_sql */ public function test_get_cleanup_sql(): void { global $DB; $this->resetAfterTest(); $coursecat = $this->getDataGenerator()->create_category(); $coursecatcontext = coursecat::instance($coursecat->id); $DB->delete_records('course_categories', ['id' => $coursecat->id]); context_helper::cleanup_instances(); $this->assertFalse($DB->record_exists('context', ['contextlevel' => coursecat::LEVEL, 'instanceid' => $coursecat->id])); } /** * Tests covered method. * @covers ::build_paths */ public function test_build_paths(): void { global $DB; $this->resetAfterTest(); $coursecat = $this->getDataGenerator()->create_category(); $coursecatcontext = coursecat::instance($coursecat->id); $syscontext = system::instance(); $DB->set_field('context', 'depth', 1, ['id' => $coursecatcontext->id]); $DB->set_field('context', 'path', '/0', ['id' => $coursecatcontext->id]); context_helper::build_all_paths(true); $record = $DB->get_record('context', ['id' => $coursecatcontext->id]); $this->assertSame('2', $record->depth); $this->assertSame('/' . $syscontext->id . '/' . $record->id, $record->path); } /** * Tests covered method. * @covers ::set_locked */ public function test_set_locked(): void { global $DB; $this->resetAfterTest(); $category1 = $this->getDataGenerator()->create_category(); $category2 = $this->getDataGenerator()->create_category(['parent' => $category1->id]); $context1 = coursecat::instance($category1->id); $context2 = coursecat::instance($category2->id); $context1->set_locked(true); $context1 = coursecat::instance($category1->id); $context2 = coursecat::instance($category2->id); $this->assertTrue($context1->locked); $this->assertTrue($context2->locked); $record = $DB->get_record('context', ['id' => $context1->id]); $this->assertSame('1', $record->locked); $record = $DB->get_record('context', ['id' => $context2->id]); $this->assertSame('0', $record->locked); $context1->set_locked(false); $context1 = coursecat::instance($category1->id); $context2 = coursecat::instance($category2->id); $this->assertFalse($context1->locked); $this->assertFalse($context2->locked); $record = $DB->get_record('context', ['id' => $context1->id]); $this->assertSame('0', $record->locked); $record = $DB->get_record('context', ['id' => $context2->id]); $this->assertSame('0', $record->locked); } }