MDL-10527 changed overridden UI logic
[moodle-pu.git] / grade / report / grader / lib.php
blobf4339a88b13c095876ccb15f7bf3bfb7c8a0dcd4
1 <?php // $Id$
2 /**
3 * File in which the grader_report class is defined.
4 * @package gradebook
5 */
7 require_once($CFG->dirroot . '/grade/report/lib.php');
8 require_once($CFG->libdir.'/tablelib.php');
10 /**
11 * Class providing an API for the grader report building and displaying.
12 * @uses grade_report
13 * @package gradebook
15 class grade_report_grader extends grade_report {
16 /**
17 * The final grades.
18 * @var array $finalgrades
20 var $finalgrades;
22 /**
23 * The grade items.
24 * @var array $items
26 var $items;
28 /**
29 * Array of errors for bulk grades updating.
30 * @var array $gradeserror
32 var $gradeserror = array();
34 //// SQL-RELATED
36 /**
37 * The id of the grade_item by which this report will be sorted.
38 * @var int $sortitemid
40 var $sortitemid;
42 /**
43 * Sortorder used in the SQL selections.
44 * @var int $sortorder
46 var $sortorder;
48 /**
49 * An SQL fragment affecting the search for users.
50 * @var string $userselect
52 var $userselect;
54 //// GROUP VARIABLES (including SQL)
56 /**
57 * The current group being displayed.
58 * @var int $currentgroup
60 var $currentgroup;
62 /**
63 * A HTML select element used to select the current group.
64 * @var string $group_selector
66 var $group_selector;
68 /**
69 * An SQL fragment used to add linking information to the group tables.
70 * @var string $groupsql
72 var $groupsql;
74 /**
75 * An SQL constraint to append to the queries used by this object to build the report.
76 * @var string $groupwheresql
78 var $groupwheresql;
81 /**
82 * Constructor. Sets local copies of user preferences and initialises grade_tree.
83 * @param int $courseid
84 * @param object $gpr grade plugin return tracking object
85 * @param string $context
86 * @param int $page The current page being viewed (when report is paged)
87 * @param int $sortitemid The id of the grade_item by which to sort the table
89 function grade_report_grader($courseid, $gpr, $context, $page=null, $sortitemid=null) {
90 global $CFG;
91 parent::grade_report($courseid, $gpr, $context, $page);
93 $this->sortitemid = $sortitemid;
95 // base url for sorting by first/last name
96 $this->baseurl = 'report.php?id='.$this->courseid.'&amp;perpage='.$this->get_pref('studentsperpage')
97 .'&amp;report=grader&amp;page='.$this->page;
99 $this->pbarurl = 'report.php?id='.$this->courseid.'&amp;perpage='.$this->get_pref('studentsperpage')
100 .'&amp;report=grader&amp;';
102 if ($this->get_pref('showgroups')) {
103 $this->setup_groups();
106 $this->setup_sortitemid();
110 * Processes the data sent by the form (grades and feedbacks).
111 * @var array $data
112 * @return bool Success or Failure (array of errors).
114 function process_data($data) {
115 // always initialize all arrays
116 $queue = array();
117 foreach ($data as $varname => $postedvalue) {
119 $needsupdate = false;
120 $note = false; // TODO implement note??
122 // skip, not a grade nor feedback
123 if (strpos($varname, 'grade') === 0) {
124 $data_type = 'grade';
125 } else if (strpos($varname, 'feedback') === 0) {
126 $data_type = 'feedback';
127 } else {
128 continue;
131 $gradeinfo = explode("_", $varname);
132 $userid = clean_param($gradeinfo[1], PARAM_INT);
133 $itemid = clean_param($gradeinfo[2], PARAM_INT);
135 $oldvalue = $data->{'old'.$varname};
137 // was change requested?
138 if ($oldvalue == $postedvalue) {
139 continue;
142 if (!$grade_item = grade_item::fetch(array('id'=>$itemid, 'courseid'=>$this->courseid))) { // we must verify course id here!
143 error('Incorrect grade item id');
146 // Pre-process grade
147 if ($data_type == 'grade') {
148 $feedback = false;
149 $feedbackformat = false;
150 if ($grade_item->gradetype == GRADE_TYPE_SCALE) {
151 if ($postedvalue == -1) { // -1 means no grade
152 $finalgrade = null;
153 } else {
154 $finalgrade = $postedvalue;
156 } else {
157 $trimmed = trim($postedvalue);
158 if (empty($trimmed)) { // empty string means no grade
159 $finalgrade = null;
160 } else {
161 $finalgrade = $this->format_grade($postedvalue);
165 } else if ($data_type == 'feedback') {
166 $finalgrade = false;
167 $trimmed = trim($postedvalue);
168 if (empty($trimmed)) {
169 $feedback = NULL;
170 } else {
171 $feedback = stripslashes($postedvalue);
175 $grade_item->update_final_grade($userid, $finalgrade, 'gradebook', $note, $feedback);
178 return true;
182 * Sets up this object's group variables, mainly to restrict the selection of users to display.
184 function setup_groups() {
185 global $CFG;
187 /// find out current groups mode
188 $course = get_record('course', 'id', $this->courseid);
189 $groupmode = $course->groupmode;
190 ob_start();
191 $this->currentgroup = setup_and_print_groups($course, $groupmode, $this->pbarurl);
192 $this->group_selector = ob_get_clean();
194 // update paging after group
195 $this->baseurl .= 'group='.$this->currentgroup.'&amp;';
196 $this->pbarurl .= 'group='.$this->currentgroup.'&amp;';
198 if ($this->currentgroup) {
199 $this->groupsql = " LEFT JOIN {$CFG->prefix}groups_members gm ON gm.userid = u.id ";
200 $this->groupwheresql = " AND gm.groupid = $this->currentgroup ";
205 * Setting the sort order, this depends on last state
206 * all this should be in the new table class that we might need to use
207 * for displaying grades.
209 function setup_sortitemid() {
211 global $SESSION;
213 if ($this->sortitemid) {
214 if (!isset($SESSION->gradeuserreport->sort)) {
215 $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC';
216 } else {
217 // this is the first sort, i.e. by last name
218 if (!isset($SESSION->gradeuserreport->sortitemid)) {
219 $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC';
220 } else if ($SESSION->gradeuserreport->sortitemid == $this->sortitemid) {
221 // same as last sort
222 if ($SESSION->gradeuserreport->sort == 'ASC') {
223 $this->sortorder = $SESSION->gradeuserreport->sort = 'DESC';
224 } else {
225 $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC';
227 } else {
228 $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC';
231 $SESSION->gradeuserreport->sortitemid = $this->sortitemid;
232 } else {
233 // not requesting sort, use last setting (for paging)
235 if (isset($SESSION->gradeuserreport->sortitemid)) {
236 $this->sortitemid = $SESSION->gradeuserreport->sortitemid;
238 if (isset($SESSION->gradeuserreport->sort)) {
239 $this->sortorder = $SESSION->gradeuserreport->sort;
240 } else {
241 $this->sortorder = 'ASC';
247 * pulls out the userids of the users to be display, and sort them
248 * the right outer join is needed because potentially, it is possible not
249 * to have the corresponding entry in grade_grades table for some users
250 * this is check for user roles because there could be some users with grades
251 * but not supposed to be displayed
253 function load_users() {
254 global $CFG;
256 if (is_numeric($this->sortitemid)) {
257 $sql = "SELECT u.id, u.firstname, u.lastname
258 FROM {$CFG->prefix}grade_grades g RIGHT OUTER JOIN
259 {$CFG->prefix}user u ON (u.id = g.userid AND g.itemid = $this->sortitemid)
260 LEFT JOIN {$CFG->prefix}role_assignments ra ON u.id = ra.userid
261 $this->groupsql
262 WHERE ra.roleid in ($this->gradebookroles)
263 $this->groupwheresql
264 AND ra.contextid ".get_related_contexts_string($this->context)."
265 ORDER BY g.finalgrade $this->sortorder";
266 $this->users = get_records_sql($sql, $this->get_pref('studentsperpage') * $this->page,
267 $this->get_pref('studentsperpage'));
268 } else {
269 // default sort
270 // get users sorted by lastname
271 $this->users = get_role_users(@implode(',', $CFG->gradebookroles), $this->context, false,
272 'u.id, u.firstname, u.lastname', 'u.'.$this->sortitemid .' '. $this->sortorder,
273 false, $this->page * $this->get_pref('studentsperpage'), $this->get_pref('studentsperpage'),
274 $this->currentgroup);
275 // need to cut users down by groups
279 if (empty($this->users)) {
280 $this->userselect = '';
281 $this->users = array();
282 } else {
283 $this->userselect = 'AND g.userid in ('.implode(',', array_keys($this->users)).')';
286 return $this->users;
290 * Fetches and returns a count of all the users that will be shows on this page.
291 * @return int Count of users
293 function get_numusers() {
294 global $CFG;
296 $countsql = "SELECT COUNT(DISTINCT u.id)
297 FROM {$CFG->prefix}grade_grades g RIGHT OUTER JOIN
298 {$CFG->prefix}user u ON (u.id = g.userid AND g.itemid = $this->sortitemid)
299 LEFT JOIN {$CFG->prefix}role_assignments ra ON u.id = ra.userid
300 $this->groupsql
301 WHERE ra.roleid in ($this->gradebookroles)
302 $this->groupwheresql
303 AND ra.contextid ".get_related_contexts_string($this->context);
304 return count_records_sql($countsql);
308 * we supply the userids in this query, and get all the grades
309 * pulls out all the grades, this does not need to worry about paging
311 function load_final_grades() {
312 global $CFG;
314 $sql = "SELECT g.id, g.itemid, g.userid, g.finalgrade, g.hidden, g.locked, g.locktime, g.overridden,
315 gt.feedback, gt.feedbackformat,
316 gi.grademin, gi.grademax
317 FROM {$CFG->prefix}grade_items gi,
318 {$CFG->prefix}grade_grades g
319 LEFT JOIN {$CFG->prefix}grade_grades_text gt ON g.id = gt.gradeid
320 WHERE g.itemid = gi.id
321 AND gi.courseid = $this->courseid $this->userselect";
323 if ($grades = get_records_sql($sql)) {
324 foreach ($grades as $grade) {
325 $this->finalgrades[$grade->userid][$grade->itemid] = $grade;
331 * Builds and returns a div with on/off toggles.
332 * @return string HTML code
334 function get_toggles_html() {
335 global $USER;
336 $html = '<div id="grade-report-toggles">';
337 if ($USER->gradeediting) {
338 $html .= $this->print_toggle('eyecons', true);
339 $html .= $this->print_toggle('locks', true);
340 $html .= $this->print_toggle('calculations', true);
343 $html .= $this->print_toggle('averages', true);
344 $html .= $this->print_toggle('groups', true);
345 $html .= $this->print_toggle('ranges', true);
346 $html .= '</div>';
347 return $html;
351 * Shortcut function for printing the grader report toggles.
352 * @param string $type The type of toggle
353 * @param bool $return Whether to return the HTML string rather than printing it
354 * @return void
356 function print_toggle($type, $return=false) {
357 global $CFG;
359 $icons = array('eyecons' => 'hide',
360 'calculations' => 'calc',
361 'locks' => 'lock',
362 'averages' => 'sigma');
364 $pref_name = 'grade_report_show' . $type;
365 $show_pref = get_user_preferences($pref_name, $CFG->$pref_name);
367 $strshow = $this->get_lang_string('show' . $type, 'grades');
368 $strhide = $this->get_lang_string('hide' . $type, 'grades');
370 $show_hide = 'show';
371 $toggle_action = 1;
373 if ($show_pref) {
374 $show_hide = 'hide';
375 $toggle_action = 0;
378 if (array_key_exists($type, $icons)) {
379 $image_name = $icons[$type];
380 } else {
381 $image_name = $type;
384 $string = ${'str' . $show_hide};
386 $img = '<img src="'.$CFG->pixpath.'/t/'.$image_name.'.gif" class="iconsmall" alt="'
387 .$string.'" title="'.$string.'" />'. "\n";
389 $retval = '<div class="gradertoggle">' . $img . '<a href="' . $this->baseurl . "&amp;toggle=$toggle_action&amp;toggle_type=$type\">"
390 . $string . '</a></div>';
392 if ($return) {
393 return $retval;
394 } else {
395 echo $retval;
400 * Builds and returns the HTML code for the headers.
401 * @return string $headerhtml
403 function get_headerhtml() {
404 global $CFG, $USER;
406 $strsortasc = $this->get_lang_string('sortasc', 'grades');
407 $strsortdesc = $this->get_lang_string('sortdesc', 'grades');
408 if ($this->sortitemid === 'lastname') {
409 if ($this->sortorder == 'ASC') {
410 $lastarrow = print_arrow('up', $strsortasc, true);
411 } else {
412 $lastarrow = print_arrow('down', $strsortdesc, true);
414 } else {
415 $lastarrow = '';
418 if ($this->sortitemid === 'firstname') {
419 if ($this->sortorder == 'ASC') {
420 $firstarrow = print_arrow('up', $strsortasc, true);
421 } else {
422 $firstarrow = print_arrow('down', $strsortdesc, true);
424 } else {
425 $firstarrow = '';
427 // Prepare Table Headers
428 $headerhtml = '';
430 $numrows = count($this->gtree->levels);
432 foreach ($this->gtree->levels as $key=>$row) {
433 if ($key == 0) {
434 // do not diplay course grade category
435 // continue;
438 $headerhtml .= '<tr class="heading">';
440 if ($key == $numrows - 1) {
441 $headerhtml .= '<th class="user"><a href="'.$this->baseurl.'&amp;sortitemid=firstname">Firstname</a> ' //TODO: localize
442 . $firstarrow. '/ <a href="'.$this->baseurl.'&amp;sortitemid=lastname">Lastname </a>'. $lastarrow .'</th>';
443 } else {
444 $headerhtml .= '<td class="topleft">&nbsp;</td>';
447 foreach ($row as $element) {
448 // Load user preferences for categories
449 if ($element['type'] == 'category') {
450 $categoryid = $element['object']->id;
451 $aggregationview = $this->get_pref('aggregationview', $categoryid);
453 if ($aggregationview == GRADE_REPORT_AGGREGATION_VIEW_COMPACT) {
454 $categorystate = get_user_preferences('grade_report_categorystate' . $categoryid, GRADE_CATEGORY_EXPANDED);
456 // Expand/Contract icon must be set appropriately
457 if ($categorystate == GRADE_CATEGORY_CONTRACTED) {
458 // The category is contracted: this means we only show 1 item for this category: the
459 // category's aggregation item. The others must be removed from the grade_tree
460 } elseif ($categorystate == GRADE_CATEGORY_EXPANDED) {
461 // The category is expanded: we only show the non-aggregated items directly descending
462 // from this category. The category's grade_item must be removed from the grade_tree
467 $eid = $element['eid'];
468 $object = $element['object'];
469 $type = $element['type'];
471 if (!empty($element['colspan'])) {
472 $colspan = 'colspan="'.$element['colspan'].'"';
473 } else {
474 $colspan = '';
477 if (!empty($element['depth'])) {
478 $catlevel = ' catlevel'.$element['depth'];
479 } else {
480 $catlevel = '';
484 if ($type == 'filler' or $type == 'fillerfirst' or $type == 'fillerlast') {
485 $headerhtml .= '<th class="'.$type.$catlevel.'" '.$colspan.'>&nbsp;</th>';
486 } else if ($type == 'category') {
487 $headerhtml .= '<th class="category'.$catlevel.'" '.$colspan.'>'.$element['object']->get_name();
489 // Print icons
490 if ($USER->gradeediting) {
491 $headerhtml .= $this->get_icons($element);
494 $headerhtml .= '</th>';
495 } else {
496 if ($element['object']->id == $this->sortitemid) {
497 if ($this->sortorder == 'ASC') {
498 $arrow = print_arrow('up', $strsortasc, true);
499 } else {
500 $arrow = print_arrow('down', $strsortdesc, true);
502 } else {
503 $arrow = '';
506 $dimmed = '';
507 if ($element['object']->is_hidden()) {
508 $dimmed = ' dimmed_text ';
511 if ($object->itemtype == 'mod') {
512 $icon = '<img src="'.$CFG->modpixpath.'/'.$object->itemmodule.'/icon.gif" class="icon" alt="'
513 .$this->get_lang_string('modulename', $object->itemmodule).'"/>';
514 } else if ($object->itemtype == 'manual') {
515 //TODO: add manual grading icon
516 $icon = '<img src="'.$CFG->pixpath.'/t/edit.gif" class="icon" alt="'.$this->get_lang_string('manualgrade', 'grades')
517 .'"/>';
521 $headerhtml .= '<th class="'.$type.$catlevel.$dimmed.'"><a href="'.$this->baseurl.'&amp;sortitemid='
522 . $element['object']->id .'">'. $element['object']->get_name()
523 . '</a>' . $arrow;
525 $headerhtml .= $this->get_icons($element) . '</th>';
527 $this->items[$element['object']->sortorder] =& $element['object'];
532 $headerhtml .= '</tr>';
534 return $headerhtml;
538 * Builds and return the HTML rows of the table (grades headed by student).
539 * @return string HTML
541 function get_studentshtml() {
542 global $CFG, $USER;
543 $studentshtml = '';
544 $strfeedback = $this->get_lang_string("feedback");
545 $gradetabindex = 1;
546 $feedbacktabindex = 16380; // The maximum number of tabindices on 1 page is 32767
547 $showuserimage = $this->get_pref('showuserimage');
549 // Preload scale objects for items with a scaleid
550 $scales_list = '';
551 foreach ($this->items as $item) {
552 if (!empty($item->scaleid)) {
553 $scales_list .= "$item->scaleid,";
556 $scales_array = array();
558 if (!empty($scales_list)) {
559 $scales_list = substr($scales_list, 0, -1);
560 $scales_array = get_records_list('scale', 'id', $scales_list);
563 foreach ($this->users as $userid => $user) {
564 // Student name and link
565 $user_pic = null;
566 if ($showuserimage) {
567 $user_pic = '<div class="userpic">' . print_user_picture($user->id, $this->courseid, true, 0, true) . '</div>';
570 $studentshtml .= '<tr><th class="user">' . $user_pic . '<a href="' . $CFG->wwwroot . '/user/view.php?id='
571 . $user->id . '">' . fullname($user) . '</a></th>';
573 foreach ($this->items as $item) {
574 // Get the decimal points preference for this item
575 $decimalpoints = $this->get_pref('decimalpoints', $item->id);
577 if (isset($this->finalgrades[$userid][$item->id])) {
578 $gradeval = $this->finalgrades[$userid][$item->id]->finalgrade;
580 $grade = new grade_grade($this->finalgrades[$userid][$item->id], false);
581 $grade->feedback = stripslashes_safe($this->finalgrades[$userid][$item->id]->feedback);
582 $grade->feedbackformat = $this->finalgrades[$userid][$item->id]->feedbackformat;
584 } else {
585 $gradeval = null;
586 $grade = new grade_grade(array('userid' => $userid, 'itemid' => $item->id), false);
587 $grade->feedback = '';
590 if ($grade->is_overridden()) {
591 $studentshtml .= '<td class="overridden">';
592 } else {
593 $studentshtml .= '<td>';
596 // emulate grade element
597 $grade->courseid = $this->courseid;
598 $grade->grade_item = $item; // this may speedup is_hidden() and other grade_grade methods
599 $element = array ('eid'=>'g'.$grade->id, 'object'=>$grade, 'type'=>'grade');
601 // Do not show any icons if no grade (no record in DB to match)
602 // TODO: change edit/hide/etc. links to use itemid and userid to allow creating of new grade objects
603 if (!empty($grade->id) && $USER->gradeediting) {
604 $states = array('is_hidden' => $item->hidden,
605 'is_locked' => $item->locked,
606 'is_editable' => $item->gradetype != GRADE_TYPE_NONE && !$grade->locked && !$item->locked);
607 $studentshtml .= $this->get_icons($element, null, true, $states);
610 // if in editting mode, we need to print either a text box
611 // or a drop down (for scales)
612 // grades in item of type grade category or course are not directly editable
613 if ($USER->gradeediting) {
614 // We need to retrieve each grade_grade object from DB in order to
615 // know if they are hidden/locked
617 if ($item->scaleid && !empty($scales_array[$item->scaleid])) {
618 $scale = $scales_array[$item->scaleid];
620 $scales = explode(",", $scale->scale);
621 // reindex because scale is off 1
622 $i = 0;
623 foreach ($scales as $scaleoption) {
624 $i++;
625 $scaleopt[$i] = $scaleoption;
628 if ($this->get_pref('quickgrading') and $grade->is_editable()) {
629 $studentshtml .= '<input type="hidden" name="oldgrade_'.$userid.'_'
630 .$item->id.'" value="'.$gradeval.'"/>';
631 $studentshtml .= choose_from_menu($scaleopt, 'grade_'.$userid.'_'.$item->id,
632 $gradeval, $this->get_lang_string('nograde'), '', '-1', true, false, $gradetabindex++);
633 } elseif(!empty($scale)) {
634 $scales = explode(",", $scale->scale);
636 // invalid grade if gradeval < 1
637 if ((int) $gradeval < 1) {
638 $studentshtml .= '-';
639 } else {
640 $studentshtml .= $scales[$gradeval-1];
642 } else {
643 // no such scale, throw error?
646 } else if ($item->gradetype != GRADE_TYPE_TEXT) { // Value type
647 if ($this->get_pref('quickgrading') and $grade->is_editable()) {
648 $value = $this->get_grade_clean($gradeval, $decimalpoints);
649 $studentshtml .= '<input type="hidden" name="oldgrade_'.$userid.'_'.$item->id.'" value="'.$value.'" />';
650 $studentshtml .= '<input size="6" tabindex="' . $gradetabindex++ . '" type="text" name="grade_'.$userid.'_'
651 .$item->id.'" value="'.$value.'" />';
652 } else {
653 $studentshtml .= $this->get_grade_clean($gradeval, $decimalpoints);
658 // If quickfeedback is on, print an input element
659 if ($this->get_pref('quickfeedback') and $grade->is_editable()) {
660 if ($this->get_pref('quickgrading')) {
661 $studentshtml .= '<br />';
663 $studentshtml .= '<input type="hidden" name="oldfeedback_'
664 .$userid.'_'.$item->id.'" value="' . s($grade->feedback) . '" />';
665 $studentshtml .= '<input tabindex="' . $feedbacktabindex++ . '" size="6" type="text" name="feedback_'
666 .$userid.'_'.$item->id.'" value="' . s($grade->feedback) . '" />';
669 } else {
670 // Percentage format if specified by user (check each item for a set preference)
671 $gradedisplaytype = $this->get_pref('gradedisplaytype', $item->id);
673 $percentsign = '';
674 $grademin = $item->grademin;
675 $grademax = $item->grademax;
677 if ($gradedisplaytype == GRADE_REPORT_GRADE_DISPLAY_TYPE_PERCENTAGE) {
678 if (!is_null($gradeval)) {
679 $gradeval = grade_grade::standardise_score($gradeval, $grademin, $grademax, 0, 100);
681 $percentsign = '%';
684 // If feedback present, surround grade with feedback tooltip
685 if (!empty($grade->feedback)) {
686 if ($grade->feedbackformat == 1) {
687 $overlib = "return overlib('" . s(ltrim($grade->feedback)) . "', FULLHTML);";
688 } else {
689 $overlib = "return overlib('" . ($grade->feedback) . "', CAPTION, '$strfeedback');";
692 $studentshtml .= '<span onmouseover="' . $overlib . '" onmouseout="return nd();">';
695 if ($gradedisplaytype == GRADE_REPORT_GRADE_DISPLAY_TYPE_LETTER) {
696 $letters = grade_report::get_grade_letters();
697 if (!is_null($gradeval)) {
698 $studentshtml .= grade_grade::get_letter($letters, $gradeval, $grademin, $grademax);
700 } else if ($item->scaleid && !empty($scales_array[$item->scaleid])
701 && $gradedisplaytype == GRADE_REPORT_GRADE_DISPLAY_TYPE_REAL) {
702 $scale = $scales_array[$item->scaleid];
703 $scales = explode(",", $scale->scale);
705 // invalid grade if gradeval < 1
706 if ((int) $gradeval < 1) {
707 $studentshtml .= '-';
708 } else {
709 $studentshtml .= $scales[$gradeval-1];
711 } else {
712 if (is_null($gradeval)) {
713 $studentshtml .= '-';
714 } else {
715 $studentshtml .= $this->get_grade_clean($gradeval, $decimalpoints). $percentsign;
718 if (!empty($grade->feedback)) {
719 $studentshtml .= '</span>';
723 if (!empty($this->gradeserror[$item->id][$userid])) {
724 $studentshtml .= $this->gradeserror[$item->id][$userid];
727 $studentshtml .= '</td>' . "\n";
729 $studentshtml .= '</tr>';
731 return $studentshtml;
735 * Builds and return the HTML rows of the table (grades headed by student).
736 * @return string HTML
738 function get_groupavghtml() {
739 global $CFG, $USER;
741 $averagesdisplaytype = $this->get_pref('averagesdisplaytype');
742 $mean_pref = $this->get_pref('meanselection');
743 $groupavghtml = '';
745 if ($mean_pref == GRADE_AGGREGATE_MEAN_GRADED) {
746 // non empty grades
747 $meanstr = "AND NOT g.finalgrade IS NULL";
748 } else {
749 $meanstr = "";
752 if ($this->currentgroup && $this->get_pref('showgroups')) {
754 /** SQL for finding group sum */
755 // do not sum -1 (no grade), treat as 0 for now
756 $SQL = "SELECT g.itemid, SUM(g.finalgrade) as sum, COUNT(DISTINCT(u.id)) as count
757 FROM {$CFG->prefix}grade_items gi LEFT JOIN
758 {$CFG->prefix}grade_grades g ON gi.id = g.itemid RIGHT OUTER JOIN
759 {$CFG->prefix}user u ON u.id = g.userid LEFT JOIN
760 {$CFG->prefix}role_assignments ra ON u.id = ra.userid
761 $this->groupsql
762 WHERE gi.courseid = $this->courseid
763 $this->groupwheresql
764 AND ra.roleid in ($this->gradebookroles)
765 AND ra.contextid ".get_related_contexts_string($this->context)."
766 $meanstr
767 GROUP BY g.itemid";
769 $groupsum = array();
770 $groupscount = array();
771 $sums = get_records_sql($SQL);
772 foreach ($sums as $itemid => $csum) {
773 $groupsum[$itemid] = $csum->sum;
774 $groupscount[$itemid] = $csum->count;
777 $groupavghtml = '<tr><th>'.get_string('groupavg', 'grades').'</th>';
778 foreach ($this->items as $item) {
779 $decimalpoints = $this->get_pref('decimalpoints', $item->id);
780 // Determine which display type to use for this average
781 $gradedisplaytype = $this->get_pref('gradedisplaytype', $item->id);
782 if ($USER->gradeediting) {
783 $displaytype = GRADE_REPORT_GRADE_DISPLAY_TYPE_REAL;
784 } elseif ($averagesdisplaytype == GRADE_REPORT_PREFERENCE_INHERIT) { // Inherit specific column or general preference
785 $displaytype = $gradedisplaytype;
786 } else { // General preference overrides specific column display type
787 $displaytype = $averagesdisplaytype;
790 if (empty($groupscount[$item->id]) || !isset($groupsum[$item->id])) {
791 $groupavghtml .= '<td>-</td>';
792 } else {
793 $sum = $groupsum[$item->id];
795 if ($item->scaleid) {
796 $gradeitemsum = $groupsum[$item->id];
797 $gradeitemavg = $gradeitemsum/$groupscount[$item->id];
799 $scaleval = round($this->get_grade_clean($gradeitemavg, $decimalpoints));
801 $scales_array = get_records_list('scale', 'id', $item->scaleid);
802 $scale = $scales_array[$item->scaleid];
803 $scales = explode(",", $scale->scale);
805 // this could be a 0 when summed and rounded, e.g, 1, no grade, no grade, no grade
806 if ($scaleval < 1) {
807 $scaleval = 1;
810 $gradehtml = $scales[$scaleval-1];
811 $rawvalue = $scaleval;
812 } else {
813 $gradeval = $this->get_grade_clean($sum/$groupscount[$item->id], $decimalpoints);
814 $gradehtml = round($gradeval, $decimalpoints);
815 $rawvalue = $gradeval;
818 if ($displaytype == GRADE_REPORT_GRADE_DISPLAY_TYPE_PERCENTAGE) {
819 $gradeval = grade_grade::standardise_score($rawvalue, $item->grademin, $item->grademax, 0, 100);
820 $gradehtml = round($gradeval, $decimalpoints) . '%';
821 } elseif ($displaytype == GRADE_REPORT_GRADE_DISPLAY_TYPE_LETTER) {
822 $letters = grade_report::get_grade_letters();
823 $gradehtml = grade_grade::get_letter($letters, $gradeval, $item->grademin, $item->grademax);
826 $groupavghtml .= '<td>'.$gradehtml.'</td>';
829 $groupavghtml .= '</tr>';
831 return $groupavghtml;
835 * Builds and return the HTML row of column totals.
836 * @return string HTML
838 function get_gradeavghtml() {
839 global $CFG, $USER;
841 $averagesdisplaytype = $this->get_pref('averagesdisplaytype');
842 $meanselection = $this->get_pref('meanselection');
843 $mean_pref = get_user_preferences('grade_report_meanselection', $CFG->grade_report_meanselection);
844 $gradeavghtml = '';
846 if ($mean_pref == 2) {
847 // non empty grades
848 $meanstr = "AND NOT g.finalgrade IS NULL";
849 } else {
850 $meanstr = "";
852 if ($this->get_pref('showaverages')) {
854 /** SQL for finding the SUM grades of all visible users ($CFG->gradebookroles) */
855 // do not sum -1 (no grade), treat as 0 for now
856 $SQL = "SELECT g.itemid, SUM(g.finalgrade) as sum, COUNT(DISTINCT(u.id)) as count
857 FROM {$CFG->prefix}grade_items gi LEFT JOIN
858 {$CFG->prefix}grade_grades g ON gi.id = g.itemid RIGHT OUTER JOIN
859 {$CFG->prefix}user u ON u.id = g.userid LEFT JOIN
860 {$CFG->prefix}role_assignments ra ON u.id = ra.userid
861 WHERE gi.courseid = $this->courseid
862 AND ra.roleid in ($this->gradebookroles)
863 AND ra.contextid ".get_related_contexts_string($this->context)."
864 $meanstr
865 GROUP BY g.itemid";
867 $classsum = array();
869 $sums = get_records_sql($SQL);
871 foreach ($sums as $itemid => $csum) {
872 $classsum[$itemid] = $csum->sum;
873 $classcount[$itemid] = $csum->count;
876 $gradeavghtml = '<tr><th>'.get_string('average', 'grades').'</th>';
877 foreach ($this->items as $item) {
878 $decimalpoints = $this->get_pref('decimalpoints', $item->id);
879 // Determine which display type to use for this average
880 $gradedisplaytype = $this->get_pref('gradedisplaytype', $item->id);
881 if ($USER->gradeediting) {
882 $displaytype = GRADE_REPORT_GRADE_DISPLAY_TYPE_REAL;
883 } elseif ($averagesdisplaytype == GRADE_REPORT_PREFERENCE_INHERIT) { // Inherit specific column or general preference
884 $displaytype = $gradedisplaytype;
885 } else { // General preference overrides specific column display type
886 $displaytype = $averagesdisplaytype;
889 if (empty($classcount[$item->id]) || !isset($classsum[$item->id])) {
890 $gradeavghtml .= '<td>-</td>';
891 } else {
892 $sum = $classsum[$item->id];
894 if ($item->scaleid) {
895 $scaleval = round($this->get_grade_clean($sum/$classcount[$item->id], $decimalpoints));
896 $scales_array = get_records_list('scale', 'id', $item->scaleid);
897 $scale = $scales_array[$item->scaleid];
898 $scales = explode(",", $scale->scale);
900 // this could be a 0 when summed and rounded, e.g, 1, no grade, no grade, no grade
901 if ($scaleval < 1) {
902 $scaleval = 1;
905 $gradehtml = $scales[$scaleval-1];
906 $rawvalue = $scaleval;
907 } else {
908 $gradeval = $this->get_grade_clean($sum/$classcount[$item->id], $decimalpoints);
910 $gradehtml = round($gradeval, $decimalpoints);
911 $rawvalue = $gradeval;
914 if ($displaytype == GRADE_REPORT_GRADE_DISPLAY_TYPE_PERCENTAGE) {
915 $gradeval = grade_grade::standardise_score($rawvalue, $item->grademin, $item->grademax, 0, 100);
916 $gradehtml = round($gradeval, $decimalpoints) . '%';
917 } elseif ($displaytype == GRADE_REPORT_GRADE_DISPLAY_TYPE_LETTER) {
918 $letters = grade_report::get_grade_letters();
919 $gradehtml = grade_grade::get_letter($letters, $gradeval, $item->grademin, $item->grademax);
922 $gradeavghtml .= '<td>'.$gradehtml.'</td>';
925 $gradeavghtml .= '</tr>';
927 return $gradeavghtml;
931 * Builds and return the HTML row of ranges for each column (i.e. range).
932 * @return string HTML
934 function get_rangehtml() {
935 global $USER;
937 $scalehtml = '';
938 if ($this->get_pref('showranges')) {
939 $rangesdisplaytype = $this->get_pref('rangesdisplaytype');
940 $scalehtml = '<tr><th class="range">'.$this->get_lang_string('range','grades').'</th>';
941 foreach ($this->items as $item) {
942 $decimalpoints = $this->get_pref('decimalpoints', $item->id);
943 // Determine which display type to use for this range
944 $gradedisplaytype = $this->get_pref('gradedisplaytype', $item->id);
946 if ($USER->gradeediting) {
947 $displaytype = GRADE_REPORT_GRADE_DISPLAY_TYPE_REAL;
948 } elseif ($rangesdisplaytype == GRADE_REPORT_PREFERENCE_INHERIT) { // Inherit specific column or general preference
949 $displaytype = $gradedisplaytype;
950 } else { // General preference overrides specific column display type
951 $displaytype = $rangesdisplaytype;
954 if ($displaytype == GRADE_REPORT_GRADE_DISPLAY_TYPE_REAL) {
955 $grademin = $this->get_grade_clean($item->grademin, $decimalpoints);
956 $grademax = $this->get_grade_clean($item->grademax, $decimalpoints);
957 } elseif ($displaytype == GRADE_REPORT_GRADE_DISPLAY_TYPE_PERCENTAGE) {
958 $grademin = 0;
959 $grademax = 100;
960 } elseif ($displaytype == GRADE_REPORT_GRADE_DISPLAY_TYPE_LETTER) {
961 $letters = grade_report::get_grade_letters();
962 $grademin = end($letters);
963 $grademax = reset($letters);
966 $scalehtml .= '<th class="range">'. $grademin.'-'. $grademax.'</th>';
968 $scalehtml .= '</tr>';
970 return $scalehtml;
974 * Given a grade_category, grade_item or grade_grade, this function
975 * figures out the state of the object and builds then returns a div
976 * with the icons needed for the grader report.
978 * @param object $object
979 * @param array $icons An array of icon names that this function is explicitly requested to print, regardless of settings
980 * @param bool $limit If true, use the $icons array as the only icons that will be printed. If false, use it to exclude these icons.
981 * @param object $states An optional array of states (hidden, locked, editable), shortcuts to increase performance.
982 * @return string HTML
984 function get_icons($element, $icons=null, $limit=true, $states=array()) {
985 global $CFG;
986 global $USER;
988 // Load language strings
989 $stredit = $this->get_lang_string("edit");
990 $streditcalculation= $this->get_lang_string("editcalculation", 'grades');
991 $strfeedback = $this->get_lang_string("feedback");
992 $strmove = $this->get_lang_string("move");
993 $strmoveup = $this->get_lang_string("moveup");
994 $strmovedown = $this->get_lang_string("movedown");
995 $strmovehere = $this->get_lang_string("movehere");
996 $strcancel = $this->get_lang_string("cancel");
997 $stredit = $this->get_lang_string("edit");
998 $strdelete = $this->get_lang_string("delete");
999 $strhide = $this->get_lang_string("hide");
1000 $strshow = $this->get_lang_string("show");
1001 $strlock = $this->get_lang_string("lock", 'grades');
1002 $strswitch_minus = $this->get_lang_string("contract", 'grades');
1003 $strswitch_plus = $this->get_lang_string("expand", 'grades');
1004 $strunlock = $this->get_lang_string("unlock", 'grades');
1006 // Prepare container div
1007 $html = '<div class="grade_icons">';
1009 // Prepare reference variables
1010 $eid = $element['eid'];
1011 $object = $element['object'];
1012 $type = $element['type'];
1014 if (empty($states)) {
1015 $states['is_hidden'] = $object->is_hidden();
1016 $states['is_locked'] = $object->is_locked();
1017 $states['is_editable'] = $object->is_editable();
1020 // Add mock attributes in case the object is not of the right type
1021 if ($type != 'grade') {
1022 $object->feedback = '';
1025 $overlib = '';
1026 if (!empty($object->feedback)) {
1027 if (empty($object->feedbackformat) || $object->feedbackformat != 1) {
1028 $function = "return overlib('" . strip_tags($object->feedback) . "', CAPTION, '$strfeedback');";
1029 } else {
1030 $function = "return overlib('" . s(ltrim($object->feedback) . "', FULLHTML);");
1032 $overlib = 'onmouseover="' . $function . '" onmouseout="return nd();"';
1035 // Prepare image strings
1036 $edit_icon = '';
1037 if ($states['is_editable']) {
1038 if ($type == 'category') {
1039 $url = GRADE_EDIT_URL . '/category.php?courseid='.$object->courseid.'&amp;id='.$object->id;
1040 $url = $this->gpr->add_url_params($url);
1041 $edit_icon = '<a href="'.$url.'"><img src="'.$CFG->pixpath.'/t/edit.gif" class="iconsmall" alt="'
1042 . $stredit.'" title="'.$stredit.'" /></a>'. "\n";
1043 } else if ($type == 'item' or $type == 'categoryitem' or $type == 'courseitem'){
1044 $url = GRADE_EDIT_URL . '/item.php?courseid='.$object->courseid.'&amp;id='.$object->id;
1045 $url = $this->gpr->add_url_params($url);
1046 $edit_icon = '<a href="'.$url.'"><img src="'.$CFG->pixpath.'/t/edit.gif" class="iconsmall" alt="'
1047 . $stredit.'" title="'.$stredit.'" /></a>'. "\n";
1048 } else if ($type == 'grade' and ($states['is_editable'] or empty($object->id))) {
1049 // TODO: change link to use itemid and userid to allow creating of new grade objects
1050 $url = GRADE_EDIT_URL . '/grade.php?courseid='.$object->courseid.'&amp;id='.$object->id;
1051 $url = $this->gpr->add_url_params($url);
1052 $edit_icon = '<a href="'.$url.'"><img ' . $overlib . ' src="'.$CFG->pixpath.'/t/edit.gif"'
1053 . 'class="iconsmall" alt="' . $stredit.'" title="'.$stredit.'" /></a>'. "\n";
1057 $edit_calculation_icon = '';
1058 if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
1059 // show calculation icon only when calculation possible
1060 if (!$object->is_normal_item() and ($object->gradetype == GRADE_TYPE_SCALE or $object->gradetype == GRADE_TYPE_VALUE)) {
1061 $url = GRADE_EDIT_URL . '/calculation.php?courseid='.$object->courseid.'&amp;id='.$object->id;
1062 $url = $this->gpr->add_url_params($url);
1063 $edit_calculation_icon = '<a href="'. $url.'"><img src="'.$CFG->pixpath.'/t/calc.gif" class="iconsmall" alt="'
1064 . $streditcalculation.'" title="'.$streditcalculation.'" /></a>'. "\n";
1068 // Prepare Hide/Show icon state
1069 $hide_show = 'hide';
1070 if ($states['is_hidden']) {
1071 $hide_show = 'show';
1074 $show_hide_icon = '<a href="report.php?report=grader&amp;target='.$eid
1075 . "&amp;action=$hide_show" . $this->gtree->commonvars . "\">\n"
1076 . '<img src="'.$CFG->pixpath.'/t/'.$hide_show.'.gif" class="iconsmall" alt="'
1077 . ${'str' . $hide_show}.'" title="'.${'str' . $hide_show}.'" /></a>'. "\n";
1079 // Prepare lock/unlock string
1080 $lock_unlock = 'lock';
1081 if ($states['is_locked']) {
1082 $lock_unlock = 'unlock';
1085 // Print lock/unlock icon
1087 $lock_unlock_icon = '<a href="report.php?report=grader&amp;target='.$eid
1088 . "&amp;action=$lock_unlock" . $this->gtree->commonvars . "\">\n"
1089 . '<img src="'.$CFG->pixpath.'/t/'.$lock_unlock.'.gif" class="iconsmall" alt="'
1090 . ${'str' . $lock_unlock}.'" title="'.${'str' . $lock_unlock}.'" /></a>'. "\n";
1092 // Prepare expand/contract string
1093 $expand_contract = 'switch_minus'; // Default: expanded
1094 $state = get_user_preferences('grade_category_' . $object->id, GRADE_CATEGORY_EXPANDED);
1095 if ($state == GRADE_CATEGORY_CONTRACTED) {
1096 $expand_contract = 'switch_plus';
1099 $contract_expand_icon = '<a href="report.php?report=grader&amp;target=' . $eid
1100 . "&amp;action=$expand_contract" . $this->gtree->commonvars . "\">\n"
1101 . '<img src="'.$CFG->pixpath.'/t/'.$expand_contract.'.gif" class="iconsmall" alt="'
1102 . ${'str' . $expand_contract}.'" title="'.${'str' . $expand_contract}.'" /></a>'. "\n";
1104 // If an array of icon names is given, return only these in the order they are given
1105 if (!empty($icons) && is_array($icons)) {
1106 $new_html = '';
1108 foreach ($icons as $icon_name) {
1109 if ($limit) {
1110 $new_html .= ${$icon_name . '_icon'};
1111 } else {
1112 ${'show_' . $icon_name} = false;
1115 if ($limit) {
1116 return $new_html;
1117 } else {
1118 $html .= $new_html;
1122 // Icons shown when edit mode is on
1123 if ($USER->gradeediting) {
1124 // Edit icon (except for grade_grade)
1125 if ($edit_icon) {
1126 $html .= $edit_icon;
1129 // Calculation icon for items and categories
1130 if ($this->get_pref('showcalculations')) {
1131 $html .= $edit_calculation_icon;
1134 if ($this->get_pref('showeyecons')) {
1135 $html .= $show_hide_icon;
1138 if ($this->get_pref('showlocks')) {
1139 $html .= $lock_unlock_icon;
1142 // If object is a category, display expand/contract icon
1143 if (get_class($object) == 'grade_category' && $this->get_pref('aggregationview') == GRADE_REPORT_AGGREGATION_VIEW_COMPACT) {
1144 $html .= $contract_expand_icon;
1146 } else { // Editing mode is off
1149 return $html . '</div>';