Gets the blocks branch for the provided course.

@param \context $coursecontext
@return null
326307
public static function get_blocks_branch(\context $coursecontext) {
        global $DB;

        if ($coursecontext->contextlevel !== CONTEXT_COURSE) {
            throw new \coding_exception('A course context should be provided');
        }

        $branches = [];

        $children = $coursecontext->get_child_contexts();
        foreach ($children as $childcontext) {

            if ($childcontext->contextlevel !== CONTEXT_BLOCK) {
                continue;
            }

            $blockinstance = block_instance_by_id($childcontext->instanceid);
            $displayname = shorten_text(format_string($blockinstance->get_title(), true, ['context' => $childcontext]));
            $branches[] = self::complete([
                'text' => $displayname,
                'contextid' => $childcontext->id,
            ]);

        }

        return $branches;
    }
367956
public static function remove_all_subscriptions_for_rule($ruleid, $coursecontext = null) {
        global $DB;

        // Store all the subscriptions we have to delete.
        $subscriptions = $DB->get_recordset('tool_monitor_subscriptions', array('ruleid' => $ruleid));

        // Now delete them.
        $success = $DB->delete_records('tool_monitor_subscriptions', array('ruleid' => $ruleid));

        // If successful and there were subscriptions that were deleted trigger a subscription deleted event.
        if ($success && $subscriptions) {
            foreach ($subscriptions as $subscription) {
                // It is possible that we are deleting rules associated with a deleted course, so we should be
                // passing the context as the second parameter.
                if (!is_null($coursecontext)) {
                    $context = $coursecontext;
                    $courseid = $subscription->courseid;
                } else if (!empty($subscription->courseid) && ($coursecontext =
                        \context_course::instance($subscription->courseid, IGNORE_MISSING))) {
                    $courseid = $subscription->courseid;
                    $context = $coursecontext;
                } else {
                    $courseid = 0;
                    $context = \context_system::instance();
                }

                $params = array(
                    'objectid' => $subscription->id,
                    'courseid' => $courseid,
                    'context' => $context
                );
                $event = \tool_monitor\event\subscription_deleted::create($params);
                $event->add_record_snapshot('tool_monitor_subscriptions', $subscription);
                $event->trigger();

                // Let's invalidate the cache.
                $cache = \cache::make('tool_monitor', 'eventsubscriptions');
                $cache->delete($courseid);
            }
        }

        $subscriptions->close();

        return $success;
    }
1098553
public static function remove_all_subscriptions_in_course($coursecontext) {
        global $DB;

        // Store all the subscriptions we have to delete.
        if ($subscriptions = $DB->get_records('tool_monitor_subscriptions', ['courseid' => $coursecontext->instanceid])) {
            // Delete subscriptions in bulk.
            $DB->delete_records('tool_monitor_subscriptions', ['courseid' => $coursecontext->instanceid]);

            // Trigger events one by one.
            foreach ($subscriptions as $subscription) {
                $params = ['objectid' => $subscription->id, 'context' => $coursecontext];
                $event = \tool_monitor\event\subscription_deleted::create($params);
                $event->add_record_snapshot('tool_monitor_subscriptions', $subscription);
                $event->trigger();
            }
        }
    }
1287635
protected function getExecutionContext() {
        if (!$this->_executionContext) {
            $this->_executionContext = new ExecutionContextList(
                $this->version,
                $this->solution['flowSid'],
                $this->solution['sid']
            );
        }

        return $this->_executionContext;
    }
65327
private function createDocBlockContext()
    {
        $file = $this->descriptor->getFile();
        $namespaceAliases = $file ? $file->getNamespaceAliases()->getAll() : array();

        return new Context($this->descriptor->getNamespace(), $namespaceAliases);
    }
1076316
protected function get_parent_context() : \context {
        global $PAGE;
        if ($this->parentcontext) {
            return $this->parentcontext;
        } else if ($PAGE->context && $PAGE->context instanceof \context_coursecat) {
            return $PAGE->context;
        }
        return \context_system::instance();
    }
