Merge branch 'wip-MDL-27145-master' of git://github.com/samhemelryk/moodle
[moodle.git] / grade / report / grader / lib.php
blob4b5d23bc73d499feddb2f3f9a7441cf3e3f08cc0
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * File in which the grader_report class is defined.
20 * @package gradebook
23 require_once($CFG->dirroot . '/grade/report/lib.php');
24 require_once($CFG->libdir.'/tablelib.php');
26 /**
27 * Class providing an API for the grader report building and displaying.
28 * @uses grade_report
29 * @package gradebook
31 class grade_report_grader extends grade_report {
32 /**
33 * The final grades.
34 * @var array $grades
36 public $grades;
38 /**
39 * Array of errors for bulk grades updating.
40 * @var array $gradeserror
42 public $gradeserror = array();
44 //// SQL-RELATED
46 /**
47 * The id of the grade_item by which this report will be sorted.
48 * @var int $sortitemid
50 public $sortitemid;
52 /**
53 * Sortorder used in the SQL selections.
54 * @var int $sortorder
56 public $sortorder;
58 /**
59 * An SQL fragment affecting the search for users.
60 * @var string $userselect
62 public $userselect;
64 /**
65 * The bound params for $userselect
66 * @var array $userselectparams
68 public $userselectparams = array();
70 /**
71 * List of collapsed categories from user preference
72 * @var array $collapsed
74 public $collapsed;
76 /**
77 * A count of the rows, used for css classes.
78 * @var int $rowcount
80 public $rowcount = 0;
82 /**
83 * Capability check caching
84 * */
85 public $canviewhidden;
87 var $preferencespage=false;
89 /**
90 * Length at which feedback will be truncated (to the nearest word) and an ellipsis be added.
91 * TODO replace this by a report preference
92 * @var int $feedback_trunc_length
94 protected $feedback_trunc_length = 50;
96 /**
97 * Constructor. Sets local copies of user preferences and initialises grade_tree.
98 * @param int $courseid
99 * @param object $gpr grade plugin return tracking object
100 * @param string $context
101 * @param int $page The current page being viewed (when report is paged)
102 * @param int $sortitemid The id of the grade_item by which to sort the table
104 public function __construct($courseid, $gpr, $context, $page=null, $sortitemid=null) {
105 global $CFG;
106 parent::__construct($courseid, $gpr, $context, $page);
108 $this->canviewhidden = has_capability('moodle/grade:viewhidden', get_context_instance(CONTEXT_COURSE, $this->course->id));
110 // load collapsed settings for this report
111 if ($collapsed = get_user_preferences('grade_report_grader_collapsed_categories')) {
112 $this->collapsed = unserialize($collapsed);
113 } else {
114 $this->collapsed = array('aggregatesonly' => array(), 'gradesonly' => array());
117 if (empty($CFG->enableoutcomes)) {
118 $nooutcomes = false;
119 } else {
120 $nooutcomes = get_user_preferences('grade_report_shownooutcomes');
123 // if user report preference set or site report setting set use it, otherwise use course or site setting
124 $switch = $this->get_pref('aggregationposition');
125 if ($switch == '') {
126 $switch = grade_get_setting($this->courseid, 'aggregationposition', $CFG->grade_aggregationposition);
129 // Grab the grade_tree for this course
130 $this->gtree = new grade_tree($this->courseid, true, $switch, $this->collapsed, $nooutcomes);
132 $this->sortitemid = $sortitemid;
134 // base url for sorting by first/last name
136 $this->baseurl = new moodle_url('index.php', array('id' => $this->courseid));
138 $studentsperpage = $this->get_pref('studentsperpage');
139 if (!empty($studentsperpage)) {
140 $this->baseurl->params(array('perpage' => $studentsperpage, 'page' => $this->page));
143 $this->pbarurl = new moodle_url('/grade/report/grader/index.php', array('id' => $this->courseid, 'perpage' => $studentsperpage));
145 $this->setup_groups();
147 $this->setup_sortitemid();
151 * Processes the data sent by the form (grades and feedbacks).
152 * Caller is responsible for all access control checks
153 * @param array $data form submission (with magic quotes)
154 * @return array empty array if success, array of warnings if something fails.
156 public function process_data($data) {
157 global $DB;
158 $warnings = array();
160 $separategroups = false;
161 $mygroups = array();
162 if ($this->groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $this->context)) {
163 $separategroups = true;
164 $mygroups = groups_get_user_groups($this->course->id);
165 $mygroups = $mygroups[0]; // ignore groupings
166 // reorder the groups fro better perf bellow
167 $current = array_search($this->currentgroup, $mygroups);
168 if ($current !== false) {
169 unset($mygroups[$current]);
170 array_unshift($mygroups, $this->currentgroup);
174 // always initialize all arrays
175 $queue = array();
176 foreach ($data as $varname => $postedvalue) {
178 $needsupdate = false;
180 // skip, not a grade nor feedback
181 if (strpos($varname, 'grade') === 0) {
182 $datatype = 'grade';
183 } else if (strpos($varname, 'feedback') === 0) {
184 $datatype = 'feedback';
185 } else {
186 continue;
189 $gradeinfo = explode("_", $varname);
190 $userid = clean_param($gradeinfo[1], PARAM_INT);
191 $itemid = clean_param($gradeinfo[2], PARAM_INT);
193 $oldvalue = $data->{'old'.$varname};
195 // was change requested?
196 if ($oldvalue == $postedvalue) { // string comparison
197 continue;
200 if (!$gradeitem = grade_item::fetch(array('id'=>$itemid, 'courseid'=>$this->courseid))) { // we must verify course id here!
201 print_error('invalidgradeitmeid');
204 // Pre-process grade
205 if ($datatype == 'grade') {
206 $feedback = false;
207 $feedbackformat = false;
208 if ($gradeitem->gradetype == GRADE_TYPE_SCALE) {
209 if ($postedvalue == -1) { // -1 means no grade
210 $finalgrade = null;
211 } else {
212 $finalgrade = $postedvalue;
214 } else {
215 $finalgrade = unformat_float($postedvalue);
218 $errorstr = '';
219 // Warn if the grade is out of bounds.
220 if (is_null($finalgrade)) {
221 // ok
222 } else {
223 $bounded = $gradeitem->bounded_grade($finalgrade);
224 if ($bounded > $finalgrade) {
225 $errorstr = 'lessthanmin';
226 } else if ($bounded < $finalgrade) {
227 $errorstr = 'morethanmax';
230 if ($errorstr) {
231 $user = $DB->get_record('user', array('id' => $userid), 'id, firstname, lastname');
232 $gradestr = new stdClass();
233 $gradestr->username = fullname($user);
234 $gradestr->itemname = $gradeitem->get_name();
235 $warnings[] = get_string($errorstr, 'grades', $gradestr);
238 } else if ($datatype == 'feedback') {
239 $finalgrade = false;
240 $trimmed = trim($postedvalue);
241 if (empty($trimmed)) {
242 $feedback = NULL;
243 } else {
244 $feedback = $postedvalue;
248 // group access control
249 if ($separategroups) {
250 // note: we can not use $this->currentgroup because it would fail badly
251 // when having two browser windows each with different group
252 $sharinggroup = false;
253 foreach($mygroups as $groupid) {
254 if (groups_is_member($groupid, $userid)) {
255 $sharinggroup = true;
256 break;
259 if (!$sharinggroup) {
260 // either group membership changed or somebody is hacking grades of other group
261 $warnings[] = get_string('errorsavegrade', 'grades');
262 continue;
266 $gradeitem->update_final_grade($userid, $finalgrade, 'gradebook', $feedback, FORMAT_MOODLE);
269 return $warnings;
274 * Setting the sort order, this depends on last state
275 * all this should be in the new table class that we might need to use
276 * for displaying grades.
278 private function setup_sortitemid() {
280 global $SESSION;
282 if ($this->sortitemid) {
283 if (!isset($SESSION->gradeuserreport->sort)) {
284 if ($this->sortitemid == 'firstname' || $this->sortitemid == 'lastname') {
285 $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC';
286 } else {
287 $this->sortorder = $SESSION->gradeuserreport->sort = 'DESC';
289 } else {
290 // this is the first sort, i.e. by last name
291 if (!isset($SESSION->gradeuserreport->sortitemid)) {
292 if ($this->sortitemid == 'firstname' || $this->sortitemid == 'lastname') {
293 $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC';
294 } else {
295 $this->sortorder = $SESSION->gradeuserreport->sort = 'DESC';
297 } else if ($SESSION->gradeuserreport->sortitemid == $this->sortitemid) {
298 // same as last sort
299 if ($SESSION->gradeuserreport->sort == 'ASC') {
300 $this->sortorder = $SESSION->gradeuserreport->sort = 'DESC';
301 } else {
302 $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC';
304 } else {
305 if ($this->sortitemid == 'firstname' || $this->sortitemid == 'lastname') {
306 $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC';
307 } else {
308 $this->sortorder = $SESSION->gradeuserreport->sort = 'DESC';
312 $SESSION->gradeuserreport->sortitemid = $this->sortitemid;
313 } else {
314 // not requesting sort, use last setting (for paging)
316 if (isset($SESSION->gradeuserreport->sortitemid)) {
317 $this->sortitemid = $SESSION->gradeuserreport->sortitemid;
318 }else{
319 $this->sortitemid = 'lastname';
322 if (isset($SESSION->gradeuserreport->sort)) {
323 $this->sortorder = $SESSION->gradeuserreport->sort;
324 } else {
325 $this->sortorder = 'ASC';
331 * pulls out the userids of the users to be display, and sorts them
333 public function load_users() {
334 global $CFG, $DB;
336 //limit to users with a gradeable role
337 list($gradebookrolessql, $gradebookrolesparams) = $DB->get_in_or_equal(explode(',', $this->gradebookroles), SQL_PARAMS_NAMED, 'grbr0');
339 //limit to users with an active enrollment
340 list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->context);
342 //fields we need from the user table
343 $userfields = user_picture::fields('u', array('idnumber'));
345 $sortjoin = $sort = $params = null;
347 //if the user has clicked one of the sort asc/desc arrows
348 if (is_numeric($this->sortitemid)) {
349 $params = array_merge(array('gitemid'=>$this->sortitemid), $gradebookrolesparams, $this->groupwheresql_params, $enrolledparams);
351 $sortjoin = "LEFT JOIN {grade_grades} g ON g.userid = u.id AND g.itemid = $this->sortitemid";
352 $sort = "g.finalgrade $this->sortorder";
354 } else {
355 $sortjoin = '';
356 switch($this->sortitemid) {
357 case 'lastname':
358 $sort = "u.lastname $this->sortorder, u.firstname $this->sortorder";
359 break;
360 case 'firstname':
361 $sort = "u.firstname $this->sortorder, u.lastname $this->sortorder";
362 break;
363 case 'idnumber':
364 default:
365 $sort = "u.idnumber $this->sortorder";
366 break;
369 $params = array_merge($gradebookrolesparams, $this->groupwheresql_params, $enrolledparams);
372 $sql = "SELECT $userfields
373 FROM {user} u
374 JOIN ($enrolledsql) je ON je.id = u.id
375 $this->groupsql
376 $sortjoin
377 JOIN (
378 SELECT DISTINCT ra.userid
379 FROM {role_assignments} ra
380 WHERE ra.roleid IN ($this->gradebookroles)
381 AND ra.contextid " . get_related_contexts_string($this->context) . "
382 ) rainner ON rainner.userid = u.id
383 AND u.deleted = 0
384 $this->groupwheresql
385 ORDER BY $sort";
387 $this->users = $DB->get_records_sql($sql, $params, $this->get_pref('studentsperpage') * $this->page, $this->get_pref('studentsperpage'));
389 if (empty($this->users)) {
390 $this->userselect = '';
391 $this->users = array();
392 $this->userselect_params = array();
393 } else {
394 list($usql, $params) = $DB->get_in_or_equal(array_keys($this->users), SQL_PARAMS_NAMED, 'usid0');
395 $this->userselect = "AND g.userid $usql";
396 $this->userselect_params = $params;
399 return $this->users;
403 * we supply the userids in this query, and get all the grades
404 * pulls out all the grades, this does not need to worry about paging
406 public function load_final_grades() {
407 global $CFG, $DB;
409 // please note that we must fetch all grade_grades fields if we want to construct grade_grade object from it!
410 $params = array_merge(array('courseid'=>$this->courseid), $this->userselect_params);
411 $sql = "SELECT g.*
412 FROM {grade_items} gi,
413 {grade_grades} g
414 WHERE g.itemid = gi.id AND gi.courseid = :courseid {$this->userselect}";
416 $userids = array_keys($this->users);
419 if ($grades = $DB->get_records_sql($sql, $params)) {
420 foreach ($grades as $graderec) {
421 if (in_array($graderec->userid, $userids) and array_key_exists($graderec->itemid, $this->gtree->get_items())) { // some items may not be present!!
422 $this->grades[$graderec->userid][$graderec->itemid] = new grade_grade($graderec, false);
423 $this->grades[$graderec->userid][$graderec->itemid]->grade_item =& $this->gtree->get_item($graderec->itemid); // db caching
428 // prefil grades that do not exist yet
429 foreach ($userids as $userid) {
430 foreach ($this->gtree->get_items() as $itemid=>$unused) {
431 if (!isset($this->grades[$userid][$itemid])) {
432 $this->grades[$userid][$itemid] = new grade_grade();
433 $this->grades[$userid][$itemid]->itemid = $itemid;
434 $this->grades[$userid][$itemid]->userid = $userid;
435 $this->grades[$userid][$itemid]->grade_item =& $this->gtree->get_item($itemid); // db caching
442 * Builds and returns a div with on/off toggles.
443 * @return string HTML code
445 public function get_toggles_html() {
446 global $CFG, $USER, $COURSE, $OUTPUT;
448 $html = '';
449 if ($USER->gradeediting[$this->courseid]) {
450 if (has_capability('moodle/grade:manage', $this->context) or has_capability('moodle/grade:hide', $this->context)) {
451 $html .= $this->print_toggle('eyecons');
453 if (has_capability('moodle/grade:manage', $this->context)
454 or has_capability('moodle/grade:lock', $this->context)
455 or has_capability('moodle/grade:unlock', $this->context)) {
456 $html .= $this->print_toggle('locks');
458 if (has_capability('moodle/grade:manage', $this->context)) {
459 $html .= $this->print_toggle('quickfeedback');
462 if (has_capability('moodle/grade:manage', $this->context)) {
463 $html .= $this->print_toggle('calculations');
467 if ($this->canviewhidden) {
468 $html .= $this->print_toggle('averages');
471 $html .= $this->print_toggle('ranges');
472 if (!empty($CFG->enableoutcomes)) {
473 $html .= $this->print_toggle('nooutcomes');
476 return $OUTPUT->container($html, 'grade-report-toggles');
480 * Shortcut function for printing the grader report toggles.
481 * @param string $type The type of toggle
482 * @param bool $return Whether to return the HTML string rather than printing it
483 * @return void
485 public function print_toggle($type) {
486 global $CFG, $OUTPUT;
488 $icons = array('eyecons' => 't/hide',
489 'calculations' => 't/calc',
490 'locks' => 't/lock',
491 'averages' => 't/mean',
492 'quickfeedback' => 't/feedback',
493 'nooutcomes' => 't/outcomes');
495 $prefname = 'grade_report_show' . $type;
497 if (array_key_exists($prefname, $CFG)) {
498 $showpref = get_user_preferences($prefname, $CFG->$prefname);
499 } else {
500 $showpref = get_user_preferences($prefname);
503 $strshow = $this->get_lang_string('show' . $type, 'grades');
504 $strhide = $this->get_lang_string('hide' . $type, 'grades');
506 $showhide = 'show';
507 $toggleaction = 1;
509 if ($showpref) {
510 $showhide = 'hide';
511 $toggleaction = 0;
514 if (array_key_exists($type, $icons)) {
515 $imagename = $icons[$type];
516 } else {
517 $imagename = "t/$type";
520 $string = ${'str' . $showhide};
522 $url = new moodle_url($this->baseurl, array('toggle' => $toggleaction, 'toggle_type' => $type));
524 $retval = $OUTPUT->container($OUTPUT->action_icon($url, new pix_icon($imagename, $string))); // TODO: this container looks wrong here
526 return $retval;
530 * Builds and returns the rows that will make up the left part of the grader report
531 * This consists of student names and icons, links to user reports and id numbers, as well
532 * as header cells for these columns. It also includes the fillers required for the
533 * categories displayed on the right side of the report.
534 * @return array Array of html_table_row objects
536 public function get_left_rows() {
537 global $CFG, $USER, $OUTPUT;
539 $rows = array();
541 $showuserimage = $this->get_pref('showuserimage');
542 $showuseridnumber = $this->get_pref('showuseridnumber');
543 $fixedstudents = $this->is_fixed_students();
545 $strfeedback = $this->get_lang_string("feedback");
546 $strgrade = $this->get_lang_string('grade');
548 $arrows = $this->get_sort_arrows();
550 $colspan = 1;
552 if (has_capability('gradereport/'.$CFG->grade_profilereport.':view', $this->context)) {
553 $colspan++;
556 if ($showuseridnumber) {
557 $colspan++;
560 $levels = count($this->gtree->levels) - 1;
562 for ($i = 0; $i < $levels; $i++) {
563 $fillercell = new html_table_cell();
564 $fillercell->attributes['class'] = 'fixedcolumn cell topleft';
565 $fillercell->text = ' ';
566 $fillercell->colspan = $colspan;
567 $row = new html_table_row(array($fillercell));
568 $rows[] = $row;
571 $headerrow = new html_table_row();
572 $headerrow->attributes['class'] = 'heading';
574 $studentheader = new html_table_cell();
575 $studentheader->attributes['class'] = 'header';
576 $studentheader->scope = 'col';
577 $studentheader->header = true;
578 $studentheader->id = 'studentheader';
579 if (has_capability('gradereport/'.$CFG->grade_profilereport.':view', $this->context)) {
580 $studentheader->colspan = 2;
582 $studentheader->text = $arrows['studentname'];
584 $headerrow->cells[] = $studentheader;
586 if ($showuseridnumber) {
587 // TODO: weird, this is not used anywhere
588 $sortidnumberlink = html_writer::link(new moodle_url($this->baseurl, array('sortitemid'=>'idnumber')), get_string('idnumber'));
590 $idnumberheader = new html_table_cell();
591 $idnumberheader->attributes['class'] = 'header useridnumber';
592 $idnumberheader->scope = 'col';
593 $idnumberheader->header = true;
594 $idnumberheader->text = $arrows['idnumber'];
596 $headerrow->cells[] = $idnumberheader;
599 $rows[] = $headerrow;
601 $rows = $this->get_left_icons_row($rows, $colspan);
603 $rowclasses = array('even', 'odd');
605 foreach ($this->users as $userid => $user) {
606 $userrow = new html_table_row();
607 $userrow->id = 'fixed_user_'.$userid;
608 $userrow->attributes['class'] = 'r'.$this->rowcount++.' '.$rowclasses[$this->rowcount % 2];
610 $usercell = new html_table_cell();
611 $usercell->attributes['class'] = 'user';
612 $usercell->header = true;
613 $usercell->scope = 'row';
615 if ($showuserimage) {
616 $usercell->text = $OUTPUT->container($OUTPUT->user_picture($user), 'userpic');
619 $usercell->text .= html_writer::link(new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $this->course->id)), fullname($user));
621 $userrow->cells[] = $usercell;
623 if (has_capability('gradereport/'.$CFG->grade_profilereport.':view', $this->context)) {
624 $userreportcell = new html_table_cell();
625 $userreportcell->attributes['class'] = 'userreport';
626 $userreportcell->header = true;
627 $a = new stdClass();
628 $a->user = fullname($user);
629 $strgradesforuser = get_string('gradesforuser', 'grades', $a);
630 $url = new moodle_url('/grade/report/'.$CFG->grade_profilereport.'/index.php', array('userid' => $user->id, 'id' => $this->course->id));
631 $userreportcell->text = $OUTPUT->action_icon($url, new pix_icon('t/grades', $strgradesforuser));
632 $userrow->cells[] = $userreportcell;
635 if ($showuseridnumber) {
636 $idnumbercell = new html_table_cell();
637 $idnumbercell->attributes['class'] = 'header useridnumber';
638 $idnumbercell->header = true;
639 $idnumbercell->scope = 'row';
640 $idnumbercell->text = $user->idnumber;
641 $userrow->cells[] = $idnumbercell;
644 $rows[] = $userrow;
647 $rows = $this->get_left_range_row($rows, $colspan);
648 $rows = $this->get_left_avg_row($rows, $colspan, true);
649 $rows = $this->get_left_avg_row($rows, $colspan);
651 return $rows;
655 * Builds and returns the rows that will make up the right part of the grader report
656 * @return array Array of html_table_row objects
658 public function get_right_rows() {
659 global $CFG, $USER, $OUTPUT, $DB, $PAGE;
661 $rows = array();
662 $this->rowcount = 0;
663 $numrows = count($this->gtree->get_levels());
664 $numusers = count($this->users);
665 $gradetabindex = 1;
666 $columnstounset = array();
667 $strgrade = $this->get_lang_string('grade');
668 $strfeedback = $this->get_lang_string("feedback");
669 $arrows = $this->get_sort_arrows();
671 $jsarguments = array(
672 'id' => '#fixed_column',
673 'cfg' => array('ajaxenabled'=>false),
674 'items' => array(),
675 'users' => array(),
676 'feedback' => array()
678 $jsscales = array();
680 foreach ($this->gtree->get_levels() as $key=>$row) {
681 if ($key == 0) {
682 // do not display course grade category
683 // continue;
686 $headingrow = new html_table_row();
687 $headingrow->attributes['class'] = 'heading_name_row';
689 foreach ($row as $columnkey => $element) {
690 $sortlink = clone($this->baseurl);
691 if (isset($element['object']->id)) {
692 $sortlink->param('sortitemid', $element['object']->id);
695 $eid = $element['eid'];
696 $object = $element['object'];
697 $type = $element['type'];
698 $categorystate = @$element['categorystate'];
700 if (!empty($element['colspan'])) {
701 $colspan = $element['colspan'];
702 } else {
703 $colspan = 1;
706 if (!empty($element['depth'])) {
707 $catlevel = 'catlevel'.$element['depth'];
708 } else {
709 $catlevel = '';
712 // Element is a filler
713 if ($type == 'filler' or $type == 'fillerfirst' or $type == 'fillerlast') {
714 $fillercell = new html_table_cell();
715 $fillercell->attributes['class'] = $type . ' ' . $catlevel;
716 $fillercell->colspan = $colspan;
717 $fillercell->text = '&nbsp;';
718 $fillercell->header = true;
719 $fillercell->scope = 'col';
720 $headingrow->cells[] = $fillercell;
722 // Element is a category
723 else if ($type == 'category') {
724 $categorycell = new html_table_cell();
725 $categorycell->attributes['class'] = 'category ' . $catlevel;
726 $categorycell->colspan = $colspan;
727 $categorycell->text = shorten_text($element['object']->get_name());
728 $categorycell->text .= $this->get_collapsing_icon($element);
729 $categorycell->header = true;
730 $categorycell->scope = 'col';
732 // Print icons
733 if ($USER->gradeediting[$this->courseid]) {
734 $categorycell->text .= $this->get_icons($element);
737 $headingrow->cells[] = $categorycell;
739 // Element is a grade_item
740 else {
741 //$itemmodule = $element['object']->itemmodule;
742 //$iteminstance = $element['object']->iteminstance;
744 if ($element['object']->id == $this->sortitemid) {
745 if ($this->sortorder == 'ASC') {
746 $arrow = $this->get_sort_arrow('up', $sortlink);
747 } else {
748 $arrow = $this->get_sort_arrow('down', $sortlink);
750 } else {
751 $arrow = $this->get_sort_arrow('move', $sortlink);
754 $headerlink = $this->gtree->get_element_header($element, true, $this->get_pref('showactivityicons'), false);
756 $itemcell = new html_table_cell();
757 $itemcell->attributes['class'] = $type . ' ' . $catlevel . 'highlightable';
759 if ($element['object']->is_hidden()) {
760 $itemcell->attributes['class'] .= ' hidden';
763 $itemcell->colspan = $colspan;
764 $itemcell->text = shorten_text($headerlink) . $arrow;
765 $itemcell->header = true;
766 $itemcell->scope = 'col';
768 $headingrow->cells[] = $itemcell;
771 $rows[] = $headingrow;
774 $rows = $this->get_right_icons_row($rows);
776 // Preload scale objects for items with a scaleid
777 $scaleslist = array();
778 $tabindices = array();
780 foreach ($this->gtree->get_items() as $itemid=>$item) {
781 $scale = null;
782 if (!empty($item->scaleid)) {
783 $scaleslist[] = $item->scaleid;
784 $jsarguments['items'][$itemid] = array('id'=>$itemid, 'name'=>$item->get_name(true), 'type'=>'scale', 'scale'=>$item->scaleid, 'decimals'=>$item->get_decimals());
785 } else {
786 $jsarguments['items'][$itemid] = array('id'=>$itemid, 'name'=>$item->get_name(true), 'type'=>'value', 'scale'=>false, 'decimals'=>$item->get_decimals());
788 $tabindices[$item->id]['grade'] = $gradetabindex;
789 $tabindices[$item->id]['feedback'] = $gradetabindex + $numusers;
790 $gradetabindex += $numusers * 2;
792 $scalesarray = array();
794 if (!empty($scaleslist)) {
795 $scalesarray = $DB->get_records_list('scale', 'id', $scaleslist);
797 $jsscales = $scalesarray;
799 $rowclasses = array('even', 'odd');
801 foreach ($this->users as $userid => $user) {
803 if ($this->canviewhidden) {
804 $altered = array();
805 $unknown = array();
806 } else {
807 $hidingaffected = grade_grade::get_hiding_affected($this->grades[$userid], $this->gtree->get_items());
808 $altered = $hidingaffected['altered'];
809 $unknown = $hidingaffected['unknown'];
810 unset($hidingaffected);
814 $itemrow = new html_table_row();
815 $itemrow->id = 'user_'.$userid;
816 $itemrow->attributes['class'] = $rowclasses[$this->rowcount % 2];
818 $jsarguments['users'][$userid] = fullname($user);
820 foreach ($this->gtree->items as $itemid=>$unused) {
821 $item =& $this->gtree->items[$itemid];
822 $grade = $this->grades[$userid][$item->id];
824 $itemcell = new html_table_cell();
826 $itemcell->id = 'u'.$userid.'i'.$itemid;
828 // Get the decimal points preference for this item
829 $decimalpoints = $item->get_decimals();
831 if (in_array($itemid, $unknown)) {
832 $gradeval = null;
833 } else if (array_key_exists($itemid, $altered)) {
834 $gradeval = $altered[$itemid];
835 } else {
836 $gradeval = $grade->finalgrade;
839 // MDL-11274
840 // Hide grades in the grader report if the current grader doesn't have 'moodle/grade:viewhidden'
841 if (!$this->canviewhidden and $grade->is_hidden()) {
842 if (!empty($CFG->grade_hiddenasdate) and $grade->get_datesubmitted() and !$item->is_category_item() and !$item->is_course_item()) {
843 // the problem here is that we do not have the time when grade value was modified, 'timemodified' is general modification date for grade_grades records
844 $itemcell->text = html_writer::tag('span', userdate($grade->get_datesubmitted(),get_string('strftimedatetimeshort')), array('class'=>'datesubmitted'));
845 } else {
846 $itemcell->text = '-';
848 $itemrow->cells[] = $itemcell;
849 continue;
852 // emulate grade element
853 $eid = $this->gtree->get_grade_eid($grade);
854 $element = array('eid'=>$eid, 'object'=>$grade, 'type'=>'grade');
856 $itemcell->attributes['class'] .= ' grade';
857 if ($item->is_category_item()) {
858 $itemcell->attributes['class'] .= ' cat';
860 if ($item->is_course_item()) {
861 $itemcell->attributes['class'] .= ' course';
863 if ($grade->is_overridden()) {
864 $itemcell->attributes['class'] .= ' overridden';
867 if ($grade->is_excluded()) {
868 // $itemcell->attributes['class'] .= ' excluded';
871 if (!empty($grade->feedback)) {
872 //should we be truncating feedback? ie $short_feedback = shorten_text($feedback, $this->feedback_trunc_length);
873 $jsarguments['feedback'][] = array('user'=>$userid, 'item'=>$itemid, 'content'=>wordwrap(trim(format_string($grade->feedback, $grade->feedbackformat)), 34, '<br/ >'));
876 if ($grade->is_excluded()) {
877 $itemcell->text .= html_writer::tag('span', get_string('excluded', 'grades'), array('class'=>'excludedfloater'));
880 // Do not show any icons if no grade (no record in DB to match)
881 if (!$item->needsupdate and $USER->gradeediting[$this->courseid]) {
882 $itemcell->text .= $this->get_icons($element);
885 $hidden = '';
886 if ($grade->is_hidden()) {
887 $hidden = ' hidden ';
890 $gradepass = ' gradefail ';
891 if ($grade->is_passed($item)) {
892 $gradepass = ' gradepass ';
893 } elseif (is_null($grade->is_passed($item))) {
894 $gradepass = '';
897 // if in editing mode, we need to print either a text box
898 // or a drop down (for scales)
899 // grades in item of type grade category or course are not directly editable
900 if ($item->needsupdate) {
901 $itemcell->text .= html_writer::tag('span', get_string('error'), array('class'=>"gradingerror$hidden"));
903 } else if ($USER->gradeediting[$this->courseid]) {
905 if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
906 $scale = $scalesarray[$item->scaleid];
907 $gradeval = (int)$gradeval; // scales use only integers
908 $scales = explode(",", $scale->scale);
909 // reindex because scale is off 1
911 // MDL-12104 some previous scales might have taken up part of the array
912 // so this needs to be reset
913 $scaleopt = array();
914 $i = 0;
915 foreach ($scales as $scaleoption) {
916 $i++;
917 $scaleopt[$i] = $scaleoption;
920 if ($this->get_pref('quickgrading') and $grade->is_editable()) {
921 $oldval = empty($gradeval) ? -1 : $gradeval;
922 if (empty($item->outcomeid)) {
923 $nogradestr = $this->get_lang_string('nograde');
924 } else {
925 $nogradestr = $this->get_lang_string('nooutcome', 'grades');
927 $itemcell->text .= '<input type="hidden" id="oldgrade_'.$userid.'_'.$item->id.'" name="oldgrade_'.$userid.'_'.$item->id.'" value="'.$oldval.'"/>';
928 $attributes = array('tabindex' => $tabindices[$item->id]['grade'], 'id'=>'grade_'.$userid.'_'.$item->id);
929 $itemcell->text .= html_writer::select($scaleopt, 'grade_'.$userid.'_'.$item->id, $gradeval, array(-1=>$nogradestr), $attributes);;
930 } elseif(!empty($scale)) {
931 $scales = explode(",", $scale->scale);
933 // invalid grade if gradeval < 1
934 if ($gradeval < 1) {
935 $itemcell->text .= html_writer::tag('span', '-', array('class'=>"gradevalue$hidden$gradepass"));
936 } else {
937 $gradeval = $grade->grade_item->bounded_grade($gradeval); //just in case somebody changes scale
938 $itemcell->text .= html_writer::tag('span', $scales[$gradeval-1], array('class'=>"gradevalue$hidden$gradepass"));
940 } else {
941 // no such scale, throw error?
944 } else if ($item->gradetype != GRADE_TYPE_TEXT) { // Value type
945 if ($this->get_pref('quickgrading') and $grade->is_editable()) {
946 $value = format_float($gradeval, $decimalpoints);
947 $itemcell->text .= '<input type="hidden" id="oldgrade_'.$userid.'_'.$item->id.'" name="oldgrade_'.$userid.'_'.$item->id.'" value="'.$value.'" />';
948 $itemcell->text .= '<input size="6" tabindex="' . $tabindices[$item->id]['grade']
949 . '" type="text" class="text" title="'. $strgrade .'" name="grade_'
950 .$userid.'_' .$item->id.'" id="grade_'.$userid.'_'.$item->id.'" value="'.$value.'" />';
951 } else {
952 $itemcell->text .= html_writer::tag('span', format_float($gradeval, $decimalpoints), array('class'=>"gradevalue$hidden$gradepass"));
957 // If quickfeedback is on, print an input element
958 if ($this->get_pref('showquickfeedback') and $grade->is_editable()) {
960 $itemcell->text .= '<input type="hidden" id="oldfeedback_'.$userid.'_'.$item->id.'" name="oldfeedback_'.$userid.'_'.$item->id.'" value="' . s($grade->feedback) . '" />';
961 $itemcell->text .= '<input class="quickfeedback" tabindex="' . $tabindices[$item->id]['feedback'].'" id="feedback_'.$userid.'_'.$item->id
962 . '" size="6" title="' . $strfeedback . '" type="text" name="feedback_'.$userid.'_'.$item->id.'" value="' . s($grade->feedback) . '" />';
965 } else { // Not editing
966 $gradedisplaytype = $item->get_displaytype();
968 if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
969 $itemcell->attributes['class'] .= ' grade_type_scale';
970 } else if ($item->gradetype != GRADE_TYPE_TEXT) {
971 $itemcell->attributes['class'] .= ' grade_type_text';
974 if ($this->get_pref('enableajax')) {
975 $itemcell->attributes['class'] .= ' clickable';
978 if ($item->needsupdate) {
979 $itemcell->text .= html_writer::tag('span', get_string('error'), array('class'=>"gradingerror$hidden$gradepass"));
980 } else {
981 $itemcell->text .= html_writer::tag('span', grade_format_gradevalue($gradeval, $item, true, $gradedisplaytype, null), array('class'=>"gradevalue$hidden$gradepass"));
985 if (!empty($this->gradeserror[$item->id][$userid])) {
986 $itemcell->text .= $this->gradeserror[$item->id][$userid];
989 $itemrow->cells[] = $itemcell;
991 $rows[] = $itemrow;
994 if ($this->get_pref('enableajax')) {
995 $jsarguments['cfg']['ajaxenabled'] = true;
996 $jsarguments['cfg']['scales'] = array();
997 foreach ($jsscales as $scale) {
998 $jsarguments['cfg']['scales'][$scale->id] = explode(',',$scale->scale);
1000 $jsarguments['cfg']['feedbacktrunclength'] = $this->feedback_trunc_length;
1002 //feedbacks are now being stored in $jsarguments['feedback'] in get_right_rows()
1003 //$jsarguments['cfg']['feedback'] = $this->feedbacks;
1005 $jsarguments['cfg']['isediting'] = (bool)$USER->gradeediting[$this->courseid];
1006 $jsarguments['cfg']['courseid'] = $this->courseid;
1007 $jsarguments['cfg']['studentsperpage'] = $this->get_pref('studentsperpage');
1008 $jsarguments['cfg']['showquickfeedback'] = (bool)$this->get_pref('showquickfeedback');
1010 $module = array(
1011 'name' => 'gradereport_grader',
1012 'fullpath' => '/grade/report/grader/module.js',
1013 'requires' => array('base', 'dom', 'event', 'event-mouseenter', 'event-key', 'io', 'json-parse', 'overlay')
1015 $PAGE->requires->js_init_call('M.gradereport_grader.init_report', $jsarguments, false, $module);
1016 $PAGE->requires->strings_for_js(array('addfeedback','feedback', 'grade'), 'grades');
1017 $PAGE->requires->strings_for_js(array('ajaxchoosescale','ajaxclicktoclose','ajaxerror','ajaxfailedupdate', 'ajaxfieldchanged'), 'gradereport_grader');
1019 $rows = $this->get_right_range_row($rows);
1020 $rows = $this->get_right_avg_row($rows, true);
1021 $rows = $this->get_right_avg_row($rows);
1023 return $rows;
1027 * Depending on the style of report (fixedstudents vs traditional one-table),
1028 * arranges the rows of data in one or two tables, and returns the output of
1029 * these tables in HTML
1030 * @return string HTML
1032 public function get_grade_table() {
1033 global $OUTPUT;
1034 $fixedstudents = $this->is_fixed_students();
1036 $leftrows = $this->get_left_rows();
1037 $rightrows = $this->get_right_rows();
1039 $html = '';
1042 if ($fixedstudents) {
1043 $fixedcolumntable = new html_table();
1044 $fixedcolumntable->id = 'fixed_column';
1045 $fixedcolumntable->data = $leftrows;
1046 $html .= $OUTPUT->container(html_writer::table($fixedcolumntable), 'left_scroller');
1048 $righttable = new html_table();
1049 $righttable->id = 'user-grades';
1050 $righttable->data = $rightrows;
1052 $html .= $OUTPUT->container(html_writer::table($righttable), 'right_scroller');
1053 } else {
1054 $fulltable = new html_table();
1055 $fulltable->attributes['class'] = 'gradestable flexible boxaligncenter generaltable';
1056 $fulltable->id = 'user-grades';
1058 // Extract rows from each side (left and right) and collate them into one row each
1059 foreach ($leftrows as $key => $row) {
1060 $row->cells = array_merge($row->cells, $rightrows[$key]->cells);
1061 $fulltable->data[] = $row;
1063 $html .= html_writer::table($fulltable);
1065 return $OUTPUT->container($html, 'gradeparent');
1069 * Builds and return the row of icons for the left side of the report.
1070 * It only has one cell that says "Controls"
1071 * @param array $rows The Array of rows for the left part of the report
1072 * @param int $colspan The number of columns this cell has to span
1073 * @return array Array of rows for the left part of the report
1075 public function get_left_icons_row($rows=array(), $colspan=1) {
1076 global $USER;
1078 if ($USER->gradeediting[$this->courseid]) {
1079 $controlsrow = new html_table_row();
1080 $controlsrow->attributes['class'] = 'controls';
1081 $controlscell = new html_table_cell();
1082 $controlscell->attributes['class'] = 'header controls';
1083 $controlscell->colspan = $colspan;
1084 $controlscell->text = $this->get_lang_string('controls','grades');
1086 $controlsrow->cells[] = $controlscell;
1087 $rows[] = $controlsrow;
1089 return $rows;
1093 * Builds and return the header for the row of ranges, for the left part of the grader report.
1094 * @param array $rows The Array of rows for the left part of the report
1095 * @param int $colspan The number of columns this cell has to span
1096 * @return array Array of rows for the left part of the report
1098 public function get_left_range_row($rows=array(), $colspan=1) {
1099 global $CFG, $USER;
1101 if ($this->get_pref('showranges')) {
1102 $rangerow = new html_table_row();
1103 $rangerow->attributes['class'] = 'range r'.$this->rowcount++;
1104 $rangecell = new html_table_cell();
1105 $rangecell->attributes['class'] = 'header range';
1106 $rangecell->colspan = $colspan;
1107 $rangecell->header = true;
1108 $rangecell->scope = 'row';
1109 $rangecell->text = $this->get_lang_string('range','grades');
1110 $rangerow->cells[] = $rangecell;
1111 $rows[] = $rangerow;
1114 return $rows;
1118 * Builds and return the headers for the rows of averages, for the left part of the grader report.
1119 * @param array $rows The Array of rows for the left part of the report
1120 * @param int $colspan The number of columns this cell has to span
1121 * @param bool $groupavg If true, returns the row for group averages, otherwise for overall averages
1122 * @return array Array of rows for the left part of the report
1124 public function get_left_avg_row($rows=array(), $colspan=1, $groupavg=false) {
1125 if (!$this->canviewhidden) {
1126 // totals might be affected by hiding, if user can not see hidden grades the aggregations might be altered
1127 // better not show them at all if user can not see all hideen grades
1128 return $rows;
1131 $showaverages = $this->get_pref('showaverages');
1132 $showaveragesgroup = $this->currentgroup && $showaverages;
1133 $straveragegroup = get_string('groupavg', 'grades');
1135 if ($groupavg) {
1136 if ($showaveragesgroup) {
1137 $groupavgrow = new html_table_row();
1138 $groupavgrow->attributes['class'] = 'groupavg r'.$this->rowcount++;
1139 $groupavgcell = new html_table_cell();
1140 $groupavgcell->attributes['class'] = 'header range';
1141 $groupavgcell->colspan = $colspan;
1142 $groupavgcell->header = true;
1143 $groupavgcell->scope = 'row';
1144 $groupavgcell->text = $straveragegroup;
1145 $groupavgrow->cells[] = $groupavgcell;
1146 $rows[] = $groupavgrow;
1148 } else {
1149 $straverage = get_string('overallaverage', 'grades');
1151 if ($showaverages) {
1152 $avgrow = new html_table_row();
1153 $avgrow->attributes['class'] = 'avg r'.$this->rowcount++;
1154 $avgcell = new html_table_cell();
1155 $avgcell->attributes['class'] = 'header range';
1156 $avgcell->colspan = $colspan;
1157 $avgcell->header = true;
1158 $avgcell->scope = 'row';
1159 $avgcell->text = $straverage;
1160 $avgrow->cells[] = $avgcell;
1161 $rows[] = $avgrow;
1165 return $rows;
1169 * Builds and return the row of icons when editing is on, for the right part of the grader report.
1170 * @param array $rows The Array of rows for the right part of the report
1171 * @return array Array of rows for the right part of the report
1173 public function get_right_icons_row($rows=array()) {
1174 global $USER;
1175 if ($USER->gradeediting[$this->courseid]) {
1176 $iconsrow = new html_table_row();
1177 $iconsrow->attributes['class'] = 'controls';
1179 $showuseridnumber = $this->get_pref('showuseridnumber');
1181 foreach ($this->gtree->items as $itemid=>$unused) {
1182 // emulate grade element
1183 $item =& $this->gtree->get_item($itemid);
1185 $eid = $this->gtree->get_item_eid($item);
1186 $element = $this->gtree->locate_element($eid);
1187 $itemcell = new html_table_cell();
1188 $itemcell->attributes['class'] = 'controls icons';
1189 $itemcell->text = $this->get_icons($element);
1190 $iconsrow->cells[] = $itemcell;
1192 $rows[] = $iconsrow;
1194 return $rows;
1198 * Builds and return the row of ranges for the right part of the grader report.
1199 * @param array $rows The Array of rows for the right part of the report
1200 * @return array Array of rows for the right part of the report
1202 public function get_right_range_row($rows=array()) {
1203 global $OUTPUT;
1205 if ($this->get_pref('showranges')) {
1206 $rangesdisplaytype = $this->get_pref('rangesdisplaytype');
1207 $rangesdecimalpoints = $this->get_pref('rangesdecimalpoints');
1208 $rangerow = new html_table_row();
1209 $rangerow->attributes['class'] = 'heading range';
1211 foreach ($this->gtree->items as $itemid=>$unused) {
1212 $item =& $this->gtree->items[$itemid];
1213 $itemcell = new html_table_cell();
1214 $itemcell->header = true;
1215 $itemcell->attributes['class'] .= ' header range';
1217 $hidden = '';
1218 if ($item->is_hidden()) {
1219 $hidden = ' hidden ';
1222 $formattedrange = $item->get_formatted_range($rangesdisplaytype, $rangesdecimalpoints);
1224 $itemcell->text = $OUTPUT->container($formattedrange, 'rangevalues'.$hidden);
1225 $rangerow->cells[] = $itemcell;
1227 $rows[] = $rangerow;
1229 return $rows;
1233 * Builds and return the row of averages for the right part of the grader report.
1234 * @param array $rows Whether to return only group averages or all averages.
1235 * @param bool $grouponly Whether to return only group averages or all averages.
1236 * @return array Array of rows for the right part of the report
1238 public function get_right_avg_row($rows=array(), $grouponly=false) {
1239 global $CFG, $USER, $DB, $OUTPUT;
1241 if (!$this->canviewhidden) {
1242 // totals might be affected by hiding, if user can not see hidden grades the aggregations might be altered
1243 // better not show them at all if user can not see all hidden grades
1244 return $rows;
1247 $showaverages = $this->get_pref('showaverages');
1248 $showaveragesgroup = $this->currentgroup && $showaverages;
1250 $averagesdisplaytype = $this->get_pref('averagesdisplaytype');
1251 $averagesdecimalpoints = $this->get_pref('averagesdecimalpoints');
1252 $meanselection = $this->get_pref('meanselection');
1253 $shownumberofgrades = $this->get_pref('shownumberofgrades');
1255 $avghtml = '';
1256 $avgcssclass = 'avg';
1258 if ($grouponly) {
1259 $straverage = get_string('groupavg', 'grades');
1260 $showaverages = $this->currentgroup && $this->get_pref('showaverages');
1261 $groupsql = $this->groupsql;
1262 $groupwheresql = $this->groupwheresql;
1263 $groupwheresqlparams = $this->groupwheresql_params;
1264 $avgcssclass = 'groupavg';
1265 } else {
1266 $straverage = get_string('overallaverage', 'grades');
1267 $showaverages = $this->get_pref('showaverages');
1268 $groupsql = "";
1269 $groupwheresql = "";
1270 $groupwheresqlparams = array();
1273 if ($shownumberofgrades) {
1274 $straverage .= ' (' . get_string('submissions', 'grades') . ') ';
1277 $totalcount = $this->get_numusers($grouponly);
1279 //limit to users with a gradeable role
1280 list($gradebookrolessql, $gradebookrolesparams) = $DB->get_in_or_equal(explode(',', $this->gradebookroles), SQL_PARAMS_NAMED, 'grbr0');
1282 //limit to users with an active enrollment
1283 list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->context);
1285 if ($showaverages) {
1286 $params = array_merge(array('courseid'=>$this->courseid), $gradebookrolesparams, $enrolledparams, $groupwheresqlparams);
1288 // find sums of all grade items in course
1289 $sql = "SELECT g.itemid, SUM(g.finalgrade) AS sum
1290 FROM {grade_items} gi
1291 JOIN {grade_grades} g ON g.itemid = gi.id
1292 JOIN {user} u ON u.id = g.userid
1293 JOIN ($enrolledsql) je ON je.id = u.id
1294 JOIN (
1295 SELECT DISTINCT ra.userid
1296 FROM {role_assignments} ra
1297 WHERE ra.roleid $gradebookrolessql
1298 AND ra.contextid " . get_related_contexts_string($this->context) . "
1299 ) rainner ON rainner.userid = u.id
1300 $groupsql
1301 WHERE gi.courseid = :courseid
1302 AND u.deleted = 0
1303 AND g.finalgrade IS NOT NULL
1304 $groupwheresql
1305 GROUP BY g.itemid";
1306 $sumarray = array();
1307 if ($sums = $DB->get_records_sql($sql, $params)) {
1308 foreach ($sums as $itemid => $csum) {
1309 $sumarray[$itemid] = $csum->sum;
1313 // MDL-10875 Empty grades must be evaluated as grademin, NOT always 0
1314 // This query returns a count of ungraded grades (NULL finalgrade OR no matching record in grade_grades table)
1315 $sql = "SELECT gi.id, COUNT(DISTINCT u.id) AS count
1316 FROM {grade_items} gi
1317 CROSS JOIN {user} u
1318 JOIN ($enrolledsql) je
1319 ON je.id = u.id
1320 JOIN {role_assignments} ra
1321 ON ra.userid = u.id
1322 LEFT OUTER JOIN {grade_grades} g
1323 ON (g.itemid = gi.id AND g.userid = u.id AND g.finalgrade IS NOT NULL)
1324 $groupsql
1325 WHERE gi.courseid = :courseid
1326 AND ra.roleid $gradebookrolessql
1327 AND ra.contextid ".get_related_contexts_string($this->context)."
1328 AND u.deleted = 0
1329 AND g.id IS NULL
1330 $groupwheresql
1331 GROUP BY gi.id";
1333 $ungradedcounts = $DB->get_records_sql($sql, $params);
1335 $avgrow = new html_table_row();
1336 $avgrow->attributes['class'] = 'avg';
1338 foreach ($this->gtree->items as $itemid=>$unused) {
1339 $item =& $this->gtree->items[$itemid];
1341 if ($item->needsupdate) {
1342 $avgcell = new html_table_cell();
1343 $avgcell->text = $OUTPUT->container(get_string('error'), 'gradingerror');
1344 $avgrow->cells[] = $avgcell;
1345 continue;
1348 if (!isset($sumarray[$item->id])) {
1349 $sumarray[$item->id] = 0;
1352 if (empty($ungradedcounts[$itemid])) {
1353 $ungradedcount = 0;
1354 } else {
1355 $ungradedcount = $ungradedcounts[$itemid]->count;
1358 if ($meanselection == GRADE_REPORT_MEAN_GRADED) {
1359 $meancount = $totalcount - $ungradedcount;
1360 } else { // Bump up the sum by the number of ungraded items * grademin
1361 $sumarray[$item->id] += $ungradedcount * $item->grademin;
1362 $meancount = $totalcount;
1365 $decimalpoints = $item->get_decimals();
1367 // Determine which display type to use for this average
1368 if ($USER->gradeediting[$this->courseid]) {
1369 $displaytype = GRADE_DISPLAY_TYPE_REAL;
1371 } else if ($averagesdisplaytype == GRADE_REPORT_PREFERENCE_INHERIT) { // no ==0 here, please resave the report and user preferences
1372 $displaytype = $item->get_displaytype();
1374 } else {
1375 $displaytype = $averagesdisplaytype;
1378 // Override grade_item setting if a display preference (not inherit) was set for the averages
1379 if ($averagesdecimalpoints == GRADE_REPORT_PREFERENCE_INHERIT) {
1380 $decimalpoints = $item->get_decimals();
1382 } else {
1383 $decimalpoints = $averagesdecimalpoints;
1386 if (!isset($sumarray[$item->id]) || $meancount == 0) {
1387 $avgcell = new html_table_cell();
1388 $avgcell->text = '-';
1389 $avgrow->cells[] = $avgcell;
1391 } else {
1392 $sum = $sumarray[$item->id];
1393 $avgradeval = $sum/$meancount;
1394 $gradehtml = grade_format_gradevalue($avgradeval, $item, true, $displaytype, $decimalpoints);
1396 $numberofgrades = '';
1397 if ($shownumberofgrades) {
1398 $numberofgrades = " ($meancount)";
1401 $avgcell = new html_table_cell();
1402 $avgcell->text = $gradehtml.$numberofgrades;
1403 $avgrow->cells[] = $avgcell;
1406 $rows[] = $avgrow;
1408 return $rows;
1412 * Given a grade_category, grade_item or grade_grade, this function
1413 * figures out the state of the object and builds then returns a div
1414 * with the icons needed for the grader report.
1416 * @param object $object
1417 * @return string HTML
1419 protected function get_icons($element) {
1420 global $CFG, $USER, $OUTPUT;
1422 if (!$USER->gradeediting[$this->courseid]) {
1423 return '<div class="grade_icons" />';
1426 // Init all icons
1427 $editicon = '';
1429 if ($element['type'] != 'categoryitem' && $element['type'] != 'courseitem') {
1430 $editicon = $this->gtree->get_edit_icon($element, $this->gpr);
1433 $editcalculationicon = '';
1434 $showhideicon = '';
1435 $lockunlockicon = '';
1437 if (has_capability('moodle/grade:manage', $this->context)) {
1439 if ($this->get_pref('showcalculations')) {
1440 $editcalculationicon = $this->gtree->get_calculation_icon($element, $this->gpr);
1443 if ($this->get_pref('showeyecons')) {
1444 $showhideicon = $this->gtree->get_hiding_icon($element, $this->gpr);
1447 if ($this->get_pref('showlocks')) {
1448 $lockunlockicon = $this->gtree->get_locking_icon($element, $this->gpr);
1452 return $OUTPUT->container($editicon.$editcalculationicon.$showhideicon.$lockunlockicon, 'grade_icons');
1456 * Given a category element returns collapsing +/- icon if available
1457 * @param object $object
1458 * @return string HTML
1460 protected function get_collapsing_icon($element) {
1461 global $OUTPUT;
1463 $icon = '';
1464 // If object is a category, display expand/contract icon
1465 if ($element['type'] == 'category') {
1466 // Load language strings
1467 $strswitchminus = $this->get_lang_string('aggregatesonly', 'grades');
1468 $strswitchplus = $this->get_lang_string('gradesonly', 'grades');
1469 $strswitchwhole = $this->get_lang_string('fullmode', 'grades');
1471 $url = new moodle_url($this->gpr->get_return_url(null, array('target'=>$element['eid'], 'sesskey'=>sesskey())));
1473 if (in_array($element['object']->id, $this->collapsed['aggregatesonly'])) {
1474 $url->param('action', 'switch_plus');
1475 $icon = $OUTPUT->action_icon($url, new pix_icon('t/switch_plus', $strswitchplus));
1477 } else if (in_array($element['object']->id, $this->collapsed['gradesonly'])) {
1478 $url->param('action', 'switch_whole');
1479 $icon = $OUTPUT->action_icon($url, new pix_icon('t/switch_whole', $strswitchwhole));
1481 } else {
1482 $url->param('action', 'switch_minus');
1483 $icon = $OUTPUT->action_icon($url, new pix_icon('t/switch_minus', $strswitchminus));
1486 return $icon;
1490 * Processes a single action against a category, grade_item or grade.
1491 * @param string $target eid ({type}{id}, e.g. c4 for category4)
1492 * @param string $action Which action to take (edit, delete etc...)
1493 * @return
1495 public function process_action($target, $action) {
1496 // TODO: this code should be in some grade_tree static method
1497 $targettype = substr($target, 0, 1);
1498 $targetid = substr($target, 1);
1499 // TODO: end
1501 if ($collapsed = get_user_preferences('grade_report_grader_collapsed_categories')) {
1502 $collapsed = unserialize($collapsed);
1503 } else {
1504 $collapsed = array('aggregatesonly' => array(), 'gradesonly' => array());
1507 switch ($action) {
1508 case 'switch_minus': // Add category to array of aggregatesonly
1509 if (!in_array($targetid, $collapsed['aggregatesonly'])) {
1510 $collapsed['aggregatesonly'][] = $targetid;
1511 set_user_preference('grade_report_grader_collapsed_categories', serialize($collapsed));
1513 break;
1515 case 'switch_plus': // Remove category from array of aggregatesonly, and add it to array of gradesonly
1516 $key = array_search($targetid, $collapsed['aggregatesonly']);
1517 if ($key !== false) {
1518 unset($collapsed['aggregatesonly'][$key]);
1520 if (!in_array($targetid, $collapsed['gradesonly'])) {
1521 $collapsed['gradesonly'][] = $targetid;
1523 set_user_preference('grade_report_grader_collapsed_categories', serialize($collapsed));
1524 break;
1525 case 'switch_whole': // Remove the category from the array of collapsed cats
1526 $key = array_search($targetid, $collapsed['gradesonly']);
1527 if ($key !== false) {
1528 unset($collapsed['gradesonly'][$key]);
1529 set_user_preference('grade_report_grader_collapsed_categories', serialize($collapsed));
1532 break;
1533 default:
1534 break;
1537 return true;
1541 * Returns whether or not to display fixed students column.
1542 * Includes a browser check, because IE6 doesn't support the scrollbar.
1544 * @return bool
1546 public function is_fixed_students() {
1547 global $USER, $CFG;
1548 return empty($USER->screenreader) && $CFG->grade_report_fixedstudents &&
1549 (check_browser_version('MSIE', '7.0') ||
1550 check_browser_version('Firefox', '2.0') ||
1551 check_browser_version('Gecko', '2006010100') ||
1552 check_browser_version('Camino', '1.0') ||
1553 check_browser_version('Opera', '6.0') ||
1554 check_browser_version('Chrome', '6') ||
1555 check_browser_version('Safari', '300'));
1559 * Refactored function for generating HTML of sorting links with matching arrows.
1560 * Returns an array with 'studentname' and 'idnumber' as keys, with HTML ready
1561 * to inject into a table header cell.
1562 * @return array An associative array of HTML sorting links+arrows
1564 public function get_sort_arrows() {
1565 global $OUTPUT;
1566 $arrows = array();
1568 $strsortasc = $this->get_lang_string('sortasc', 'grades');
1569 $strsortdesc = $this->get_lang_string('sortdesc', 'grades');
1570 $strfirstname = $this->get_lang_string('firstname');
1571 $strlastname = $this->get_lang_string('lastname');
1573 $firstlink = html_writer::link(new moodle_url($this->baseurl, array('sortitemid'=>'firstname')), $strfirstname);
1574 $lastlink = html_writer::link(new moodle_url($this->baseurl, array('sortitemid'=>'lastname')), $strlastname);
1575 $idnumberlink = html_writer::link(new moodle_url($this->baseurl, array('sortitemid'=>'idnumber')), get_string('idnumber'));
1577 $arrows['studentname'] = $lastlink;
1579 if ($this->sortitemid === 'lastname') {
1580 if ($this->sortorder == 'ASC') {
1581 $arrows['studentname'] .= print_arrow('up', $strsortasc, true);
1582 } else {
1583 $arrows['studentname'] .= print_arrow('down', $strsortdesc, true);
1587 $arrows['studentname'] .= ' ' . $firstlink;
1589 if ($this->sortitemid === 'firstname') {
1590 if ($this->sortorder == 'ASC') {
1591 $arrows['studentname'] .= print_arrow('up', $strsortasc, true);
1592 } else {
1593 $arrows['studentname'] .= print_arrow('down', $strsortdesc, true);
1597 $arrows['idnumber'] = $idnumberlink;
1599 if ('idnumber' == $this->sortitemid) {
1600 if ($this->sortorder == 'ASC') {
1601 $arrows['idnumber'] .= print_arrow('up', $strsortasc, true);
1602 } else {
1603 $arrows['idnumber'] .= print_arrow('down', $strsortdesc, true);
1607 return $arrows;