Html to add a button for adding a new rule.

@param int $courseid course id.

@return string html for the button.
185978
protected function render_add_button($courseid) {
        global $CFG;

        $button = \html_writer::tag('button', get_string('addrule', 'tool_monitor'), ['class' => 'btn btn-primary']);
        $addurl = new \moodle_url($CFG->wwwroot. '/admin/tool/monitor/edit.php', array('courseid' => $courseid));
        return \html_writer::link($addurl, $button);
    }
977470
protected function get_all_groups($courseid) {
        global $CFG;
        require_once($CFG->libdir . '/grouplib.php');

        if ($courseid != $this->allgroupscourseid) {
            $this->allgroups = groups_get_all_groups($courseid, 0, 0, 'g.id, g.name');
            $this->allgroupscourseid = $courseid;
        }
        return $this->allgroups;
    }
1221372
public static function preload_course($courseid) {
        // Users can call this multiple times without doing any harm
        if (isset(context::$cache_preloaded[$courseid])) {
            return;
        }
        $coursecontext = context_course::instance($courseid);
        $coursecontext->get_child_contexts();

        context::$cache_preloaded[$courseid] = true;
    }
871979
protected Button newButton(final String id)
	{
		return new Button(id)
		{
			/** The serialVersionUID. */
			private static final long serialVersionUID = 1L;

			/**
			 * {@inheritDoc}
			 */
			@Override
			public void onSubmit()
			{
				onDeregistration(null);
			}
		};
	}
79194
public function get_course($courseid) {
        global $DB;
        if (!array_key_exists($courseid, $this->courses)) {
            $ctxquery = context_helper::get_preload_record_columns_sql('ctx');
            $sql = "SELECT c.id,c.visible,c.fullname,c.shortname,c.cacherev, $ctxquery
            FROM {course} c JOIN {context} ctx ON ctx.contextlevel = ? AND ctx.instanceid=c.id
            WHERE c.id = ?";
            $params = array(CONTEXT_COURSE, $courseid);
            $this->courses[$courseid] = $DB->get_record_sql($sql, $params);
            context_helper::preload_from_record($this->courses[$courseid]);
        }
        return $this->courses[$courseid];
    }
405398
protected static function get_course_concepts($courseid) {
        global $DB;

        if (empty($courseid)) {
            return array(array(), array());
        }

        $courseid = (int)$courseid;

        // Get info on any glossaries in this course.
        $modinfo = get_fast_modinfo($courseid);
        $cminfos = $modinfo->get_instances_of('glossary');
        if (!$cminfos) {
            // No glossaries in this course, so don't do any work.
            return array(array(), array());
        }

        $cache = \cache::make('mod_glossary', 'concepts');
        $data = $cache->get($courseid);
        if (is_array($data)) {
            list($glossaries, $allconcepts) = $data;

        } else {
            // Find all course glossaries.
            $sql = "SELECT g.id, g.name
                      FROM {glossary} g
                      JOIN {course_modules} cm ON (cm.instance = g.id)
                      JOIN {modules} m ON (m.name = 'glossary' AND m.id = cm.module)
                     WHERE g.usedynalink = 1 AND g.course = :course AND cm.visible = 1 AND m.visible = 1
                  ORDER BY g.globalglossary, g.id";
            $glossaries = $DB->get_records_sql_menu($sql, array('course' => $courseid));
            if (!$glossaries) {
                $data = array(array(), array());
                $cache->set($courseid, $data);
                return $data;
            }
            foreach ($glossaries as $id => $name) {
                $name = str_replace(':', '-', $name);
                $glossaries[$id] = replace_ampersands_not_followed_by_entity(strip_tags($name));
            }

            $allconcepts = self::fetch_concepts(array_keys($glossaries));
            foreach ($glossaries as $gid => $unused) {
                if (!isset($allconcepts[$gid])) {
                    unset($glossaries[$gid]);
                }
            }
            if (!$glossaries) {
                // This means there are no interesting concepts in the existing glossaries.
                $data = array(array(), array());
                $cache->set($courseid, $data);
                return $data;
            }
            $cache->set($courseid, array($glossaries, $allconcepts));
        }

        $concepts = $allconcepts;

        // Verify access control to glossary instances.
        foreach ($concepts as $modid => $unused) {
            if (!isset($cminfos[$modid])) {
                // This should not happen.
                unset($concepts[$modid]);
                unset($glossaries[$modid]);
                continue;
            }
            if (!$cminfos[$modid]->uservisible) {
                unset($concepts[$modid]);
                unset($glossaries[$modid]);
                continue;
            }
        }

        return array($glossaries, $concepts);
    }
