/**
  * Utility method to get the grade for a user.
  * @param $user
  * @param $assign
  * @param $course
  * @return testable_assign
  */
 private function get_user_assign_grade($user, $assign, $course)
 {
     $gradebookgrades = \grade_get_grades($course->id, 'mod', 'assign', $assign->get_instance()->id, $user->id);
     $gradebookitem = array_shift($gradebookgrades->items);
     $grade = $gradebookitem->grades[$user->id];
     return $grade->str_grade;
 }
示例#2
0
    function process_feedback($formdata=null) {
        global $CFG, $USER, $DB;
        require_once($CFG->libdir.'/gradelib.php');

        if (!$feedback = data_submitted() or !confirm_sesskey()) {      // No incoming data?
            return false;
        }

        ///For save and next, we need to know the userid to save, and the userid to go
        ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
        ///as the userid to store
        if ((int)$feedback->saveuserid !== -1){
            $feedback->userid = $feedback->saveuserid;
        }

        if (!empty($feedback->cancel)) {          // User hit cancel button
            return false;
        }

        $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $feedback->userid);

        // store outcomes if needed
        $this->process_outcomes($feedback->userid);

        $submission = $this->get_submission($feedback->userid, true);  // Get or make one

        if (!$grading_info->items[0]->grades[$feedback->userid]->locked and
            !$grading_info->items[0]->grades[$feedback->userid]->overridden) {

            $submission->grade      = $feedback->xgrade;
            $submission->submissioncomment    = $feedback->submissioncomment_editor['text'];
            $submission->teacher    = $USER->id;
            $mailinfo = get_user_preferences('assignment_mailinfo', 0);
            if (!$mailinfo) {
                $submission->mailed = 1;       // treat as already mailed
            } else {
                $submission->mailed = 0;       // Make sure mail goes out (again, even)
            }
            $submission->timemarked = time();

            unset($submission->data1);  // Don't need to update this.
            unset($submission->data2);  // Don't need to update this.

            if (empty($submission->timemodified)) {   // eg for offline assignments
                $submission->timemodified = time();
            }

            $DB->update_record('assignment_submissions', $submission);

            // trigger grade event
            $this->update_grade($submission);

            add_to_log($this->course->id, 'assignment', 'update grades',
                       'submissions.php?id='.$this->assignment->id.'&user='.$feedback->userid, $feedback->userid, $this->cm->id);
        }

        return $submission;

    }
 /** add info about this users attaches to the postsdata object
  * 
  * @global object $DB
  * @global record $USER
  * @param record $postsdata
  * @return boolean, true if succeded
  */
 public static function add_attaches_to_posts($courseid, &$postsdata)
 {
     global $DB, $USER;
     if (empty($postsdata->posts)) {
         return false;
     }
     $posts = $postsdata->posts;
     $params = array($USER->id);
     list($inpoststr, $inparams) = $DB->get_in_or_equal(array_keys($posts));
     $params = array_merge($params, $inparams);
     $params[] = $courseid;
     // ... fetch attaches an grade_items.
     $sql = "SELECT at.id as atid, at.postid, at.coursemoduleid, gi.*\n                FROM {format_socialwall_attaches} at\n                JOIN {course_modules} cm ON cm.id = at.coursemoduleid\n                JOIN {modules} m ON m.id = cm.module\n                LEFT JOIN\n                    (SELECT gg.id, gri.iteminstance, gri.itemmodule, gri.itemtype\n                     FROM {grade_items} gri\n                     JOIN {grade_grades} gg ON (gg.itemid = gri.id AND userid = ?)) as\n                     gi ON (gi.itemmodule = m.name AND gi.iteminstance = cm.instance)\n                WHERE postid {$inpoststr} AND cm.course = ?";
     if (!($attaches = $DB->get_records_sql($sql, $params))) {
         return false;
     }
     foreach ($attaches as $attachment) {
         if (!isset($postsdata->posts[$attachment->postid]->attaches)) {
             $postsdata->posts[$attachment->postid]->attaches = array();
             $postsdata->posts[$attachment->postid]->grades = array();
         }
         $postsdata->posts[$attachment->postid]->attaches[$attachment->atid] = $attachment;
         if (!empty($attachment->iteminstance)) {
             $gradedata = grade_get_grades($courseid, $attachment->itemtype, $attachment->itemmodule, $attachment->iteminstance, $USER->id);
             // Add author of grades, to retrieve complete user record later.
             if (!empty($gradedata->outcomes[0]->grades[$USER->id])) {
                 $usermodified = $gradedata->outcomes[0]->grades[$USER->id]->usermodified;
                 $postsdata->authors[$usermodified] = $usermodified;
                 $postsdata->posts[$attachment->postid]->grades[$attachment->coursemoduleid] = $gradedata->outcomes[0];
             }
             if (!empty($gradedata->items[0]->grades[$USER->id])) {
                 $usermodified = $gradedata->items[0]->grades[$USER->id]->usermodified;
                 $postsdata->authors[$usermodified] = $usermodified;
                 $postsdata->posts[$attachment->postid]->grades[$attachment->coursemoduleid] = $gradedata->items[0];
             }
         }
     }
     return true;
 }
 /**
  * overridden constructor keeps a reference to the assignment class that is displaying this table
  *
  * @param assign $assignment The assignment class
  * @param int $perpage how many per page
  * @param string $filter The current filter
  * @param int $rowoffset For showing a subsequent page of results
  * @param bool $quickgrading Is this table wrapped in a quickgrading form?
  * @param string $downloadfilename
  */
 public function __construct(assign $assignment, $perpage, $filter, $rowoffset, $quickgrading, $downloadfilename = null)
 {
     global $CFG, $PAGE, $DB, $USER;
     parent::__construct('mod_assign_grading');
     $this->is_persistent(true);
     $this->assignment = $assignment;
     // Check permissions up front.
     $this->hasgrantextension = has_capability('mod/assign:grantextension', $this->assignment->get_context());
     $this->hasgrade = $this->assignment->can_grade();
     // Check if we have the elevated view capablities to see the blind details.
     $this->hasviewblind = has_capability('mod/assign:viewblinddetails', $this->assignment->get_context());
     foreach ($assignment->get_feedback_plugins() as $plugin) {
         if ($plugin->is_visible() && $plugin->is_enabled()) {
             foreach ($plugin->get_grading_batch_operations() as $action => $description) {
                 if (empty($this->plugingradingbatchoperations)) {
                     $this->plugingradingbatchoperations[$plugin->get_type()] = array();
                 }
                 $this->plugingradingbatchoperations[$plugin->get_type()][$action] = $description;
             }
         }
     }
     $this->perpage = $perpage;
     $this->quickgrading = $quickgrading && $this->hasgrade;
     $this->output = $PAGE->get_renderer('mod_assign');
     $urlparams = array('action' => 'grading', 'id' => $assignment->get_course_module()->id);
     $url = new moodle_url($CFG->wwwroot . '/mod/assign/view.php', $urlparams);
     $this->define_baseurl($url);
     // Do some business - then set the sql.
     $currentgroup = groups_get_activity_group($assignment->get_course_module(), true);
     if ($rowoffset) {
         $this->rownum = $rowoffset - 1;
     }
     $users = array_keys($assignment->list_participants($currentgroup, true));
     if (count($users) == 0) {
         // Insert a record that will never match to the sql is still valid.
         $users[] = -1;
     }
     $params = array();
     $params['assignmentid1'] = (int) $this->assignment->get_instance()->id;
     $params['assignmentid2'] = (int) $this->assignment->get_instance()->id;
     $params['assignmentid3'] = (int) $this->assignment->get_instance()->id;
     $extrauserfields = get_extra_user_fields($this->assignment->get_context());
     $fields = user_picture::fields('u', $extrauserfields) . ', ';
     $fields .= 'u.id as userid, ';
     $fields .= 's.status as status, ';
     $fields .= 's.id as submissionid, ';
     $fields .= 's.timecreated as firstsubmission, ';
     $fields .= 's.timemodified as timesubmitted, ';
     $fields .= 's.attemptnumber as attemptnumber, ';
     $fields .= 'g.id as gradeid, ';
     $fields .= 'g.grade as grade, ';
     $fields .= 'g.timemodified as timemarked, ';
     $fields .= 'g.timecreated as firstmarked, ';
     $fields .= 'uf.mailed as mailed, ';
     $fields .= 'uf.locked as locked, ';
     $fields .= 'uf.extensionduedate as extensionduedate, ';
     $fields .= 'uf.workflowstate as workflowstate, ';
     $fields .= 'uf.allocatedmarker as allocatedmarker ';
     $from = '{user} u
                      LEFT JOIN {assign_submission} s
                             ON u.id = s.userid
                            AND s.assignment = :assignmentid1
                            AND s.latest = 1
                      LEFT JOIN {assign_grades} g
                             ON u.id = g.userid
                            AND g.assignment = :assignmentid2 ';
     // For group submissions we don't immediately create an entry in the assign_submission table for each user,
     // instead the userid is set to 0. In this case we use a different query to retrieve the grade for the user.
     if ($this->assignment->get_instance()->teamsubmission) {
         $params['assignmentid4'] = (int) $this->assignment->get_instance()->id;
         $grademaxattempt = 'SELECT mxg.userid, MAX(mxg.attemptnumber) AS maxattempt
                               FROM {assign_grades} mxg
                              WHERE mxg.assignment = :assignmentid4
                           GROUP BY mxg.userid';
         $from .= 'LEFT JOIN (' . $grademaxattempt . ') gmx
                          ON u.id = gmx.userid
                         AND g.attemptnumber = gmx.maxattempt ';
     } else {
         $from .= 'AND g.attemptnumber = s.attemptnumber ';
     }
     $from .= 'LEFT JOIN {assign_user_flags} uf
                      ON u.id = uf.userid
                     AND uf.assignment = :assignmentid3';
     $userparams = array();
     $userindex = 0;
     list($userwhere, $userparams) = $DB->get_in_or_equal($users, SQL_PARAMS_NAMED, 'user');
     $where = 'u.id ' . $userwhere;
     $params = array_merge($params, $userparams);
     // The filters do not make sense when there are no submissions, so do not apply them.
     if ($this->assignment->is_any_submission_plugin_enabled()) {
         if ($filter == ASSIGN_FILTER_SUBMITTED) {
             $where .= ' AND (s.timemodified IS NOT NULL AND
                              s.status = :submitted) ';
             $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
         } else {
             if ($filter == ASSIGN_FILTER_NOT_SUBMITTED) {
                 $where .= ' AND (s.timemodified IS NULL OR s.status != :submitted) ';
                 $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
             } else {
                 if ($filter == ASSIGN_FILTER_REQUIRE_GRADING) {
                     $where .= ' AND (s.timemodified IS NOT NULL AND
                              s.status = :submitted AND
                              (s.timemodified >= g.timemodified OR g.timemodified IS NULL OR g.grade IS NULL))';
                     $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
                 } else {
                     if (strpos($filter, ASSIGN_FILTER_SINGLE_USER) === 0) {
                         $userfilter = (int) array_pop(explode('=', $filter));
                         $where .= ' AND (u.id = :userid)';
                         $params['userid'] = $userfilter;
                     }
                 }
             }
         }
     }
     if ($this->assignment->get_instance()->markingworkflow && $this->assignment->get_instance()->markingallocation) {
         if (has_capability('mod/assign:manageallocations', $this->assignment->get_context())) {
             // Check to see if marker filter is set.
             $markerfilter = (int) get_user_preferences('assign_markerfilter', '');
             if (!empty($markerfilter)) {
                 if ($markerfilter == ASSIGN_MARKER_FILTER_NO_MARKER) {
                     $where .= ' AND (uf.allocatedmarker IS NULL OR uf.allocatedmarker = 0)';
                 } else {
                     $where .= ' AND uf.allocatedmarker = :markerid';
                     $params['markerid'] = $markerfilter;
                 }
             }
         } else {
             // Only show users allocated to this marker.
             $where .= ' AND uf.allocatedmarker = :markerid';
             $params['markerid'] = $USER->id;
         }
     }
     if ($this->assignment->get_instance()->markingworkflow) {
         $workflowstates = $this->assignment->get_marking_workflow_states_for_current_user();
         if (!empty($workflowstates)) {
             $workflowfilter = get_user_preferences('assign_workflowfilter', '');
             if ($workflowfilter == ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED) {
                 $where .= ' AND (uf.workflowstate = :workflowstate OR uf.workflowstate IS NULL OR ' . $DB->sql_isempty('assign_user_flags', 'workflowstate', true, true) . ')';
                 $params['workflowstate'] = $workflowfilter;
             } else {
                 if (array_key_exists($workflowfilter, $workflowstates)) {
                     $where .= ' AND uf.workflowstate = :workflowstate';
                     $params['workflowstate'] = $workflowfilter;
                 }
             }
         }
     }
     $this->set_sql($fields, $from, $where, $params);
     if ($downloadfilename) {
         $this->is_downloading('csv', $downloadfilename);
     }
     $columns = array();
     $headers = array();
     // Select.
     if (!$this->is_downloading() && $this->hasgrade) {
         $columns[] = 'select';
         $headers[] = get_string('select') . '<div class="selectall"><label class="accesshide" for="selectall">' . get_string('selectall') . '</label>
                 <input type="checkbox" id="selectall" name="selectall" title="' . get_string('selectall') . '"/></div>';
     }
     // User picture.
     if ($this->hasviewblind || !$this->assignment->is_blind_marking()) {
         if (!$this->is_downloading()) {
             $columns[] = 'picture';
             $headers[] = get_string('pictureofuser');
         } else {
             $columns[] = 'recordid';
             $headers[] = get_string('recordid', 'assign');
         }
         // Fullname.
         $columns[] = 'fullname';
         $headers[] = get_string('fullname');
         foreach ($extrauserfields as $extrafield) {
             $columns[] = $extrafield;
             $headers[] = get_user_field_name($extrafield);
         }
     } else {
         // Record ID.
         $columns[] = 'recordid';
         $headers[] = get_string('recordid', 'assign');
     }
     // Submission status.
     $columns[] = 'status';
     $headers[] = get_string('status', 'assign');
     // Team submission columns.
     if ($assignment->get_instance()->teamsubmission) {
         $columns[] = 'team';
         $headers[] = get_string('submissionteam', 'assign');
     }
     // Allocated marker.
     if ($this->assignment->get_instance()->markingworkflow && $this->assignment->get_instance()->markingallocation && has_capability('mod/assign:manageallocations', $this->assignment->get_context())) {
         // Add a column for the allocated marker.
         $columns[] = 'allocatedmarker';
         $headers[] = get_string('marker', 'assign');
     }
     // Grade.
     $columns[] = 'grade';
     $headers[] = get_string('grade');
     if ($this->is_downloading()) {
         if ($this->assignment->get_instance()->grade >= 0) {
             $columns[] = 'grademax';
             $headers[] = get_string('maxgrade', 'assign');
         } else {
             // This is a custom scale.
             $columns[] = 'scale';
             $headers[] = get_string('scale', 'assign');
         }
         if ($this->assignment->get_instance()->markingworkflow) {
             // Add a column for the marking workflow state.
             $columns[] = 'workflowstate';
             $headers[] = get_string('markingworkflowstate', 'assign');
         }
         // Add a column for the list of valid marking workflow states.
         $columns[] = 'gradecanbechanged';
         $headers[] = get_string('gradecanbechanged', 'assign');
     }
     if (!$this->is_downloading() && $this->hasgrade) {
         // We have to call this column userid so we can use userid as a default sortable column.
         $columns[] = 'userid';
         $headers[] = get_string('edit');
     }
     // Submission plugins.
     if ($assignment->is_any_submission_plugin_enabled()) {
         $columns[] = 'timesubmitted';
         $headers[] = get_string('lastmodifiedsubmission', 'assign');
         foreach ($this->assignment->get_submission_plugins() as $plugin) {
             if ($this->is_downloading()) {
                 if ($plugin->is_visible() && $plugin->is_enabled()) {
                     foreach ($plugin->get_editor_fields() as $field => $description) {
                         $index = 'plugin' . count($this->plugincache);
                         $this->plugincache[$index] = array($plugin, $field);
                         $columns[] = $index;
                         $headers[] = $plugin->get_name();
                     }
                 }
             } else {
                 if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->has_user_summary()) {
                     $index = 'plugin' . count($this->plugincache);
                     $this->plugincache[$index] = array($plugin);
                     $columns[] = $index;
                     $headers[] = $plugin->get_name();
                 }
             }
         }
     }
     // Time marked.
     $columns[] = 'timemarked';
     $headers[] = get_string('lastmodifiedgrade', 'assign');
     // Feedback plugins.
     foreach ($this->assignment->get_feedback_plugins() as $plugin) {
         if ($this->is_downloading()) {
             if ($plugin->is_visible() && $plugin->is_enabled()) {
                 foreach ($plugin->get_editor_fields() as $field => $description) {
                     $index = 'plugin' . count($this->plugincache);
                     $this->plugincache[$index] = array($plugin, $field);
                     $columns[] = $index;
                     $headers[] = $description;
                 }
             }
         } else {
             if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->has_user_summary()) {
                 $index = 'plugin' . count($this->plugincache);
                 $this->plugincache[$index] = array($plugin);
                 $columns[] = $index;
                 $headers[] = $plugin->get_name();
             }
         }
     }
     // Exclude 'Final grade' column in downloaded grading worksheets.
     if (!$this->is_downloading()) {
         // Final grade.
         $columns[] = 'finalgrade';
         $headers[] = get_string('finalgrade', 'grades');
     }
     // Load the grading info for all users.
     $this->gradinginfo = grade_get_grades($this->assignment->get_course()->id, 'mod', 'assign', $this->assignment->get_instance()->id, $users);
     if (!empty($CFG->enableoutcomes) && !empty($this->gradinginfo->outcomes)) {
         $columns[] = 'outcomes';
         $headers[] = get_string('outcomes', 'grades');
     }
     // Set the columns.
     $this->define_columns($columns);
     $this->define_headers($headers);
     foreach ($extrauserfields as $extrafield) {
         $this->column_class($extrafield, $extrafield);
     }
     $this->no_sorting('recordid');
     $this->no_sorting('finalgrade');
     $this->no_sorting('userid');
     $this->no_sorting('select');
     $this->no_sorting('outcomes');
     if ($assignment->get_instance()->teamsubmission) {
         $this->no_sorting('team');
     }
     $plugincolumnindex = 0;
     foreach ($this->assignment->get_submission_plugins() as $plugin) {
         if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->has_user_summary()) {
             $submissionpluginindex = 'plugin' . $plugincolumnindex++;
             $this->no_sorting($submissionpluginindex);
         }
     }
     foreach ($this->assignment->get_feedback_plugins() as $plugin) {
         if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->has_user_summary()) {
             $feedbackpluginindex = 'plugin' . $plugincolumnindex++;
             $this->no_sorting($feedbackpluginindex);
         }
     }
     // When there is no data we still want the column headers printed in the csv file.
     if ($this->is_downloading()) {
         $this->start_output();
     }
 }
