Displays one grading instance

@param gradingform_guide_instance $instance
@param int $idx unique number of instance on page
@param bool $cangrade whether current user has capability to grade in this context
964763
public function display_instance(gradingform_guide_instance $instance, $idx, $cangrade) {
        $criteria = $instance->get_controller()->get_definition()->guide_criteria;
        $options = $instance->get_controller()->get_options();
        $values = $instance->get_guide_filling();
        if ($cangrade) {
            $mode = gradingform_guide_controller::DISPLAY_REVIEW;
        } else {
            $mode = gradingform_guide_controller::DISPLAY_VIEW;
        }

        $output = $this->box($instance->get_controller()->get_formatted_description(), 'gradingform_guide-description').
                  $this->display_guide($criteria, array(), $options, $mode, 'guide'.$idx, $values);
        return $output;
    }
458321
public function restore_role_assignment($instance, $roleid, $userid, $contextid) {
        role_assign($roleid, $userid, $contextid, 'enrol_'.$instance->enrol, $instance->id);
    }
469632
public function save_quickgrading_changes($userid, $grade) {
        global $DB;
        $feedbackcomment = $this->get_feedback_comments($grade->id);
        $quickgradecomments = optional_param('quickgrade_comments_' . $userid, null, PARAM_RAW);
        if (!$quickgradecomments && $quickgradecomments !== '') {
            return true;
        }
        if ($feedbackcomment) {
            $feedbackcomment->commenttext = $quickgradecomments;
            return $DB->update_record('assignfeedback_comments', $feedbackcomment);
        } else {
            $feedbackcomment = new stdClass();
            $feedbackcomment->commenttext = $quickgradecomments;
            $feedbackcomment->commentformat = FORMAT_HTML;
            $feedbackcomment->grade = $grade->id;
            $feedbackcomment->assignment = $this->assignment->get_instance()->id;
            return $DB->insert_record('assignfeedback_comments', $feedbackcomment) > 0;
        }
    }
1005890
public function newInstance($selfedit = "false", $instanceName=null, $instanceClass=null) {
        //$componentsList = Moufspector::getComponentsList();
        $this->selfedit = $selfedit;
        $componentsList = MoufReflectionProxy::getComponentsList($selfedit=="true");
        sort($componentsList);

        $template = $this->template;
        $template->addContentFunction(array($this, "displayNewInstanceScreen"), $componentsList, $selfedit, $instanceName, $instanceClass);
        //$template->addContentFile(dirname(__FILE__)."/../views/displayNewInstance.php", $this);
        $template->toHtml();
    }
762128
public function delete_instance() {
        global $DB;
        $grades = $DB->get_records('assign_grades', array('assignment'=>$this->assignment->get_instance()->id), '', 'id');
        if ($grades) {
            list($gradeids, $params) = $DB->get_in_or_equal(array_keys($grades), SQL_PARAMS_NAMED);
            $DB->delete_records_select('assignfeedback_editpdf_annot', 'gradeid ' . $gradeids, $params);
            $DB->delete_records_select('assignfeedback_editpdf_cmnt', 'gradeid ' . $gradeids, $params);
        }
        return true;
    }
640007
public function get_gradinginstance() {
        if (is_array($this->gradingattributes) && array_key_exists('gradinginstance', $this->gradingattributes)) {
            return $this->gradingattributes['gradinginstance'];
        } else {
            return null;
        }
    }
1064073
public static function delete_feedback_document($assignment, $userid, $attemptnumber) {

        $assignment = self::get_assignment_from_param($assignment);

        if (!$assignment->can_view_submission($userid)) {
            print_error('nopermission');
        }
        if (!$assignment->can_grade()) {
            print_error('nopermission');
        }

        $grade = $assignment->get_user_grade($userid, true, $attemptnumber);

        $contextid = $assignment->get_context()->id;
        $component = 'assignfeedback_editpdf';
        $filearea = self::FINAL_PDF_FILEAREA;
        $itemid = $grade->id;

        $fs = get_file_storage();
        return $fs->delete_area_files($contextid, $component, $filearea, $itemid);
    }