588911
protected static function get_course_public_information(core_course_list_element $course, $coursecontext) {

        static $categoriescache = array();

        // Category information.
        if (!array_key_exists($course->category, $categoriescache)) {
            $categoriescache[$course->category] = core_course_category::get($course->category, IGNORE_MISSING);
        }
        $category = $categoriescache[$course->category];

        // Retrieve course overview used files.
        $files = array();
        foreach ($course->get_course_overviewfiles() as $file) {
            $fileurl = moodle_url::make_webservice_pluginfile_url($file->get_contextid(), $file->get_component(),
                                                                    $file->get_filearea(), null, $file->get_filepath(),
                                                                    $file->get_filename())->out(false);
            $files[] = array(
                'filename' => $file->get_filename(),
                'fileurl' => $fileurl,
                'filesize' => $file->get_filesize(),
                'filepath' => $file->get_filepath(),
                'mimetype' => $file->get_mimetype(),
                'timemodified' => $file->get_timemodified(),
            );
        }

        // Retrieve the course contacts,
        // we need here the users fullname since if we are not enrolled can be difficult to obtain them via other Web Services.
        $coursecontacts = array();
        foreach ($course->get_course_contacts() as $contact) {
             $coursecontacts[] = array(
                'id' => $contact['user']->id,
                'fullname' => $contact['username'],
                'roles' => array_map(function($role){
                    return array('id' => $role->id, 'name' => $role->displayname);
                }, $contact['roles']),
                'role' => array('id' => $contact['role']->id, 'name' => $contact['role']->displayname),
                'rolename' => $contact['rolename']
             );
        }

        // Allowed enrolment methods (maybe we can self-enrol).
        $enroltypes = array();
        $instances = enrol_get_instances($course->id, true);
        foreach ($instances as $instance) {
            $enroltypes[] = $instance->enrol;
        }

        // Format summary.
        list($summary, $summaryformat) =
            external_format_text($course->summary, $course->summaryformat, $coursecontext->id, 'course', 'summary', null);

        $categoryname = '';
        if (!empty($category)) {
            $categoryname = external_format_string($category->name, $category->get_context());
        }

        $displayname = get_course_display_name_for_list($course);
        $coursereturns = array();
        $coursereturns['id']                = $course->id;
        $coursereturns['fullname']          = external_format_string($course->fullname, $coursecontext->id);
        $coursereturns['displayname']       = external_format_string($displayname, $coursecontext->id);
        $coursereturns['shortname']         = external_format_string($course->shortname, $coursecontext->id);
        $coursereturns['categoryid']        = $course->category;
        $coursereturns['categoryname']      = $categoryname;
        $coursereturns['summary']           = $summary;
        $coursereturns['summaryformat']     = $summaryformat;
        $coursereturns['summaryfiles']      = external_util::get_area_files($coursecontext->id, 'course', 'summary', false, false);
        $coursereturns['overviewfiles']     = $files;
        $coursereturns['contacts']          = $coursecontacts;
        $coursereturns['enrollmentmethods'] = $enroltypes;
        $coursereturns['sortorder']         = $course->sortorder;

        $handler = core_course\customfield\course_handler::create();
        if ($customfields = $handler->export_instance_data($course->id)) {
            $coursereturns['customfields'] = [];
            foreach ($customfields as $data) {
                $coursereturns['customfields'][] = [
                    'type' => $data->get_type(),
                    'value' => $data->get_value(),
                    'name' => $data->get_name(),
                    'shortname' => $data->get_shortname()
                ];
            }
        }

        return $coursereturns;
    }
758229
public function getContext() {
        return new ExecutionStepContextContext(
            $this->version,
            $this->solution['flowSid'],
            $this->solution['executionSid'],
            $this->solution['stepSid']
        );
    }
1227355
public function get_child_contexts() {
        global $DB;

        if (empty($this->_path) or 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, CONTEXT_COURSECAT);
        $records = $DB->get_records_sql($sql, $params);

        $result = array();
        foreach ($records as $record) {
            $result[$record->id] = context::create_instance_from_record($record);
        }

        return $result;
    }
625182
public function get_supported_orders(\context $context) {
        $orders = parent::get_supported_orders($context);

        // If not within a course, no other kind of sorting supported.
        $coursecontext = $context->get_course_context(false);
        if ($coursecontext) {
            // Within a course or activity/block, support sort by location.
            $orders['location'] = get_string('order_location', 'search',
                    $context->get_context_name());
        }

        return $orders;
    }
1314083
protected function get_role_options($instance, $coursecontext) {
        global $DB;

        $roles = get_assignable_roles($coursecontext);
        $roles[0] = get_string('none');
        $roles = array_reverse($roles, true); // Descending default sortorder.
        if ($instance->id and !isset($roles[$instance->roleid])) {
            if ($role = $DB->get_record('role', array('id' => $instance->roleid))) {
                $roles = role_fix_names($roles, $coursecontext, ROLENAME_ALIAS, true);
                $roles[$instance->roleid] = role_get_name($role, $coursecontext);
            } else {
                $roles[$instance->roleid] = get_string('error');
            }
        }

        return $roles;
    }
1232213
public function get_context() {
        if ($this->itemtype == 'mod') {
            $modinfo = get_fast_modinfo($this->courseid);
            // Sometimes the course module cache is out of date and needs to be rebuilt.
            if (!isset($modinfo->instances[$this->itemmodule][$this->iteminstance])) {
                rebuild_course_cache($this->courseid, true);
                $modinfo = get_fast_modinfo($this->courseid);
            }
            // Even with a rebuilt cache the module does not exist. This means the
            // database is in an invalid state - we will log an error and return
            // the course context but the calling code should be updated.
            if (!isset($modinfo->instances[$this->itemmodule][$this->iteminstance])) {
                mtrace(get_string('moduleinstancedoesnotexist', 'error'));
                $context = \context_course::instance($this->courseid);
            } else {
                $cm = $modinfo->instances[$this->itemmodule][$this->iteminstance];
                $context = \context_module::instance($cm->id);
            }
        } else {
            $context = \context_course::instance($this->courseid);
        }
        return $context;
    }