示例#5
0
 /**
  * Save grade update.
  *
  * @param int $userid
  * @param  stdClass $data
  * @return bool - was the grade saved
  */
 public function save_grade($userid, $data)
 {
     // Need grade permission.
     require_capability('mod/assign:grade', $this->context);
     $instance = $this->get_instance();
     $submission = null;
     if ($instance->teamsubmission) {
         $submission = $this->get_group_submission($userid, 0, false, $data->attemptnumber);
     } else {
         $submission = $this->get_user_submission($userid, false, $data->attemptnumber);
     }
     if ($instance->teamsubmission && $data->applytoall) {
         $groupid = 0;
         if ($this->get_submission_group($userid)) {
             $group = $this->get_submission_group($userid);
             if ($group) {
                 $groupid = $group->id;
             }
         }
         $members = $this->get_submission_group_members($groupid, true);
         foreach ($members as $member) {
             // User may exist in multple groups (which should put them in the default group).
             $this->apply_grade_to_user($data, $member->id, $data->attemptnumber);
             $this->process_outcomes($member->id, $data);
         }
     } else {
         $this->apply_grade_to_user($data, $userid, $data->attemptnumber);
         $this->process_outcomes($userid, $data);
     }
     $maxattemptsreached = !empty($submission) && $submission->attemptnumber >= $instance->maxattempts - 1 && $instance->maxattempts != ASSIGN_UNLIMITED_ATTEMPTS;
     $shouldreopen = false;
     if ($instance->attemptreopenmethod == ASSIGN_ATTEMPT_REOPEN_METHOD_UNTILPASS) {
         // Check the gradetopass from the gradebook.
         $gradinginfo = grade_get_grades($this->get_course()->id, 'mod', 'assign', $instance->id, $userid);
         // What do we do if the grade has not been added to the gradebook (e.g. blind marking)?
         $gradingitem = null;
         $gradebookgrade = null;
         if (isset($gradinginfo->items[0])) {
             $gradingitem = $gradinginfo->items[0];
             $gradebookgrade = $gradingitem->grades[$userid];
         }
         if ($gradebookgrade) {
             // TODO: This code should call grade_grade->is_passed().
             $shouldreopen = true;
             if (is_null($gradebookgrade->grade)) {
                 $shouldreopen = false;
             }
             if (empty($gradingitem->gradepass) || $gradingitem->gradepass == $gradingitem->grademin) {
                 $shouldreopen = false;
             }
             if ($gradebookgrade->grade >= $gradingitem->gradepass) {
                 $shouldreopen = false;
             }
         }
     }
     if ($instance->attemptreopenmethod == ASSIGN_ATTEMPT_REOPEN_METHOD_MANUAL && !empty($data->addattempt)) {
         $shouldreopen = true;
     }
     // Never reopen if we are editing a previous attempt.
     if ($data->attemptnumber != -1) {
         $shouldreopen = false;
     }
     if ($shouldreopen && !$maxattemptsreached) {
         $this->add_attempt($userid);
     }
     return true;
 }
示例#6
0
/**
 * Print the grade information for the assignment for this user
 *
 * @param stdClass $course
 * @param stdClass $user
 * @param stdClass $coursemodule
 * @param stdClass $assignment
 */
function assign_user_outline($course, $user, $coursemodule, $assignment)
{
    global $CFG;
    require_once $CFG->libdir . '/gradelib.php';
    require_once $CFG->dirroot . '/grade/grading/lib.php';
    $gradinginfo = grade_get_grades($course->id, 'mod', 'assign', $assignment->id, $user->id);
    $gradingitem = $gradinginfo->items[0];
    $gradebookgrade = $gradingitem->grades[$user->id];
    if (!$gradebookgrade) {
        return null;
    }
    $result = new stdClass();
    $result->info = get_string('outlinegrade', 'assign', $gradebookgrade->grade);
    $result->time = $gradebookgrade->dategraded;
    return $result;
}
示例#7
0
/**
 * Get a grade for the given user from the gradebook.
 *
 * @param integer $userid        ID of the user
 * @param integer $courseid      ID of the course
 * @param integer $facetofaceid  ID of the Face-to-face activity
 *
 * @returns object String grade and the time that it was graded
 */