1270413
public static function can_manage_course($courseid) {
        $context = context_course::instance($courseid);

        $capabilities = array('moodle/competency:coursecompetencyconfigure');

        return has_any_capability($capabilities, $context);
    }
330532
public static function get_course_contents($courseid, $options = array()) {
        global $CFG, $DB;
        require_once($CFG->dirroot . "/course/lib.php");
        require_once($CFG->libdir . '/completionlib.php');

        //validate parameter
        $params = self::validate_parameters(self::get_course_contents_parameters(),
                        array('courseid' => $courseid, 'options' => $options));

        $filters = array();
        if (!empty($params['options'])) {

            foreach ($params['options'] as $option) {
                $name = trim($option['name']);
                // Avoid duplicated options.
                if (!isset($filters[$name])) {
                    switch ($name) {
                        case 'excludemodules':
                        case 'excludecontents':
                        case 'includestealthmodules':
                            $value = clean_param($option['value'], PARAM_BOOL);
                            $filters[$name] = $value;
                            break;
                        case 'sectionid':
                        case 'sectionnumber':
                        case 'cmid':
                        case 'modid':
                            $value = clean_param($option['value'], PARAM_INT);
                            if (is_numeric($value)) {
                                $filters[$name] = $value;
                            } else {
                                throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
                            }
                            break;
                        case 'modname':
                            $value = clean_param($option['value'], PARAM_PLUGIN);
                            if ($value) {
                                $filters[$name] = $value;
                            } else {
                                throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
                            }
                            break;
                        default:
                            throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
                    }
                }
            }
        }

        //retrieve the course
        $course = $DB->get_record('course', array('id' => $params['courseid']), '*', MUST_EXIST);

        if ($course->id != SITEID) {
            // Check course format exist.
            if (!file_exists($CFG->dirroot . '/course/format/' . $course->format . '/lib.php')) {
                throw new moodle_exception('cannotgetcoursecontents', 'webservice', '', null,
                                            get_string('courseformatnotfound', 'error', $course->format));
            } else {
                require_once($CFG->dirroot . '/course/format/' . $course->format . '/lib.php');
            }
        }

        // now security checks
        $context = context_course::instance($course->id, IGNORE_MISSING);
        try {
            self::validate_context($context);
        } catch (Exception $e) {
            $exceptionparam = new stdClass();
            $exceptionparam->message = $e->getMessage();
            $exceptionparam->courseid = $course->id;
            throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
        }

        $canupdatecourse = has_capability('moodle/course:update', $context);

        //create return value
        $coursecontents = array();

        if ($canupdatecourse or $course->visible
                or has_capability('moodle/course:viewhiddencourses', $context)) {

            //retrieve sections
            $modinfo = get_fast_modinfo($course);
            $sections = $modinfo->get_section_info_all();
            $coursenumsections = course_get_format($course)->get_last_section_number();
            $stealthmodules = array();   // Array to keep all the modules available but not visible in a course section/topic.

            $completioninfo = new completion_info($course);

            //for each sections (first displayed to last displayed)
            $modinfosections = $modinfo->get_sections();
            foreach ($sections as $key => $section) {

                // This becomes true when we are filtering and we found the value to filter with.
                $sectionfound = false;

                // Filter by section id.
                if (!empty($filters['sectionid'])) {
                    if ($section->id != $filters['sectionid']) {
                        continue;
                    } else {
                        $sectionfound = true;
                    }
                }

                // Filter by section number. Note that 0 is a valid section number.
                if (isset($filters['sectionnumber'])) {
                    if ($key != $filters['sectionnumber']) {
                        continue;
                    } else {
                        $sectionfound = true;
                    }
                }

                // reset $sectioncontents
                $sectionvalues = array();
                $sectionvalues['id'] = $section->id;
                $sectionvalues['name'] = get_section_name($course, $section);
                $sectionvalues['visible'] = $section->visible;

                $options = (object) array('noclean' => true);
                list($sectionvalues['summary'], $sectionvalues['summaryformat']) =
                        external_format_text($section->summary, $section->summaryformat,
                                $context->id, 'course', 'section', $section->id, $options);
                $sectionvalues['section'] = $section->section;
                $sectionvalues['hiddenbynumsections'] = $section->section > $coursenumsections ? 1 : 0;
                $sectionvalues['uservisible'] = $section->uservisible;
                if (!empty($section->availableinfo)) {
                    $sectionvalues['availabilityinfo'] = \core_availability\info::format_info($section->availableinfo, $course);
                }

                $sectioncontents = array();

                // For each module of the section.
                if (empty($filters['excludemodules']) and !empty($modinfosections[$section->section])) {
                    foreach ($modinfosections[$section->section] as $cmid) {
                        $cm = $modinfo->cms[$cmid];

                        // Stop here if the module is not visible to the user on the course main page:
                        // The user can't access the module and the user can't view the module on the course page.
                        if (!$cm->uservisible && !$cm->is_visible_on_course_page()) {
                            continue;
                        }

                        // This becomes true when we are filtering and we found the value to filter with.
                        $modfound = false;

                        // Filter by cmid.
                        if (!empty($filters['cmid'])) {
                            if ($cmid != $filters['cmid']) {
                                continue;
                            } else {
                                $modfound = true;
                            }
                        }

                        // Filter by module name and id.
                        if (!empty($filters['modname'])) {
                            if ($cm->modname != $filters['modname']) {
                                continue;
                            } else if (!empty($filters['modid'])) {
                                if ($cm->instance != $filters['modid']) {
                                    continue;
                                } else {
                                    // Note that if we are only filtering by modname we don't break the loop.
                                    $modfound = true;
                                }
                            }
                        }

                        $module = array();

                        $modcontext = context_module::instance($cm->id);

                        //common info (for people being able to see the module or availability dates)
                        $module['id'] = $cm->id;
                        $module['name'] = external_format_string($cm->name, $modcontext->id);
                        $module['instance'] = $cm->instance;
                        $module['modname'] = $cm->modname;
                        $module['modplural'] = $cm->modplural;
                        $module['modicon'] = $cm->get_icon_url()->out(false);
                        $module['indent'] = $cm->indent;
                        $module['onclick'] = $cm->onclick;
                        $module['afterlink'] = $cm->afterlink;
                        $module['customdata'] = json_encode($cm->customdata);
                        $module['completion'] = $cm->completion;

                        // Check module completion.
                        $completion = $completioninfo->is_enabled($cm);
                        if ($completion != COMPLETION_DISABLED) {
                            $completiondata = $completioninfo->get_data($cm, true);
                            $module['completiondata'] = array(
                                'state'         => $completiondata->completionstate,
                                'timecompleted' => $completiondata->timemodified,
                                'overrideby'    => $completiondata->overrideby,
                                'valueused'     => core_availability\info::completion_value_used($course, $cm->id)
                            );
                        }

                        if (!empty($cm->showdescription) or $cm->modname == 'label') {
                            // We want to use the external format. However from reading get_formatted_content(), $cm->content format is always FORMAT_HTML.
                            $options = array('noclean' => true);
                            list($module['description'], $descriptionformat) = external_format_text($cm->content,
                                FORMAT_HTML, $modcontext->id, $cm->modname, 'intro', $cm->id, $options);
                        }

                        //url of the module
                        $url = $cm->url;
                        if ($url) { //labels don't have url
                            $module['url'] = $url->out(false);
                        }

                        $canviewhidden = has_capability('moodle/course:viewhiddenactivities',
                                            context_module::instance($cm->id));
                        //user that can view hidden module should know about the visibility
                        $module['visible'] = $cm->visible;
                        $module['visibleoncoursepage'] = $cm->visibleoncoursepage;
                        $module['uservisible'] = $cm->uservisible;
                        if (!empty($cm->availableinfo)) {
                            $module['availabilityinfo'] = \core_availability\info::format_info($cm->availableinfo, $course);
                        }

                        // Availability date (also send to user who can see hidden module).
                        if ($CFG->enableavailability && ($canviewhidden || $canupdatecourse)) {
                            $module['availability'] = $cm->availability;
                        }

                        // Return contents only if the user can access to the module.
                        if ($cm->uservisible) {
                            $baseurl = 'webservice/pluginfile.php';

                            // Call $modulename_export_contents (each module callback take care about checking the capabilities).
                            require_once($CFG->dirroot . '/mod/' . $cm->modname . '/lib.php');
                            $getcontentfunction = $cm->modname.'_export_contents';
                            if (function_exists($getcontentfunction)) {
                                $contents = $getcontentfunction($cm, $baseurl);
                                $module['contentsinfo'] = array(
                                    'filescount' => count($contents),
                                    'filessize' => 0,
                                    'lastmodified' => 0,
                                    'mimetypes' => array(),
                                );
                                foreach ($contents as $content) {
                                    // Check repository file (only main file).
                                    if (!isset($module['contentsinfo']['repositorytype'])) {
                                        $module['contentsinfo']['repositorytype'] =
                                            isset($content['repositorytype']) ? $content['repositorytype'] : '';
                                    }
                                    if (isset($content['filesize'])) {
                                        $module['contentsinfo']['filessize'] += $content['filesize'];
                                    }
                                    if (isset($content['timemodified']) &&
                                            ($content['timemodified'] > $module['contentsinfo']['lastmodified'])) {

                                        $module['contentsinfo']['lastmodified'] = $content['timemodified'];
                                    }
                                    if (isset($content['mimetype'])) {
                                        $module['contentsinfo']['mimetypes'][$content['mimetype']] = $content['mimetype'];
                                    }
                                }

                                if (empty($filters['excludecontents']) and !empty($contents)) {
                                    $module['contents'] = $contents;
                                } else {
                                    $module['contents'] = array();
                                }
                            }
                        }

                        // Assign result to $sectioncontents, there is an exception,
                        // stealth activities in non-visible sections for students go to a special section.
                        if (!empty($filters['includestealthmodules']) && !$section->uservisible && $cm->is_stealth()) {
                            $stealthmodules[] = $module;
                        } else {
                            $sectioncontents[] = $module;
                        }

                        // If we just did a filtering, break the loop.
                        if ($modfound) {
                            break;
                        }

                    }
                }
                $sectionvalues['modules'] = $sectioncontents;

                // assign result to $coursecontents
                $coursecontents[$key] = $sectionvalues;

                // Break the loop if we are filtering.
                if ($sectionfound) {
                    break;
                }
            }

            // Now that we have iterated over all the sections and activities, check the visibility.
            // We didn't this before to be able to retrieve stealth activities.
            foreach ($coursecontents as $sectionnumber => $sectioncontents) {
                $section = $sections[$sectionnumber];
                // Show the section if the user is permitted to access it, OR if it's not available
                // but there is some available info text which explains the reason & should display.
                $showsection = $section->uservisible ||
                    ($section->visible && !$section->available &&
                    !empty($section->availableinfo));

                if (!$showsection) {
                    unset($coursecontents[$sectionnumber]);
                    continue;
                }

                // Remove modules information if the section is not visible for the user.
                if (!$section->uservisible) {
                    $coursecontents[$sectionnumber]['modules'] = array();
                }
            }

            // Include stealth modules in special section (without any info).
            if (!empty($stealthmodules)) {
                $coursecontents[] = array(
                    'id' => -1,
                    'name' => '',
                    'summary' => '',
                    'summaryformat' => FORMAT_MOODLE,
                    'modules' => $stealthmodules
                );
            }

        }
        return $coursecontents;
    }
