public function print_grades() { global $CFG; $export_tracking = $this->track_exports(); $strgrades = get_string('grades'); switch ($this->separator) { case 'comma': $separator = ","; break; case 'tab': default: $separator = "\t"; } /// Print header to force download if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431 @header('Cache-Control: max-age=10'); @header('Expires: ' . gmdate('D, d M Y H:i:s', 0) . ' GMT'); @header('Pragma: '); } else { //normal http - prevent caching at all cost @header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0'); @header('Expires: ' . gmdate('D, d M Y H:i:s', 0) . ' GMT'); @header('Pragma: no-cache'); } header("Content-Type: application/download\n"); $downloadfilename = clean_filename("{$this->course->shortname} {$strgrades}"); header("Content-Disposition: attachment; filename=\"{$downloadfilename}.txt\""); /// Print names of all the fields echo get_string("firstname") . $separator . get_string("lastname") . $separator . get_string("idnumber") . $separator . get_string("institution") . $separator . get_string("department") . $separator . get_string("email"); foreach ($this->columns as $grade_item) { echo $separator . $this->format_column_name($grade_item); /// add a feedback column if ($this->export_feedback) { echo $separator . $this->format_column_name($grade_item, true); } } echo "\n"; /// Print all the lines of data. $geub = new grade_export_update_buffer(); $gui = new graded_users_iterator($this->course, $this->columns, $this->groupid); $gui->init(); while ($userdata = $gui->next_user()) { $user = $userdata->user; echo $user->firstname . $separator . $user->lastname . $separator . $user->idnumber . $separator . $user->institution . $separator . $user->department . $separator . $user->email; foreach ($userdata->grades as $itemid => $grade) { if ($export_tracking) { $status = $geub->track($grade); } echo $separator . $this->format_grade($grade); if ($this->export_feedback) { echo $separator . $this->format_feedback($userdata->feedbacks[$itemid]); } } echo "\n"; } $gui->close(); $geub->close(); exit; }
public function print_grades() { global $CFG; $export_tracking = $this->track_exports(); $strgrades = get_string('grades'); $profilefields = grade_helper::get_user_profile_fields($this->course->id, $this->usercustomfields); $shortname = format_string($this->course->shortname, true, array('context' => context_course::instance($this->course->id))); $downloadfilename = clean_filename("{$shortname} {$strgrades}"); $csvexport = new csv_export_writer($this->separator); $csvexport->set_filename($downloadfilename); // Print names of all the fields $exporttitle = array(); foreach ($profilefields as $field) { $exporttitle[] = $field->fullname; } if (!$this->onlyactive) { $exporttitle[] = get_string("suspended"); } // Add a feedback column. foreach ($this->columns as $grade_item) { $exporttitle[] = $this->format_column_name($grade_item); if ($this->export_feedback) { $exporttitle[] = $this->format_column_name($grade_item, true); } } $csvexport->add_data($exporttitle); // Print all the lines of data. $geub = new grade_export_update_buffer(); $gui = new graded_users_iterator($this->course, $this->columns, $this->groupid); $gui->require_active_enrolment($this->onlyactive); $gui->allow_user_custom_fields($this->usercustomfields); $gui->init(); while ($userdata = $gui->next_user()) { $exportdata = array(); $user = $userdata->user; foreach ($profilefields as $field) { $fieldvalue = grade_helper::get_user_field_value($user, $field); $exportdata[] = $fieldvalue; } if (!$this->onlyactive) { $issuspended = $user->suspendedenrolment ? get_string('yes') : ''; $exportdata[] = $issuspended; } foreach ($userdata->grades as $itemid => $grade) { if ($export_tracking) { $status = $geub->track($grade); } $exportdata[] = $this->format_grade($grade); if ($this->export_feedback) { $exportdata[] = $this->format_feedback($userdata->feedbacks[$itemid]); } } $csvexport->add_data($exportdata); } $gui->close(); $geub->close(); $csvexport->download_file(); exit; }
/** * Get the report data * @param stdClass $course course object * @param stdClass $context context object * @param stdClass $user user object (it can be null for all the users) * @param int $userid the user to retrieve data from, 0 for all * @param int $groupid the group id to filter * @param bool $tabledata whether to get the table data (true) or the gradeitemdata * @return array data and possible warnings * @since Moodle 3.2 */ protected static function get_report_data($course, $context, $user, $userid, $groupid, $tabledata = true) { global $CFG; $warnings = array(); // Require files here to save some memory in case validation fails. require_once $CFG->dirroot . '/group/lib.php'; require_once $CFG->libdir . '/gradelib.php'; require_once $CFG->dirroot . '/grade/lib.php'; require_once $CFG->dirroot . '/grade/report/user/lib.php'; // Force regrade to update items marked as 'needupdate'. grade_regrade_final_grades($course->id); $gpr = new grade_plugin_return(array('type' => 'report', 'plugin' => 'user', 'courseid' => $course->id, 'userid' => $userid)); $reportdata = array(); // Just one user. if ($user) { $report = new grade_report_user($course->id, $gpr, $context, $userid); $report->fill_table(); $gradeuserdata = array('courseid' => $course->id, 'userid' => $user->id, 'userfullname' => fullname($user), 'maxdepth' => $report->maxdepth); if ($tabledata) { $gradeuserdata['tabledata'] = $report->tabledata; } else { $gradeuserdata['gradeitems'] = $report->gradeitemsdata; } $reportdata[] = $gradeuserdata; } else { $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol); $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol); $showonlyactiveenrol = $showonlyactiveenrol || !has_capability('moodle/course:viewsuspendedusers', $context); $gui = new graded_users_iterator($course, null, $groupid); $gui->require_active_enrolment($showonlyactiveenrol); $gui->init(); while ($userdata = $gui->next_user()) { $currentuser = $userdata->user; $report = new grade_report_user($course->id, $gpr, $context, $currentuser->id); $report->fill_table(); $gradeuserdata = array('courseid' => $course->id, 'userid' => $currentuser->id, 'userfullname' => fullname($currentuser), 'maxdepth' => $report->maxdepth); if ($tabledata) { $gradeuserdata['tabledata'] = $report->tabledata; } else { $gradeuserdata['gradeitems'] = $report->gradeitemsdata; } $reportdata[] = $gradeuserdata; } $gui->close(); } return array($reportdata, $warnings); }
/** * To be implemented by child classes * @param boolean $feedback * @param boolean $publish Whether to output directly, or send as a file * @return string */ public function print_grades($feedback = false) { global $CFG; require_once $CFG->libdir . '/filelib.php'; $export_tracking = $this->track_exports(); $strgrades = get_string('grades'); /// Calculate file name $shortname = format_string($this->course->shortname, true, array('context' => context_course::instance($this->course->id))); $downloadfilename = clean_filename("{$shortname} {$strgrades}.xml"); make_temp_directory('gradeexport'); $tempfilename = $CFG->tempdir . '/gradeexport/' . md5(sesskey() . microtime() . $downloadfilename); if (!($handle = fopen($tempfilename, 'w+b'))) { print_error('cannotcreatetempdir'); } /// time stamp to ensure uniqueness of batch export fwrite($handle, '<results batch="xml_export_' . time() . '">' . "\n"); $export_buffer = array(); $geub = new grade_export_update_buffer(); $gui = new graded_users_iterator($this->course, $this->columns, $this->groupid); $gui->require_active_enrolment($this->onlyactive); $gui->init(); while ($userdata = $gui->next_user()) { $user = $userdata->user; if (empty($user->idnumber)) { //id number must exist otherwise we cant match up students when importing continue; } // studentgrades[] index should match with corresponding $index foreach ($userdata->grades as $itemid => $grade) { $grade_item = $this->grade_items[$itemid]; $grade->grade_item =& $grade_item; $gradestr = $this->format_grade($grade, $this->displaytype); // no formating for now // MDL-11669, skip exported grades or bad grades (if setting says so) if ($export_tracking) { $status = $geub->track($grade); if ($this->updatedgradesonly && ($status == 'nochange' || $status == 'unknown')) { continue; } } fwrite($handle, "\t<result>\n"); if ($export_tracking) { fwrite($handle, "\t\t<state>{$status}</state>\n"); } // only need id number fwrite($handle, "\t\t<assignment>{$grade_item->idnumber}</assignment>\n"); // this column should be customizable to use either student id, idnumber, uesrname or email. fwrite($handle, "\t\t<student>{$user->idnumber}</student>\n"); fwrite($handle, "\t\t<score>{$gradestr}</score>\n"); if ($this->export_feedback) { $feedbackstr = $this->format_feedback($userdata->feedbacks[$itemid]); fwrite($handle, "\t\t<feedback>{$feedbackstr}</feedback>\n"); } fwrite($handle, "\t</result>\n"); } } fwrite($handle, "</results>"); fclose($handle); $gui->close(); $geub->close(); if (defined('BEHAT_SITE_RUNNING')) { // If behat is running, we cannot test the output if we force a file download. include $tempfilename; } else { @header("Content-type: text/xml; charset=UTF-8"); send_temp_file($tempfilename, $downloadfilename, false); } }
/** * To be implemented by child classes * @param boolean $feedback * @param boolean $publish Whether to output directly, or send as a file * @return string */ function print_grades($feedback = false) { global $CFG; require_once $CFG->libdir . '/filelib.php'; $export_tracking = $this->track_exports(); $strgrades = get_string('grades'); /// Calculate file name $downloadfilename = clean_filename("{$this->course->shortname} {$strgrades}.xml"); make_upload_directory('temp/gradeexport', false); $tempfilename = $CFG->dataroot . '/temp/gradeexport/' . md5(sesskey() . microtime() . $downloadfilename); if (!($handle = fopen($tempfilename, 'w+b'))) { error("Could not create a temporary file into which to dump the XML data."); return false; } /// time stamp to ensure uniqueness of batch export fwrite($handle, '<results batch="xml_export_' . time() . '">' . "\n"); $export_buffer = array(); $geub = new grade_export_update_buffer(); $gui = new graded_users_iterator($this->course, $this->columns, $this->groupid); $gui->init(); while ($userdata = $gui->next_user()) { $user = $userdata->user; if (empty($user->idnumber)) { //id number must exist continue; } // studentgrades[] index should match with corresponding $index foreach ($userdata->grades as $itemid => $grade) { $grade_item = $this->grade_items[$itemid]; $grade->grade_item =& $grade_item; $gradestr = $this->format_grade($grade); // no formating for now // MDL-11669, skip exported grades or bad grades (if setting says so) if ($export_tracking) { $status = $geub->track($grade); if ($this->updatedgradesonly && ($status == 'nochange' || $status == 'unknown')) { continue; } } fwrite($handle, "\t<result>\n"); if ($export_tracking) { fwrite($handle, "\t\t<state>{$status}</state>\n"); } // only need id number fwrite($handle, "\t\t<assignment>{$grade_item->idnumber}</assignment>\n"); // this column should be customizable to use either student id, idnumber, uesrname or email. fwrite($handle, "\t\t<student>{$user->idnumber}</student>\n"); fwrite($handle, "\t\t<score>{$gradestr}</score>\n"); if ($this->export_feedback) { $feedbackstr = $this->format_feedback($userdata->feedbacks[$itemid]); fwrite($handle, "\t\t<feedback>{$feedbackstr}</feedback>\n"); } fwrite($handle, "\t</result>\n"); } } fwrite($handle, "</results>"); fclose($handle); $gui->close(); $geub->close(); if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431 @header('Cache-Control: max-age=10'); @header('Expires: ' . gmdate('D, d M Y H:i:s', 0) . ' GMT'); @header('Pragma: '); } else { //normal http - prevent caching at all cost @header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0'); @header('Expires: ' . gmdate('D, d M Y H:i:s', 0) . ' GMT'); @header('Pragma: no-cache'); } header("Content-type: text/xml; charset=UTF-8"); header("Content-Disposition: attachment; filename=\"{$downloadfilename}\""); readfile_chunked($tempfilename); @unlink($tempfilename); exit; }
function cm_synchronize_moodle_class_grades() { global $CFG, $CURMAN; require_once $CFG->dirroot . '/grade/lib.php'; if ($moodleclasses = moodle_get_classes()) { $timenow = time(); foreach ($moodleclasses as $class) { $cmclass = new cmclass($class->classid); $context = get_context_instance(CONTEXT_COURSE, $class->moodlecourseid); $moodlecourse = $CURMAN->db->get_record('course', 'id', $class->moodlecourseid); // Get CM enrolment information (based on Moodle enrolments) // IMPORTANT: this record set must be sorted using the Moodle // user ID $relatedcontextsstring = get_related_contexts_string($context); $sql = "SELECT DISTINCT u.id AS muid, u.username, cu.id AS cmid, stu.*\n FROM {$CURMAN->db->prefix_table('user')} u\n JOIN {$CURMAN->db->prefix_table('role_assignments')} ra ON u.id = ra.userid\n LEFT JOIN {$CURMAN->db->prefix_table(USRTABLE)} cu ON cu.idnumber = u.idnumber\n LEFT JOIN {$CURMAN->db->prefix_table(STUTABLE)} stu on stu.userid = cu.id AND stu.classid = {$cmclass->id}\n WHERE ra.roleid in ({$CFG->gradebookroles})\n AND ra.contextid {$relatedcontextsstring}\n ORDER BY muid ASC"; $causers = get_recordset_sql($sql); if (empty($causers)) { // nothing to see here, move on continue; } /// Get CM completion elements and related Moodle grade items $comp_elements = array(); $gis = array(); if (isset($cmclass->course) && get_class($cmclass->course) == 'course' && ($elements = $cmclass->course->get_completion_elements())) { foreach ($elements as $element) { // It looks like Moodle actually stores the "slashes" on the idnumber field in the grade_items // table so we need to addslashes twice to this value if it needs them. =( - ELIS-1830 $idnumber = addslashes($element->idnumber); if ($idnumber != $element->idnumber) { $idnumber = addslashes($idnumber); } if ($gi = get_record('grade_items', 'courseid', $class->moodlecourseid, 'idnumber', $idnumber)) { $gis[$gi->id] = $gi; $comp_elements[$gi->id] = $element; } } } // add grade item for the overall course grade $coursegradeitem = grade_item::fetch_course_item($moodlecourse->id); $gis[$coursegradeitem->id] = $coursegradeitem; if ($coursegradeitem->grademax == 0) { // no maximum course grade, so we can't calculate the // student's grade continue; } if (!empty($elements)) { // get current completion element grades if we have any // IMPORTANT: this record set must be sorted using the Moodle // user ID $sql = "SELECT grades.*, mu.id AS muid\n FROM {$CURMAN->db->prefix_table(GRDTABLE)} grades\n JOIN {$CURMAN->db->prefix_table(USRTABLE)} cu ON grades.userid = cu.id\n JOIN {$CURMAN->db->prefix_table('user')} mu ON cu.idnumber = mu.idnumber\n WHERE grades.classid = {$cmclass->id}\n ORDER BY mu.id"; $allcompelemgrades = get_recordset_sql($sql); $last_rec = null; // will be used to store the last completion // element that we fetched from the // previous iteration (which may belong // to the current user) } // get the Moodle course grades // IMPORTANT: this iterator must be sorted using the Moodle // user ID $gradedusers = new graded_users_iterator($moodlecourse, $gis, 0, 'id', 'ASC', null); $gradedusers->init(); // only create a new enrolment record if there is only one CM // class attached to this Moodle course $doenrol = $CURMAN->db->count_records(CLSMDLTABLE, 'moodlecourseid', $class->moodlecourseid) == 1; // main loop -- go through the student grades while (($sturec = rs_fetch_next_record($causers)) && ($stugrades = $gradedusers->next_user())) { // skip user records that don't match up // (this works since both sets are sorted by Moodle user ID) // (in theory, we shouldn't need this, but just in case...) while ($sturec && $sturec->muid < $stugrades->user->id) { $sturec = rs_fetch_next_record($causers); } if (!$sturec) { break; } while ($stugrades && $stugrades->user->id < $sturec->muid) { $stugrades = $gradedusers->next_user(); } if (!$stugrades) { break; } /// If the user doesn't exist in CM, skip it -- should we flag it? if (empty($sturec->cmid)) { mtrace("No user record for Moodle user id: {$sturec->muid}: {$sturec->username}<br />\n"); continue; } $cmuserid = $sturec->cmid; /// If no enrolment record in ELIS, then let's set one. if (empty($sturec->id)) { if (!$doenrol) { continue; } $sturec->classid = $class->classid; $sturec->userid = $cmuserid; /// Enrolment time will be the earliest found role assignment for this user. $enroltime = get_field('role_assignments', 'MIN(timestart) as enroltime', 'contextid', $context->id, 'userid', $sturec->muid); $sturec->enrolmenttime = !empty($enroltime) ? $enroltime : $timenow; $sturec->completetime = 0; $sturec->endtime = 0; $sturec->completestatusid = STUSTATUS_NOTCOMPLETE; $sturec->grade = 0; $sturec->credits = 0; $sturec->locked = 0; $sturec->id = $CURMAN->db->insert_record(STUTABLE, $sturec); } /// Handle the course grade if (isset($stugrades->grades[$coursegradeitem->id]->finalgrade)) { /// Set the course grade if there is one and it's not locked. $usergradeinfo = $stugrades->grades[$coursegradeitem->id]; if (!$sturec->locked && !is_null($usergradeinfo->finalgrade)) { // clone of student record, to see if we actually change anything $old_sturec = clone $sturec; $grade = $usergradeinfo->finalgrade / $coursegradeitem->grademax * 100.0; $sturec->grade = $grade; /// Update completion status if all that is required is a course grade. if (empty($elements)) { if ($cmclass->course->completion_grade <= $sturec->grade) { $sturec->completetime = $usergradeinfo->get_dategraded(); $sturec->completestatusid = STUSTATUS_PASSED; $sturec->credits = floatval($cmclass->course->credits); } else { $sturec->completetime = 0; $sturec->completestatusid = STUSTATUS_NOTCOMPLETE; $sturec->credits = 0; } } else { $sturec->completetime = 0; $sturec->completestatusid = STUSTATUS_NOTCOMPLETE; $sturec->credits = 0; } // only update if we actually changed anything // (exception: if the completetime gets smaller, // it's probably because $usergradeinfo->get_dategraded() // returned an empty value, so ignore that change) if ($old_sturec->grade != $sturec->grade || $old_sturec->completetime < $sturec->completetime || $old_sturec->completestatusid != $sturec->completestatusid || $old_sturec->credits != $sturec->credits) { if ($sturec->completestatusid == STUSTATUS_PASSED && empty($sturec->completetime)) { // make sure we have a valid complete time, if we passed $sturec->completetime = $timenow; } $CURMAN->db->update_record(STUTABLE, $sturec); } } } /// Handle completion elements if (!empty($allcompelemgrades)) { // get student's completion elements $cmgrades = array(); // NOTE: we use a do-while loop, since $last_rec might // be set from the last run, so we need to check it // before we load from the database do { if ($last_rec) { if ($last_rec->muid > $sturec->muid) { // we've reached the end of this student's // grades ($last_rec will save this record // for the next student's run) break; } if ($last_rec->muid == $sturec->muid) { $cmgrades[$last_rec->completionid] = $last_rec; } } } while ($last_rec = rs_fetch_next_record($allcompelemgrades)); foreach ($comp_elements as $gi_id => $element) { if (!isset($stugrades->grades[$gi_id]->finalgrade)) { continue; } // calculate Moodle grade as a percentage $gradeitem = $stugrades->grades[$gi_id]; $maxgrade = $gis[$gi_id]->grademax; /// Ignore mingrade for now... Don't really know what to do with it. $gradepercent = $gradeitem->finalgrade >= $maxgrade ? 100.0 : ($gradeitem->finalgrade <= 0 ? 0.0 : $gradeitem->finalgrade / $maxgrade * 100.0); if (isset($cmgrades[$element->id])) { // update existing completion element grade $grade_element = $cmgrades[$element->id]; if (!$grade_element->locked && $gradeitem->get_dategraded() > $grade_element->timegraded) { // clone of record, to see if we actually change anything $old_grade = clone $grade_element; $grade_element->grade = $gradepercent; $grade_element->timegraded = $gradeitem->get_dategraded(); /// If completed, lock it. $grade_element->locked = $grade_element->grade >= $element->completion_grade ? 1 : 0; // only update if we actually changed anything if ($old_grade->grade != $grade_element->grade || $old_grade->timegraded != $grade_element->timegraded || $old_grade->grade != $grade_element->grade || $old_grade->locked != $grade_element->locked) { $grade_element->timemodified = $timenow; $CURMAN->db->update_record(GRDTABLE, $grade_element); } } } else { // no completion element grade exists: create a new one $grade_element = new Object(); $grade_element->classid = $class->classid; $grade_element->userid = $cmuserid; $grade_element->completionid = $element->id; $grade_element->grade = $gradepercent; $grade_element->timegraded = $gradeitem->get_dategraded(); $grade_element->timemodified = $timenow; /// If completed, lock it. $grade_element->locked = $grade_element->grade >= $element->completion_grade ? 1 : 0; $CURMAN->db->insert_record(GRDTABLE, $grade_element); } } } } set_time_limit(600); } } }
function grade_get_graded_users_select($report, $course, $userid, $groupid, $includeall) { global $USER, $CFG; if (is_null($userid)) { $userid = $USER->id; } $coursecontext = context_course::instance($course->id); $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol); $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol); $showonlyactiveenrol = $showonlyactiveenrol || !has_capability('moodle/course:viewsuspendedusers', $coursecontext); $menu = array(); // Will be a list of userid => user name $menususpendedusers = array(); // Suspended users go to a separate optgroup. $gui = new graded_users_iterator($course, null, $groupid); $gui->require_active_enrolment($showonlyactiveenrol); $gui->init(); $label = get_string('selectauser', 'grades'); if ($includeall) { $menu[0] = get_string('allusers', 'grades'); $label = get_string('selectalloroneuser', 'grades'); } while ($userdata = $gui->next_user()) { $user = $userdata->user; $userfullname = fullname($user); if ($user->suspendedenrolment) { $menususpendedusers[$user->id] = $userfullname; } else { $menu[$user->id] = $userfullname; } } $gui->close(); if ($includeall) { $menu[0] .= " (" . (count($menu) + count($menususpendedusers) - 1) . ")"; } if (!empty($menususpendedusers)) { $menu[] = array(get_string('suspendedusers') => $menususpendedusers); } $select = new single_select(new moodle_url('/grade/report/' . $report . '/index.php', array('id' => $course->id)), 'userid', $menu, $userid); $select->label = $label; $select->formid = 'choosegradeuser'; return $select; }
/** * Prints preview of exported grades on screen as a feedback mechanism * @param bool $require_user_idnumber true means skip users without idnumber */ function display_preview($require_user_idnumber = false) { print_heading(get_string('previewrows', 'grades')); echo '<table>'; echo '<tr>'; echo '<th>' . get_string("firstname") . "</th>" . '<th>' . get_string("lastname") . "</th>" . '<th>' . get_string("idnumber") . "</th>" . '<th>' . get_string("institution") . "</th>" . '<th>' . get_string("department") . "</th>" . '<th>' . get_string("email") . "</th>"; foreach ($this->columns as $grade_item) { echo '<th>' . $this->format_column_name($grade_item) . '</th>'; /// add a column_feedback column if ($this->export_feedback) { echo '<th>' . $this->format_column_name($grade_item, true) . '</th>'; } } echo '</tr>'; /// Print all the lines of data. $i = 0; $gui = new graded_users_iterator($this->course, $this->columns, $this->groupid); $gui->init(); while ($userdata = $gui->next_user()) { // number of preview rows if ($this->previewrows and $this->previewrows <= $i) { break; } $user = $userdata->user; if ($require_user_idnumber and empty($user->idnumber)) { // some exports require user idnumber continue; } $gradeupdated = false; // if no grade is update at all for this user, do not display this row $rowstr = ''; foreach ($this->columns as $itemid => $unused) { $gradetxt = $this->format_grade($userdata->grades[$itemid]); // get the status of this grade, and put it through track to get the status $g = new grade_export_update_buffer(); $grade_grade = new grade_grade(array('itemid' => $itemid, 'userid' => $user->id)); $status = $g->track($grade_grade); if ($this->updatedgradesonly && ($status == 'nochange' || $status == 'unknown')) { $rowstr .= '<td>' . get_string('unchangedgrade', 'grades') . '</td>'; } else { $rowstr .= "<td>{$gradetxt}</td>"; $gradeupdated = true; } if ($this->export_feedback) { $rowstr .= '<td>' . $this->format_feedback($userdata->feedbacks[$itemid]) . '</td>'; } } // if we are requesting updated grades only, we are not interested in this user at all if (!$gradeupdated && $this->updatedgradesonly) { continue; } echo '<tr>'; echo "<td>{$user->firstname}</td><td>{$user->lastname}</td><td>{$user->idnumber}</td><td>{$user->institution}</td><td>{$user->department}</td><td>{$user->email}</td>"; echo $rowstr; echo "</tr>"; $i++; // increment the counter } echo '</table>'; $gui->close(); }
/** * To be implemented by child classes */ public function print_grades() { global $CFG; require_once $CFG->dirroot . '/lib/excellib.class.php'; $export_tracking = $this->track_exports(); $strgrades = get_string('grades'); /// Calculate file name $downloadfilename = clean_filename("{$this->course->shortname} {$strgrades}.xls"); /// Creating a workbook $workbook = new MoodleExcelWorkbook("-"); /// Sending HTTP headers $workbook->send($downloadfilename); /// Adding the worksheet $myxls =& $workbook->add_worksheet($strgrades); /// Print names of all the fields $myxls->write_string(0, 0, get_string("firstname")); $myxls->write_string(0, 1, get_string("lastname")); $myxls->write_string(0, 2, get_string("idnumber")); $myxls->write_string(0, 3, get_string("institution")); $myxls->write_string(0, 4, get_string("department")); $myxls->write_string(0, 5, get_string("email")); $pos = 6; foreach ($this->columns as $grade_item) { $myxls->write_string(0, $pos++, $this->format_column_name($grade_item)); /// add a column_feedback column if ($this->export_feedback) { $myxls->write_string(0, $pos++, $this->format_column_name($grade_item, true)); } } /// Print all the lines of data. $i = 0; $geub = new grade_export_update_buffer(); $gui = new graded_users_iterator($this->course, $this->columns, $this->groupid); $gui->init(); while ($userdata = $gui->next_user()) { $i++; $user = $userdata->user; $myxls->write_string($i, 0, $user->firstname); $myxls->write_string($i, 1, $user->lastname); $myxls->write_string($i, 2, $user->idnumber); $myxls->write_string($i, 3, $user->institution); $myxls->write_string($i, 4, $user->department); $myxls->write_string($i, 5, $user->email); $j = 6; foreach ($userdata->grades as $itemid => $grade) { if ($export_tracking) { $status = $geub->track($grade); } $gradestr = $this->format_grade($grade); if (is_numeric($gradestr)) { $myxls->write_number($i, $j++, $gradestr); } else { $myxls->write_string($i, $j++, $gradestr); } // writing feedback if requested if ($this->export_feedback) { $myxls->write_string($i, $j++, $this->format_feedback($userdata->feedbacks[$itemid])); } } } $gui->close(); $geub->close(); /// Close the workbook $workbook->close(); exit; }
public function export_grades($oauth) { global $CFG, $OUTPUT; $export_tracking = $this->track_exports(); $tables = $oauth->show_tables(); $this->tablename .= ' ' . date("Y-m-d H:i:s", strtotime('+0 days')); if (!$oauth->table_exists($this->tablename)) { $columns = array("firstname" => 'STRING', "lastname" => 'STRING', "idnumber" => 'STRING', "institution" => 'STRING', "department" => 'STRING', "email" => 'STRING'); foreach ($this->columns as $grade_item) { $column = self::clean_column_name($this->format_column_name($grade_item)); $columns[$column] = 'NUMBER'; } $result = $oauth->create_table($this->tablename, $columns); $tables = $oauth->show_tables(); } /// Print all the lines of data. $geub = new grade_export_update_buffer(); $gui = new graded_users_iterator($this->course, $this->columns, $this->groupid); $gui->init(); $rows = array(); $separator = ' | '; while ($userdata = $gui->next_user()) { $user = $userdata->user; $row = array($user->firstname, $user->lastname, $user->idnumber, $user->institution, $user->department, $user->email); $grades = array(); foreach ($userdata->grades as $itemid => $grade) { $grades[(int) $itemid] = $this->format_grade($grade); } ksort($grades); foreach ($grades as $itemid => $grade) { $row[] = $grade; } $rows[] = $row; } $gui->close(); $geub->close(); $result = $oauth->insert_rows($this->tablename, $rows); $table = $oauth->table_by_name($this->tablename, true); $table_id = $table['table id']; // output a basic page and do the popup and redirect $table_url = 'https://www.google.com/fusiontables/DataSource?docid=' . $table_id; $course_url = $CFG->wwwroot . '/course/view.php?id=' . $this->course->id; print_grade_page_head($this->course->id, 'export', 'fusion', get_string('exportto', 'grades') . ' ' . get_string('modulename', 'gradeexport_fusion')); echo $OUTPUT->heading(get_string('popup', 'gradeexport_fusion')); ?> <script type="text/javascript"> //<![CDATA[ url = "<?php echo $table_url; ?> "; courseurl = "<?php echo $course_url; ?> "; window.open(url, "_blank", 'left=20,top=20,width=1024,height=768,toolbar=1,resizable=1,menubar=1,scrollbars=1,status=1,location=1'); window.location = courseurl; //]]> </script> <noscript> <?php echo get_string('noscript', 'gradeexport_fusion'); ?> </noscript> <?php echo $OUTPUT->footer(); exit; }
function generate_jwc_xml($jwc_courses, $export_users, $include_cats = false, $dryrun = true) { global $course, $output, $jwc, $DB, $USER, $nonexist_users; if ($include_cats) { $heading = '导出分项成绩及总分到教务处'; } else { $heading = '导出总分到教务处'; } if ($dryrun) { $heading .= '(模拟)'; } else { $heading .= '(正式)'; } echo $output->heading($heading); //first make sure we have proper final grades - this must be done before constructing of the grade tree grade_regrade_final_grades($course->id); // 获得成绩类别和项信息 $tree = new grade_tree($course->id, true, true); $levels = $tree->get_levels(); // 总分 $total_item = normalize_grade_item($levels[0][0]['object']->grade_item); $sub_items = array(); $extra_items = array(); $items = array(); // 顶级成绩分类和项 if (array_key_exists(1, $levels) && $include_cats) { foreach ($levels[1] as $element) { if ($element['type'] == 'item') { $grade_item = normalize_grade_item($element['object']); } else { if ($element['type'] == 'category') { $tmp = array_pop($element['children']); $grade_item = normalize_grade_item($tmp['object']); //用类别名做成绩名 $grade_item->itemname = $element['object']->fullname; } else { // ignore unused fillers continue; } } if ($grade_item->grademax <= 0) { // 不计分成绩项/类别 continue; } if ($grade_item->aggregationcoef) { // 额外加分 $extra_items[$grade_item->id] = $grade_item; } else { $sub_items[$grade_item->id] = $grade_item; } } } /// 验证成绩项是否符合教务处要求 $result = true; // 总成绩满分必须是100分 if ($total_item->grademax != MAX_TOTAL_GRADE) { echo $output->require_max_total_grade($total_item->grademax); $result = false; } if ($include_cats) { // 总成绩算法必须是“简单加权平均分” $total_aggregation = $levels[0][0]['object']->aggregation; if ($total_aggregation != GRADE_AGGREGATE_WEIGHTED_MEAN2 and $total_aggregation != GRADE_AGGREGATE_SUM) { echo $output->require_aggregation($total_aggregation); $result = false; } // 子成绩项权重和必须为100 // 所有非加分的分项相加为100,才合法,除非不包含子类别 $weight_sum = 0; foreach ($sub_items as $item) { $weight_sum += $item->grademax; } if ($include_cats and $weight_sum != MAX_TOTAL_GRADE) { echo $output->require_100_weight($weight_sum); $result = false; } // 子成绩项数量不能超过8 if (count($sub_items) > MAX_SUB_GRADE_COUNT) { echo $output->require_max_subitems(count($sub_items)); $result = false; } // 加分成绩项数量不能超过2 if (count($extra_items) > MAX_EXTRA_SUB_GRADE_COUNT) { echo $output->require_max_extraitems(count($extra_items)); $result = false; } } if (!$result) { echo $output->modify_items_link(); return false; } $xml = new gradebook_xml(); if ($dryrun) { echo $output->box_start(); echo $output->heading('可导出成绩项', 3); } $itemtable = new html_table(); $itemtable->head = array('成绩分项名称', '权重', '加分'); foreach ($sub_items as $item) { $itemtable->data[] = new html_table_row(array($item->itemname, $item->grademax . '%', '否')); $xml->add_weight_item($item->id, $item->itemname, $item->grademax, $item->grademax); } foreach ($extra_items as $item) { $itemtable->data[] = new html_table_row(array($item->itemname, $item->grademax . '%', '是')); $xml->add_weight_item($item->id, $item->itemname, $item->grademax, $item->grademax, true); } $itemtable->data[] = new html_table_row(array($total_item->itemname, $total_item->grademax . '%', '-')); if ($dryrun) { echo html_writer::table($itemtable); } // 本地不存在的用户 if (!empty($nonexist_users)) { echo $output->heading('教务处有记录而本站无对应用户的学生', 3); $usertable = new html_table(); $usertable->head = array('序号', '姓名', '学号'); $count = 0; foreach ($nonexist_users as $user) { $row = array(); $count++; $row[] = new html_table_cell($count); $row[] = new html_table_cell($user->name); $row[] = new html_table_cell($user->code); $usertable->data[] = new html_table_row($row); } echo html_writer::table($usertable); } // 用户成绩 if ($dryrun) { echo $output->heading('可导出成绩', 3); } $items = $sub_items + $extra_items; $items[$total_item->id] = $total_item; $geub = new grade_export_update_buffer(); $gui = new graded_users_iterator($course, $items); $gui->init(); $usertable = new html_table(); $usertable->head = array('序号', '姓名', '学号'); foreach ($items as $item) { $usertable->head[] = $item->itemname; } $count = 0; while ($userdata = $gui->next_user()) { $user = $userdata->user; if ($user->auth != 'cas' || empty($user->idnumber)) { // 非cas用户成绩不可导出 continue; } if (!array_key_exists($user->id, $export_users)) { // 教务处无记录用户不导出 continue; } $row = array(); $count++; $row[] = new html_table_cell($count); $row[] = new html_table_cell($user->firstname); $row[] = new html_table_cell($user->idnumber); $grades = array(); foreach ($userdata->grades as $itemid => $grade) { if ($itemid == $total_item->id) { // 总分 $finalgrade = round($grade->finalgrade); $grades[0] = $finalgrade; } else { $finalgrade = round($grade->finalgrade, 1); $grades[$itemid] = $finalgrade; } $row[] = new html_table_cell($finalgrade); } $xml->add_user($user->idnumber, $user->firstname, $grades); $usertable->data[] = new html_table_row($row); } $gui->close(); $geub->close(); if ($dryrun) { echo html_writer::table($usertable); echo $output->box_end(); } // 存入数据库 foreach ($jwc_courses as $jwc_course) { $xml->set_xkid($jwc_course->xkid); $new = new stdClass(); $new->xml = $xml->asXML(); $new->requestkey = md5($new->xml); $new->expiredtime = time() + KEY_EXPIRED_TIME; $new->user = $USER->id; $new->course = $course->id; if (!$dryrun) { if ($old = $DB->get_record('grade_export_jwc', array('requestkey' => $new->requestkey))) { $old->expiredtime = time() + KEY_EXPIRED_TIME; $DB->update_record('grade_export_jwc', $old); } else { $DB->insert_record('grade_export_jwc', $new); } // real export $errormsg = ''; if (!$jwc->export($jwc_course->xkid, $new->requestkey, $errormsg)) { $errormsg = textlib_get_instance()->convert($errormsg, 'gbk'); echo $output->notification('导出过程出错(' . $errormsg . ')。请将这串字符串报告给管理员:' . $new->requestkey); return false; } } } return true; }
/** * Load a valid list of users for this gradebook as the screen "items". * @return array $users A list of enroled users. */ protected function load_users() { global $CFG; // Create a graded_users_iterator because it will properly check the groups etc. $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol); $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol); $showonlyactiveenrol = $showonlyactiveenrol || !has_capability('moodle/course:viewsuspendedusers', $this->context); require_once $CFG->dirroot . '/grade/lib.php'; $gui = new \graded_users_iterator($this->course, null, $this->groupid); $gui->require_active_enrolment($showonlyactiveenrol); $gui->init(); // Flatten the users. $users = array(); while ($user = $gui->next_user()) { $users[$user->user->id] = $user->user; } return $users; }
public function display_preview($require_user_idnumber = false) { global $OUTPUT; $userprofilefields = grade_helper::get_user_profile_fields($this->course->id, $this->usercustomfields); $formatoptions = new stdClass(); $formatoptions->para = false; $exporttitle = array('Client Code', 'Client Name', 'Qualification Code', 'Unit Code', 'Unit Start Date', 'Unit End Date', 'Outcome Name', 'Outcome Code'); echo $OUTPUT->heading(get_string('previewrows', 'grades')); echo '<table class="csv-table">'; echo '<tr>'; foreach ($exporttitle as $field) { echo '<th>' . $field . '</th>'; } if (!$this->onlyactive) { echo '<th>' . get_string("suspended") . "</th>"; } // foreach ($this->columns as $grade_item) { // echo '<th>'.$this->format_column_name($grade_item).'</th>'; // /// add a column_feedback column // if ($this->export_feedback) { // echo '<th>'.$this->format_column_name($grade_item, true).'</th>'; // } // } echo '</tr>'; /// Print all the lines of data. $i = 0; $gui = new graded_users_iterator($this->course, $this->columns, $this->groupid); $gui->require_active_enrolment($this->onlyactive); $gui->allow_user_custom_fields($this->usercustomfields); $gui->init(); while ($userdata = $gui->next_user()) { // number of preview rows if ($this->previewrows and $this->previewrows <= $i) { break; } $user = $userdata->user; if ($require_user_idnumber and empty($user->idnumber)) { // some exports require user idnumber so we can match up students when importing the data continue; } $gradeupdated = false; // if no grade is update at all for this user, do not display this row $rowstr = ''; foreach ($this->columns as $itemid => $grade_item) { $gradetxt = $this->format_grade($userdata->grades[$itemid]); $activity_start_date = $this->get_activity_start_date($this->course, $user, $grade_item); $grade_modified = $userdata->grades[$itemid]->timemodified; $client_code = $userdata->user->idnumber; $client_name = $userdata->user->firstname . ' ' . $userdata->user->lastname; // $course_code = $this->get_course_short_name($grade_item); $course_code = $this->course->idnumber; // $unit_code = $grade_item->itemname; $unit_code = $grade_item->idnumber; $unit_start = $activity_start_date ? $activity_start_date->format('d-m-Y') : '-'; $unit_end = $grade_modified ? userdate($grade_modified, '%d-%m-%Y') : '-'; $grade_name = $this->get_grade_name($gradetxt); if ($grade_item->itemtype == 'category') { $category_start_date = $this->get_category_start_date($this->course, $user, $grade_item); $unit_start = $category_start_date ? $category_start_date->format('d-m-Y') : '-'; } // get the status of this grade, and put it through track to get the status $g = new grade_export_update_buffer(); $grade_grade = new grade_grade(array('itemid' => $itemid, 'userid' => $user->id)); $status = $g->track($grade_grade); if ($this->updatedgradesonly && ($status == 'nochange' || $status == 'unknown')) { $rowstr .= '<td>' . get_string('unchangedgrade', 'grades') . '</td>'; } else { $rowstr .= "<tr>\n <td>{$client_code}</td>\n <td>{$client_name}</td>\n <td>{$course_code}</td>\n <td>{$unit_code}</td>\n <td>{$unit_start}</td>\n <td>{$unit_end}</td>\n <td>{$grade_name}</td>\n <td>{$gradetxt}</td>\n </tr>"; $gradeupdated = true; } if ($this->export_feedback) { $rowstr .= '<td>' . $this->format_feedback($userdata->feedbacks[$itemid]) . '</td>'; } } // if we are requesting updated grades only, we are not interested in this user at all if (!$gradeupdated && $this->updatedgradesonly) { continue; } echo '<tr>'; echo $rowstr; echo "</tr>"; $i++; // increment the counter } echo '</table>'; $gui->close(); }
public function print_grades() { global $CFG; $exporttracking = $this->track_exports(); $course = $this->course; $strgrades = get_string('grades'); $profilefields = grade_helper::get_user_profile_fields($this->course->id, $this->usercustomfields); $courseid = $course->id; $shortname = format_string($this->course->shortname, true, array('context' => context_course::instance($this->course->id))); $downloadfilename = clean_filename("{$shortname} {$strgrades}"); $csvexport = new csv_export_writer($this->separator); $csvexport->filename = clean_filename("{$downloadfilename}.csv"); // Print names of all the fields. $exporttitle = array(); $shortname = format_string($this->course->shortname, true, array('context' => context_course::instance($this->course->id))); $exporttitle[] = $shortname . ""; $csvexport->add_data($exporttitle); $exporttitle = array(); $exporttitle[] = "TERM"; $exporttitle[] = "Class Number"; $exporttitle[] = "ID"; $exporttitle[] = "Final Grade"; $exporttitle[] = "" . get_string("firstname"); $exporttitle[] = "" . get_string("lastname"); $exporttitle[] = "" . get_string("idnumber"); $exporttitle[] = "" . get_string("institution"); $exporttitle[] = "" . get_string("department"); $exporttitle[] = "" . get_string("email"); foreach ($this->columns as $gradeitem) { $exporttitle[] = trim($gradeitem->get_name()); } $csvexport->add_data($exporttitle); $sseat = $this->primcomp($courseid); // Print all the lines of data. $geub = new grade_export_update_buffer(); $gui = new graded_users_iterator($this->course, $this->columns, $this->groupid); $gui->require_active_enrolment($this->onlyactive); $gui->allow_user_custom_fields($this->usercustomfields); $gui->init(); while ($userdata = $gui->next_user()) { $exportdata = array(); $user = $userdata->user; if (!isset($sseat[$user->username])) { continue; } foreach ($userdata->grades as $itemid => $grade) { if ($this->finalitemid == $itemid) { $finalletter = $this->format_grade($userdata->grades[$itemid]); if ($this->displaytype == 1) { $userdata->grades[$itemid]->finalgrade = $finalletter; } } } $coarr = explode('.', $sseat[$user->username]); $exportdata[] = $coarr[0]; $exportdata[] = $coarr[1]; $exportdata[] = $user->username; $exportdata[] = $finalletter; $exportdata[] = $user->firstname; $exportdata[] = $user->lastname; $exportdata[] = $user->idnumber; $exportdata[] = $user->institution; $exportdata[] = $user->department; $exportdata[] = $user->email; foreach ($userdata->grades as $itemid => $grade) { $gradestr = $userdata->grades[$itemid]->finalgrade; $exportdata[] = $gradestr; } $csvexport->add_data($exportdata); } $gui->close(); $geub->close(); $csvexport->download_file(); exit; }
/** * Return grade for given user or all users. * * @param int $schedulerid id of scheduler * @param int $userid optional user id, 0 means all users * @return array array of grades, false if none */ public function get_user_grades($userid = 0) { global $CFG, $DB; if ($this->scale == 0) { return false; } $usersql = ''; $params = array(); if ($userid) { $usersql = ' AND a.studentid = :userid'; $params['userid'] = $userid; } $params['sid'] = $this->id; $sql = 'SELECT a.id, a.studentid, a.grade ' . 'FROM {scheduler_slots} s JOIN {scheduler_appointment} a ON s.id = a.slotid ' . 'WHERE s.schedulerid = :sid AND a.grade IS NOT NULL' . $usersql; $grades = $DB->get_records_sql($sql, $params); $finalgrades = array(); $gradesums = array(); foreach ($grades as $grade) { $gradesums[$grade->studentid] = new stdClass(); $finalgrades[$grade->studentid] = new stdClass(); $finalgrades[$grade->studentid]->userid = $grade->studentid; } if ($this->scale > 0) { // Grading numerically. foreach ($grades as $grade) { $gradesums[$grade->studentid]->sum = @$gradesums[$grade->studentid]->sum + $grade->grade; $gradesums[$grade->studentid]->count = @$gradesums[$grade->studentid]->count + 1; $gradesums[$grade->studentid]->max = @$gradesums[$grade->studentid]->max < $grade->grade ? $grade->grade : @$gradesums[$grade->studentid]->max; } // Retrieve the adequate strategy. foreach ($gradesums as $student => $gradeset) { switch ($this->gradingstrategy) { case SCHEDULER_MAX_GRADE: $finalgrades[$student]->rawgrade = $gradeset->max; break; case SCHEDULER_MEAN_GRADE: $finalgrades[$student]->rawgrade = $gradeset->sum / $gradeset->count; break; } } } else { // Grading on scales. $scaleid = -$this->scale; $maxgrade = ''; if ($scale = $DB->get_record('scale', array('id' => $scaleid))) { $scalegrades = make_menu_from_list($scale->scale); foreach ($grades as $grade) { $gradesums[$grade->studentid]->sum = @$gradesums[$grade->studentid]->sum + $grade->grade; $gradesums[$grade->studentid]->count = @$gradesums[$grade->studentid]->count + 1; $gradesums[$grade->studentid]->max = @$gradesums[$grade->studentid]->max < $grade ? $grade->grade : @$gradesums[$grade->studentid]->max; } $maxgrade = $scale->name; } // Retrieve the adequate strategy. foreach ($gradesums as $student => $gradeset) { switch ($this->gradingstrategy) { case SCHEDULER_MAX_GRADE: $finalgrades[$student]->rawgrade = $gradeset->max; break; case SCHEDULER_MEAN_GRADE: $finalgrades[$student]->rawgrade = $gradeset->sum / $gradeset->count; break; } } } // Include any empty grades. if ($userid > 0) { if (!array_key_exists($userid, $finalgrades)) { $finalgrades[$userid] = new stdClass(); $finalgrades[$userid]->userid = $userid; $finalgrades[$userid]->rawgrade = null; } } else { $gui = new graded_users_iterator($this->get_courserec()); $gui->init(); while ($userdata = $gui->next_user()) { $uid = $userdata->user->id; if (!array_key_exists($uid, $finalgrades)) { $finalgrades[$uid] = new stdClass(); $finalgrades[$uid]->userid = $uid; $finalgrades[$uid]->rawgrade = null; } } } return $finalgrades; }
/** * Prints preview of exported grades on screen as a feedback mechanism * @param bool $require_user_idnumber true means skip users without idnumber * @deprecated since 2.8 MDL-46548. Previews are not useful on export. */ public function display_preview($require_user_idnumber = false) { global $OUTPUT; debugging('function grade_export::display_preview is deprecated.', DEBUG_DEVELOPER); $userprofilefields = grade_helper::get_user_profile_fields($this->course->id, $this->usercustomfields); $formatoptions = new stdClass(); $formatoptions->para = false; echo $OUTPUT->heading(get_string('previewrows', 'grades')); echo '<table>'; echo '<tr>'; foreach ($userprofilefields as $field) { echo '<th>' . $field->fullname . '</th>'; } if (!$this->onlyactive) { echo '<th>' . get_string("suspended") . "</th>"; } foreach ($this->columns as $grade_item) { echo '<th>' . $this->format_column_name($grade_item) . '</th>'; /// add a column_feedback column if ($this->export_feedback) { echo '<th>' . $this->format_column_name($grade_item, true) . '</th>'; } } echo '</tr>'; /// Print all the lines of data. $i = 0; $gui = new graded_users_iterator($this->course, $this->columns, $this->groupid); $gui->require_active_enrolment($this->onlyactive); $gui->allow_user_custom_fields($this->usercustomfields); $gui->init(); while ($userdata = $gui->next_user()) { // number of preview rows if ($this->previewrows and $this->previewrows <= $i) { break; } $user = $userdata->user; if ($require_user_idnumber and empty($user->idnumber)) { // some exports require user idnumber so we can match up students when importing the data continue; } $gradeupdated = false; // if no grade is update at all for this user, do not display this row $rowstr = ''; foreach ($this->columns as $itemid => $unused) { $gradetxt = $this->format_grade($userdata->grades[$itemid]); // get the status of this grade, and put it through track to get the status $g = new grade_export_update_buffer(); $grade_grade = new grade_grade(array('itemid' => $itemid, 'userid' => $user->id)); $status = $g->track($grade_grade); if ($this->updatedgradesonly && ($status == 'nochange' || $status == 'unknown')) { $rowstr .= '<td>' . get_string('unchangedgrade', 'grades') . '</td>'; } else { $rowstr .= "<td>{$gradetxt}</td>"; $gradeupdated = true; } if ($this->export_feedback) { $rowstr .= '<td>' . $this->format_feedback($userdata->feedbacks[$itemid]) . '</td>'; } } // if we are requesting updated grades only, we are not interested in this user at all if (!$gradeupdated && $this->updatedgradesonly) { continue; } echo '<tr>'; foreach ($userprofilefields as $field) { $fieldvalue = grade_helper::get_user_field_value($user, $field); // @see profile_field_base::display_data(). echo '<td>' . format_text($fieldvalue, FORMAT_MOODLE, $formatoptions) . '</td>'; } if (!$this->onlyactive) { $issuspended = $user->suspendedenrolment ? get_string('yes') : ''; echo "<td>{$issuspended}</td>"; } echo $rowstr; echo "</tr>"; $i++; // increment the counter } echo '</table>'; $gui->close(); }
// Groups are being used $currentgroup = groups_get_course_group($course, true); if (!$currentgroup) { // To make some other functions work better later $currentgroup = NULL; } $isseparategroups = ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)); if ($isseparategroups and !$currentgroup) { // no separate group access, can view only self $userid = $USER->id; $user_selector = false; } else { $user_selector = true; } if (empty($userid)) { $gui = new graded_users_iterator($course, null, $currentgroup); $gui->init(); // Add tabs print_grade_page_head($courseid, 'report', 'user'); groups_print_course_menu($course, $gpr->get_return_url('index.php?id=' . $courseid, array('userid' => 0))); if ($user_selector) { $renderer = $PAGE->get_renderer('gradereport_user'); echo $renderer->graded_users_selector('user', $course, $userid, $currentgroup, false); } while ($userdata = $gui->next_user()) { $user = $userdata->user; $report = new grade_report_user($courseid, $gpr, $context, $user->id); echo $OUTPUT->heading(get_string('pluginname', 'gradereport_user') . ' - ' . fullname($report->user)); if ($report->fill_table()) { echo '<br />' . $report->print_table(true); }
/** * Print a selection popup form of the graded users in a course. * * @param int $course id of the course * @param string $actionpage The page receiving the data from the popoup form * @param int $userid id of the currently selected user (or 'all' if they are all selected) * @param int $groupid id of requested group, 0 means all * @param int $includeall bool include all option * @param bool $return If true, will return the HTML, otherwise, will print directly * @return null */ function print_graded_users_selector($course, $actionpage, $userid = 0, $groupid = 0, $includeall = true, $return = false) { global $CFG, $USER, $OUTPUT; if (is_null($userid)) { $userid = $USER->id; } $context = get_context_instance(CONTEXT_COURSE, $course->id); $menu = array(); // Will be a list of userid => user name $gui = new graded_users_iterator($course, null, $groupid); $gui->init(); $label = get_string('selectauser', 'grades'); if ($includeall) { $menu[0] = get_string('allusers', 'grades'); $label = get_string('selectalloroneuser', 'grades'); } $nextuser = $gui->next_user(); while ($userdata = $gui->next_user()) { $user = $userdata->user; $menu[$user->id] = fullname($user); } $gui->close(); if ($includeall) { $menu[0] .= " (" . (count($menu) - 1) . ")"; } $select = html_select::make_popup_form($CFG->wwwroot . '/grade/' . $actionpage, 'userid', $menu, 'choosegradeuser', $userid); $select->set_label($label); return $OUTPUT->select($select); }
// To make some other functions work better later $currentgroup = NULL; } $isseparategroups = ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)); if ($isseparategroups and !$currentgroup) { // no separate group access, can view only self $userid = $USER->id; $user_selector = false; } else { $user_selector = true; } $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol); $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol); $showonlyactiveenrol = $showonlyactiveenrol || !has_capability('moodle/course:viewsuspendedusers', $context); if (empty($userid)) { $gui = new graded_users_iterator($course, null, $currentgroup); $gui->require_active_enrolment($showonlyactiveenrol); $gui->init(); // Add tabs print_grade_page_head($courseid, 'report', 'user'); groups_print_course_menu($course, $gpr->get_return_url('index.php?id=' . $courseid, array('userid' => 0))); if ($user_selector) { $renderer = $PAGE->get_renderer('gradereport_user'); echo $renderer->graded_users_selector('user', $course, $userid, $currentgroup, true); } while ($userdata = $gui->next_user()) { $user = $userdata->user; $report = new grade_report_user($courseid, $gpr, $context, $user->id); $studentnamelink = html_writer::link(new moodle_url('/user/view.php', array('id' => $report->user->id, 'course' => $courseid)), fullname($report->user)); echo $OUTPUT->heading(get_string('pluginname', 'gradereport_user') . ' - ' . $studentnamelink); if ($report->fill_table()) {
/** * Prints preview of exported grades on screen as a feedback mechanism */ function display_preview() { print_heading(get_string('previewrows', 'grades')); echo '<table>'; echo '<tr>'; echo '<th>' . get_string("firstname") . "</th>" . '<th>' . get_string("lastname") . "</th>" . '<th>' . get_string("idnumber") . "</th>" . '<th>' . get_string("institution") . "</th>" . '<th>' . get_string("department") . "</th>" . '<th>' . get_string("email") . "</th>"; foreach ($this->columns as $grade_item) { echo '<th>' . $this->format_column_name($grade_item) . '</th>'; /// add a column_feedback column if ($this->export_feedback) { echo '<th>' . $this->format_column_name($grade_item, true) . '</th>'; } } echo '</tr>'; /// Print all the lines of data. $i = 0; $gui = new graded_users_iterator($this->course, $this->columns, $this->groupid); $gui->init(); while ($userdata = $gui->next_user()) { // number of preview rows if ($this->previewrows and $this->previewrows < ++$i) { break; } $user = $userdata->user; echo '<tr>'; echo "<td>{$user->firstname}</td><td>{$user->lastname}</td><td>{$user->idnumber}</td><td>{$user->institution}</td><td>{$user->department}</td><td>{$user->email}</td>"; foreach ($this->columns as $itemid => $unused) { $gradetxt = $this->format_grade($userdata->grades[$itemid]); echo "<td>{$gradetxt}</td>"; if ($this->export_feedback) { echo '<td>' . $this->format_feedback($userdata->feedbacks[$itemid]) . '</td>'; } } echo "</tr>"; } echo '</table>'; $gui->close(); }
/** * Returns a list of grades tables for users in a course. * * @param int $courseid Course Id * @param int $userid Only this user (optional) * * @return array the grades tables * @since Moodle 2.9 */ public static function get_grades_table($courseid, $userid = 0) { global $CFG, $USER; $warnings = array(); // Validate the parameter. $params = self::validate_parameters(self::get_grades_table_parameters(), array('courseid' => $courseid, 'userid' => $userid)); // Compact/extract functions are not recommended. $courseid = $params['courseid']; $userid = $params['userid']; // Function get_course internally throws an exception if the course doesn't exist. $course = get_course($courseid); $context = context_course::instance($courseid); self::validate_context($context); // Specific capabilities. require_capability('gradereport/user:view', $context); $user = null; if (empty($userid)) { require_capability('moodle/grade:viewall', $context); } else { $user = core_user::get_user($userid, '*', MUST_EXIST); } $access = false; if (has_capability('moodle/grade:viewall', $context)) { // Can view all course grades. $access = true; } else { if ($userid == $USER->id and has_capability('moodle/grade:view', $context) and $course->showgrades) { // View own grades. $access = true; } } if (!$access) { throw new moodle_exception('nopermissiontoviewgrades', 'error'); } // Require files here to save some memory in case validation fails. require_once $CFG->dirroot . '/group/lib.php'; require_once $CFG->libdir . '/gradelib.php'; require_once $CFG->dirroot . '/grade/lib.php'; require_once $CFG->dirroot . '/grade/report/user/lib.php'; $gpr = new grade_plugin_return(array('type' => 'report', 'plugin' => 'user', 'courseid' => $courseid, 'userid' => $userid)); $tables = array(); // Just one user. if ($user) { $report = new grade_report_user($courseid, $gpr, $context, $userid); $report->fill_table(); $tables[] = array('courseid' => $courseid, 'userid' => $user->id, 'userfullname' => fullname($user), 'maxdepth' => $report->maxdepth, 'tabledata' => $report->tabledata); } else { $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol); $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol); $showonlyactiveenrol = $showonlyactiveenrol || !has_capability('moodle/course:viewsuspendedusers', $context); $gui = new graded_users_iterator($course); $gui->require_active_enrolment($showonlyactiveenrol); $gui->init(); while ($userdata = $gui->next_user()) { $currentuser = $userdata->user; $report = new grade_report_user($courseid, $gpr, $context, $currentuser->id); $report->fill_table(); $tables[] = array('courseid' => $courseid, 'userid' => $currentuser->id, 'userfullname' => fullname($currentuser), 'maxdepth' => $report->maxdepth, 'tabledata' => $report->tabledata); } $gui->close(); } $result = array(); $result['tables'] = $tables; $result['warnings'] = $warnings; return $result; }
function grade_get_graded_users_select($report, $course, $userid, $groupid, $includeall) { global $USER; if (is_null($userid)) { $userid = $USER->id; } $menu = array(); // Will be a list of userid => user name $gui = new graded_users_iterator($course, null, $groupid); $gui->init(); $label = get_string('selectauser', 'grades'); if ($includeall) { $menu[0] = get_string('allusers', 'grades'); $label = get_string('selectalloroneuser', 'grades'); } while ($userdata = $gui->next_user()) { $user = $userdata->user; $menu[$user->id] = fullname($user); } $gui->close(); if ($includeall) { $menu[0] .= " (" . (count($menu) - 1) . ")"; } $select = new single_select(new moodle_url('/grade/report/' . $report . '/index.php', array('id' => $course->id)), 'userid', $menu, $userid); $select->label = $label; $select->formid = 'choosegradeuser'; return $select; }
/** * To be implemented by child classes */ public function print_grades() { global $CFG; require_once $CFG->dirroot . '/lib/excellib.class.php'; $export_tracking = $this->track_exports(); $strgrades = get_string('grades'); // Calculate file name $shortname = format_string($this->course->shortname, true, array('context' => context_course::instance($this->course->id))); $downloadfilename = clean_filename("{$shortname} {$strgrades}.xls"); // Creating a workbook $workbook = new MoodleExcelWorkbook("-"); // Sending HTTP headers $workbook->send($downloadfilename); // Adding the worksheet $myxls = $workbook->add_worksheet($strgrades); // Print names of all the fields $profilefields = grade_helper::get_user_profile_fields($this->course->id, $this->usercustomfields); foreach ($profilefields as $id => $field) { $myxls->write_string(0, $id, $field->fullname); } $pos = count($profilefields); if (!$this->onlyactive) { $myxls->write_string(0, $pos++, get_string("suspended")); } foreach ($this->columns as $grade_item) { $myxls->write_string(0, $pos++, $this->format_column_name($grade_item)); // Add a column_feedback column if ($this->export_feedback) { $myxls->write_string(0, $pos++, $this->format_column_name($grade_item, true)); } } // Print all the lines of data. $i = 0; $geub = new grade_export_update_buffer(); $gui = new graded_users_iterator($this->course, $this->columns, $this->groupid); $gui->require_active_enrolment($this->onlyactive); $gui->allow_user_custom_fields($this->usercustomfields); $gui->init(); while ($userdata = $gui->next_user()) { $i++; $user = $userdata->user; foreach ($profilefields as $id => $field) { $fieldvalue = grade_helper::get_user_field_value($user, $field); $myxls->write_string($i, $id, $fieldvalue); } $j = count($profilefields); if (!$this->onlyactive) { $issuspended = $user->suspendedenrolment ? get_string('yes') : ''; $myxls->write_string($i, $j++, $issuspended); } foreach ($userdata->grades as $itemid => $grade) { if ($export_tracking) { $status = $geub->track($grade); } $gradestr = $this->format_grade($grade); if (is_numeric($gradestr)) { $myxls->write_number($i, $j++, $gradestr); } else { $myxls->write_string($i, $j++, $gradestr); } // writing feedback if requested if ($this->export_feedback) { $myxls->write_string($i, $j++, $this->format_feedback($userdata->feedbacks[$itemid])); } } } $gui->close(); $geub->close(); /// Close the workbook $workbook->close(); exit; }
/** * Print a selection popup form of the graded users in a course. * * @param int $courseid id of the course * @param string $actionpage The page receiving the data from the popoup form * @param int $userid id of the currently selected user (or 'all' if they are all selected) * @param bool $return If true, will return the HTML, otherwise, will print directly * @return null */ function print_graded_users_selector($course, $actionpage, $userid = null, $return = false) { global $CFG, $USER; if (is_null($userid)) { $userid = $USER->id; } $context = get_context_instance(CONTEXT_COURSE, $course->id); $menu = array(); // Will be a list of userid => user name $gui = new graded_users_iterator($course); $gui->init(); if ($userid !== 0) { $menu[0] = get_string('allusers', 'grades'); } while ($userdata = $gui->next_user()) { $user = $userdata->user; $menu[$user->id] = fullname($user); } $gui->close(); if ($userid !== 0) { $menu[0] .= " (" . (count($menu) - 1) . ")"; } return popup_form($CFG->wwwroot . '/grade/' . $actionpage . '&userid=', $menu, 'choosegradeduser', $userid, 'choose', '', '', $return, 'self', get_string('selectalloroneuser', 'grades')); }