function facetoface_get_grade($userid, $courseid, $facetofaceid) {

    $ret = new stdClass();
    $ret->grade = 0;
    $ret->dategraded = 0;

    $grading_info = grade_get_grades($courseid, 'mod', 'facetoface', $facetofaceid, $userid);
    if (!empty($grading_info->items)) {
        $ret->grade = $grading_info->items[0]->grades[$userid]->str_grade;
        $ret->dategraded = $grading_info->items[0]->grades[$userid]->dategraded;
    }

    return $ret;
}
示例#8
0
 /**
  * Save outcomes submitted from grading form.
  *
  * @param int $userid
  * @param stdClass $formdata
  * @param int $sourceuserid The user ID under which the outcome data is accessible. This is relevant
  *                          for an outcome set to a user but applied to an entire group.
  */
 protected function process_outcomes($userid, $formdata, $sourceuserid = null)
 {
     global $CFG, $USER;
     if (empty($CFG->enableoutcomes)) {
         return;
     }
     if ($this->grading_disabled($userid)) {
         return;
     }
     require_once $CFG->libdir . '/gradelib.php';
     $data = array();
     $gradinginfo = grade_get_grades($this->get_course()->id, 'mod', 'assign', $this->get_instance()->id, $userid);
     if (!empty($gradinginfo->outcomes)) {
         foreach ($gradinginfo->outcomes as $index => $oldoutcome) {
             $name = 'outcome_' . $index;
             $sourceuserid = $sourceuserid !== null ? $sourceuserid : $userid;
             if (isset($formdata->{$name}[$sourceuserid]) && $oldoutcome->grades[$userid]->grade != $formdata->{$name}[$sourceuserid]) {
                 $data[$index] = $formdata->{$name}[$sourceuserid];
             }
         }
     }
     if (count($data) > 0) {
         grade_update_outcomes('mod/assign', $this->course->id, 'mod', 'assign', $this->get_instance()->id, $userid, $data);
     }
 }
 /**
  *  Display all the submissions ready for grading
  */
 function display_submissions($message = '')
 {
     global $CFG, $db, $USER;
     require_once $CFG->libdir . '/gradelib.php';
     /* first we check to see if the form has just been submitted
      * to request user_preference updates
      */
     /*if (isset($_POST['updatepref'])){
           $perpage = optional_param('perpage', 10, PARAM_INT);
           $perpage = ($perpage <= 0) ? 10 : $perpage ;
           set_user_preference('problemstatement_perpage', $perpage);
           set_user_preference('problemstatement_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL));
       }*/
     /* next we get perpage and quickgrade (allow quick grade) params
      * from database
      */
     $perpage = get_user_preferences('problemstatement_perpage', 10);
     $quickgrade = get_user_preferences('problemstatement_quickgrade', 0);
     $grading_info = grade_get_grades($this->course->id, 'mod', 'problemstatement', $this->problemstatement->id);
     if (!empty($CFG->enableoutcomes) and !empty($grading_info->outcomes)) {
         $uses_outcomes = true;
     } else {
         $uses_outcomes = false;
     }
     $page = optional_param('page', 0, PARAM_INT);
     $strsaveallfeedback = get_string('saveallfeedback', 'problemstatement');
     /// Some shortcuts to make the code read better
     $course = $this->course;
     $problemstatement = $this->problemstatement;
     $cm = $this->cm;
     $tabindex = 1;
     //tabindex for quick grading tabbing; Not working for dropdowns yet
     add_to_log($course->id, 'problemstatement', 'view submission', 'submissions.php?id=' . $this->problemstatement->id, $this->problemstatement->id, $this->cm->id);
     $navigation = build_navigation($this->strsubmissions, $this->cm);
     print_header_simple(format_string($this->problemstatement->name, true), "", $navigation, '', '', true, update_module_button($cm->id, $course->id, $this->strproblemstatement), navmenu($course, $cm));
     $course_context = get_context_instance(CONTEXT_COURSE, $course->id);
     if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
         echo '<div class="allcoursegrades"><a href="' . $CFG->wwwroot . '/grade/report/grader/index.php?id=' . $course->id . '">' . get_string('seeallcoursegrades', 'grades') . '</a></div>';
     }
     if (!empty($message)) {
         echo $message;
         // display messages here if any
     }
     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
     /// Check to see if groups are being used in this problemstatement
     /// find out current groups mode
     $groupmode = groups_get_activity_groupmode($cm);
     $currentgroup = groups_get_activity_group($cm, true);
     groups_print_activity_menu($cm, 'submissions.php?id=' . $this->cm->id);
     /// Get all ppl that are allowed to submit problemstatements
     if ($users = get_users_by_capability($context, 'mod/problemstatement:submit', 'u.id', '', '', '', $currentgroup, '', false)) {
         $users = array_keys($users);
     }
     // if groupmembersonly used, remove users who are not in any group
     if ($users and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
         if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
             $users = array_intersect($users, array_keys($groupingusers));
         }
     }
     $tablecolumns = array('picture', 'fullname', 'grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade');
     if ($uses_outcomes) {
         $tablecolumns[] = 'outcome';
         // no sorting based on outcomes column
     }
     $tableheaders = array('', get_string('fullname'), get_string('grade'), get_string('comment', 'problemstatement'), get_string('lastmodified') . ' (' . $course->student . ')', get_string('lastmodified') . ' (' . $course->teacher . ')', get_string('status'), get_string('finalgrade', 'grades'));
     if ($uses_outcomes) {
         $tableheaders[] = get_string('outcome', 'grades');
     }
     require_once $CFG->libdir . '/tablelib.php';
     $table = new flexible_table('mod-problemstatement-submissions');
     $table->define_columns($tablecolumns);
     $table->define_headers($tableheaders);
     $table->define_baseurl($CFG->wwwroot . '/mod/problemstatement/submissions.php?id=' . $this->cm->id . '&amp;currentgroup=' . $currentgroup);
     $table->sortable(true, 'lastname');
     //sorted by lastname by default
     $table->collapsible(true);
     $table->initialbars(true);
     $table->column_suppress('picture');
     $table->column_suppress('fullname');
     $table->column_class('picture', 'picture');
     $table->column_class('fullname', 'fullname');
     $table->column_class('grade', 'grade');
     $table->column_class('submissioncomment', 'comment');
     $table->column_class('timemodified', 'timemodified');
     $table->column_class('timemarked', 'timemarked');
     $table->column_class('status', 'status');
     $table->column_class('finalgrade', 'finalgrade');
     if ($uses_outcomes) {
         $table->column_class('outcome', 'outcome');
     }
     $table->set_attribute('cellspacing', '0');
     $table->set_attribute('id', 'attempts');
     $table->set_attribute('class', 'submissions');
     $table->set_attribute('width', '100%');
     //$table->set_attribute('align', 'center');
     $table->no_sorting('finalgrade');
     $table->no_sorting('outcome');
     // Start working -- this is necessary as soon as the niceties are over
     $table->setup();
     if (empty($users)) {
         print_heading(get_string('nosubmitusers', 'problemstatement'));
         return true;
     }
     /// Construct the SQL
     if ($where = $table->get_sql_where()) {
         $where .= ' AND ';
     }
     if ($sort = $table->get_sql_sort()) {
         $sort = ' ORDER BY ' . $sort;
     }
     $select = 'SELECT u.id, u.firstname, u.lastname, u.picture, u.imagealt,
                       s.id AS submissionid, s.grade, s.submissioncomment,
                       s.timemodified,
                       s.processed, s.succeeded ';
     $sql = 'FROM ' . $CFG->prefix . 'user u ' . 'LEFT JOIN ' . $CFG->prefix . 'problemstatement_submissions s ON u.id = s.userid
                                                               AND s.problemstatement = ' . $this->problemstatement->id . ' ' . 'WHERE ' . $where . 'u.id IN (' . implode(',', $users) . ') ';
     $table->pagesize($perpage, count($users));
     ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
     $offset = $page * $perpage;
     $strupdate = get_string('update');
     $strgrade = get_string('grade');
     $grademenu = make_grades_menu($this->problemstatement->grade);
     //echo $select.$sql.$sort;
     if (($ausers = get_records_sql($select . $sql . $sort, $table->get_page_start(), $table->get_page_size())) !== false) {
         $grading_info = grade_get_grades($this->course->id, 'mod', 'problemstatement', $this->problemstatement->id, array_keys($ausers));
         foreach ($ausers as $auser) {
             $final_grade = $grading_info->items[0]->grades[$auser->id];
             $grademax = $grading_info->items[0]->gradprocess_feedbackemax;
             $final_grade->formatted_grade = round($final_grade->grade, 2) . ' / ' . round($grademax, 2);
             $locked_overridden = 'locked';
             if ($final_grade->overridden) {
                 $locked_overridden = 'overridden';
             }
             /// Calculate user status
             //$auser->status = $auser->status;//($auser->timemarked > 0) && ($auser->timemarked >= $auser->timemodified);
             $picture = print_user_picture($auser, $course->id, $auser->picture, false, true);
             if (empty($auser->submissionid)) {
                 $auser->grade = -1;
                 //no submission yet
             }
             if (!empty($auser->submissionid)) {
                 ///Prints student answer and student modified date
                 ///attach file or print link to student answer, depending on the type of the problemstatement.
                 ///Refer to print_student_answer in inherited classes.
                 if ($auser->timemodified > 0) {
                     $studentmodified = '<div id="ts' . $auser->id . '">' . $this->print_student_answer($auser->id) . userdate($auser->timemodified) . '</div>';
                 } else {
                     $studentmodified = '<div id="ts' . $auser->id . '">&nbsp;</div>';
                 }
                 ///Print grade, dropdown or text
                 if ($auser->timemarked > 0) {
                     $teachermodified = '<div id="tt' . $auser->id . '">' . userdate($auser->timemarked) . '</div>';
                     if ($final_grade->locked or $final_grade->overridden) {
                         $grade = '<div id="g' . $auser->id . '" class="' . $locked_overridden . '">' . $final_grade->formatted_grade . '</div>';
                     } else {
                         if ($quickgrade) {
                             $menu = choose_from_menu(make_grades_menu($this->problemstatement->grade), 'menu[' . $auser->id . ']', $auser->grade, get_string('nograde'), '', -1, true, false, $tabindex++);
                             $grade = '<div id="g' . $auser->id . '">' . $menu . '</div>';
                         } else {
                             $grade = '<div id="g' . $auser->id . '">' . $this->display_grade($auser->grade) . '</div>';
                         }
                     }
                 } else {
                     $teachermodified = '<div id="tt' . $auser->id . '">&nbsp;</div>';
                     if ($final_grade->locked or $final_grade->overridden) {
                         $grade = '<div id="g' . $auser->id . '" class="' . $locked_overridden . '">' . $final_grade->formatted_grade . '</div>';
                     } else {
                         if ($quickgrade) {
                             $menu = choose_from_menu(make_grades_menu($this->problemstatement->grade), 'menprocess_feedbacku[' . $auser->id . ']', $auser->grade, get_string('nograde'), '', -1, true, false, $tabindex++);
                             $grade = '<div id="g' . $auser->id . '">' . $menu . '</div>';
                         } else {
                             $grade = '<div id="g' . $auser->id . '">' . $this->display_grade($auser->grade) . '</div>';
                         }
                     }
                 }
                 ///Print Comment
                 if ($final_grade->locked or $final_grade->overridden) {
                     $comment = '<div id="com' . $auser->id . '">' . shorten_text(strip_tags($final_grade->str_feedback), 15) . '</div>';
                 } else {
                     if ($quickgrade) {
                         $comment = '<div id="com' . $auser->id . '">' . '<textarea tabindex="' . $tabindex++ . '" name="submissioncomment[' . $auser->id . ']" id="submissioncomment' . $auser->id . '" rows="2" cols="20">' . $auser->submissioncomment . '</textarea></div>';
                     } else {
                         $msg = "";
                         $color = "#000000";
                         switch ($auser->processed) {
                             case "0":
                                 $msg .= "unprocessed";
                                 $color = "#AAAA00";
                                 break;
                             case "1":
                                 switch ($auser->succeeded) {
                                     case "4":
                                         //timeout
                                     //timeout
                                     case "6":
                                         //runtimeerror
                                     //runtimeerror
                                     case "2":
                                         //compilationerror
                                     //compilationerror
                                     case "5":
                                         //memoryout
                                     //memoryout
                                     case "0":
                                         $msg .= "failed";
                                         $color = "#AA0000";
                                         break;
                                     case "1":
                                         $msg .= "passed";
                                         $color = "#00AA00";
                                         break;
                                     case "3":
                                         $msg .= "internalerror";
                                         $color = "#0000AA";
                                         break;
                                 }
                                 break;
                             case "2":
                                 $msg .= "waiting";
                                 $color = "#00AAAA";
                                 break;
                         }
                         //$comment='<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
                         $comment = '<div id="com' . $auser->id . '">' . '<div class="files"><font color="' . $color . '"><strong>' . $msg . '</strong></font></div>' . '</div>';
                     }
                 }
             } else {
                 $studentmodified = '<div id="ts' . $auser->id . '">&nbsp;</div>';
                 $teachermodified = '<div id="tt' . $auser->id . '">&nbsp;</div>';
                 $status = '<div id="st' . $auser->id . '">&nbsp;</div>';
                 if ($final_grade->locked or $final_grade->overridden) {
                     $grade = '<div id="g' . $auser->id . '">' . $final_grade->formatted_grade . '</div>';
                 } else {
                     if ($quickgrade) {
                         // allow editing
                         $menu = choose_from_menu(make_grades_menu($this->problemstatement->grade), 'menu[' . $auser->id . ']', $auser->grade, get_string('nograde'), '', -1, true, false, $tabindex++);
                         $grade = '<div id="g' . $auser->id . '">' . $menu . '</div>';
                     } else {
                         $grade = '<div id="g' . $auser->id . '">-</div>';
                     }
                 }
                 if ($final_grade->locked or $final_grade->overridden) {
                     $comment = '<div id="com' . $auser->id . '">' . $final_grade->str_feedback . '</div>';
                 } else {
                     if ($quickgrade) {
                         $comment = '<div id="com' . $auser->id . '">' . '<textarea tabindex="' . $tabindex++ . '" name="submissioncomment[' . $auser->id . ']" id="submissioncomment' . $auser->id . '" rows="2" cols="20">' . $auser->submissioncomment . '</textarea></div>';
                     } else {
                         $comment = '<div id="com' . $auser->id . '">&nbsp;</div>';
                     }
                 }
             }
             if (empty($auser->processed)) {
                 /// Confirm we have exclusively 0 or 1
                 //$auser->status = 0;
             } else {
                 //$auser->status = 1;
             }
             $buttontext = $auser->processed == 1 ? $strupdate : $strgrade;
             ///No more buttons, we use popups ;-).
             $popup_url = '/mod/problemstatement/submissions.php?id=' . $this->cm->id . '&amp;userid=' . $auser->id . '&amp;mode=single' . '&amp;offset=' . $offset++;
             $button = link_to_popup_window($popup_url, 'grade' . $auser->id, $buttontext, 600, 780, $buttontext, 'none', true, 'button' . $auser->id);
             $status = '<div id="up' . $auser->id . '" class="s' . $auser->processed . '">' . $button . '</div>';
             $finalgrade = '<span id="finalgrade_' . $auser->id . '">' . $final_grade->str_grade . '</span>';
             $outcomes = '';
             if ($uses_outcomes) {
                 foreach ($grading_info->outcomes as $n => $outcome) {
                     $outcomes .= '<div class="outcome"><label>' . $outcome->name . '</label>';
                     $options = make_grades_menu(-$outcome->scaleid);
                     if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
                         $options[0] = get_string('nooutcome', 'grades');
                         $outcomes .= ': <span id="outcome_' . $n . '_' . $auser->id . '">' . $options[$outcome->grades[$auser->id]->grade] . '</span>';
                     } else {
                         $outcomes .= ' ';
                         $outcomes .= choose_from_menu($options, 'outcome_' . $n . '[' . $auser->id . ']', $outcome->grades[$auser->id]->grade, get_string('nooutcome', 'grades'), '', 0, true, false, 0, 'outcome_' . $n . '_' . $auser->id);
                     }
                     $outcomes .= '</div>';
                 }
             }
             $userlink = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $auser->id . '&amp;course=' . $course->id . '">' . fullname($auser) . '</a>';
             $row = array($picture, $userlink, $grade, $comment, $studentmodified, $teachermodified, $status, $finalgrade);
             if ($uses_outcomes) {
                 $row[] = $outcomes;
             }
             $table->add_data($row);
         }
     }
     /// Print quickgrade form around the table
     if ($quickgrade) {
         echo '<form action="submissions.php" id="fastg" method="post">';
         echo '<div>';
         echo '<input type="hidden" name="id" value="' . $this->cm->id . '" />';
         echo '<input type="hidden" name="mode" value="fastgrade" />';
         echo '<input type="hidden" name="page" value="' . $page . '" />';
         echo '</div>';
     }
     $table->print_html();
     /// Print the whole table
     if ($quickgrade) {
         $lastmailinfo = get_user_preferences('problemstatement_mailinfo', 1) ? 'checked="checked"' : '';
         echo '<div class="fgcontrols">';
         echo '<div class="emailnotification">';
         echo '<label for="mailinfo">' . get_string('enableemailnotification', 'problemstatement') . '</label>';
         echo '<input type="hidden" name="mailinfo" value="0" />';
         echo '<input type="checkbox" id="mailinfo" name="mailinfo" value="1" ' . $lastmailinfo . ' />';
         helpbutton('emailnotification', get_string('enableemailnotification', 'problemstatement'), 'problemstatement') . '</p></div>';
         echo '</div>';
         echo '<div class="fastgbutton"><input type="submit" name="fastg" value="' . get_string('saveallfeedback', 'problemstatement') . '" /></div>';
         echo '</div>';
         echo '</form>';
     }
     /// End of fast grading form
     /// Mini form for setting user preference
     echo '<div class="qgprefs">';
     echo '<form id="options" action="submissions.php?id=' . $this->cm->id . '" method="post"><div>';
     echo '<input type="hidden" name="updatepref" value="1" />';
     echo '<table id="optiontable">';
     echo '<tr><td>';
     echo '<label for="perpage">' . get_string('pagesize', 'problemstatement') . '</label>';
     echo '</td>';
     echo '<td>';
     echo '<input type="text" id="perpage" name="perpage" size="1" value="' . $perpage . '" />';
     helpbutton('pagesize', get_string('pagesize', 'problemstatement'), 'problemstatement');
     echo '</td></tr>';
     echo '<tr><td>';
     echo '<label for="quickgrade">' . get_string('quickgrade', 'problemstatement') . '</label>';
     echo '</td>';
     echo '<td>';
     $checked = $quickgrade ? 'checked="checked"' : '';
     echo '<input type="checkbox" id="quickgrade" name="quickgrade" value="1" ' . $checked . ' />';
     helpbutton('quickgrade', get_string('quickgrade', 'problemstatement'), 'problemstatement') . '</p></div>';
     echo '</td></tr>';
     echo '<tr><td colspan="2">';
     echo '<input type="submit" value="' . get_string('savepreferences') . '" />';
     echo '</td></tr></table>';
     echo '</div></form></div>';
     ///End of mini form
     print_footer($this->course);
 }