862512
public static function get_course_enrolment_methods($courseid) {
        global $DB;

        $params = self::validate_parameters(self::get_course_enrolment_methods_parameters(), array('courseid' => $courseid));
        self::validate_context(context_system::instance());

        $course = $DB->get_record('course', array('id' => $params['courseid']), '*', MUST_EXIST);
        if (!core_course_category::can_view_course_info($course) && !can_access_course($course)) {
            throw new moodle_exception('coursehidden');
        }

        $result = array();
        $enrolinstances = enrol_get_instances($params['courseid'], true);
        foreach ($enrolinstances as $enrolinstance) {
            if ($enrolplugin = enrol_get_plugin($enrolinstance->enrol)) {
                if ($instanceinfo = $enrolplugin->get_enrol_info($enrolinstance)) {
                    $result[] = (array) $instanceinfo;
                }
            }
        }
        return $result;
    }
348892
public static function get_competency($courseid, $competencyid) {
        global $DB;

        $sql = 'SELECT comp.*
                  FROM {' . competency::TABLE . '} comp
                  JOIN {' . self::TABLE . '} crscomp
                    ON crscomp.competencyid = comp.id
                 WHERE crscomp.courseid = ? AND crscomp.competencyid = ?';
        $params = array($courseid, $competencyid);

        $result = $DB->get_record_sql($sql, $params);
        if (!$result) {
            throw new coding_exception('The competency does not belong to this course: ' . $competencyid . ', ' . $courseid);
        }

        return new competency(0, $result);
    }