1229667
private function getCurrentClassName(Context $context)
    {
        $class = null;
        /** @var PropertyMetadata $metadata */
        if (null !== ($metadata = $context->getMetadataStack()->top())) {
            if ($metadata->class) {
                $class = $metadata->class;
            }
        }

        return $class;
    }
498304
public function compile(CompilationContext $compilationContext)
    {
        $compilationContext->codePrinter->output('while (1) {');

        /*
         * Variables are initialized in a different way inside cycle
         */
        ++$compilationContext->insideCycle;

        /*
         * Compile statements in the 'loop' block
         */
        if (!isset($this->statement['statements'])) {
            throw new CompilerException("Infinite loop without at least a 'break' statement is not allowed", $this->statement);
        }

        $st = new StatementsBlock($this->statement['statements']);

        /**
         * Check if the block contain at least a break statement.
         */
        $loopBreakPass = new LoopBreakPass();
        $loopBreakPass->pass($st);
        if (!$loopBreakPass->hasBreak()) {
            throw new CompilerException("Infinite loop without at least a 'break' statement is not allowed", $this->statement);
        }

        $st->isLoop(true);
        $st->compile($compilationContext, false, Branch::TYPE_LOOP_INFINITE);

        --$compilationContext->insideCycle;

        $compilationContext->codePrinter->output('}');
    }
473421
public function initializeAvailableProxyClasses(ApplicationContext $context = null)
    {
        if ($context === null) {
            return;
        }

        $proxyClasses = @include(FLOW_PATH_TEMPORARY_BASE . '/' . (string)$context . '/AvailableProxyClasses.php');
        if ($proxyClasses !== false) {
            $this->availableProxyClasses = $proxyClasses;
        }
    }
886412
private function createDocBlockContext(): Context
    {
        $file = $this->descriptor->getFile();
        $namespaceAliases = $file ? $file->getNamespaceAliases()->getAll() : [];
        foreach ($namespaceAliases as $alias => $fqsen) {
            $namespaceAliases[$alias] = (string) $fqsen;
        }

        return new Context((string) $this->descriptor->getNamespace(), $namespaceAliases);
    }
681346
public static function restore_find_best_target_context($categories, $courseid, $contextlevel) {
        global $DB;

        $targetcontext = false;

        // Depending of $contextlevel, we perform different actions
        switch ($contextlevel) {
             // For system is easy, the best context is the system context
             case CONTEXT_SYSTEM:
                 $targetcontext = context_system::instance();
                 break;

             // For coursecat, we are going to look for stamps in all the
             // course categories between CONTEXT_SYSTEM and CONTEXT_COURSE
             // (i.e. in all the course categories in the path)
             //
             // And only will return one "best" target context if all the
             // matches belong to ONE and ONLY ONE context. If multiple
             // matches are found, that means that there is some annoying
             // qbank "fragmentation" in the categories, so we'll fallback
             // to create the qbank at course level
             case CONTEXT_COURSECAT:
                 // Build the array of stamps we are going to match
                 $stamps = array();
                 foreach ($categories as $category) {
                     $stamps[] = $category->stamp;
                 }
                 $contexts = array();
                 // Build the array of contexts we are going to look
                 $systemctx = context_system::instance();
                 $coursectx = context_course::instance($courseid);
                 $parentctxs = $coursectx->get_parent_context_ids();
                 foreach ($parentctxs as $parentctx) {
                     // Exclude system context
                     if ($parentctx == $systemctx->id) {
                         continue;
                     }
                     $contexts[] = $parentctx;
                 }
                 if (!empty($stamps) && !empty($contexts)) {
                     // Prepare the query
                     list($stamp_sql, $stamp_params) = $DB->get_in_or_equal($stamps);
                     list($context_sql, $context_params) = $DB->get_in_or_equal($contexts);
                     $sql = "SELECT DISTINCT contextid
                               FROM {question_categories}
                              WHERE stamp $stamp_sql
                                AND contextid $context_sql";
                     $params = array_merge($stamp_params, $context_params);
                     $matchingcontexts = $DB->get_records_sql($sql, $params);
                     // Only if ONE and ONLY ONE context is found, use it as valid target
                     if (count($matchingcontexts) == 1) {
                         $targetcontext = context::instance_by_id(reset($matchingcontexts)->contextid);
                     }
                 }
                 break;

             // For course is easy, the best context is the course context
             case CONTEXT_COURSE:
                 $targetcontext = context_course::instance($courseid);
                 break;

             // For module is easy, there is not best context, as far as the
             // activity hasn't been created yet. So we return context course
             // for them, so permission checks and friends will work. Note this
             // case is handled by {@link prechek_precheck_qbanks_by_level}
             // in an special way
             case CONTEXT_MODULE:
                 $targetcontext = context_course::instance($courseid);
                 break;
        }
        return $targetcontext;
    }