示例#10
0
 /**
  * Performs the synchronisation of grades.
  *
  * @return bool|void
  */
 public function execute()
 {
     global $DB, $CFG;
     require_once $CFG->dirroot . '/enrol/lti/ims-blti/OAuth.php';
     require_once $CFG->dirroot . '/enrol/lti/ims-blti/OAuthBody.php';
     require_once $CFG->dirroot . '/lib/completionlib.php';
     require_once $CFG->libdir . '/gradelib.php';
     require_once $CFG->dirroot . '/grade/querylib.php';
     // Check if the authentication plugin is disabled.
     if (!is_enabled_auth('lti')) {
         mtrace('Skipping task - ' . get_string('pluginnotenabled', 'auth', get_string('pluginname', 'auth_lti')));
         return true;
     }
     // Check if the enrolment plugin is disabled - isn't really necessary as the task should not run if
     // the plugin is disabled, but there is no harm in making sure core hasn't done something wrong.
     if (!enrol_is_enabled('lti')) {
         mtrace('Skipping task - ' . get_string('enrolisdisabled', 'enrol_lti'));
         return true;
     }
     // Get all the enabled tools.
     if ($tools = \enrol_lti\helper::get_lti_tools(array('status' => ENROL_INSTANCE_ENABLED, 'gradesync' => 1))) {
         foreach ($tools as $tool) {
             mtrace("Starting - Grade sync for shared tool '{$tool->id}' for the course '{$tool->courseid}'.");
             // Variables to keep track of information to display later.
             $usercount = 0;
             $sendcount = 0;
             // We check for all the users - users can access the same tool from different consumers.
             if ($ltiusers = $DB->get_records('enrol_lti_users', array('toolid' => $tool->id), 'lastaccess DESC')) {
                 $completion = new \completion_info(get_course($tool->courseid));
                 foreach ($ltiusers as $ltiuser) {
                     $mtracecontent = "for the user '{$ltiuser->userid}' in the tool '{$tool->id}' for the course " . "'{$tool->courseid}'";
                     $usercount = $usercount + 1;
                     // Check if we do not have a serviceurl - this can happen if the sync process has an unexpected error.
                     if (empty($ltiuser->serviceurl)) {
                         mtrace("Skipping - Empty serviceurl {$mtracecontent}.");
                         continue;
                     }
                     // Check if we do not have a sourceid - this can happen if the sync process has an unexpected error.
                     if (empty($ltiuser->sourceid)) {
                         mtrace("Skipping - Empty sourceid {$mtracecontent}.");
                         continue;
                     }
                     // Need a valid context to continue.
                     if (!($context = \context::instance_by_id($tool->contextid))) {
                         mtrace("Failed - Invalid contextid '{$tool->contextid}' for the tool '{$tool->id}'.");
                         continue;
                     }
                     // Ok, let's get the grade.
                     $grade = false;
                     if ($context->contextlevel == CONTEXT_COURSE) {
                         // Check if the user did not completed the course when it was required.
                         if ($tool->gradesynccompletion && !$completion->is_course_complete($ltiuser->userid)) {
                             mtrace("Skipping - Course not completed {$mtracecontent}.");
                             continue;
                         }
                         // Get the grade.
                         if ($grade = grade_get_course_grade($ltiuser->userid, $tool->courseid)) {
                             $grademax = floatval($grade->item->grademax);
                             $grade = $grade->grade;
                         }
                     } else {
                         if ($context->contextlevel == CONTEXT_MODULE) {
                             $cm = get_coursemodule_from_id(false, $context->instanceid, 0, false, MUST_EXIST);
                             if ($tool->gradesynccompletion) {
                                 $data = $completion->get_data($cm, false, $ltiuser->userid);
                                 if ($data->completionstate != COMPLETION_COMPLETE_PASS && $data->completionstate != COMPLETION_COMPLETE) {
                                     mtrace("Skipping - Activity not completed {$mtracecontent}.");
                                     continue;
                                 }
                             }
                             $grades = grade_get_grades($cm->course, 'mod', $cm->modname, $cm->instance, $ltiuser->userid);
                             if (!empty($grades->items[0]->grades)) {
                                 $grade = reset($grades->items[0]->grades);
                                 if (!empty($grade->item)) {
                                     $grademax = floatval($grade->item->grademax);
                                 } else {
                                     $grademax = floatval($grades->items[0]->grademax);
                                 }
                                 $grade = $grade->grade;
                             }
                         }
                     }
                     if ($grade === false || $grade === null || strlen($grade) < 1) {
                         mtrace("Skipping - Invalid grade {$mtracecontent}.");
                         continue;
                     }
                     // No need to be dividing by zero.
                     if (empty($grademax)) {
                         mtrace("Skipping - Invalid grade {$mtracecontent}.");
                         continue;
                     }
                     // This can happen if the sync process has an unexpected error.
                     if ($grade == $ltiuser->lastgrade) {
                         mtrace("Not sent - The grade {$mtracecontent} was not sent as the grades are the same.");
                         continue;
                     }
                     // Sync with the external system.
                     $floatgrade = $grade / $grademax;
                     $body = \enrol_lti\helper::create_service_body($ltiuser->sourceid, $floatgrade);
                     try {
                         $response = sendOAuthBodyPOST('POST', $ltiuser->serviceurl, $ltiuser->consumerkey, $ltiuser->consumersecret, 'application/xml', $body);
                     } catch (\Exception $e) {
                         mtrace("Failed - The grade '{$floatgrade}' {$mtracecontent} failed to send.");
                         mtrace($e->getMessage());
                         continue;
                     }
                     if (strpos(strtolower($response), 'success') !== false) {
                         $DB->set_field('enrol_lti_users', 'lastgrade', intval($grade), array('id' => $ltiuser->id));
                         mtrace("Success - The grade '{$floatgrade}' {$mtracecontent} was sent.");
                         $sendcount = $sendcount + 1;
                     } else {
                         mtrace("Failed - The grade '{$floatgrade}' {$mtracecontent} failed to send.");
                     }
                 }
             }
             mtrace("Completed - Synced grades for tool '{$tool->id}' in the course '{$tool->courseid}'. " . "Processed {$usercount} users; sent {$sendcount} grades.");
             mtrace("");
         }
     }
 }
 function view_feedback($submission = NULL)
 {
     global $USER, $CFG;
     require_once $CFG->libdir . '/gradelib.php';
     if (!$submission) {
         /// Get submission for this assignment
         $submission = $this->get_submission($USER->id);
     }
     if (empty($submission->timemarked)) {
         /// Nothing to show, so print nothing
         if ($this->count_responsefiles($USER->id)) {
             print_heading(get_string('responsefiles', 'assignment', $this->course->teacher), '', 3);
             $responsefiles = $this->print_responsefiles($USER->id, true);
             print_simple_box($responsefiles, 'center');
         }
         return;
     }
     $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $USER->id);
     $item = $grading_info->items[0];
     $grade = $item->grades[$USER->id];
     if ($grade->hidden or $grade->grade === false) {
         // hidden or error
         return;
     }
     if ($grade->grade === null and empty($grade->str_feedback)) {
         /// Nothing to show yet
         return;
     }
     $graded_date = $grade->dategraded;
     $graded_by = $grade->usermodified;
     /// We need the teacher info
     if (!($teacher = get_record('user', 'id', $graded_by))) {
         error('Could not find the teacher');
     }
     /// Print the feedback
     print_heading(get_string('submissionfeedback', 'assignment'), '', 3);
     echo '<table cellspacing="0" class="feedback">';
     echo '<tr>';
     echo '<td class="left picture">';
     print_user_picture($teacher, $this->course->id, $teacher->picture);
     echo '</td>';
     echo '<td class="topic">';
     echo '<div class="from">';
     echo '<div class="fullname">' . fullname($teacher) . '</div>';
     echo '<div class="time">' . userdate($graded_date) . '</div>';
     echo '</div>';
     echo '</td>';
     echo '</tr>';
     echo '<tr>';
     echo '<td class="left side">&nbsp;</td>';
     echo '<td class="content">';
     if ($this->assignment->grade) {
         echo '<div class="grade">';
         echo get_string("grade") . ': ' . $grade->str_long_grade;
         echo '</div>';
         echo '<div class="clearer"></div>';
     }
     echo '<div class="comment">';
     echo $grade->str_feedback;
     echo '</div>';
     echo '</tr>';
     echo '<tr>';
     echo '<td class="left side">&nbsp;</td>';
     echo '<td class="content">';
     echo $this->print_responsefiles($USER->id, true);
     echo '</tr>';
     echo '</table>';
 }
示例#12
0
文件: lib.php 项目: e-rasvet/reader
/**
 * Create grade item for given quiz
 *
 * @param object $quiz object with extra cmidnumber
 * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
 * @return int 0 if ok, error code otherwise
 */
function quiz_grade_item_update($quiz, $grades = NULL)
{
    global $CFG;
    if (!function_exists('grade_update')) {
        //workaround for buggy PHP versions
        require_once $CFG->libdir . '/gradelib.php';
    }
    if (array_key_exists('cmidnumber', $quiz)) {
        //it may not be always present
        $params = array('itemname' => $quiz->name, 'idnumber' => $quiz->cmidnumber);
    } else {
        $params = array('itemname' => $quiz->name);
    }
    if ($quiz->grade > 0) {
        $params['gradetype'] = GRADE_TYPE_VALUE;
        $params['grademax'] = $quiz->grade;
        $params['grademin'] = 0;
    } else {
        $params['gradetype'] = GRADE_TYPE_NONE;
    }
    /* description by TJ:
    1/ If the quiz is set to not show scores while the quiz is still open, and is set to show scores after
       the quiz is closed, then create the grade_item with a show-after date that is the quiz close date.
    2/ If the quiz is set to not show scores at either of those times, create the grade_item as hidden.
    3/ If the quiz is set to show scores, create the grade_item visible.
    */
    if (!($quiz->review & QUIZ_REVIEW_SCORES & QUIZ_REVIEW_CLOSED) and !($quiz->review & QUIZ_REVIEW_SCORES & QUIZ_REVIEW_OPEN)) {
        $params['hidden'] = 1;
    } else {
        if ($quiz->review & QUIZ_REVIEW_SCORES & QUIZ_REVIEW_CLOSED and !($quiz->review & QUIZ_REVIEW_SCORES & QUIZ_REVIEW_OPEN)) {
            if ($quiz->timeclose) {
                $params['hidden'] = $quiz->timeclose;
            } else {
                $params['hidden'] = 1;
            }
        } else {
            // a) both open and closed enabled
            // b) open enabled, closed disabled - we can not "hide after", grades are kept visible even after closing
            $params['hidden'] = 0;
        }
    }
    if ($grades === 'reset') {
        $params['reset'] = true;
        $grades = NULL;
    }
    $gradebook_grades = grade_get_grades($quiz->course, 'mod', 'quiz', $quiz->id);
    if (!empty($gradebook_grades->items)) {
        $grade_item = $gradebook_grades->items[0];
        if ($grade_item->locked) {
            $confirm_regrade = optional_param('confirm_regrade', 0, PARAM_INT);
            if (!$confirm_regrade) {
                $message = get_string('gradeitemislocked', 'grades');
                $back_link = $CFG->wwwroot . '/mod/quiz/report.php?q=' . $quiz->id . '&amp;mode=overview';
                $regrade_link = qualified_me() . '&amp;confirm_regrade=1';
                print_box_start('generalbox', 'notice');
                echo '<p>' . $message . '</p>';
                echo '<div class="buttons">';
                print_single_button($regrade_link, null, get_string('regradeanyway', 'grades'), 'post', $CFG->framename);
                print_single_button($back_link, null, get_string('cancel'), 'post', $CFG->framename);
                echo '</div>';
                print_box_end();
                return GRADE_UPDATE_ITEM_LOCKED;
            }
        }
    }
    return grade_update('mod/quiz', $quiz->course, 'mod', 'quiz', $quiz->id, 0, $grades, $params);
}
示例#13
0
/**
 * Write in the worksheet the given facetoface attendance information
 * filtered by location.
 *
 * This function includes lots of custom SQL because it's otherwise
 * way too slow.
 *
 * @param object  $worksheet    Currently open worksheet
 * @param integer $startingrow  Index of the starting row (usually 1)
 * @param integer $facetofaceid ID of the facetoface activity
 * @param string  $location     Location to filter by
 * @param string  $coursename   Name of the course (optional)
 * @param string  $activityname Name of the facetoface activity (optional)
 * @param object  $dateformat   Use to write out dates in the spreadsheet
 * @returns integer Index of the last row written
 */