1270136
public static function get_last_completed($feedbackid, $courseid = 0) {
        global $PAGE;

        $params = array('feedbackid' => $feedbackid, 'courseid' => $courseid);
        $params = self::validate_parameters(self::get_last_completed_parameters(), $params);
        $warnings = array();

        list($feedback, $course, $cm, $context, $completioncourse) = self::validate_feedback($params['feedbackid'],
            $params['courseid']);
        $feedbackcompletion = new mod_feedback_completion($feedback, $cm, $completioncourse->id);

        if ($feedbackcompletion->is_anonymous()) {
             throw new moodle_exception('anonymous', 'feedback');
        }
        if ($completed = $feedbackcompletion->find_last_completed()) {
            $exporter = new feedback_completed_exporter($completed);
            return array(
                'completed' => $exporter->export($PAGE->get_renderer('core')),
                'warnings' => $warnings,
            );
        }
        throw new moodle_exception('not_completed_yet', 'feedback');
    }
629480
public static function get_course_groupings($courseid) {
        global $CFG;
        require_once("$CFG->dirroot/group/lib.php");
        require_once("$CFG->libdir/filelib.php");

        $params = self::validate_parameters(self::get_course_groupings_parameters(), array('courseid'=>$courseid));

        // Now security checks.
        $context = context_course::instance($params['courseid']);

        try {
            self::validate_context($context);
        } catch (Exception $e) {
                $exceptionparam = new stdClass();
                $exceptionparam->message = $e->getMessage();
                $exceptionparam->courseid = $params['courseid'];
                throw new moodle_exception('errorcoursecontextnotvalid' , 'webservice', '', $exceptionparam);
        }
        require_capability('moodle/course:managegroups', $context);

        $gs = groups_get_all_groupings($params['courseid']);

        $groupings = array();
        foreach ($gs as $grouping) {
            list($grouping->description, $grouping->descriptionformat) =
                external_format_text($grouping->description, $grouping->descriptionformat,
                        $context->id, 'grouping', 'description', $grouping->id);
            $groupings[] = (array)$grouping;
        }

        return $groupings;
    }