675249
public function list_participants($currentgroup, $idsonly, $tablesort = false) {
        global $DB, $USER;

        // Get the last known sort order for the grading table.

        if (empty($currentgroup)) {
            $currentgroup = 0;
        }

        $key = $this->context->id . '-' . $currentgroup . '-' . $this->show_only_active_users();
        if (!isset($this->participants[$key])) {
            list($esql, $params) = get_enrolled_sql($this->context, 'mod/assign:submit', $currentgroup,
                    $this->show_only_active_users());

            $fields = 'u.*';
            $orderby = 'u.lastname, u.firstname, u.id';

            $additionaljoins = '';
            $additionalfilters = '';
            $instance = $this->get_instance();
            if (!empty($instance->blindmarking)) {
                $additionaljoins .= " LEFT JOIN {assign_user_mapping} um
                                  ON u.id = um.userid
                                 AND um.assignment = :assignmentid1
                           LEFT JOIN {assign_submission} s
                                  ON u.id = s.userid
                                 AND s.assignment = :assignmentid2
                                 AND s.latest = 1
                        ";
                $params['assignmentid1'] = (int) $instance->id;
                $params['assignmentid2'] = (int) $instance->id;
                $fields .= ', um.id as recordid ';

                // Sort by submission time first, then by um.id to sort reliably by the blind marking id.
                // Note, different DBs have different ordering of NULL values.
                // Therefore we coalesce the current time into the timecreated field, and the max possible integer into
                // the ID field.
                if (empty($tablesort)) {
                    $orderby = "COALESCE(s.timecreated, " . time() . ") ASC, COALESCE(s.id, " . PHP_INT_MAX . ") ASC, um.id ASC";
                }
            }

            if ($instance->markingworkflow &&
                    $instance->markingallocation &&
                    !has_capability('mod/assign:manageallocations', $this->get_context()) &&
                    has_capability('mod/assign:grade', $this->get_context())) {

                $additionaljoins .= ' LEFT JOIN {assign_user_flags} uf
                                     ON u.id = uf.userid
                                     AND uf.assignment = :assignmentid3';

                $params['assignmentid3'] = (int) $instance->id;

                $additionalfilters .= ' AND uf.allocatedmarker = :markerid';
                $params['markerid'] = $USER->id;
            }

            $sql = "SELECT $fields
                      FROM {user} u
                      JOIN ($esql) je ON je.id = u.id
                           $additionaljoins
                     WHERE u.deleted = 0
                           $additionalfilters
                  ORDER BY $orderby";

            $users = $DB->get_records_sql($sql, $params);

            $cm = $this->get_course_module();
            $info = new \core_availability\info_module($cm);
            $users = $info->filter_user_list($users);

            $this->participants[$key] = $users;
        }

        if ($tablesort) {
            // Resort the user list according to the grading table sort and filter settings.
            $sortedfiltereduserids = $this->get_grading_userid_list(true, '');
            $sortedfilteredusers = [];
            foreach ($sortedfiltereduserids as $nextid) {
                $nextid = intval($nextid);
                if (isset($this->participants[$key][$nextid])) {
                    $sortedfilteredusers[$nextid] = $this->participants[$key][$nextid];
                }
            }
            $this->participants[$key] = $sortedfilteredusers;
        }

        if ($idsonly) {
            $idslist = array();
            foreach ($this->participants[$key] as $id => $user) {
                $idslist[$id] = new stdClass();
                $idslist[$id]->id = $id;
            }
            return $idslist;
        }
        return $this->participants[$key];
    }
417575
public function unenrol_user(stdClass $instance, $userid) {
        global $DB;

        // Get the tool associated with this instance. Note - it may not exist if we have deleted
        // the tool. This is fine because we have already cleaned the 'enrol_lti_users' table.
        if ($tool = $DB->get_record('enrol_lti_tools', array('enrolid' => $instance->id), 'id')) {
            // Need to remove the user from the users table.
            $DB->delete_records('enrol_lti_users', array('userid' => $userid, 'toolid' => $tool->id));
        }

        parent::unenrol_user($instance, $userid);
    }