function facetoface_write_activity_attendance(&$worksheet, $startingrow, $facetofaceid, $location, $coursename, $activityname, $dateformat)
{
    global $CFG, $DB;
    $trainerroles = facetoface_get_trainer_roles();
    $userfields = facetoface_get_userfields();
    $customsessionfields = facetoface_get_session_customfields();
    $timenow = time();
    $i = $startingrow;
    $locationcondition = '';
    $locationparam = array();
    if (!empty($location)) {
        $locationcondition = "AND s.location = ?";
        $locationparam = array($location);
    }
    // Fast version of "facetoface_get_attendees()" for all sessions.
    $sessionsignups = array();
    $signups = $DB->get_records_sql("\n        SELECT\n            su.id AS submissionid,\n            s.id AS sessionid,\n            u.*,\n            f.course AS courseid,\n            ss.grade,\n            sign.timecreated\n        FROM\n            {facetoface} f\n        JOIN\n            {facetoface_sessions} s\n         ON s.facetoface = f.id\n        JOIN\n            {facetoface_signups} su\n         ON s.id = su.sessionid\n        JOIN\n            {facetoface_signups_status} ss\n         ON su.id = ss.signupid\n        LEFT JOIN\n            (\n            SELECT\n                ss.signupid,\n                MAX(ss.timecreated) AS timecreated\n            FROM\n                {facetoface_signups_status} ss\n            INNER JOIN\n                {facetoface_signups} s\n             ON s.id = ss.signupid\n            INNER JOIN\n                {facetoface_sessions} se\n             ON s.sessionid = se.id\n            AND se.facetoface = {$facetofaceid}\n            WHERE\n                ss.statuscode IN (?,?)\n            GROUP BY\n                ss.signupid\n            ) sign\n         ON su.id = sign.signupid\n        JOIN\n            {user} u\n         ON u.id = su.userid\n        WHERE\n            f.id = ?\n        AND ss.superceded != 1\n        AND ss.statuscode >= ?\n        ORDER BY\n            s.id, u.firstname, u.lastname\n    ", array(MDL_F2F_STATUS_BOOKED, MDL_F2F_STATUS_WAITLISTED, $facetofaceid, MDL_F2F_STATUS_APPROVED));
    if ($signups) {
        // Get all grades at once.
        $userids = array();
        foreach ($signups as $signup) {
            if ($signup->id > 0) {
                $userids[] = $signup->id;
            }
        }
        $gradinginfo = grade_get_grades(reset($signups)->courseid, 'mod', 'facetoface', $facetofaceid, $userids);
        foreach ($signups as $signup) {
            $userid = $signup->id;
            if ($customuserfields = facetoface_get_user_customfields($userid, $userfields)) {
                foreach ($customuserfields as $fieldname => $value) {
                    if (!isset($signup->{$fieldname})) {
                        $signup->{$fieldname} = $value;
                    }
                }
            }
            // Set grade.
            if (!empty($gradinginfo->items) and !empty($gradinginfo->items[0]->grades[$userid])) {
                $signup->grade = $gradinginfo->items[0]->grades[$userid]->str_grade;
            }
            $sessionsignups[$signup->sessionid][$signup->id] = $signup;
        }
    }
    // Fast version of "facetoface_get_sessions($facetofaceid, $location)".
    $sql = "SELECT d.id as dateid, s.id, s.datetimeknown, s.capacity,\n                   s.duration, d.timestart, d.timefinish\n              FROM {facetoface_sessions} s\n              JOIN {facetoface_sessions_dates} d ON s.id = d.sessionid\n              WHERE\n                s.facetoface = ?\n              AND d.sessionid = s.id\n                   {$locationcondition}\n                   ORDER BY s.datetimeknown, d.timestart";
    $sessions = $DB->get_records_sql($sql, array_merge(array($facetofaceid), $locationparam));
    $i = $i - 1;
    // Will be incremented BEFORE each row is written.
    foreach ($sessions as $session) {
        $customdata = $DB->get_records('facetoface_session_data', array('sessionid' => $session->id), '', 'fieldid, data');
        $sessiondate = false;
        $starttime = get_string('wait-listed', 'facetoface');
        $finishtime = get_string('wait-listed', 'facetoface');
        $status = get_string('wait-listed', 'facetoface');
        $sessiontrainers = facetoface_get_trainers($session->id);
        if ($session->datetimeknown) {
            // Display only the first date.
            if (method_exists($worksheet, 'write_date')) {
                // Needs the patch in MDL-20781.
                $sessiondate = (int) $session->timestart;
            } else {
                $sessiondate = userdate($session->timestart, get_string('strftimedate', 'langconfig'));
            }
            $starttime = userdate($session->timestart, get_string('strftimetime', 'langconfig'));
            $finishtime = userdate($session->timefinish, get_string('strftimetime', 'langconfig'));
            if ($session->timestart < $timenow) {
                $status = get_string('sessionover', 'facetoface');
            } else {
                $signupcount = 0;
                if (!empty($sessionsignups[$session->id])) {
                    $signupcount = count($sessionsignups[$session->id]);
                }
                if ($signupcount >= $session->capacity) {
                    $status = get_string('bookingfull', 'facetoface');
                } else {
                    $status = get_string('bookingopen', 'facetoface');
                }
            }
        }
        if (!empty($sessionsignups[$session->id])) {
            foreach ($sessionsignups[$session->id] as $attendee) {
                $i++;
                $j = 0;
                // Custom session fields.
                foreach ($customsessionfields as $field) {
                    if (empty($field->showinsummary)) {
                        continue;
                        // Skip.
                    }
                    $data = '-';
                    if (!empty($customdata[$field->id])) {
                        if (CUSTOMFIELD_TYPE_MULTISELECT == $field->type) {
                            $data = str_replace(CUSTOMFIELD_DELIMITER, "\n", $customdata[$field->id]->data);
                        } else {
                            $data = $customdata[$field->id]->data;
                        }
                    }
                    $worksheet->write_string($i, $j++, $data);
                }
                if (empty($sessiondate)) {
                    $worksheet->write_string($i, $j++, $status);
                    // Session date.
                } else {
                    if (method_exists($worksheet, 'write_date')) {
                        $worksheet->write_date($i, $j++, $sessiondate, $dateformat);
                    } else {
                        $worksheet->write_string($i, $j++, $sessiondate);
                    }
                }
                $worksheet->write_string($i, $j++, $starttime);
                $worksheet->write_string($i, $j++, $finishtime);
                $worksheet->write_number($i, $j++, (int) $session->duration);
                $worksheet->write_string($i, $j++, $status);
                if ($trainerroles) {
                    foreach (array_keys($trainerroles) as $roleid) {
                        if (!empty($sessiontrainers[$roleid])) {
                            $trainers = array();
                            foreach ($sessiontrainers[$roleid] as $trainer) {
                                $trainers[] = fullname($trainer);
                            }
                            $trainers = implode(', ', $trainers);
                        } else {
                            $trainers = '-';
                        }
                        $worksheet->write_string($i, $j++, $trainers);
                    }
                }
                foreach ($userfields as $shortname => $fullname) {
                    $value = '-';
                    if (!empty($attendee->{$shortname})) {
                        $value = $attendee->{$shortname};
                    }
                    if ('firstaccess' == $shortname || 'lastaccess' == $shortname || 'lastlogin' == $shortname || 'currentlogin' == $shortname) {
                        if (method_exists($worksheet, 'write_date')) {
                            $worksheet->write_date($i, $j++, (int) $value, $dateformat);
                        } else {
                            $worksheet->write_string($i, $j++, userdate($value, get_string('strftimedate', 'langconfig')));
                        }
                    } else {
                        $worksheet->write_string($i, $j++, $value);
                    }
                }
                $worksheet->write_string($i, $j++, $attendee->grade);
                if (method_exists($worksheet, 'write_date')) {
                    $worksheet->write_date($i, $j++, (int) $attendee->timecreated, $dateformat);
                } else {
                    $signupdate = userdate($attendee->timecreated, get_string('strftimedatetime', 'langconfig'));
                    if (empty($signupdate)) {
                        $signupdate = '-';
                    }
                    $worksheet->write_string($i, $j++, $signupdate);
                }
                if (!empty($coursename)) {
                    $worksheet->write_string($i, $j++, $coursename);
                }
                if (!empty($activityname)) {
                    $worksheet->write_string($i, $j++, $activityname);
                }
            }
        } else {
            // No one is sign-up, so let's just print the basic info.
            $i++;
            $j = 0;
            // Custom session fields.
            foreach ($customsessionfields as $field) {
                if (empty($field->showinsummary)) {
                    continue;
                    // Skip.
                }
                $data = '-';
                if (!empty($customdata[$field->id])) {
                    if (CUSTOMFIELD_TYPE_MULTISELECT == $field->type) {
                        $data = str_replace(CUSTOMFIELD_DELIMITER, "\n", $customdata[$field->id]->data);
                    } else {
                        $data = $customdata[$field->id]->data;
                    }
                }
                $worksheet->write_string($i, $j++, $data);
            }
            if (empty($sessiondate)) {
                $worksheet->write_string($i, $j++, $status);
                // Session date.
            } else {
                if (method_exists($worksheet, 'write_date')) {
                    $worksheet->write_date($i, $j++, $sessiondate, $dateformat);
                } else {
                    $worksheet->write_string($i, $j++, $sessiondate);
                }
            }
            $worksheet->write_string($i, $j++, $starttime);
            $worksheet->write_string($i, $j++, $finishtime);
            $worksheet->write_number($i, $j++, (int) $session->duration);
            $worksheet->write_string($i, $j++, $status);
            foreach ($userfields as $unused) {
                $worksheet->write_string($i, $j++, '-');
            }
            $worksheet->write_string($i, $j++, '-');
            if (!empty($coursename)) {
                $worksheet->write_string($i, $j++, $coursename);
            }
            if (!empty($activityname)) {
                $worksheet->write_string($i, $j++, $activityname);
            }
        }
    }
    return $i;
}
 public function test_update_submission()
 {
     $this->create_extra_users();
     $this->setUser($this->editingteachers[0]);
     $assign = $this->create_instance();
     $this->setUser($this->extrastudents[0]);
     $now = time();
     $submission = $assign->get_user_submission($this->extrastudents[0]->id, true);
     $assign->testable_update_submission($submission, $this->extrastudents[0]->id, true, false);
     $this->setUser($this->teachers[0]);
     // Verify the gradebook update.
     $gradinginfo = grade_get_grades($this->course->id, 'mod', 'assign', $assign->get_instance()->id, $this->extrastudents[0]->id);
     $this->assertEquals($this->extrastudents[0]->id, $gradinginfo->items[0]->grades[$this->extrastudents[0]->id]->usermodified);
     // Now verify group assignments.
     $this->setUser($this->editingteachers[0]);
     $assign = $this->create_instance(array('teamsubmission' => 1));
     $this->setUser($this->extrastudents[0]);
     $now = time();
     $submission = $assign->get_group_submission($this->extrastudents[0]->id, 0, true);
     $assign->testable_update_submission($submission, $this->extrastudents[0]->id, true, true);
     // Check that at least 2 active members and 1 suspended member of the submission group had their submission updated.
     $this->setUser($this->editingteachers[0]);
     $gradinginfo = grade_get_grades($this->course->id, 'mod', 'assign', $assign->get_instance()->id, $this->extrastudents[0]->id);
     $this->assertEquals($this->extrastudents[0]->id, $gradinginfo->items[0]->grades[$this->extrastudents[0]->id]->usermodified);
     $gradinginfo = grade_get_grades($this->course->id, 'mod', 'assign', $assign->get_instance()->id, $this->extrastudents[self::GROUP_COUNT]->id);
     $this->assertEquals($this->extrastudents[self::GROUP_COUNT]->id, $gradinginfo->items[0]->grades[$this->extrastudents[self::GROUP_COUNT]->id]->usermodified);
     $gradinginfo = grade_get_grades($this->course->id, 'mod', 'assign', $assign->get_instance()->id, $this->extrasuspendedstudents[0]->id);
     $this->assertEquals($this->extrasuspendedstudents[0]->id, $gradinginfo->items[0]->grades[$this->extrasuspendedstudents[0]->id]->usermodified);
     // Check the same with non-editing teacher and make sure submission is not updated for suspended user.
     $this->setUser($this->editingteachers[0]);
     $assign = $this->create_instance(array('teamsubmission' => 1));
     $this->setUser($this->extrastudents[1]);
     $now = time();
     $submission = $assign->get_group_submission($this->extrastudents[1]->id, 0, true);
     $assign->testable_update_submission($submission, $this->extrastudents[1]->id, true, true);
     $this->setUser($this->teachers[0]);
     $gradinginfo = grade_get_grades($this->course->id, 'mod', 'assign', $assign->get_instance()->id, $this->extrastudents[1]->id);
     $this->assertEquals($this->extrastudents[1]->id, $gradinginfo->items[0]->grades[$this->extrastudents[1]->id]->usermodified);
     $gradinginfo = grade_get_grades($this->course->id, 'mod', 'assign', $assign->get_instance()->id, $this->extrastudents[self::GROUP_COUNT + 1]->id);
     $this->assertEquals($this->extrastudents[self::GROUP_COUNT + 1]->id, $gradinginfo->items[0]->grades[$this->extrastudents[self::GROUP_COUNT + 1]->id]->usermodified);
     $gradinginfo = grade_get_grades($this->course->id, 'mod', 'assign', $assign->get_instance()->id, $this->extrasuspendedstudents[1]->id);
     $this->assertEquals($this->extrasuspendedstudents[1]->id, $gradinginfo->items[0]->grades[$this->extrasuspendedstudents[1]->id]->usermodified);
     // Now verify blind marking.
     $this->setUser($this->editingteachers[0]);
     $assign = $this->create_instance(array('blindmarking' => 1));
     $this->setUser($this->extrastudents[0]);
     $now = time();
     $submission = $assign->get_user_submission($this->extrastudents[0]->id, true);
     $assign->testable_update_submission($submission, $this->extrastudents[0]->id, true, false);
     $this->setUser($this->editingteachers[0]);
     $gradinginfo = grade_get_grades($this->course->id, 'mod', 'assign', $assign->get_instance()->id, $this->extrastudents[0]->id);
     $this->assertEquals(null, $gradinginfo->items[0]->grades[$this->extrastudents[0]->id]->datesubmitted);
 }
 /**
  * Process and save the data from the feedback form. Mostly lifted from
  * $assignmentinstance->process_feedback().
  *
  * @param object $data from the feedback form
  * @param $params
  * @return string
  */
 public function process_data($data, $params)
 {
     global $CFG, $DB;
     // TODO validate data.
     require_once $CFG->libdir . '/gradelib.php';
     require_once "{$CFG->dirroot}/repository/lib.php";
     // For save and next, we need to know the userid to save, and the userid to go
     // We use a new hidden field in the form, and set it to -1. If it's set, we use this
     // as the userid to store.
     // This seems to be something that the pop up javascript will change in the normal run of
     // things. Normally it will be the -1 default.
     if ((int) $data->saveuserid !== -1) {
         $data->userid = $data->saveuserid;
     }
     if (!empty($data->cancel)) {
         // User hit cancel button.
         return 'cancelled';
     }
     // Get DB records.
     $coursemodule = $DB->get_record('course_modules', array('id' => $params['coursemoduleid']), '*', MUST_EXIST);
     $course = $DB->get_record('course', array('id' => $coursemodule->course), '*', MUST_EXIST);
     $assignment = $DB->get_record('assignment', array('id' => $coursemodule->instance), '*', MUST_EXIST);
     /* @var stdClass[] $grading_info */
     $grading_info = grade_get_grades($coursemodule->course, 'mod', 'assignment', $assignment->id, $data->userid);
     $submission = $DB->get_record('assignment_submissions', array('assignment' => $assignment->id, 'userid' => $data->userid), '*', MUST_EXIST);
     $user = $DB->get_record('user', array('id' => $data->userid), '*', MUST_EXIST);
     $assignmentinstance = $this->get_assignment_instance($assignment, $coursemodule, $course);
     // If 'revert to draft' has been clicked, we want a confirm button only.
     // We don't want to return yet because the main use case is to comment/grade and then
     // ask the student to improve.
     if (!empty($data->unfinalize) || !empty($data->revertbutton)) {
         $this->unfinalise_submission($submission, $assignment, $coursemodule, $course);
     }
     if (!$grading_info) {
         return 'Could not retrieve grading info.';
     }
     // Check to see if grade has been locked or overridden. If so, we can't save anything.
     if ($grading_info->items[0]->grades[$data->userid]->locked || $grading_info->items[0]->grades[$data->userid]->overridden) {
         return 'Grade is locked or overridden';
     }
     // Advanced grading if enabled. From assignment_base->validate_and_process_feedback().
     // Sort out the form ready to tell it to display.
     list($mformdata, $advancedgradingwarning) = $this->get_mform_data_object($course, $assignment, $submission, $user, $coursemodule, $assignmentinstance);
     $submitform = new block_ajax_marking_assignment_form(block_ajax_marking_form_url($params), $mformdata);
     $submitform->set_data($mformdata);
     if ($submitform->is_submitted() || !empty($data->revertbutton)) {
         // Possibly redundant.
         // Form was submitted (= a submit button other than 'cancel' or 'next' has been
         // clicked).
         if (!$submitform->is_validated()) {
             return 'form not validated';
         }
         /* @var gradingform_instance $gradinginstance */
         $gradinginstance = $submitform->use_advanced_grading();
         // Preprocess advanced grading here.
         if ($gradinginstance) {
             $formdata = $submitform->get_data();
             // Create submission if it did not exist yet because we need submission->id for
             // storing the grading instance.
             $advancedgrading = $formdata->advancedgrading;
             // Calculates the gradebook grade based on the rubrics.
             $data->xgrade = $gradinginstance->submit_and_get_grade($advancedgrading, $submission->id);
         }
     }
     // Save outcomes if necessary.
     if (!empty($CFG->enableoutcomes)) {
         $assignmentinstance->process_outcomes($data->userid);
     }
     $submission = $this->save_submission($submission, $data);
     if (!$submission) {
         return 'Problem saving feedback';
     }
     // Trigger grade event to update gradebook.
     $assignment->cmidnumber = $coursemodule->id;
     assignment_update_grades($assignment, $data->userid);
     add_to_log($coursemodule->course, 'assignment', 'update grades', 'submissions.php?id=' . $coursemodule->id . '&user='******'';
 }
示例#16
0
 /**
  * Returns the information about the user's grades as they are stored in the gradebook
  *
  * The submission grade is returned for users with the capability mod/workshop:submit and the
  * assessment grade is returned for users with the capability mod/workshop:peerassess. Unless the
  * user has the capability to view hidden grades, grades must be visible to be returned. Null
  * grades are not returned. If none grade is to be returned, this method returns false.
  *
  * @param int $userid the user's id
  * @return workshop_final_grades|false
  */
 public function get_gradebook_grades($userid)
 {
     global $CFG;
     require_once $CFG->libdir . '/gradelib.php';
     if (empty($userid)) {
         throw new coding_exception('User id expected, empty value given.');
     }
     // Read data via the Gradebook API
     $gradebook = grade_get_grades($this->course->id, 'mod', 'workshop', $this->id, $userid);
     $grades = new workshop_final_grades();
     if (has_capability('mod/workshop:submit', $this->context, $userid)) {
         if (!empty($gradebook->items[0]->grades)) {
             $submissiongrade = reset($gradebook->items[0]->grades);
             if (!is_null($submissiongrade->grade)) {
                 if (!$submissiongrade->hidden or has_capability('moodle/grade:viewhidden', $this->context, $userid)) {
                     $grades->submissiongrade = $submissiongrade;
                 }
             }
         }
     }
     if (has_capability('mod/workshop:peerassess', $this->context, $userid)) {
         if (!empty($gradebook->items[1]->grades)) {
             $assessmentgrade = reset($gradebook->items[1]->grades);
             if (!is_null($assessmentgrade->grade)) {
                 if (!$assessmentgrade->hidden or has_capability('moodle/grade:viewhidden', $this->context, $userid)) {
                     $grades->assessmentgrade = $assessmentgrade;
                 }
             }
         }
     }
     if (!is_null($grades->submissiongrade) or !is_null($grades->assessmentgrade)) {
         return $grades;
     }
     return false;
 }
示例#17
0
    }
}
/// Get this user's attempts.
$attempts = game_get_user_attempts($game->id, $USER->id);
$lastfinishedattempt = end($attempts);
$unfinished = false;
if ($unfinishedattempt = game_get_user_attempt_unfinished($game->id, $USER->id)) {
    $attempts[] = $unfinishedattempt;
    $unfinished = true;
}
$numattempts = count($attempts);
/// Work out the final grade, checking whether it was overridden in the gradebook.
$mygrade = game_get_best_grade($game, $USER->id);
$mygradeoverridden = false;
$gradebookfeedback = '';
$grading_info = grade_get_grades($course->id, 'mod', 'game', $game->id, $USER->id);
if (!empty($grading_info->items)) {
    $item = $grading_info->items[0];
    if (isset($item->grades[$USER->id])) {
        $grade = $item->grades[$USER->id];
        if ($grade->overridden) {
            $mygrade = $grade->grade + 0;
            // Convert to number.
            $mygradeoverridden = true;
        }
        if (!empty($grade->str_feedback)) {
            $gradebookfeedback = $grade->str_feedback;
        }
    }
}
/// Print table with existing attempts
示例#18
0
文件: lib.php 项目: ncsu-delta/moodle
/**
 * Returns all activity in course workshops since a given time
 *
 * @param array $activities sequentially indexed array of objects
 * @param int $index
 * @param int $timestart
 * @param int $courseid
 * @param int $cmid
 * @param int $userid defaults to 0
 * @param int $groupid defaults to 0
 * @return void adds items into $activities and increases $index
 */