859673
public static function get_lessons_by_courses($courseids = array()) {
        global $PAGE;

        $warnings = array();
        $returnedlessons = array();

        $params = array(
            'courseids' => $courseids,
        );
        $params = self::validate_parameters(self::get_lessons_by_courses_parameters(), $params);

        $mycourses = array();
        if (empty($params['courseids'])) {
            $mycourses = enrol_get_my_courses();
            $params['courseids'] = array_keys($mycourses);
        }

        // Ensure there are courseids to loop through.
        if (!empty($params['courseids'])) {

            list($courses, $warnings) = external_util::validate_courses($params['courseids'], $mycourses);

            // Get the lessons in this course, this function checks users visibility permissions.
            // We can avoid then additional validate_context calls.
            $lessons = get_all_instances_in_courses("lesson", $courses);
            foreach ($lessons as $lessonrecord) {
                $context = context_module::instance($lessonrecord->coursemodule);

                // Remove fields added by get_all_instances_in_courses.
                unset($lessonrecord->coursemodule, $lessonrecord->section, $lessonrecord->visible, $lessonrecord->groupmode,
                    $lessonrecord->groupingid);

                $lessonrecord = self::get_lesson_summary_for_exporter($lessonrecord);

                $exporter = new lesson_summary_exporter($lessonrecord, array('context' => $context));
                $returnedlessons[] = $exporter->export($PAGE->get_renderer('core'));
            }
        }
        $result = array();
        $result['lessons'] = $returnedlessons;
        $result['warnings'] = $warnings;
        return $result;
    }
