MDL-9628 Removed superfluous & in URL (part of $report->baseurl) and reversed the...
[moodle-pu.git] / grade / report / grader / lib.php
bloba620934d1ba5e807b965730e312ecbb1533e24c0
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 /**
55 * List of collapsed captegories from user perference
56 * @var array $collapsed
58 var $collapsed;
60 /**
61 * Constructor. Sets local copies of user preferences and initialises grade_tree.
62 * @param int $courseid
63 * @param object $gpr grade plugin return tracking object
64 * @param string $context
65 * @param int $page The current page being viewed (when report is paged)
66 * @param int $sortitemid The id of the grade_item by which to sort the table
68 function grade_report_grader($courseid, $gpr, $context, $page=null, $sortitemid=null) {
69 global $CFG;
70 parent::grade_report($courseid, $gpr, $context, $page);
72 // load collapsed settings for this report
73 if ($collapsed = get_user_preferences('grade_report_grader_collapsed_categories')) {
74 $this->collapsed = unserialize($collapsed);
75 foreach ($this->collapsed as $key=>$id) {
76 if ($this->get_pref('aggregationview', $id) == GRADE_REPORT_AGGREGATION_VIEW_FULL) {
77 unset($this->collapsed[$key]); // full view categories can not be collapsed
80 } else {
81 $this->collapsed = array();
83 // Grab the grade_tree for this course
84 $this->gtree = new grade_tree($this->courseid, true, $this->get_pref('aggregationposition'), $this->collapsed);
86 $this->sortitemid = $sortitemid;
88 // base url for sorting by first/last name
89 $this->baseurl = 'index.php?id='.$this->courseid.'&amp;perpage='.$this->get_pref('studentsperpage')
90 .'&amp;page='.$this->page;
92 $this->pbarurl = 'index.php?id='.$this->courseid.'&amp;perpage='.$this->get_pref('studentsperpage');
94 // Setup groups if requested
95 if ($this->get_pref('showgroups')) {
96 $this->setup_groups();
99 $this->setup_sortitemid();
103 * Processes the data sent by the form (grades and feedbacks).
104 * @var array $data
105 * @return bool Success or Failure (array of errors).
107 function process_data($data) {
109 if (!has_capability('moodle/grade:override', $this->context)) {
110 return false;
113 // always initialize all arrays
114 $queue = array();
115 foreach ($data as $varname => $postedvalue) {
117 $needsupdate = false;
118 $note = false; // TODO implement note??
120 // skip, not a grade nor feedback
121 if (strpos($varname, 'grade') === 0) {
122 $data_type = 'grade';
123 } else if (strpos($varname, 'feedback') === 0) {
124 $data_type = 'feedback';
125 } else {
126 continue;
129 $gradeinfo = explode("_", $varname);
130 $userid = clean_param($gradeinfo[1], PARAM_INT);
131 $itemid = clean_param($gradeinfo[2], PARAM_INT);
133 $oldvalue = $data->{'old'.$varname};
135 // was change requested?
136 if ($oldvalue == $postedvalue) {
137 continue;
140 if (!$grade_item = grade_item::fetch(array('id'=>$itemid, 'courseid'=>$this->courseid))) { // we must verify course id here!
141 error('Incorrect grade item id');
144 // Pre-process grade
145 if ($data_type == 'grade') {
146 $feedback = false;
147 $feedbackformat = false;
148 if ($grade_item->gradetype == GRADE_TYPE_SCALE) {
149 if ($postedvalue == -1) { // -1 means no grade
150 $finalgrade = null;
151 } else {
152 $finalgrade = $postedvalue;
154 } else {
155 $trimmed = trim($postedvalue);
156 if (empty($trimmed)) { // empty string means no grade
157 $finalgrade = null;
158 } else {
159 $finalgrade = $this->format_grade($postedvalue);
163 } else if ($data_type == 'feedback') {
164 $finalgrade = false;
165 $trimmed = trim($postedvalue);
166 if (empty($trimmed)) {
167 $feedback = NULL;
168 } else {
169 $feedback = stripslashes($postedvalue);
173 $grade_item->update_final_grade($userid, $finalgrade, 'gradebook', $note, $feedback);
176 return true;
181 * Setting the sort order, this depends on last state
182 * all this should be in the new table class that we might need to use
183 * for displaying grades.
185 function setup_sortitemid() {
187 global $SESSION;
189 if ($this->sortitemid) {
190 if (!isset($SESSION->gradeuserreport->sort)) {
191 $this->sortorder = $SESSION->gradeuserreport->sort = 'DESC';
192 } else {
193 // this is the first sort, i.e. by last name
194 if (!isset($SESSION->gradeuserreport->sortitemid)) {
195 $this->sortorder = $SESSION->gradeuserreport->sort = 'DESC';
196 } else if ($SESSION->gradeuserreport->sortitemid == $this->sortitemid) {
197 // same as last sort
198 if ($SESSION->gradeuserreport->sort == 'ASC') {
199 $this->sortorder = $SESSION->gradeuserreport->sort = 'DESC';
200 } else {
201 $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC';
203 } else {
204 $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC';
207 $SESSION->gradeuserreport->sortitemid = $this->sortitemid;
208 } else {
209 // not requesting sort, use last setting (for paging)
211 if (isset($SESSION->gradeuserreport->sortitemid)) {
212 $this->sortitemid = $SESSION->gradeuserreport->sortitemid;
214 if (isset($SESSION->gradeuserreport->sort)) {
215 $this->sortorder = $SESSION->gradeuserreport->sort;
216 } else {
217 $this->sortorder = 'ASC';
223 * pulls out the userids of the users to be display, and sort them
224 * the right outer join is needed because potentially, it is possible not
225 * to have the corresponding entry in grade_grades table for some users
226 * this is check for user roles because there could be some users with grades
227 * but not supposed to be displayed
229 function load_users() {
230 global $CFG;
232 if (is_numeric($this->sortitemid)) {
233 $sql = "SELECT u.id, u.firstname, u.lastname
234 FROM {$CFG->prefix}grade_grades g RIGHT OUTER JOIN
235 {$CFG->prefix}user u ON (u.id = g.userid AND g.itemid = $this->sortitemid)
236 LEFT JOIN {$CFG->prefix}role_assignments ra ON u.id = ra.userid
237 $this->groupsql
238 WHERE ra.roleid in ($this->gradebookroles)
239 $this->groupwheresql
240 AND ra.contextid ".get_related_contexts_string($this->context)."
241 ORDER BY g.finalgrade $this->sortorder";
242 $this->users = get_records_sql($sql, $this->get_pref('studentsperpage') * $this->page,
243 $this->get_pref('studentsperpage'));
244 } else {
245 // default sort
246 // get users sorted by lastname
247 $this->users = get_role_users(@implode(',', $CFG->gradebookroles), $this->context, false,
248 'u.id, u.firstname, u.lastname', 'u.'.$this->sortitemid .' '. $this->sortorder,
249 false, $this->page * $this->get_pref('studentsperpage'), $this->get_pref('studentsperpage'),
250 $this->currentgroup);
251 // need to cut users down by groups
255 if (empty($this->users)) {
256 $this->userselect = '';
257 $this->users = array();
258 } else {
259 $this->userselect = 'AND g.userid in ('.implode(',', array_keys($this->users)).')';
262 return $this->users;
266 * Fetches and returns a count of all the users that will be shown on this page.
267 * @return int Count of users
269 function get_numusers() {
270 global $CFG;
272 $countsql = "SELECT COUNT(DISTINCT u.id)
273 FROM {$CFG->prefix}grade_grades g RIGHT OUTER JOIN
274 {$CFG->prefix}user u ON (u.id = g.userid AND g.itemid = $this->sortitemid)
275 LEFT JOIN {$CFG->prefix}role_assignments ra ON u.id = ra.userid
276 $this->groupsql
277 WHERE ra.roleid in ($this->gradebookroles)
278 $this->groupwheresql
279 AND ra.contextid ".get_related_contexts_string($this->context);
280 return count_records_sql($countsql);
284 * we supply the userids in this query, and get all the grades
285 * pulls out all the grades, this does not need to worry about paging
287 function load_final_grades() {
288 global $CFG;
290 // please note that we must fetch all grade_grades fields if we want to contruct grade_grade object from it!
291 $sql = "SELECT g.*, gt.feedback, gt.feedbackformat, gi.grademin, gi.grademax
292 FROM {$CFG->prefix}grade_items gi,
293 {$CFG->prefix}grade_grades g
294 LEFT JOIN {$CFG->prefix}grade_grades_text gt ON g.id = gt.gradeid
295 WHERE g.itemid = gi.id AND gi.courseid = $this->courseid $this->userselect";
297 if ($grades = get_records_sql($sql)) {
298 foreach ($grades as $grade) {
299 $this->finalgrades[$grade->userid][$grade->itemid] = $grade;
305 * Builds and returns a div with on/off toggles.
306 * @return string HTML code
308 function get_toggles_html() {
309 global $USER;
310 $html = '<div id="grade-report-toggles">';
311 if ($USER->gradeediting[$this->courseid]) {
312 if (has_capability('moodle/grade:manage', $this->context) or has_capability('moodle/grade:hide', $this->context)) {
313 $html .= $this->print_toggle('eyecons', true);
315 if (has_capability('moodle/grade:manage', $this->context)
316 or has_capability('moodle/grade:lock', $this->context)
317 or has_capability('moodle/grade:unlock', $this->context)) {
318 $html .= $this->print_toggle('locks', true);
320 if (has_capability('moodle/grade:manage', $this->context)) {
321 $html .= $this->print_toggle('calculations', true);
325 $html .= $this->print_toggle('averages', true);
326 $html .= $this->print_toggle('groups', true);
327 $html .= $this->print_toggle('ranges', true);
328 $html .= '</div>';
329 return $html;
333 * Shortcut function for printing the grader report toggles.
334 * @param string $type The type of toggle
335 * @param bool $return Whether to return the HTML string rather than printing it
336 * @return void
338 function print_toggle($type, $return=false) {
339 global $CFG;
341 $icons = array('eyecons' => 'hide',
342 'calculations' => 'calc',
343 'locks' => 'lock',
344 'averages' => 'sigma');
346 $pref_name = 'grade_report_show' . $type;
347 $show_pref = get_user_preferences($pref_name, $CFG->$pref_name);
349 $strshow = $this->get_lang_string('show' . $type, 'grades');
350 $strhide = $this->get_lang_string('hide' . $type, 'grades');
352 $show_hide = 'show';
353 $toggle_action = 1;
355 if ($show_pref) {
356 $show_hide = 'hide';
357 $toggle_action = 0;
360 if (array_key_exists($type, $icons)) {
361 $image_name = $icons[$type];
362 } else {
363 $image_name = $type;
366 $string = ${'str' . $show_hide};
368 $img = '<img src="'.$CFG->pixpath.'/t/'.$image_name.'.gif" class="iconsmall" alt="'
369 .$string.'" title="'.$string.'" />'. "\n";
371 $retval = '<div class="gradertoggle">' . $img . '<a href="' . $this->baseurl . "&amp;toggle=$toggle_action&amp;toggle_type=$type\">"
372 . $string . '</a></div>';
374 if ($return) {
375 return $retval;
376 } else {
377 echo $retval;
382 * Builds and returns the HTML code for the headers.
383 * @return string $headerhtml
385 function get_headerhtml() {
386 global $CFG, $USER;
388 $strsortasc = $this->get_lang_string('sortasc', 'grades');
389 $strsortdesc = $this->get_lang_string('sortdesc', 'grades');
390 $strfirstname = $this->get_lang_string('firstname');
391 $strlastname = $this->get_lang_string('lastname');
393 if ($this->sortitemid === 'lastname') {
394 if ($this->sortorder == 'ASC') {
395 $lastarrow = print_arrow('up', $strsortasc, true);
396 } else {
397 $lastarrow = print_arrow('down', $strsortdesc, true);
399 } else {
400 $lastarrow = '';
403 if ($this->sortitemid === 'firstname') {
404 if ($this->sortorder == 'ASC') {
405 $firstarrow = print_arrow('up', $strsortasc, true);
406 } else {
407 $firstarrow = print_arrow('down', $strsortdesc, true);
409 } else {
410 $firstarrow = '';
412 // Prepare Table Headers
413 $headerhtml = '';
415 $numrows = count($this->gtree->levels);
417 $columns_to_unset = array();
419 foreach ($this->gtree->levels as $key=>$row) {
420 if ($key == 0) {
421 // do not display course grade category
422 // continue;
425 $headerhtml .= '<tr class="heading">';
427 if ($key == $numrows - 1) {
428 $headerhtml .= '<th class="user"><a href="'.$this->baseurl.'&amp;sortitemid=firstname">' . $strfirstname . '</a> ' //TODO: localize
429 . $firstarrow. '/ <a href="'.$this->baseurl.'&amp;sortitemid=lastname">' . $strlastname . '</a>'. $lastarrow .'</th>';
430 } else {
431 $headerhtml .= '<td class="topleft">&nbsp;</td>';
434 foreach ($row as $columnkey => $element) {
435 $sort_link = '';
436 if (isset($element['object']->id)) {
437 $sort_link = $this->baseurl.'&amp;sortitemid=' . $element['object']->id;
440 $eid = $element['eid'];
441 $object = $element['object'];
442 $type = $element['type'];
443 $categorystate = @$element['categorystate'];
444 $itemmodule = null;
445 $iteminstance = null;
447 if (!empty($element['colspan'])) {
448 $colspan = 'colspan="'.$element['colspan'].'"';
449 } else {
450 $colspan = '';
453 if (!empty($element['depth'])) {
454 $catlevel = ' catlevel'.$element['depth'];
455 } else {
456 $catlevel = '';
459 // Element is a filler
460 if ($type == 'filler' or $type == 'fillerfirst' or $type == 'fillerlast') {
461 $headerhtml .= '<th class="'.$type.$catlevel.'" '.$colspan.'>&nbsp;</th>';
463 // Element is a category
464 else if ($type == 'category') {
465 $headerhtml .= '<th class="category'.$catlevel.'" '.$colspan.'>'.$element['object']->get_name();
466 $headerhtml .= $this->get_collapsing_icon($element);
468 // Print icons
469 if ($USER->gradeediting[$this->courseid]) {
470 $headerhtml .= $this->get_icons($element);
473 $headerhtml .= '</th>';
475 // Element is a grade_item
476 else {
477 $itemmodule = $element['object']->itemmodule;
478 $iteminstance = $element['object']->iteminstance;
480 if ($element['object']->id == $this->sortitemid) {
481 if ($this->sortorder == 'ASC') {
482 $arrow = $this->get_sort_arrow('up', $sort_link);
483 } else {
484 $arrow = $this->get_sort_arrow('down', $sort_link);
486 } else {
487 $arrow = $this->get_sort_arrow('move', $sort_link);
490 $dimmed = '';
491 if ($element['object']->is_hidden()) {
492 $dimmed = ' dimmed_text ';
495 if ($object->itemtype == 'mod') {
496 $icon = '<img src="'.$CFG->modpixpath.'/'.$object->itemmodule.'/icon.gif" class="icon" alt="'
497 .$this->get_lang_string('modulename', $object->itemmodule).'"/>';
498 } else if ($object->itemtype == 'manual') {
499 //TODO: add manual grading icon
500 $icon = '<img src="'.$CFG->pixpath.'/t/edit.gif" class="icon" alt="'
501 .$this->get_lang_string('manualgrade', 'grades') .'"/>';
504 $headerlink = $this->get_module_link($element['object']->get_name(), $itemmodule, $iteminstance);
505 $headerhtml .= '<th class="'.$type.$catlevel.$dimmed.'">'. $headerlink . $arrow;
506 $headerhtml .= $this->get_icons($element) . '</th>';
508 $this->items[$element['object']->sortorder] =& $element['object'];
513 $headerhtml .= '</tr>';
515 return $headerhtml;
519 * Builds and return the HTML rows of the table (grades headed by student).
520 * @return string HTML
522 function get_studentshtml() {
523 global $CFG, $USER;
524 $studentshtml = '';
525 $strfeedback = $this->get_lang_string("feedback");
526 $gradetabindex = 1;
527 $showuserimage = $this->get_pref('showuserimage');
528 $numusers = count($this->users);
530 // Preload scale objects for items with a scaleid
531 $scales_list = '';
532 $tabindices = array();
533 foreach ($this->items as $item) {
534 if (!empty($item->scaleid)) {
535 $scales_list .= "$item->scaleid,";
537 $tabindices[$item->id]['grade'] = $gradetabindex;
538 $tabindices[$item->id]['feedback'] = $gradetabindex + $numusers;
539 $gradetabindex += $numusers * 2;
541 $scales_array = array();
543 if (!empty($scales_list)) {
544 $scales_list = substr($scales_list, 0, -1);
545 $scales_array = get_records_list('scale', 'id', $scales_list);
548 foreach ($this->users as $userid => $user) {
549 // Student name and link
550 $user_pic = null;
551 if ($showuserimage) {
552 $user_pic = '<div class="userpic">' . print_user_picture($user->id, $this->courseid, true, 0, true) . '</div>';
555 $studentshtml .= '<tr><th class="user">' . $user_pic . '<a href="' . $CFG->wwwroot . '/user/view.php?id='
556 . $user->id . '">' . fullname($user) . '</a></th>';
558 foreach ($this->items as $itemid=>$item) {
559 // Get the decimal points preference for this item
560 $decimalpoints = $this->get_pref('decimalpoints', $item->id);
562 if (isset($this->finalgrades[$userid][$item->id])) {
563 $gradeval = $this->finalgrades[$userid][$item->id]->finalgrade;
565 $grade = new grade_grade($this->finalgrades[$userid][$item->id], false);
566 $grade->feedback = stripslashes_safe($this->finalgrades[$userid][$item->id]->feedback);
567 $grade->feedbackformat = $this->finalgrades[$userid][$item->id]->feedbackformat;
569 } else {
570 $gradeval = null;
571 $grade = new grade_grade(array('userid'=>$userid, 'itemid'=>$item->id), false);
572 $grade->feedback = '';
575 $grade->courseid = $this->courseid;
576 $grade->grade_item =& $this->items[$itemid]; // this speedsup is_hidden() and other grade_grade methods
578 // emulate grade element
579 $element = array('eid'=>'g'.$grade->id, 'object'=>$grade, 'type'=>'grade');
581 if ($grade->is_overridden()) {
582 $studentshtml .= '<td class="overridden">';
583 } else {
584 $studentshtml .= '<td>';
587 if ($grade->is_excluded()) {
588 $studentshtml .= get_string('excluded', 'grades'); // TODO: improve visual representation of excluded grades
591 // Do not show any icons if no grade (no record in DB to match)
592 // TODO: change edit/hide/etc. links to use itemid and userid to allow creating of new grade objects
593 if (!$item->needsupdate and !empty($grade->id) and $USER->gradeediting[$this->courseid]) {
594 $studentshtml .= $this->get_icons($element);
597 // if in editting mode, we need to print either a text box
598 // or a drop down (for scales)
599 // grades in item of type grade category or course are not directly editable
600 if ($item->needsupdate) {
601 $studentshtml .= '<span class="gradingerror">'.get_string('error').'</span>';
603 } else if ($USER->gradeediting[$this->courseid]) {
604 // We need to retrieve each grade_grade object from DB in order to
605 // know if they are hidden/locked
607 if ($item->scaleid && !empty($scales_array[$item->scaleid])) {
608 $scale = $scales_array[$item->scaleid];
610 $scales = explode(",", $scale->scale);
611 // reindex because scale is off 1
612 $i = 0;
613 foreach ($scales as $scaleoption) {
614 $i++;
615 $scaleopt[$i] = $scaleoption;
618 if ($this->get_pref('quickgrading') and $grade->is_editable()) {
619 $studentshtml .= '<input type="hidden" name="oldgrade_'.$userid.'_'
620 .$item->id.'" value="'.$gradeval.'"/>';
621 $studentshtml .= choose_from_menu($scaleopt, 'grade_'.$userid.'_'.$item->id,
622 $gradeval, $this->get_lang_string('nograde'), '', '-1',
623 true, false, $tabindices[$item->id]['grade']);
624 } elseif(!empty($scale)) {
625 $scales = explode(",", $scale->scale);
627 // invalid grade if gradeval < 1
628 if ((int) $gradeval < 1) {
629 $studentshtml .= '-';
630 } else {
631 $studentshtml .= $scales[$gradeval-1];
633 } else {
634 // no such scale, throw error?
637 } else if ($item->gradetype != GRADE_TYPE_TEXT) { // Value type
638 if ($this->get_pref('quickgrading') and $grade->is_editable()) {
639 $value = $this->get_grade_clean($gradeval, $decimalpoints);
640 $studentshtml .= '<input type="hidden" name="oldgrade_'.$userid.'_'.$item->id.'" value="'.$value.'" />';
641 $studentshtml .= '<input size="6" tabindex="' . $tabindices[$item->id]['grade'] . '" type="text" name="grade_'
642 .$userid.'_' .$item->id.'" value="'.$value.'" />';
643 } else {
644 $studentshtml .= $this->get_grade_clean($gradeval, $decimalpoints);
649 // If quickfeedback is on, print an input element
650 if ($this->get_pref('quickfeedback') and $grade->is_editable()) {
651 if ($this->get_pref('quickgrading')) {
652 $studentshtml .= '<br />';
654 $studentshtml .= '<input type="hidden" name="oldfeedback_'
655 .$userid.'_'.$item->id.'" value="' . s($grade->feedback) . '" />';
656 $studentshtml .= '<input tabindex="' . $tabindices[$item->id]['feedback'] . '" size="6" type="text" name="feedback_'
657 .$userid.'_'.$item->id.'" value="' . s($grade->feedback) . '" />';
660 } else {
661 // Percentage format if specified by user (check each item for a set preference)
662 $gradedisplaytype = $this->get_pref('gradedisplaytype', $item->id);
664 $percentsign = '';
665 $grademin = $item->grademin;
666 $grademax = $item->grademax;
668 if ($gradedisplaytype == GRADE_REPORT_GRADE_DISPLAY_TYPE_PERCENTAGE) {
669 if (!is_null($gradeval)) {
670 $gradeval = grade_grade::standardise_score($gradeval, $grademin, $grademax, 0, 100);
672 $percentsign = '%';
675 // If feedback present, surround grade with feedback tooltip
676 if (!empty($grade->feedback)) {
677 if ($grade->feedbackformat == 1) {
678 $overlib = "return overlib('" . s(ltrim($grade->feedback)) . "', FULLHTML);";
679 } else {
680 $overlib = "return overlib('" . ($grade->feedback) . "', CAPTION, '$strfeedback');";
683 $studentshtml .= '<span onmouseover="' . $overlib . '" onmouseout="return nd();">';
686 if ($item->needsupdate) {
687 $studentshtml .= '<span class="gradingerror">'.get_string('error').'</span>';
689 } else if ($gradedisplaytype == GRADE_REPORT_GRADE_DISPLAY_TYPE_LETTER) {
690 $letters = grade_report::get_grade_letters();
691 if (!is_null($gradeval)) {
692 $studentshtml .= grade_grade::get_letter($letters, $gradeval, $grademin, $grademax);
694 } else if ($item->scaleid && !empty($scales_array[$item->scaleid])
695 && $gradedisplaytype == GRADE_REPORT_GRADE_DISPLAY_TYPE_REAL) {
696 $scale = $scales_array[$item->scaleid];
697 $scales = explode(",", $scale->scale);
699 // invalid grade if gradeval < 1
700 if ((int) $gradeval < 1) {
701 $studentshtml .= '-';
702 } else {
703 $studentshtml .= $scales[$gradeval-1];
705 } else {
706 if (is_null($gradeval)) {
707 $studentshtml .= '-';
708 } else {
709 $studentshtml .= $this->get_grade_clean($gradeval, $decimalpoints). $percentsign;
712 if (!empty($grade->feedback)) {
713 $studentshtml .= '</span>';
717 if (!empty($this->gradeserror[$item->id][$userid])) {
718 $studentshtml .= $this->gradeserror[$item->id][$userid];
721 $studentshtml .= '</td>' . "\n";
723 $studentshtml .= '</tr>';
725 return $studentshtml;
729 * Builds and return the HTML row of column totals.
730 * @param bool $grouponly Whether to return only group averages or all averages.
731 * @return string HTML
733 function get_avghtml($grouponly=false) {
734 global $CFG, $USER;
736 $averagesdisplaytype = $this->get_pref('averagesdisplaytype');
737 $averagesdecimalpoints = $this->get_pref('averagesdecimalpoints');
738 $meanselection = $this->get_pref('meanselection');
739 $avghtml = '';
741 if ($grouponly) {
742 $straverage = get_string('groupavg', 'grades');
743 $showaverages = $this->currentgroup && $this->get_pref('showgroups');
744 $groupsql = $this->groupsql;
745 $groupwheresql = $this->groupwheresql;
746 } else {
747 $straverage = get_string('average', 'grades');
748 $showaverages = $this->get_pref('showaverages');
749 $groupsql = null;
750 $groupwheresql = null;
753 if ($meanselection == GRADE_AGGREGATE_MEAN_GRADED) {
754 $totalcount = 0;
755 } else {
756 $totalcount = $this->get_numusers();
759 if ($showaverages) {
761 * this sql is broken in the event of multiple grade book roles assigned to one user
762 * or same role in multiple contexts
763 $SQL = "SELECT g.itemid, SUM(g.finalgrade) as sum, COUNT(DISTINCT(u.id)) as count
764 FROM {$CFG->prefix}grade_items gi LEFT JOIN
765 {$CFG->prefix}grade_grades g ON gi.id = g.itemid LEFT JOIN
766 {$CFG->prefix}user u ON u.id = g.userid LEFT JOIN
767 {$CFG->prefix}role_assignments ra ON u.id = ra.userid
768 $groupsql
769 WHERE gi.courseid = $this->courseid
770 $groupwheresql
771 AND ra.roleid in ($this->gradebookroles)
772 AND ra.contextid ".get_related_contexts_string($this->context)."
773 GROUP BY g.itemid";
776 // the first join on user is needed for groupsql
777 $SQL = "SELECT g.itemid, SUM(g.finalgrade) as sum, COUNT(DISTINCT(u.id)) as count
778 FROM {$CFG->prefix}grade_items gi LEFT JOIN
779 {$CFG->prefix}grade_grades g ON gi.id = g.itemid LEFT JOIN
780 {$CFG->prefix}user u ON g.userid = u.id
781 $groupsql
782 WHERE gi.courseid = $this->courseid
783 $groupwheresql
784 AND g.userid IN (
785 SELECT DISTINCT(u.id)
786 FROM {$CFG->prefix}user u LEFT JOIN
787 {$CFG->prefix}role_assignments ra ON u.id = ra.userid
788 WHERE ra.roleid in ($this->gradebookroles)
789 AND ra.contextid ".get_related_contexts_string($this->context)."
791 GROUP BY g.itemid";
793 $sum_array = array();
794 $count_array = array();
795 $sums = get_records_sql($SQL);
796 foreach ($sums as $itemid => $csum) {
797 $sum_array[$itemid] = $csum->sum;
798 if ($totalcount) {
799 $count_array[$itemid] = $totalcount;
800 } else {
801 $count_array[$itemid] = $csum->count;
804 $avghtml = '<tr><th>'.$straverage.'</th>';
805 foreach ($this->items as $item) {
806 $decimalpoints = $this->get_pref('decimalpoints', $item->id);
807 // Determine which display type to use for this average
808 $gradedisplaytype = $this->get_pref('gradedisplaytype', $item->id);
809 if ($USER->gradeediting[$this->courseid]) {
810 $displaytype = GRADE_REPORT_GRADE_DISPLAY_TYPE_REAL;
811 } elseif ($averagesdisplaytype == GRADE_REPORT_PREFERENCE_INHERIT) { // Inherit specific column or general preference
812 $displaytype = $gradedisplaytype;
813 } else { // General preference overrides specific column display type
814 $displaytype = $averagesdisplaytype;
817 if ($averagesdecimalpoints != GRADE_REPORT_PREFERENCE_INHERIT) {
818 $decimalpoints = $averagesdecimalpoints;
821 if (empty($count_array[$item->id]) || !isset($sum_array[$item->id])) {
822 $avghtml .= '<td>-</td>';
823 } else {
824 $sum = $sum_array[$item->id];
826 if ($item->scaleid) {
827 if ($grouponly) {
828 $finalsum = $sum_array[$item->id];
829 $finalavg = $finalsum/$count_array[$item->id];
830 } else {
831 $finalavg = $sum/$count_array[$item->id];
834 $scaleval = round($this->get_grade_clean($finalavg, $decimalpoints));
835 $scale_object = new grade_scale(array('id' => $item->scaleid), false);
836 $gradehtml = $scale_object->get_nearest_item($scaleval);
837 $rawvalue = $scaleval;
838 } else {
839 $gradeval = $this->get_grade_clean($sum/$count_array[$item->id], $decimalpoints);
841 $gradehtml = round($gradeval, $decimalpoints);
842 $rawvalue = $gradeval;
845 if ($displaytype == GRADE_REPORT_GRADE_DISPLAY_TYPE_PERCENTAGE) {
846 $gradeval = grade_grade::standardise_score($rawvalue, $item->grademin, $item->grademax, 0, 100);
847 $gradehtml = round($gradeval, $decimalpoints) . '%';
848 } elseif ($displaytype == GRADE_REPORT_GRADE_DISPLAY_TYPE_LETTER) {
849 $letters = grade_report::get_grade_letters();
850 $gradehtml = grade_grade::get_letter($letters, $gradeval, $item->grademin, $item->grademax);
853 $avghtml .= '<td>'.$gradehtml.'</td>';
856 $avghtml .= '</tr>';
858 return $avghtml;
862 * Builds and return the HTML row of ranges for each column (i.e. range).
863 * @return string HTML
865 function get_rangehtml() {
866 global $USER;
868 $scalehtml = '';
869 if ($this->get_pref('showranges')) {
870 $rangesdisplaytype = $this->get_pref('rangesdisplaytype');
871 $rangesdecimalpoints = $this->get_pref('rangesdecimalpoints');
872 $scalehtml = '<tr><th class="range">'.$this->get_lang_string('range','grades').'</th>';
874 foreach ($this->items as $item) {
875 $decimalpoints = $this->get_pref('decimalpoints', $item->id);
876 // Determine which display type to use for this range
877 $gradedisplaytype = $this->get_pref('gradedisplaytype', $item->id);
879 if ($USER->gradeediting[$this->courseid]) {
880 $displaytype = GRADE_REPORT_GRADE_DISPLAY_TYPE_REAL;
881 } elseif ($rangesdisplaytype == GRADE_REPORT_PREFERENCE_INHERIT) { // Inherit specific column or general preference
882 $displaytype = $gradedisplaytype;
883 } else { // General preference overrides specific column display type
884 $displaytype = $rangesdisplaytype;
887 if ($rangesdecimalpoints != GRADE_REPORT_PREFERENCE_INHERIT) {
888 $decimalpoints = $rangesdecimalpoints;
891 if ($displaytype == GRADE_REPORT_GRADE_DISPLAY_TYPE_REAL) {
892 $grademin = $this->get_grade_clean($item->grademin, $decimalpoints);
893 $grademax = $this->get_grade_clean($item->grademax, $decimalpoints);
894 } elseif ($displaytype == GRADE_REPORT_GRADE_DISPLAY_TYPE_PERCENTAGE) {
895 $grademin = 0;
896 $grademax = 100;
897 } elseif ($displaytype == GRADE_REPORT_GRADE_DISPLAY_TYPE_LETTER) {
898 $letters = grade_report::get_grade_letters();
899 $grademin = end($letters);
900 $grademax = reset($letters);
903 $scalehtml .= '<th class="range">'. $grademin.'-'. $grademax.'</th>';
905 $scalehtml .= '</tr>';
907 return $scalehtml;
911 * Given a grade_category, grade_item or grade_grade, this function
912 * figures out the state of the object and builds then returns a div
913 * with the icons needed for the grader report.
915 * @param object $object
916 * @return string HTML
918 function get_icons($element) {
919 global $CFG, $USER;
921 if (!$USER->gradeediting[$this->courseid]) {
922 return '<div class="grade_icons" />';
925 // Init all icons
926 $edit_icon = $this->gtree->get_edit_icon($element, $this->gpr);
927 $edit_calculation_icon = '';
928 $show_hide_icon = '';
929 $lock_unlock_icon = '';
931 if ($this->get_pref('showcalculations')) {
932 $edit_calculation_icon = $this->gtree->get_calculation_icon($element, $this->gpr);
935 if ($this->get_pref('showeyecons')) {
936 $show_hide_icon = $this->gtree->get_hiding_icon($element, $this->gpr);
939 if ($this->get_pref('showlocks')) {
940 $lock_unlock_icon = $this->gtree->get_locking_icon($element, $this->gpr);
943 return '<div class="grade_icons">'.$edit_icon.$edit_calculation_icon.$show_hide_icon.$lock_unlock_icon.'</div>';
947 * Given a category element returns collapsing +/- icon if available
948 * @param object $object
949 * @return string HTML
951 function get_collapsing_icon($element) {
952 global $CFG;
954 $contract_expand_icon = '';
955 // If object is a category, display expand/contract icon
956 if ($element['type'] == 'category' && $this->get_pref('aggregationview', $element['object']->id) == GRADE_REPORT_AGGREGATION_VIEW_COMPACT) {
957 // Load language strings
958 $strswitch_minus = $this->get_lang_string('contract', 'grades');
959 $strswitch_plus = $this->get_lang_string('expand', 'grades');
960 $expand_contract = 'switch_minus'; // Default: expanded
962 if (in_array($element['object']->id, $this->collapsed)) {
963 $expand_contract = 'switch_plus';
965 $url = $this->gpr->get_return_url(null, array('target'=>$element['eid'], 'action'=>$expand_contract, 'sesskey'=>sesskey()));
966 $contract_expand_icon = '<a href="'.$url.'"><img src="'.$CFG->pixpath.'/t/'.$expand_contract.'.gif" class="iconsmall" alt="'
967 .${'str'.$expand_contract}.'" title="'.${'str'.$expand_contract}.'" /></a>';
969 return $contract_expand_icon;
973 * Processes a single action against a category, grade_item or grade.
974 * @param string $target eid ({type}{id}, e.g. c4 for category4)
975 * @param string $action Which action to take (edit, delete etc...)
976 * @return
978 function process_action($target, $action) {
979 // TODO: this code should be in some grade_tree static method
980 $targettype = substr($target, 0, 1);
981 $targetid = substr($target, 1);
982 // TODO: end
984 if ($collapsed = get_user_preferences('grade_report_grader_collapsed_categories')) {
985 $collapsed = unserialize($collapsed);
986 } else {
987 $collapsed = array();
990 switch ($action) {
991 case 'switch_minus':
992 if (!in_array($targetid, $collapsed)) {
993 $collapsed[] = $targetid;
994 set_user_preference('grade_report_grader_collapsed_categories', serialize($collapsed));
996 break;
998 case 'switch_plus':
999 $key = array_search($targetid, $collapsed);
1000 if ($key !== false) {
1001 unset($collapsed[$key]);
1002 set_user_preference('grade_report_grader_collapsed_categories', serialize($collapsed));
1004 break;
1006 default:
1007 break;
1010 return true;