function workshop_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0) {
    global $CFG, $COURSE, $USER, $DB;

    if ($COURSE->id == $courseid) {
        $course = $COURSE;
    } else {
        $course = $DB->get_record('course', array('id'=>$courseid));
    }

    $modinfo = get_fast_modinfo($course);

    $cm = $modinfo->cms[$cmid];

    $params = array();
    if ($userid) {
        $userselect = "AND (author.id = :authorid OR reviewer.id = :reviewerid)";
        $params['authorid'] = $userid;
        $params['reviewerid'] = $userid;
    } else {
        $userselect = "";
    }

    if ($groupid) {
        $groupselect = "AND (authorgroupmembership.groupid = :authorgroupid OR reviewergroupmembership.groupid = :reviewergroupid)";
        $groupjoin   = "LEFT JOIN {groups_members} authorgroupmembership ON authorgroupmembership.userid = author.id
                        LEFT JOIN {groups_members} reviewergroupmembership ON reviewergroupmembership.userid = reviewer.id";
        $params['authorgroupid'] = $groupid;
        $params['reviewergroupid'] = $groupid;
    } else {
        $groupselect = "";
        $groupjoin   = "";
    }

    $params['cminstance'] = $cm->instance;
    $params['submissionmodified'] = $timestart;
    $params['assessmentmodified'] = $timestart;

    $sql = "SELECT s.id AS submissionid, s.title AS submissiontitle, s.timemodified AS submissionmodified,
                   author.id AS authorid, author.lastname AS authorlastname, author.firstname AS authorfirstname,
                   author.picture AS authorpicture, author.imagealt AS authorimagealt, author.email AS authoremail,
                   a.id AS assessmentid, a.timemodified AS assessmentmodified,
                   reviewer.id AS reviewerid, reviewer.lastname AS reviewerlastname, reviewer.firstname AS reviewerfirstname,
                   reviewer.picture AS reviewerpicture, reviewer.imagealt AS reviewerimagealt, reviewer.email AS revieweremail
              FROM {workshop_submissions} s
        INNER JOIN {workshop} w ON s.workshopid = w.id
        INNER JOIN {user} author ON s.authorid = author.id
         LEFT JOIN {workshop_assessments} a ON a.submissionid = s.id
         LEFT JOIN {user} reviewer ON a.reviewerid = reviewer.id
        $groupjoin
             WHERE w.id = :cminstance
                   AND s.example = 0
                   $userselect $groupselect
                   AND (s.timemodified > :submissionmodified OR a.timemodified > :assessmentmodified)
          ORDER BY s.timemodified ASC, a.timemodified ASC";

    $rs = $DB->get_recordset_sql($sql, $params);

    $groupmode       = groups_get_activity_groupmode($cm, $course);
    $context         = get_context_instance(CONTEXT_MODULE, $cm->id);
    $grader          = has_capability('moodle/grade:viewall', $context);
    $accessallgroups = has_capability('moodle/site:accessallgroups', $context);
    $viewfullnames   = has_capability('moodle/site:viewfullnames', $context);
    $viewauthors     = has_capability('mod/workshop:viewauthornames', $context);
    $viewreviewers   = has_capability('mod/workshop:viewreviewernames', $context);

    if (is_null($modinfo->groups)) {
        $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
    }

    $submissions = array(); // recent submissions indexed by submission id
    $assessments = array(); // recent assessments indexed by assessment id
    $users       = array();

    foreach ($rs as $activity) {

        if ($viewfullnames) {
            // remember all user names we can use later
            if (empty($users[$activity->authorid])) {
                $u = new stdclass();
                $u->id = $activity->authorid;
                $u->lastname = $activity->authorlastname;
                $u->firstname = $activity->authorfirstname;
                $u->picture = $activity->authorpicture;
                $u->imagealt = $activity->authorimagealt;
                $u->email = $activity->authoremail;
                $users[$activity->authorid] = $u;
            }
            if ($activity->reviewerid and empty($users[$activity->reviewerid])) {
                $u = new stdclass();
                $u->id = $activity->reviewerid;
                $u->lastname = $activity->reviewerlastname;
                $u->firstname = $activity->reviewerfirstname;
                $u->picture = $activity->reviewerpicture;
                $u->imagealt = $activity->reviewerimagealt;
                $u->email = $activity->revieweremail;
                $users[$activity->reviewerid] = $u;
            }
        }

        if ($activity->submissionmodified > $timestart and empty($submissions[$activity->submissionid])) {
            $s = new stdclass();
            $s->id = $activity->submissionid;
            $s->title = $activity->submissiontitle;
            $s->authorid = $activity->authorid;
            $s->timemodified = $activity->submissionmodified;
            if (has_capability('mod/workshop:viewauthornames', $context)) {
                $s->authornamevisible = true;
            } else {
                $s->authornamevisible = false;
            }

            // the following do-while wrapper allows to break from deeply nested if-statements
            do {
                if ($s->authorid === $USER->id) {
                    // own submissions always visible
                    $submissions[$activity->submissionid] = $s;
                    break;
                }

                if (has_capability('mod/workshop:viewallsubmissions', $context)) {
                    if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
                        if (isguestuser()) {
                            // shortcut - guest user does not belong into any group
                            break;
                        }

                        // this might be slow - show only submissions by users who share group with me in this cm
                        if (empty($modinfo->groups[$cm->id])) {
                            break;
                        }
                        $authorsgroups = groups_get_all_groups($course->id, $s->authorid, $cm->groupingid);
                        if (is_array($authorsgroups)) {
                            $authorsgroups = array_keys($authorsgroups);
                            $intersect = array_intersect($authorsgroups, $modinfo->groups[$cm->id]);
                            if (empty($intersect)) {
                                break;
                            } else {
                                // can see all submissions and shares a group with the author
                                $submissions[$activity->submissionid] = $s;
                                break;
                            }
                        }

                    } else {
                        // can see all submissions from all groups
                        $submissions[$activity->submissionid] = $s;
                    }
                }
            } while (0);
        }

        if ($activity->assessmentmodified > $timestart and empty($assessments[$activity->assessmentid])) {
            $a = new stdclass();
            $a->id = $activity->assessmentid;
            $a->submissionid = $activity->submissionid;
            $a->submissiontitle = $activity->submissiontitle;
            $a->reviewerid = $activity->reviewerid;
            $a->timemodified = $activity->assessmentmodified;
            if (has_capability('mod/workshop:viewreviewernames', $context)) {
                $a->reviewernamevisible = true;
            } else {
                $a->reviewernamevisible = false;
            }

            // the following do-while wrapper allows to break from deeply nested if-statements
            do {
                if ($a->reviewerid === $USER->id) {
                    // own assessments always visible
                    $assessments[$activity->assessmentid] = $a;
                    break;
                }

                if (has_capability('mod/workshop:viewallassessments', $context)) {
                    if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
                        if (isguestuser()) {
                            // shortcut - guest user does not belong into any group
                            break;
                        }

                        // this might be slow - show only submissions by users who share group with me in this cm
                        if (empty($modinfo->groups[$cm->id])) {
                            break;
                        }
                        $reviewersgroups = groups_get_all_groups($course->id, $a->reviewerid, $cm->groupingid);
                        if (is_array($reviewersgroups)) {
                            $reviewersgroups = array_keys($reviewersgroups);
                            $intersect = array_intersect($reviewersgroups, $modinfo->groups[$cm->id]);
                            if (empty($intersect)) {
                                break;
                            } else {
                                // can see all assessments and shares a group with the reviewer
                                $assessments[$activity->assessmentid] = $a;
                                break;
                            }
                        }

                    } else {
                        // can see all assessments from all groups
                        $assessments[$activity->assessmentid] = $a;
                    }
                }
            } while (0);
        }
    }
    $rs->close();

    $workshopname = format_string($cm->name, true);

    if ($grader) {
        require_once($CFG->libdir.'/gradelib.php');
        $grades = grade_get_grades($courseid, 'mod', 'workshop', $cm->instance, array_keys($users));
    }

    foreach ($submissions as $submission) {
        $tmpactivity                = new stdclass();
        $tmpactivity->type          = 'workshop';
        $tmpactivity->cmid          = $cm->id;
        $tmpactivity->name          = $workshopname;
        $tmpactivity->sectionnum    = $cm->sectionnum;
        $tmpactivity->timestamp     = $submission->timemodified;
        $tmpactivity->subtype       = 'submission';
        $tmpactivity->content       = $submission;
        if ($grader) {
            $tmpactivity->grade     = $grades->items[0]->grades[$submission->authorid]->str_long_grade;
        }
        if ($submission->authornamevisible and !empty($users[$submission->authorid])) {
            $tmpactivity->user      = $users[$submission->authorid];
        }
        $activities[$index++]       = $tmpactivity;
    }

    foreach ($assessments as $assessment) {
        $tmpactivity                = new stdclass();
        $tmpactivity->type          = 'workshop';
        $tmpactivity->cmid          = $cm->id;
        $tmpactivity->name          = $workshopname;
        $tmpactivity->sectionnum    = $cm->sectionnum;
        $tmpactivity->timestamp     = $assessment->timemodified;
        $tmpactivity->subtype       = 'assessment';
        $tmpactivity->content       = $assessment;
        if ($grader) {
            $tmpactivity->grade     = $grades->items[1]->grades[$assessment->reviewerid]->str_long_grade;
        }
        if ($assessment->reviewernamevisible and !empty($users[$assessment->reviewerid])) {
            $tmpactivity->user      = $users[$assessment->reviewerid];
        }
        $activities[$index++]       = $tmpactivity;
    }
}
示例#19
0
 * @copyright  2015 UC Regents
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
require_once dirname(dirname(dirname(__FILE__))) . '/config.php';
require_once $CFG->libdir . '/gradelib.php';
require_once $CFG->libdir . '/moodlelib.php';
$id = required_param('id', PARAM_INT);
// Course_module ID.
if ($id) {
    $cm = get_coursemodule_from_id('zoom', $id, 0, false, MUST_EXIST);
    $course = get_course($cm->course);
    $zoom = $DB->get_record('zoom', array('id' => $cm->instance), '*', MUST_EXIST);
} else {
    error('You must specify a course_module ID');
}
require_login($course, true, $cm);
$context = context_module::instance($cm->id);
$PAGE->set_context($context);
require_capability('mod/zoom:view', $context);
// Check whether user had a grade. If no, then assign full credits to him or her.
$gradelist = grade_get_grades($course->id, 'mod', 'zoom', $cm->instance, $USER->id);
// Assign full credits for user who has no grade yet, if this meeting is gradable
// (i.e. the grade type is not "None").
if (!empty($gradelist->items) && empty($gradelist->items[0]->grades[$USER->id]->grade)) {
    $grademax = $gradelist->items[0]->grademax;
    $grades = array('rawgrade' => $grademax, 'userid' => $USER->id, 'usermodified' => $USER->id, 'dategraded' => '', 'feedbackformat' => '', 'feedback' => '');
    zoom_grade_item_update($zoom, $grades);
}
// Redirect user to join zoom meeting.
$joinurl = new moodle_url($zoom->join_url, array('uname' => fullname($USER)));
redirect($joinurl);
示例#20
0
文件: lista.php 项目: jrlamb/alexBado
                $feedback = $_POST['quickgrade_comments_' . $name];
                $nota->feedback = $feedback;
                if ($n = $DB->get_record($table, array('jcode_id' => $jcode->id, 'user_id' => $name))) {
                    $nota->id = $n->id;
                    $DB->update_record($table, $nota);
                } else {
                    $DB->insert($table, $nota);
                }
            }
        }
    }
}
$t = new html_table();
jcode_add_table_row_cells($t, array('Aluno', 'Nota', 'Feedback', 'Data de Entrega', 'Arquivo', 'Resultado'));
require_once $CFG->libdir . '/gradelib.php';
$grading_info = grade_get_grades($COURSE->id, 'mod', 'jcode', $cm->instance, $USER->id);
$grade_item_grademax = $grading_info->items[0]->grademax;
foreach ($students as $student) {
    $file = $DB->get_record('jcode_files', array('jcode_id' => $jcode->id, 'user_id' => $student->id));
    //data da entrega
    $submit_date = ' - ';
    if ($file) {
        $submit_date = userdate($file->submit_date);
    }
    // Nota
    $nota = ' - ';
    if ($file && $jcode->grade > 0) {
        $nota = '<label class="accesshide" for="quickgrade_' . $student->id . '">Nota do usuário</label><input id="quickgrade_' . $student->id . '" class="quickgrade" type="text" maxlength="10" size="6"  value="' . $file->grade . '" name="quickgrade_' . $student->id . '"> / ' . $jcode->grade;
    }
    // feedback
    $feedback = ' - ';
示例#21
0
文件: lib.php 项目: nottmoo/moodle
/**
 * Prints all the records uploaded by this user
 *
 * @global object
 * @param object $course
 * @param object $user
 * @param object $mod
 * @param object $data
 */
function data_user_complete($course, $user, $mod, $data) {
    global $DB, $CFG, $OUTPUT;
    require_once("$CFG->libdir/gradelib.php");

    $grades = grade_get_grades($course->id, 'mod', 'data', $data->id, $user->id);
    if (!empty($grades->items[0]->grades)) {
        $grade = reset($grades->items[0]->grades);
        echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
        if ($grade->str_feedback) {
            echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
        }
    }

    if ($records = $DB->get_records('data_records', array('dataid'=>$data->id,'userid'=>$user->id), 'timemodified DESC')) {
        data_print_template('singletemplate', $records, $data);
    }
}
示例#22
0
 /**
  * overridden constructor keeps a reference to the assignment class that is displaying this table
  *
  * @param assign $assignment The assignment class
  * @param int $perpage how many per page
  * @param string $filter The current filter
  * @param int $rowoffset For showing a subsequent page of results
  * @param bool $quickgrading Is this table wrapped in a quickgrading form?
  */
 public function __construct(assign $assignment, $perpage, $filter, $rowoffset, $quickgrading, $downloadfilename = null)
 {
     global $CFG, $PAGE, $DB;
     parent::__construct('mod_assign_grading');
     $this->assignment = $assignment;
     foreach ($assignment->get_feedback_plugins() as $plugin) {
         if ($plugin->is_visible() && $plugin->is_enabled()) {
             foreach ($plugin->get_grading_batch_operations() as $action => $description) {
                 if (empty($this->plugingradingbatchoperations)) {
                     $this->plugingradingbatchoperations[$plugin->get_type()] = array();
                 }
                 $this->plugingradingbatchoperations[$plugin->get_type()][$action] = $description;
             }
         }
     }
     $this->perpage = $perpage;
     $this->quickgrading = $quickgrading;
     $this->output = $PAGE->get_renderer('mod_assign');
     $this->define_baseurl(new moodle_url($CFG->wwwroot . '/mod/assign/view.php', array('action' => 'grading', 'id' => $assignment->get_course_module()->id)));
     // do some business - then set the sql
     $currentgroup = groups_get_activity_group($assignment->get_course_module(), true);
     if ($rowoffset) {
         $this->rownum = $rowoffset - 1;
     }
     $users = array_keys($assignment->list_participants($currentgroup, true));
     if (count($users) == 0) {
         // insert a record that will never match to the sql is still valid.
         $users[] = -1;
     }
     $params = array();
     $params['assignmentid1'] = (int) $this->assignment->get_instance()->id;
     $params['assignmentid2'] = (int) $this->assignment->get_instance()->id;
     $fields = user_picture::fields('u') . ', ';
     $fields .= 'u.id as userid, ';
     $fields .= 's.status as status, ';
     $fields .= 's.id as submissionid, ';
     $fields .= 's.timecreated as firstsubmission, ';
     $fields .= 's.timemodified as timesubmitted, ';
     $fields .= 'g.id as gradeid, ';
     $fields .= 'g.grade as grade, ';
     $fields .= 'g.timemodified as timemarked, ';
     $fields .= 'g.timecreated as firstmarked, ';
     $fields .= 'g.mailed as mailed, ';
     $fields .= 'g.locked as locked, ';
     $fields .= 'g.extensionduedate as extensionduedate';
     $from = '{user} u LEFT JOIN {assign_submission} s ON u.id = s.userid AND s.assignment = :assignmentid1' . ' LEFT JOIN {assign_grades} g ON u.id = g.userid AND g.assignment = :assignmentid2';
     $userparams = array();
     $userindex = 0;
     list($userwhere, $userparams) = $DB->get_in_or_equal($users, SQL_PARAMS_NAMED, 'user');
     $where = 'u.id ' . $userwhere;
     $params = array_merge($params, $userparams);
     if ($filter == ASSIGN_FILTER_SUBMITTED) {
         $where .= ' AND s.timecreated > 0 ';
     }
     if ($filter == ASSIGN_FILTER_REQUIRE_GRADING) {
         $where .= ' AND (s.timemodified > g.timemodified OR (s.timemodified IS NOT NULL AND g.timemodified IS NULL))';
     }
     if (strpos($filter, ASSIGN_FILTER_SINGLE_USER) === 0) {
         $userfilter = (int) array_pop(explode('=', $filter));
         $where .= ' AND (u.id = :userid)';
         $params['userid'] = $userfilter;
     }
     $this->set_sql($fields, $from, $where, $params);
     if ($downloadfilename) {
         $this->is_downloading('csv', $downloadfilename);
     }
     $columns = array();
     $headers = array();
     // Select.
     if (!$this->is_downloading()) {
         $columns[] = 'select';
         $headers[] = get_string('select') . '<div class="selectall"><label class="accesshide" for="selectall">' . get_string('selectall') . '</label>
                 <input type="checkbox" id="selectall" name="selectall" title="' . get_string('selectall') . '"/></div>';
     }
     // User picture.
     if (!$this->assignment->is_blind_marking()) {
         if (!$this->is_downloading()) {
             $columns[] = 'picture';
             $headers[] = get_string('pictureofuser');
         } else {
             $columns[] = 'recordid';
             $headers[] = get_string('recordid', 'assign');
         }
         // Fullname.
         $columns[] = 'fullname';
         $headers[] = get_string('fullname');
     } else {
         // Record ID.
         $columns[] = 'recordid';
         $headers[] = get_string('recordid', 'assign');
     }
     // Submission status
     if ($assignment->is_any_submission_plugin_enabled()) {
         $columns[] = 'status';
         $headers[] = get_string('status');
     }
     // Team submission columns
     if ($assignment->get_instance()->teamsubmission) {
         $columns[] = 'team';
         $headers[] = get_string('submissionteam', 'assign');
         $columns[] = 'teamstatus';
         $headers[] = get_string('teamsubmissionstatus', 'assign');
     }
     // Grade
     $columns[] = 'grade';
     $headers[] = get_string('grade');
     if ($this->is_downloading()) {
         if ($this->assignment->get_instance()->grade >= 0) {
             $columns[] = 'grademax';
             $headers[] = get_string('maxgrade', 'assign');
         } else {
             // This is a custom scale.
             $columns[] = 'scale';
             $headers[] = get_string('scale', 'assign');
         }
     }
     if (!$this->is_downloading()) {
         // We have to call this column userid so we can use userid as a default sortable column.
         $columns[] = 'userid';
         $headers[] = get_string('edit');
     }
     // Submission plugins
     if ($assignment->is_any_submission_plugin_enabled()) {
         $columns[] = 'timesubmitted';
         $headers[] = get_string('lastmodifiedsubmission', 'assign');
         foreach ($this->assignment->get_submission_plugins() as $plugin) {
             if ($this->is_downloading()) {
                 if ($plugin->is_visible() && $plugin->is_enabled()) {
                     foreach ($plugin->get_editor_fields() as $field => $description) {
                         $index = 'plugin' . count($this->plugincache);
                         $this->plugincache[$index] = array($plugin, $field);
                         $columns[] = $index;
                         $headers[] = $plugin->get_name();
                     }
                 }
             } else {
                 if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->has_user_summary()) {
                     $index = 'plugin' . count($this->plugincache);
                     $this->plugincache[$index] = array($plugin);
                     $columns[] = $index;
                     $headers[] = $plugin->get_name();
                 }
             }
         }
     }
     // time marked
     $columns[] = 'timemarked';
     $headers[] = get_string('lastmodifiedgrade', 'assign');
     // Feedback plugins
     foreach ($this->assignment->get_feedback_plugins() as $plugin) {
         if ($this->is_downloading()) {
             if ($plugin->is_visible() && $plugin->is_enabled()) {
                 foreach ($plugin->get_editor_fields() as $field => $description) {
                     $index = 'plugin' . count($this->plugincache);
                     $this->plugincache[$index] = array($plugin, $field);
                     $columns[] = $index;
                     $headers[] = $description;
                 }
             }
         } else {
             if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->has_user_summary()) {
                 $index = 'plugin' . count($this->plugincache);
                 $this->plugincache[$index] = array($plugin);
                 $columns[] = $index;
                 $headers[] = $plugin->get_name();
             }
         }
     }
     // Exclude 'Final grade' column in downloaded grading worksheets.
     if (!$this->is_downloading()) {
         // Final grade.
         $columns[] = 'finalgrade';
         $headers[] = get_string('finalgrade', 'grades');
     }
     // load the grading info for all users
     $this->gradinginfo = grade_get_grades($this->assignment->get_course()->id, 'mod', 'assign', $this->assignment->get_instance()->id, $users);
     $this->hasgrantextension = has_capability('mod/assign:grantextension', $this->assignment->get_context());
     if (!empty($CFG->enableoutcomes) && !empty($this->gradinginfo->outcomes)) {
         $columns[] = 'outcomes';
         $headers[] = get_string('outcomes', 'grades');
     }
     // set the columns
     $this->define_columns($columns);
     $this->define_headers($headers);
     // We require at least one unique column for the sort.
     $this->sortable(true, 'userid');
     $this->no_sorting('recordid');
     $this->no_sorting('finalgrade');
     $this->no_sorting('userid');
     $this->no_sorting('select');
     $this->no_sorting('outcomes');
     if ($assignment->get_instance()->teamsubmission) {
         $this->no_sorting('team');
         $this->no_sorting('teamstatus');
     }
     $plugincolumnindex = 0;
     foreach ($this->assignment->get_submission_plugins() as $plugin) {
         if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->has_user_summary()) {
             $submissionpluginindex = 'plugin' . $plugincolumnindex++;
             $this->no_sorting($submissionpluginindex);
         }
     }
     foreach ($this->assignment->get_feedback_plugins() as $plugin) {
         if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->has_user_summary()) {
             $feedbackpluginindex = 'plugin' . $plugincolumnindex++;
             $this->no_sorting($feedbackpluginindex);
         }
     }
     // When there is no data we still want the column headers printed in the csv file.
     if ($this->is_downloading()) {
         $this->start_output();
     }
 }