485771
public function unenrol_user(stdClass $instance, $userid) {
        global $CFG, $USER, $DB;
        require_once("$CFG->dirroot/group/lib.php");

        $name = $this->get_name();
        $courseid = $instance->courseid;

        if ($instance->enrol !== $name) {
            throw new coding_exception('invalid enrol instance!');
        }
        $context = context_course::instance($instance->courseid, MUST_EXIST);

        if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
            // weird, user not enrolled
            return;
        }

        // Remove all users groups linked to this enrolment instance.
        if ($gms = $DB->get_records('groups_members', array('userid'=>$userid, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id))) {
            foreach ($gms as $gm) {
                groups_remove_member($gm->groupid, $gm->userid);
            }
        }

        role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id));
        $DB->delete_records('user_enrolments', array('id'=>$ue->id));

        // add extra info and trigger event
        $ue->courseid  = $courseid;
        $ue->enrol     = $name;

        $sql = "SELECT 'x'
                  FROM {user_enrolments} ue
                  JOIN {enrol} e ON (e.id = ue.enrolid)
                 WHERE ue.userid = :userid AND e.courseid = :courseid";
        if ($DB->record_exists_sql($sql, array('userid'=>$userid, 'courseid'=>$courseid))) {
            $ue->lastenrol = false;

        } else {
            // the big cleanup IS necessary!
            require_once("$CFG->libdir/gradelib.php");

            // remove all remaining roles
            role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id), true, false);

            //clean up ALL invisible user data from course if this is the last enrolment - groups, grades, etc.
            groups_delete_group_members($courseid, $userid);

            grade_user_unenrol($courseid, $userid);

            $DB->delete_records('user_lastaccess', array('userid'=>$userid, 'courseid'=>$courseid));

            $ue->lastenrol = true; // means user not enrolled any more
        }
        // Trigger event.
        $event = \core\event\user_enrolment_deleted::create(
                array(
                    'courseid' => $courseid,
                    'context' => $context,
                    'relateduserid' => $ue->userid,
                    'objectid' => $ue->id,
                    'other' => array(
                        'userenrolment' => (array)$ue,
                        'enrol' => $name
                        )
                    )
                );
        $event->trigger();

        // User enrolments have changed, so mark user as dirty.
        mark_user_dirty($userid);

        // Check if courrse contacts cache needs to be cleared.
        core_course_category::user_enrolment_changed($courseid, $ue->userid, ENROL_USER_SUSPENDED);

        // reset current user enrolment caching
        if ($userid == $USER->id) {
            if (isset($USER->enrol['enrolled'][$courseid])) {
                unset($USER->enrol['enrolled'][$courseid]);
            }
            if (isset($USER->enrol['tempguest'][$courseid])) {
                unset($USER->enrol['tempguest'][$courseid]);
                remove_temp_course_roles($context);
            }
        }
    }
1039812
private static function grading_instance() {
        global $CFG;
        $instance = array();
        $instance['id']                = new external_value(PARAM_INT, 'instance id');
        $instance['raterid']           = new external_value(PARAM_INT, 'rater id');
        $instance['itemid']            = new external_value(PARAM_INT, 'item id');
        $instance['rawgrade']          = new external_value(PARAM_TEXT, 'raw grade', VALUE_OPTIONAL);
        $instance['status']            = new external_value(PARAM_INT, 'status');
        $instance['feedback']          = new external_value(PARAM_RAW, 'feedback', VALUE_OPTIONAL);
        $instance['feedbackformat']    = new external_format_value('feedback', VALUE_OPTIONAL);
        $instance['timemodified']      = new external_value(PARAM_INT, 'modified time');
        foreach (self::get_grading_methods() as $method) {
            require_once($CFG->dirroot.'/grade/grading/form/'.$method.'/lib.php');
            $details  = call_user_func('gradingform_'.$method.'_controller::get_external_instance_filling_details');
            if ($details != null) {
                $items = array();
                foreach ($details as $key => $value) {
                    $details[$key]->required = VALUE_OPTIONAL;
                    $items[$key] = $value;
                }
                $instance[$method] = new external_single_structure($items, 'items', VALUE_OPTIONAL);
            }
        }
        return new external_single_structure($instance);
    }
636691
public function edit_instance_form($instance, MoodleQuickForm $mform, $context) {

        $mform->addElement('text', 'name', get_string('custominstancename', 'enrol'));
        $mform->setType('name', PARAM_TEXT);

        $options = $this->get_status_options();
        $mform->addElement('select', 'status', get_string('status', 'enrol_paypal'), $options);
        $mform->setDefault('status', $this->get_config('status'));

        $mform->addElement('text', 'cost', get_string('cost', 'enrol_paypal'), array('size' => 4));
        $mform->setType('cost', PARAM_RAW);
        $mform->setDefault('cost', format_float($this->get_config('cost'), 2, true));

        $paypalcurrencies = $this->get_currencies();
        $mform->addElement('select', 'currency', get_string('currency', 'enrol_paypal'), $paypalcurrencies);
        $mform->setDefault('currency', $this->get_config('currency'));

        $roles = $this->get_roleid_options($instance, $context);
        $mform->addElement('select', 'roleid', get_string('assignrole', 'enrol_paypal'), $roles);
        $mform->setDefault('roleid', $this->get_config('roleid'));

        $options = array('optional' => true, 'defaultunit' => 86400);
        $mform->addElement('duration', 'enrolperiod', get_string('enrolperiod', 'enrol_paypal'), $options);
        $mform->setDefault('enrolperiod', $this->get_config('enrolperiod'));
        $mform->addHelpButton('enrolperiod', 'enrolperiod', 'enrol_paypal');

        $options = array('optional' => true);
        $mform->addElement('date_time_selector', 'enrolstartdate', get_string('enrolstartdate', 'enrol_paypal'), $options);
        $mform->setDefault('enrolstartdate', 0);
        $mform->addHelpButton('enrolstartdate', 'enrolstartdate', 'enrol_paypal');

        $options = array('optional' => true);
        $mform->addElement('date_time_selector', 'enrolenddate', get_string('enrolenddate', 'enrol_paypal'), $options);
        $mform->setDefault('enrolenddate', 0);
        $mform->addHelpButton('enrolenddate', 'enrolenddate', 'enrol_paypal');

        if (enrol_accessing_via_instance($instance)) {
            $warningtext = get_string('instanceeditselfwarningtext', 'core_enrol');
            $mform->addElement('static', 'selfwarn', get_string('instanceeditselfwarning', 'core_enrol'), $warningtext);
        }
    }