702557
public function print_user_summaries($courseid) {
        global $PAGE;
        $usersummaries = $this->get_user_summaries($courseid);
        $PAGE->requires->data_for_js('userSummaries', $usersummaries);
    }
174511
public static function get_items($feedbackid, $courseid = 0) {
        global $PAGE;

        $params = array('feedbackid' => $feedbackid, 'courseid' => $courseid);
        $params = self::validate_parameters(self::get_items_parameters(), $params);
        $warnings = array();

        list($feedback, $course, $cm, $context, $completioncourse) = self::validate_feedback($params['feedbackid'],
            $params['courseid']);

        $feedbackstructure = new mod_feedback_structure($feedback, $cm, $completioncourse->id);
        $returneditems = array();
        if ($items = $feedbackstructure->get_items()) {
            foreach ($items as $item) {
                $itemnumber = empty($item->itemnr) ? null : $item->itemnr;
                unset($item->itemnr);   // Added by the function, not part of the record.
                $exporter = new feedback_item_exporter($item, array('context' => $context, 'itemnumber' => $itemnumber));
                $returneditems[] = $exporter->export($PAGE->get_renderer('core'));
            }
        }

        $result = array(
            'items' => $returneditems,
            'warnings' => $warnings
        );
        return $result;
    }
617543
public static function read_course_competency_settings($courseid) {
        static::require_enabled();

        // First we do a permissions check.
        if (!course_competency_settings::can_read($courseid)) {
            $context = context_course::instance($courseid);
            throw new required_capability_exception($context, 'moodle/competency:coursecompetencyview', 'nopermissions', '');
        }

        return course_competency_settings::get_by_courseid($courseid);
    }
1166841
public static function load($lessonid) {
        global $DB;

        if (!$lesson = $DB->get_record('lesson', array('id' => $lessonid))) {
            print_error('invalidcoursemodule');
        }
        return new lesson($lesson);
    }