示例#23
0
/**
 * Prepare to print an activity grade.
 *
 * @param stdClass $course
 * @param int $moduleid
 * @return mixed
 */
function certificate_print_mod_grade($course, $moduleid)
{
    global $USER, $DB;
    $cm = $DB->get_record('course_modules', array('id' => $moduleid));
    $module = $DB->get_record('modules', array('id' => $cm->module));
    if ($grade_item = grade_get_grades($course->id, 'mod', $module->name, $cm->instance, $USER->id)) {
        $item = new grade_item();
        $itemproperties = reset($grade_item->items);
        foreach ($itemproperties as $key => $value) {
            $item->{$key} = $value;
        }
        $modinfo = new stdClass();
        $modinfo->name = utf8_decode($DB->get_field($module->name, 'name', array('id' => $cm->instance)));
        $grade = $item->grades[$USER->id]->grade;
        $item->gradetype = GRADE_TYPE_VALUE;
        $item->courseid = $course->id;
        $modinfo->points = grade_format_gradevalue($grade, $item, true, GRADE_DISPLAY_TYPE_REAL, $decimals = 2);
        $modinfo->percentage = grade_format_gradevalue($grade, $item, true, GRADE_DISPLAY_TYPE_PERCENTAGE, $decimals = 2);
        $modinfo->letter = grade_format_gradevalue($grade, $item, true, GRADE_DISPLAY_TYPE_LETTER, $decimals = 0);
        if ($grade) {
            $modinfo->dategraded = $item->grades[$USER->id]->dategraded;
        } else {
            $modinfo->dategraded = time();
        }
        return $modinfo;
    }
    return false;
}
示例#24
0
    $users_key = array_keys($students);
    $vtAction = new vtAction($session->getEmail(), $params);
    $resource = $vtAction->getResource($resource_id);
    if ($resource === false) {
        //problem to get the grade
        redirection($redirectionUrl . '&error=problem_vt');
    }
    $options = $resource->getOptions();
    $isAverageMethodAvailable = true;
    $arrayAverageLength = $vtAction->getAverageMessageLengthPerUser($resource_id);
    if ($arrayAverageLength == "not_implemented") {
        $isAverageMethodAvailable = false;
    }
    $arrayNbMessage = $vtAction->getNbMessagePerUser($resource_id);
    $urlParams = 'resource_id=' . $resource_id . '&type=board&id=' . $params["enc_course_id"] . '&' . voiceboard_get_url_params($params["enc_course_id"]) . '&time=' . $session->timeOfLoad;
    $previousGrade = grade_get_grades($params["enc_course_id"], "mod", "voiceboard", $params["gradeId"], $users_key);
    if (!empty($previousGrade) && isset($previousGrade->items[0])) {
        //extract only the grade information from the object that we get
        //we take the items 0 because we ask only for one grade item
        $previousGrade = $previousGrade->items[0]->grades;
    }
    ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Voice Board grading page</title>
    <link rel="STYLESHEET" href="css/StyleSheet.css" type="text/css" />
    <!--[if lt IE 7]>
            <script type="text/javascript" src="lib/web/js/lib/iepngfix/iepngfix_tilebg.js"></script>