885120
public function format_grade($grade, $gradedisplayconst = null) {
        $displaytype = $this->displaytype;
        if (is_array($this->displaytype) && !is_null($gradedisplayconst)) {
            $displaytype = $gradedisplayconst;
        }

        $gradeitem = $this->grade_items[$grade->itemid];

        // We are going to store the min and max so that we can "reset" the grade_item for later.
        $grademax = $gradeitem->grademax;
        $grademin = $gradeitem->grademin;

        // Updating grade_item with this grade_grades min and max.
        $gradeitem->grademax = $grade->get_grade_max();
        $gradeitem->grademin = $grade->get_grade_min();

        $formattedgrade = grade_format_gradevalue($grade->finalgrade, $gradeitem, false, $displaytype, $this->decimalpoints);

        // Resetting the grade item in case it is reused.
        $gradeitem->grademax = $grademax;
        $gradeitem->grademin = $grademin;

        return $formattedgrade;
    }
583651
public static function submit_for_grading($assignmentid, $acceptsubmissionstatement) {
        global $CFG, $USER;

        $params = self::validate_parameters(self::submit_for_grading_parameters(),
                                            array('assignmentid' => $assignmentid,
                                                  'acceptsubmissionstatement' => $acceptsubmissionstatement));

        list($assignment, $course, $cm, $context) = self::validate_assign($params['assignmentid']);

        $warnings = array();
        $data = new stdClass();
        $data->submissionstatement = $params['acceptsubmissionstatement'];
        $notices = array();

        if (!$assignment->submit_for_grading($data, $notices)) {
            $detail = 'User id: ' . $USER->id . ', Assignment id: ' . $params['assignmentid'] . ' Notices:' . implode(', ', $notices);
            $warnings[] = self::generate_warning($params['assignmentid'],
                                                 'couldnotsubmitforgrading',
                                                 $detail);
        }

        return $warnings;
    }
728470
protected function process_grading_instance($data) {
        global $DB;

        $data = (object)$data;

        // new form definition id
        $newformid = $this->get_new_parentid('grading_definition');

        // get the name of the area we are restoring to
        $sql = "SELECT ga.areaname
                  FROM {grading_definitions} gd
                  JOIN {grading_areas} ga ON gd.areaid = ga.id
                 WHERE gd.id = ?";
        $areaname = $DB->get_field_sql($sql, array($newformid), MUST_EXIST);

        // get the mapped itemid - the activity module is expected to define the mappings
        // for each gradable area
        $newitemid = $this->get_mappingid(restore_gradingform_plugin::itemid_mapping($areaname), $data->itemid);

        $oldid = $data->id;
        $data->definitionid = $newformid;
        $data->raterid = $this->get_mappingid('user', $data->raterid);
        $data->itemid = $newitemid;

        $newid = $DB->insert_record('grading_instances', $data);
        $this->set_mapping('grading_instance', $oldid, $newid);
    }
1136447
private function selectChildSettingsAmongTwo(
        SettingsInterface $instance1,
        SettingsInterface $instance2
    ): ?SettingsInterface {
        return is_subclass_of($instance1, get_class($instance2)) === true ?
            $instance1 : (is_subclass_of($instance2, get_class($instance1)) === true ? $instance2 : null);
    }
69605
public function can_delete_instance($instance) {
        $context = context_course::instance($instance->courseid);
        if (!has_capability('enrol/ldap:manage', $context)) {
            return false;
        }

        if (!enrol_is_enabled('ldap')) {
            return true;
        }

        if (!$this->get_config('ldap_host') or !$this->get_config('objectclass') or !$this->get_config('course_idnumber')) {
            return true;
        }

        // TODO: connect to external system and make sure no users are to be enrolled in this course
        return false;
    }