2 // This file is part of Moodle - https://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <https://www.gnu.org/licenses/>.
23 * Context maintenance and helper methods.
25 * This is "extends context" is a bloody hack that tires to work around the deficiencies
26 * in the "protected" keyword in PHP, this helps us to hide all the internals of context
27 * level implementation from the rest of code, the code completion returns what developers need.
29 * Thank you Tim Hunt for helping me with this nasty trick.
31 * @package core_access
33 * @copyright Petr Skoda
34 * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37 abstract class context_helper
extends context
{
40 * @var array An array definitions of all context levels
42 private static $alllevels;
45 * Reset internal context levels array.
47 public static function reset_levels() {
48 self
::$alllevels = null;
52 * Initialise context levels, call before using self::$alllevels.
54 private static function init_levels():void
{
57 if (isset(self
::$alllevels)) {
60 self
::$alllevels = array(
61 CONTEXT_SYSTEM
=> \core\context\system
::class,
62 CONTEXT_USER
=> \core\context\user
::class,
63 CONTEXT_COURSECAT
=> \core\context\coursecat
::class,
64 CONTEXT_COURSE
=> \core\context\course
::class,
65 CONTEXT_MODULE
=> \core\context\module
::class,
66 CONTEXT_BLOCK
=> \core\context\block
::class,
69 if (empty($CFG->custom_context_classes
)) {
73 $levels = $CFG->custom_context_classes
;
74 if (!is_array($levels)) {
75 $levels = @unserialize
($levels);
77 if (!is_array($levels)) {
78 debugging('Invalid $CFG->custom_context_classes detected, value ignored.', DEBUG_DEVELOPER
);
82 // Unsupported custom levels, use with care!!!
83 foreach ($levels as $level => $classname) {
84 self
::$alllevels[$level] = $classname;
86 ksort(self
::$alllevels);
90 * Converts legacy context_* class name to new class name.
92 * NOTE: this is needed for external API which uses short context names.
95 * @param int|string $extlevel
96 * @return string|null context class name or null if not found
98 public static function parse_external_level($extlevel): ?
string {
100 if (is_number($extlevel)) {
101 if (isset(self
::$alllevels[$extlevel])) {
102 return self
::$alllevels[$extlevel];
107 if ($extlevel && is_string($extlevel)) {
109 foreach (self
::$alllevels as $classname) {
110 if ($classname::get_short_name() === $extlevel) {
112 debugging("Duplicate short context level name found '$extlevel', use numeric value instead",
125 * Resolve reference to context used in behat feature files.
127 * @param string $level
128 * @param string $reference
129 * @return context|null
131 public static function resolve_behat_reference(string $level, string $reference): ?context
{
134 if (!PHPUNIT_TEST
&& !defined('BEHAT_SITE_RUNNING')) {
135 throw new coding_exception('resolve_behat_reference() cannot be used outside of tests');
140 if (is_number($level)) {
141 if (isset(self
::$alllevels[$level])) {
142 $classname = self
::$alllevels[$level];
145 foreach (self
::$alllevels as $levelclassname) {
146 if ($level === $levelclassname::get_level_name()) {
147 $classname = $levelclassname;
150 if ($level === $levelclassname::get_short_name()) {
151 $classname = $levelclassname;
160 if ($classname::LEVEL
=== context\system
::LEVEL
) {
161 return context\system
::instance();
164 if (trim($reference) === '') {
168 $table = $classname::get_instance_table();
173 $columns = $classname::get_behat_reference_columns();
174 foreach ($columns as $column) {
175 $instance = $DB->get_record($table, [$column => $reference]);
177 $context = $classname::instance($instance->id
, IGNORE_MISSING
);
189 * Returns a class name of the context level class
191 * @param int $contextlevel (CONTEXT_SYSTEM, etc.)
192 * @return string class name of the context class
193 * @throws coding_exception if level does not exist
195 public static function get_class_for_level(int $contextlevel): string {
197 if (isset(self
::$alllevels[$contextlevel])) {
198 return self
::$alllevels[$contextlevel];
200 throw new coding_exception('Invalid context level specified');
205 * Returns a list of all context levels
207 * @return array int=>string (level=>level class name)
209 public static function get_all_levels(): array {
211 return self
::$alllevels;
215 * Get list of possible child levels for given level.
218 * @param int $parentlevel
219 * @return int[] list of context levels that my be children of given context level.
221 public static function get_child_levels(int $parentlevel): array {
224 $definitions = self
::$alllevels;
226 $recursion = function(int $pl) use (&$result, $definitions, &$recursion): void
{
227 foreach ($definitions as $contextlevel => $classname) {
228 $parentlevels = $classname::get_possible_parent_levels();
229 if (in_array($pl, $parentlevels)) {
230 if (isset($result[$contextlevel])) {
233 $result[$contextlevel] = $contextlevel;
234 $recursion($contextlevel);
238 $recursion($parentlevel);
240 $classname = self
::get_class_for_level($parentlevel);
241 $parentlevels = $classname::get_possible_parent_levels();
242 if (!in_array($parentlevel, $parentlevels)) {
243 unset($result[$parentlevel]);
246 return array_values($result);
250 * Returns context levels that compatible with role archetype assignments.
253 * @param string $archetype
256 public static function get_compatible_levels(string $archetype): array {
260 foreach (self
::$alllevels as $contextlevel => $classname) {
261 $compatiblearchetypes = $classname::get_compatible_role_archetypes();
262 foreach ($compatiblearchetypes as $at) {
263 if ($at === $archetype) {
264 $result[] = $contextlevel;
273 * Remove stale contexts that belonged to deleted instances.
274 * Ideally all code should cleanup contexts properly, unfortunately accidents happen...
278 public static function cleanup_instances() {
283 foreach (self
::$alllevels as $classname) {
284 $sqls[] = $classname::get_cleanup_sql();
287 $sql = implode(" UNION ", $sqls);
289 // It is probably better to use transactions, it might be faster too.
290 $transaction = $DB->start_delegated_transaction();
292 $rs = $DB->get_recordset_sql($sql);
293 foreach ($rs as $record) {
294 $context = context
::create_instance_from_record($record);
299 $transaction->allow_commit();
303 * Create all context instances at the given level and above.
305 * @param int $contextlevel null means all levels
306 * @param bool $buildpaths
309 public static function create_instances($contextlevel = null, $buildpaths = true) {
311 foreach (self
::$alllevels as $level => $classname) {
312 if ($contextlevel && $contextlevel != context\block
::LEVEL
&& $level > $contextlevel) {
313 // Skip potential sub-contexts,
314 // in case of blocks build all contexts because plugin contexts may have higher levels.
317 $classname::create_level_instances();
319 $classname::build_paths(false);
325 * Rebuild paths and depths in all context levels.
327 * @param bool $force false means add missing only
330 public static function build_all_paths($force = false) {
332 foreach (self
::$alllevels as $classname) {
333 $classname::build_paths($force);
336 // Reset static course cache - it might have incorrect cached data.
337 accesslib_clear_all_caches(true);
341 * Resets the cache to remove all data.
343 public static function reset_caches() {
344 context
::reset_caches();
348 * Returns all fields necessary for context preloading from user $rec.
350 * This helps with performance when dealing with hundreds of contexts.
352 * @param string $tablealias context table alias in the query
353 * @return array (table.column=>alias, ...)
355 public static function get_preload_record_columns($tablealias) {
357 "$tablealias.id" => "ctxid",
358 "$tablealias.path" => "ctxpath",
359 "$tablealias.depth" => "ctxdepth",
360 "$tablealias.contextlevel" => "ctxlevel",
361 "$tablealias.instanceid" => "ctxinstance",
362 "$tablealias.locked" => "ctxlocked",
367 * Returns all fields necessary for context preloading from user $rec.
369 * This helps with performance when dealing with hundreds of contexts.
371 * @param string $tablealias context table alias in the query
374 public static function get_preload_record_columns_sql($tablealias) {
375 return "$tablealias.id AS ctxid, " .
376 "$tablealias.path AS ctxpath, " .
377 "$tablealias.depth AS ctxdepth, " .
378 "$tablealias.contextlevel AS ctxlevel, " .
379 "$tablealias.instanceid AS ctxinstance, " .
380 "$tablealias.locked AS ctxlocked";
384 * Preloads context cache with information from db record and strips the cached info.
386 * The db request has to contain all columns from context_helper::get_preload_record_columns().
388 * @param stdClass $rec
389 * @return void This is intentional. See MDL-37115. You will need to get the context
390 * in the normal way, but it is now cached, so that will be fast.
392 public static function preload_from_record(stdClass
$rec): void
{
393 context
::preload_from_record($rec);
397 * Preload a set of contexts using their contextid.
399 * @param array $contextids
401 public static function preload_contexts_by_id(array $contextids): void
{
404 // Determine which contexts are not already cached.
406 foreach ($contextids as $contextid) {
407 if (!self
::cache_get_by_id($contextid)) {
408 $tofetch[] = $contextid;
412 if (count($tofetch) > 1) {
413 // There are at least two to fetch.
414 // There is no point only fetching a single context as this would be no more efficient than calling the existing code.
415 list($insql, $inparams) = $DB->get_in_or_equal($tofetch, SQL_PARAMS_NAMED
);
416 $ctxs = $DB->get_records_select('context', "id {$insql}", $inparams, '',
417 self
::get_preload_record_columns_sql('{context}'));
418 foreach ($ctxs as $ctx) {
419 self
::preload_from_record($ctx);
425 * Preload all contexts instances from course.
427 * To be used if you expect multiple queries for course activities...
429 * @param int $courseid
431 public static function preload_course($courseid) {
432 // Users can call this multiple times without doing any harm.
433 if (isset(context
::$cache_preloaded[$courseid])) {
436 $coursecontext = context\course
::instance($courseid);
437 $coursecontext->get_child_contexts();
439 context
::$cache_preloaded[$courseid] = true;
443 * Delete context instance
445 * @param int $contextlevel
446 * @param int $instanceid
449 public static function delete_instance($contextlevel, $instanceid) {
452 // Double check the context still exists.
453 if ($record = $DB->get_record('context', array('contextlevel' => $contextlevel, 'instanceid' => $instanceid))) {
454 $context = context
::create_instance_from_record($record);
460 * Returns the name of specified context level
462 * @param int $contextlevel
463 * @return string name of the context level
465 public static function get_level_name($contextlevel) {
466 $classname = self
::get_class_for_level($contextlevel);
467 return $classname::get_level_name();
471 * Gets the current context to be used for navigation tree filtering.
473 * @param context|null $context The current context to be checked against.
474 * @return context|null the context that navigation tree filtering should use.
476 public static function get_navigation_filter_context(?context
$context): ?context
{
478 if (!empty($CFG->filternavigationwithsystemcontext
)) {
479 return context\system
::instance();