示例#25
0
文件: lib.php 项目: nuckey/moodle
    function process_outcomes($userid) {
        global $CFG, $USER;

        if (empty($CFG->enableoutcomes)) {
            return;
        }

        require_once($CFG->libdir.'/gradelib.php');

        if (!$formdata = data_submitted() or !confirm_sesskey()) {
            return;
        }

        $data = array();
        $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);

        if (!empty($grading_info->outcomes)) {
            foreach($grading_info->outcomes as $n=>$old) {
                $name = 'outcome_'.$n;
                if (isset($formdata->{$name}[$userid]) and $old->grades[$userid]->grade != $formdata->{$name}[$userid]) {
                    $data[$n] = $formdata->{$name}[$userid];
                }
            }
        }
        if (count($data) > 0) {
            grade_update_outcomes('mod/assignment', $this->course->id, 'mod', 'assignment', $this->assignment->id, $userid, $data);
        }

    }
示例#26
0
function attendance_user_outline($course, $user, $mod, $attendance)
{
    global $CFG;
    require_once dirname(__FILE__) . '/locallib.php';
    require_once $CFG->libdir . '/gradelib.php';
    $grades = grade_get_grades($course->id, 'mod', 'attendance', $attendance->id, $user->id);
    $result = new stdClass();
    if (!empty($grades->items[0]->grades)) {
        $grade = reset($grades->items[0]->grades);
        $result->time = $grade->dategraded;
    } else {
        $result->time = 0;
    }
    if (has_capability('mod/attendance:canbelisted', $mod->context, $user->id)) {
        $statuses = att_get_statuses($attendance->id);
        $grade = att_get_user_grade(att_get_user_statuses_stat($attendance->id, $course->startdate, $user->id, $mod), $statuses);
        $maxgrade = att_get_user_max_grade(att_get_user_taken_sessions_count($attendance->id, $course->startdate, $user->id, $mod), $statuses);
        $result->info = $grade . ' / ' . $maxgrade;
    }
    return $result;
}
示例#27
0
文件: view.php 项目: numbas/moodle
// Work out the final grade, checking whether it was overridden in the gradebook.
if (!$canpreview) {
    $mygrade = quiz_get_best_grade($quiz, $USER->id);
} else if ($lastfinishedattempt) {
    // Users who can preview the quiz don't get a proper grade, so work out a
    // plausible value to display instead, so the page looks right.
    $mygrade = quiz_rescale_grade($lastfinishedattempt->sumgrades, $quiz, false);
} else {
    $mygrade = null;
}

$mygradeoverridden = false;
$gradebookfeedback = '';

$grading_info = grade_get_grades($course->id, 'mod', 'quiz', $quiz->id, $USER->id);
if (!empty($grading_info->items)) {
    $item = $grading_info->items[0];
    if (isset($item->grades[$USER->id])) {
        $grade = $item->grades[$USER->id];

        if ($grade->overridden) {
            $mygrade = $grade->grade + 0; // Convert to number.
            $mygradeoverridden = true;
        }
        if (!empty($grade->str_feedback)) {
            $gradebookfeedback = $grade->str_feedback;
        }
    }
}
示例#28
0
文件: lib.php 项目: ruddj/moodle
/**
 * Print a detailed representation of what a user has done with
 * a given particular instance of this module, for user activity reports.
 *
 * @global stdClass
 * @global object
 * @param object $course
 * @param object $user
 * @param object $mod
 * @param object $scorm
 * @return boolean
 */
function scorm_user_complete($course, $user, $mod, $scorm) {
    global $CFG, $DB, $OUTPUT;
    require_once("$CFG->libdir/gradelib.php");

    $liststyle = 'structlist';
    $now = time();
    $firstmodify = $now;
    $lastmodify = 0;
    $sometoreport = false;
    $report = '';

    // First Access and Last Access dates for SCOs.
    require_once($CFG->dirroot.'/mod/scorm/locallib.php');
    $timetracks = scorm_get_sco_runtime($scorm->id, false, $user->id);
    $firstmodify = $timetracks->start;
    $lastmodify = $timetracks->finish;

    $grades = grade_get_grades($course->id, 'mod', 'scorm', $scorm->id, $user->id);
    if (!empty($grades->items[0]->grades)) {
        $grade = reset($grades->items[0]->grades);
        echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
        if ($grade->str_feedback) {
            echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
        }
    }

    if ($orgs = $DB->get_records_select('scorm_scoes', 'scorm = ? AND '.
                                         $DB->sql_isempty('scorm_scoes', 'launch', false, true).' AND '.
                                         $DB->sql_isempty('scorm_scoes', 'organization', false, false),
                                         array($scorm->id), 'sortorder, id', 'id, identifier, title')) {
        if (count($orgs) <= 1) {
            unset($orgs);
            $orgs = array();
            $org = new stdClass();
            $org->identifier = '';
            $orgs[] = $org;
        }
        $report .= html_writer::start_div('mod-scorm');
        foreach ($orgs as $org) {
            $conditions = array();
            $currentorg = '';
            if (!empty($org->identifier)) {
                $report .= html_writer::div($org->title, 'orgtitle');
                $currentorg = $org->identifier;
                $conditions['organization'] = $currentorg;
            }
            $report .= html_writer::start_tag('ul', array('id' => '0', 'class' => $liststyle));
                $conditions['scorm'] = $scorm->id;
            if ($scoes = $DB->get_records('scorm_scoes', $conditions, "sortorder, id")) {
                // Drop keys so that we can access array sequentially.
                $scoes = array_values($scoes);
                $level = 0;
                $sublist = 1;
                $parents[$level] = '/';
                foreach ($scoes as $pos => $sco) {
                    if ($parents[$level] != $sco->parent) {
                        if ($level > 0 && $parents[$level - 1] == $sco->parent) {
                            $report .= html_writer::end_tag('ul').html_writer::end_tag('li');
                            $level--;
                        } else {
                            $i = $level;
                            $closelist = '';
                            while (($i > 0) && ($parents[$level] != $sco->parent)) {
                                $closelist .= html_writer::end_tag('ul').html_writer::end_tag('li');
                                $i--;
                            }
                            if (($i == 0) && ($sco->parent != $currentorg)) {
                                $report .= html_writer::start_tag('li');
                                $report .= html_writer::start_tag('ul', array('id' => $sublist, 'class' => $liststyle));
                                $level++;
                            } else {
                                $report .= $closelist;
                                $level = $i;
                            }
                            $parents[$level] = $sco->parent;
                        }
                    }
                    $report .= html_writer::start_tag('li');
                    if (isset($scoes[$pos + 1])) {
                        $nextsco = $scoes[$pos + 1];
                    } else {
                        $nextsco = false;
                    }
                    if (($nextsco !== false) && ($sco->parent != $nextsco->parent) &&
                            (($level == 0) || (($level > 0) && ($nextsco->parent == $sco->identifier)))) {
                        $sublist++;
                    } else {
                        $report .= $OUTPUT->spacer(array("height" => "12", "width" => "13"));
                    }

                    if ($sco->launch) {
                        $score = '';
                        $totaltime = '';
                        if ($usertrack = scorm_get_tracks($sco->id, $user->id)) {
                            if ($usertrack->status == '') {
                                $usertrack->status = 'notattempted';
                            }
                            $strstatus = get_string($usertrack->status, 'scorm');
                            $report .= html_writer::img($OUTPUT->pix_url($usertrack->status, 'scorm'),
                                                        $strstatus, array('title' => $strstatus));
                        } else {
                            if ($sco->scormtype == 'sco') {
                                $report .= html_writer::img($OUTPUT->pix_url('notattempted', 'scorm'),
                                                            get_string('notattempted', 'scorm'),
                                                            array('title' => get_string('notattempted', 'scorm')));
                            } else {
                                $report .= html_writer::img($OUTPUT->pix_url('asset', 'scorm'), get_string('asset', 'scorm'),
                                                            array('title' => get_string('asset', 'scorm')));
                            }
                        }
                        $report .= "&nbsp;$sco->title $score$totaltime".html_writer::end_tag('li');
                        if ($usertrack !== false) {
                            $sometoreport = true;
                            $report .= html_writer::start_tag('li').html_writer::start_tag('ul', array('class' => $liststyle));
                            foreach ($usertrack as $element => $value) {
                                if (substr($element, 0, 3) == 'cmi') {
                                    $report .= html_writer::tag('li', $element.' => '.s($value));
                                }
                            }
                            $report .= html_writer::end_tag('ul').html_writer::end_tag('li');
                        }
                    } else {
                        $report .= "&nbsp;$sco->title".html_writer::end_tag('li');
                    }
                }
                for ($i = 0; $i < $level; $i++) {
                    $report .= html_writer::end_tag('ul').html_writer::end_tag('li');
                }
            }
            $report .= html_writer::end_tag('ul').html_writer::empty_tag('br');
        }
        $report .= html_writer::end_div();
    }
    if ($sometoreport) {
        if ($firstmodify < $now) {
            $timeago = format_time($now - $firstmodify);
            echo get_string('firstaccess', 'scorm').': '.userdate($firstmodify).' ('.$timeago.")".html_writer::empty_tag('br');
        }
        if ($lastmodify > 0) {
            $timeago = format_time($now - $lastmodify);
            echo get_string('lastaccess', 'scorm').': '.userdate($lastmodify).' ('.$timeago.")".html_writer::empty_tag('br');
        }
        echo get_string('report', 'scorm').":".html_writer::empty_tag('br');
        echo $report;
    } else {
        print_string('noactivity', 'scorm');
    }

    return true;
}
示例#29
0
/**
 * @global object
 * @global object
 * @param object $coure
 * @param object $user
 * @param object $mod
 * @param object $forum
 */
function forum_user_complete($course, $user, $mod, $forum) {
    global $CFG,$USER, $OUTPUT;
    require_once("$CFG->libdir/gradelib.php");

    $grades = grade_get_grades($course->id, 'mod', 'forum', $forum->id, $user->id);
    if (!empty($grades->items[0]->grades)) {
        $grade = reset($grades->items[0]->grades);
        echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
        if ($grade->str_feedback) {
            echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
        }
    }

    if ($posts = forum_get_user_posts($forum->id, $user->id)) {

        if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $course->id)) {
            print_error('invalidcoursemodule');
        }
        $discussions = forum_get_user_involved_discussions($forum->id, $user->id);

        foreach ($posts as $post) {
            if (!isset($discussions[$post->discussion])) {
                continue;
            }
            $discussion = $discussions[$post->discussion];

            forum_print_post($post, $discussion, $forum, $cm, $course, false, false, false);
        }
    } else {
        echo "<p>".get_string("noposts", "forum")."</p>";
    }
}
示例#30
0
/**
 * Returns a small object with summary information about what a
 * user has done with a given particular instance of this module
 * Used for user activity reports.
 *
 * $return->time = the time they did it
 * $return->info = a short text description
 *
 * @param stdClass $course The course record
 * @param stdClass $user The user record
 * @param cm_info|stdClass $mod The course module info object or record
 * @param stdClass $content The content instance record
 * @return stdClass|null
 */
function content_user_outline($course, $user, $mod, $content)
{
    /*$return = new stdClass();
      $return->time = 0;
      $return->info = '';
      return $return; */
    global $CFG;
    require_once "{$CFG->libdir}/gradelib.php";
    $grades = grade_get_grades($course->id, 'mod', 'content', $content->id, $user->id);
    $return = new stdClass();
    if (empty($grades->items[0]->grades)) {
        $return->info = get_string("no") . " " . get_string("attempts", "content");
    } else {
        $grade = reset($grades->items[0]->grades);
        $return->info = get_string("grade") . ': ' . $grade->str_long_grade;
        //datesubmitted == time created. dategraded == time modified or time overridden
        //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
        //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
        if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
            $return->time = $grade->dategraded;
        } else {
            $return->time = $grade->datesubmitted;
        }
    }
    return $return;
}