MDL-20204 fixed html-writer::tag() parameter order to match the rest of the api
[moodle.git] / grade / report / grader / lib.php
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.
14 //
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
21  */
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
30  */
31 class grade_report_grader extends grade_report {
32     /**
33      * The final grades.
34      * @var array $grades
35      */
36     public $grades;
38     /**
39      * Array of errors for bulk grades updating.
40      * @var array $gradeserror
41      */
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
49      */
50     public $sortitemid;
52     /**
53      * Sortorder used in the SQL selections.
54      * @var int $sortorder
55      */
56     public $sortorder;
58     /**
59      * An SQL fragment affecting the search for users.
60      * @var string $userselect
61      */
62     public $userselect;
64     /**
65      * The bound params for $userselect
66      * @var array $userselectparams
67      */
68     public $userselectparams = array();
70     /**
71      * List of collapsed categories from user preference
72      * @var array $collapsed
73      */
74     public $collapsed;
76     /**
77      * A count of the rows, used for css classes.
78      * @var int $rowcount
79      */
80     public $rowcount = 0;
82     /**
83      * Capability check caching
84      * */
85     public $canviewhidden;
87     var $preferencespage=false;
89     /**
90      * Constructor. Sets local copies of user preferences and initialises grade_tree.
91      * @param int $courseid
92      * @param object $gpr grade plugin return tracking object
93      * @param string $context
94      * @param int $page The current page being viewed (when report is paged)
95      * @param int $sortitemid The id of the grade_item by which to sort the table
96      */
97     public function __construct($courseid, $gpr, $context, $page=null, $sortitemid=null) {
98         global $CFG;
99         parent::__construct($courseid, $gpr, $context, $page);
101         $this->canviewhidden = has_capability('moodle/grade:viewhidden', get_context_instance(CONTEXT_COURSE, $this->course->id));
103         // load collapsed settings for this report
104         if ($collapsed = get_user_preferences('grade_report_grader_collapsed_categories')) {
105             $this->collapsed = unserialize($collapsed);
106         } else {
107             $this->collapsed = array('aggregatesonly' => array(), 'gradesonly' => array());
108         }
110         if (empty($CFG->enableoutcomes)) {
111             $nooutcomes = false;
112         } else {
113             $nooutcomes = get_user_preferences('grade_report_shownooutcomes');
114         }
116         // if user report preference set or site report setting set use it, otherwise use course or site setting
117         $switch = $this->get_pref('aggregationposition');
118         if ($switch == '') {
119             $switch = grade_get_setting($this->courseid, 'aggregationposition', $CFG->grade_aggregationposition);
120         }
122         // Grab the grade_tree for this course
123         $this->gtree = new grade_tree($this->courseid, true, $switch, $this->collapsed, $nooutcomes);
125         $this->sortitemid = $sortitemid;
127         // base url for sorting by first/last name
129         $this->baseurl = new moodle_url('index.php', array('id' => $this->courseid));
131         $studentsperpage = $this->get_pref('studentsperpage');
132         if (!empty($studentsperpage)) {
133             $this->baseurl->params(array('perpage' => $studentsperpage, 'page' => $this->page));
134         }
136         $this->pbarurl = new moodle_url('/grade/report/grader/index.php', array('id' => $this->courseid, 'perpage' => $studentsperpage));
138         $this->setup_groups();
140         $this->setup_sortitemid();
141     }
143     /**
144      * Processes the data sent by the form (grades and feedbacks).
145      * Caller is reposible for all access control checks
146      * @param array $data form submission (with magic quotes)
147      * @return array empty array if success, array of warnings if something fails.
148      */
149     public function process_data($data) {
150         global $DB;
151         $warnings = array();
153         $separategroups = false;
154         $mygroups       = array();
155         if ($this->groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $this->context)) {
156             $separategroups = true;
157             $mygroups = groups_get_user_groups($this->course->id);
158             $mygroups = $mygroups[0]; // ignore groupings
159             // reorder the groups fro better perf bellow
160             $current = array_search($this->currentgroup, $mygroups);
161             if ($current !== false) {
162                 unset($mygroups[$current]);
163                 array_unshift($mygroups, $this->currentgroup);
164             }
165         }
167         // always initialize all arrays
168         $queue = array();
169         foreach ($data as $varname => $postedvalue) {
171             $needsupdate = false;
173             // skip, not a grade nor feedback
174             if (strpos($varname, 'grade') === 0) {
175                 $datatype = 'grade';
176             } else if (strpos($varname, 'feedback') === 0) {
177                 $datatype = 'feedback';
178             } else {
179                 continue;
180             }
182             $gradeinfo = explode("_", $varname);
183             $userid = clean_param($gradeinfo[1], PARAM_INT);
184             $itemid = clean_param($gradeinfo[2], PARAM_INT);
186             $oldvalue = $data->{'old'.$varname};
188             // was change requested?
189             if ($oldvalue == $postedvalue) { // string comparison
190                 continue;
191             }
193             if (!$gradeitem = grade_item::fetch(array('id'=>$itemid, 'courseid'=>$this->courseid))) { // we must verify course id here!
194                 print_error('invalidgradeitmeid');
195             }
197             // Pre-process grade
198             if ($datatype == 'grade') {
199                 $feedback = false;
200                 $feedbackformat = false;
201                 if ($gradeitem->gradetype == GRADE_TYPE_SCALE) {
202                     if ($postedvalue == -1) { // -1 means no grade
203                         $finalgrade = null;
204                     } else {
205                         $finalgrade = $postedvalue;
206                     }
207                 } else {
208                     $finalgrade = unformat_float($postedvalue);
209                 }
211                 $errorstr = '';
212                 // Warn if the grade is out of bounds.
213                 if (is_null($finalgrade)) {
214                     // ok
215                 } else {
216                     $bounded = $gradeitem->bounded_grade($finalgrade);
217                     if ($bounded > $finalgrade) {
218                     $errorstr = 'lessthanmin';
219                     } else if ($bounded < $finalgrade) {
220                         $errorstr = 'morethanmax';
221                     }
222                 }
223                 if ($errorstr) {
224                     $user = $DB->get_record('user', array('id' => $userid), 'id, firstname, lastname');
225                     $gradestr = new object();
226                     $gradestr->username = fullname($user);
227                     $gradestr->itemname = $gradeitem->get_name();
228                     $warnings[] = get_string($errorstr, 'grades', $gradestr);
229                 }
231             } else if ($datatype == 'feedback') {
232                 $finalgrade = false;
233                 $trimmed = trim($postedvalue);
234                 if (empty($trimmed)) {
235                      $feedback = NULL;
236                 } else {
237                      $feedback = stripslashes($postedvalue);
238                 }
239             }
241             // group access control
242             if ($separategroups) {
243                 // note: we can not use $this->currentgroup because it would fail badly
244                 //       when having two browser windows each with different group
245                 $sharinggroup = false;
246                 foreach($mygroups as $groupid) {
247                     if (groups_is_member($groupid, $userid)) {
248                         $sharinggroup = true;
249                         break;
250                     }
251                 }
252                 if (!$sharinggroup) {
253                     // either group membership changed or somebedy is hacking grades of other group
254                     $warnings[] = get_string('errorsavegrade', 'grades');
255                     continue;
256                 }
257             }
259             $gradeitem->update_final_grade($userid, $finalgrade, 'gradebook', $feedback, FORMAT_MOODLE);
260         }
262         return $warnings;
263     }
266     /**
267      * Setting the sort order, this depends on last state
268      * all this should be in the new table class that we might need to use
269      * for displaying grades.
270      */
271     private function setup_sortitemid() {
273         global $SESSION;
275         if ($this->sortitemid) {
276             if (!isset($SESSION->gradeuserreport->sort)) {
277                 if ($this->sortitemid == 'firstname' || $this->sortitemid == 'lastname') {
278                     $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC';
279                 } else {
280                     $this->sortorder = $SESSION->gradeuserreport->sort = 'DESC';
281                 }
282             } else {
283                 // this is the first sort, i.e. by last name
284                 if (!isset($SESSION->gradeuserreport->sortitemid)) {
285                     if ($this->sortitemid == 'firstname' || $this->sortitemid == 'lastname') {
286                         $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC';
287                     } else {
288                         $this->sortorder = $SESSION->gradeuserreport->sort = 'DESC';
289                     }
290                 } else if ($SESSION->gradeuserreport->sortitemid == $this->sortitemid) {
291                     // same as last sort
292                     if ($SESSION->gradeuserreport->sort == 'ASC') {
293                         $this->sortorder = $SESSION->gradeuserreport->sort = 'DESC';
294                     } else {
295                         $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC';
296                     }
297                 } else {
298                     if ($this->sortitemid == 'firstname' || $this->sortitemid == 'lastname') {
299                         $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC';
300                     } else {
301                         $this->sortorder = $SESSION->gradeuserreport->sort = 'DESC';
302                     }
303                 }
304             }
305             $SESSION->gradeuserreport->sortitemid = $this->sortitemid;
306         } else {
307             // not requesting sort, use last setting (for paging)
309             if (isset($SESSION->gradeuserreport->sortitemid)) {
310                 $this->sortitemid = $SESSION->gradeuserreport->sortitemid;
311             }else{
312                 $this->sortitemid = 'lastname';
313             }
315             if (isset($SESSION->gradeuserreport->sort)) {
316                 $this->sortorder = $SESSION->gradeuserreport->sort;
317             } else {
318                 $this->sortorder = 'ASC';
319             }
320         }
321     }
323     /**
324      * pulls out the userids of the users to be display, and sorts them
325      */
326     public function load_users() {
327         global $CFG, $DB;
329         list($usql, $gbrparams) = $DB->get_in_or_equal(explode(',', $this->gradebookroles), SQL_PARAMS_NAMED, 'grbr0');
331         if (is_numeric($this->sortitemid)) {
332             $params = array_merge(array('gitemid'=>$this->sortitemid), $gbrparams, $this->groupwheresql_params);
333             // the MAX() magic is required in order to please PG
334             $sort = "MAX(g.finalgrade) $this->sortorder";
336             $sql = "SELECT u.id, u.firstname, u.lastname, u.imagealt, u.picture, u.idnumber
337                       FROM {user} u
338                            JOIN {role_assignments} ra ON ra.userid = u.id
339                            $this->groupsql
340                            LEFT JOIN {grade_grades} g ON (g.userid = u.id AND g.itemid = :gitemid)
341                      WHERE ra.roleid $usql AND u.deleted = 0
342                            $this->groupwheresql
343                            AND ra.contextid ".get_related_contexts_string($this->context)."
344                   GROUP BY u.id, u.firstname, u.lastname, u.imagealt, u.picture, u.idnumber
345                   ORDER BY $sort";
347         } else {
348             switch($this->sortitemid) {
349                 case 'lastname':
350                     $sort = "u.lastname $this->sortorder, u.firstname $this->sortorder"; break;
351                 case 'firstname':
352                     $sort = "u.firstname $this->sortorder, u.lastname $this->sortorder"; break;
353                 case 'idnumber':
354                 default:
355                     $sort = "u.idnumber $this->sortorder"; break;
356             }
358             $params = array_merge($gbrparams, $this->groupwheresql_params);
359             $sql = "SELECT DISTINCT u.id, u.firstname, u.lastname, u.imagealt, u.picture, u.idnumber
360                       FROM {user} u
361                            JOIN {role_assignments} ra ON u.id = ra.userid
362                            $this->groupsql
363                      WHERE ra.roleid $usql AND u.deleted = 0
364                            $this->groupwheresql
365                            AND ra.contextid ".get_related_contexts_string($this->context)."
366                   ORDER BY $sort";
367         }
370         $this->users = $DB->get_records_sql($sql, $params, $this->get_pref('studentsperpage') * $this->page, $this->get_pref('studentsperpage'));
372         if (empty($this->users)) {
373             $this->userselect = '';
374             $this->users = array();
375             $this->userselect_params = array();
376         } else {
377             list($usql, $params) = $DB->get_in_or_equal(array_keys($this->users), SQL_PARAMS_NAMED, 'usid0');
378             $this->userselect = "AND g.userid $usql";
379             $this->userselect_params = $params;
380         }
382         return $this->users;
383     }
385     /**
386      * we supply the userids in this query, and get all the grades
387      * pulls out all the grades, this does not need to worry about paging
388      */
389     public function load_final_grades() {
390         global $CFG, $DB;
392         // please note that we must fetch all grade_grades fields if we want to contruct grade_grade object from it!
393         $params = array_merge(array('courseid'=>$this->courseid), $this->userselect_params);
394         $sql = "SELECT g.*
395                   FROM {grade_items} gi,
396                        {grade_grades} g
397                  WHERE g.itemid = gi.id AND gi.courseid = :courseid {$this->userselect}";
399         $userids = array_keys($this->users);
402         if ($grades = $DB->get_records_sql($sql, $params)) {
403             foreach ($grades as $graderec) {
404                 if (in_array($graderec->userid, $userids) and array_key_exists($graderec->itemid, $this->gtree->get_items())) { // some items may not be present!!
405                     $this->grades[$graderec->userid][$graderec->itemid] = new grade_grade($graderec, false);
406                     $this->grades[$graderec->userid][$graderec->itemid]->grade_item =& $this->gtree->get_item($graderec->itemid); // db caching
407                 }
408             }
409         }
411         // prefil grades that do not exist yet
412         foreach ($userids as $userid) {
413             foreach ($this->gtree->get_items() as $itemid=>$unused) {
414                 if (!isset($this->grades[$userid][$itemid])) {
415                     $this->grades[$userid][$itemid] = new grade_grade();
416                     $this->grades[$userid][$itemid]->itemid = $itemid;
417                     $this->grades[$userid][$itemid]->userid = $userid;
418                     $this->grades[$userid][$itemid]->grade_item =& $this->gtree->get_item($itemid); // db caching
419                 }
420             }
421         }
422     }
424     /**
425      * Builds and returns a div with on/off toggles.
426      * @return string HTML code
427      */
428     public function get_toggles_html() {
429         global $CFG, $USER, $COURSE, $OUTPUT;
431         $html = '';
432         if ($USER->gradeediting[$this->courseid]) {
433             if (has_capability('moodle/grade:manage', $this->context) or has_capability('moodle/grade:hide', $this->context)) {
434                 $html .= $this->print_toggle('eyecons');
435             }
436             if (has_capability('moodle/grade:manage', $this->context)
437              or has_capability('moodle/grade:lock', $this->context)
438              or has_capability('moodle/grade:unlock', $this->context)) {
439                 $html .= $this->print_toggle('locks');
440             }
441             if (has_capability('moodle/grade:manage', $this->context)) {
442                 $html .= $this->print_toggle('quickfeedback');
443             }
445             if (has_capability('moodle/grade:manage', $this->context)) {
446                 $html .= $this->print_toggle('calculations');
447             }
448         }
450         if ($this->canviewhidden) {
451             $html .= $this->print_toggle('averages');
452         }
454         $html .= $this->print_toggle('ranges');
455         if (!empty($CFG->enableoutcomes)) {
456             $html .= $this->print_toggle('nooutcomes');
457         }
459         return $OUTPUT->container($html, 'grade-report-toggles');
460     }
462     /**
463     * Shortcut function for printing the grader report toggles.
464     * @param string $type The type of toggle
465     * @param bool $return Whether to return the HTML string rather than printing it
466     * @return void
467     */
468     public function print_toggle($type) {
469         global $CFG, $OUTPUT;
471         $icons = array('eyecons' => 't/hide',
472                        'calculations' => 't/calc',
473                        'locks' => 't/lock',
474                        'averages' => 't/mean',
475                        'quickfeedback' => 't/feedback',
476                        'nooutcomes' => 't/outcomes');
478         $prefname = 'grade_report_show' . $type;
480         if (array_key_exists($prefname, $CFG)) {
481             $showpref = get_user_preferences($prefname, $CFG->$prefname);
482         } else {
483             $showpref = get_user_preferences($prefname);
484         }
486         $strshow = $this->get_lang_string('show' . $type, 'grades');
487         $strhide = $this->get_lang_string('hide' . $type, 'grades');
489         $showhide = 'show';
490         $toggleaction = 1;
492         if ($showpref) {
493             $showhide = 'hide';
494             $toggleaction = 0;
495         }
497         if (array_key_exists($type, $icons)) {
498             $imagename = $icons[$type];
499         } else {
500             $imagename = "t/$type.gif";
501         }
503         $string = ${'str' . $showhide};
505         $aurl = clone($this->baseurl);
506         $url->params(array('toggle' => $toggleaction, 'toggle_type' => $type));
508         $retval = $OUTPUT->container($OUTPUT->action_icon($url, new pix_icon($imagename, $string))); // TODO: this container looks wrong here
510         return $retval;
511     }
513     /**
514      * Builds and returns the rows that will make up the left part of the grader report
515      * This consists of student names and icons, links to user reports and id numbers, as well
516      * as header cells for these columns. It also includes the fillers required for the
517      * categories displayed on the right side of the report.
518      * @return array Array of html_table_row objects
519      */
520     public function get_left_rows() {
521         global $CFG, $USER, $OUTPUT;
523         $rows = array();
525         $showuserimage = $this->get_pref('showuserimage');
526         $showuseridnumber = $this->get_pref('showuseridnumber');
527         $fixedstudents = $this->is_fixed_students();
529         $strfeedback  = $this->get_lang_string("feedback");
530         $strgrade     = $this->get_lang_string('grade');
532         $arrows = $this->get_sort_arrows();
534         $colspan = 1;
536         if (has_capability('gradereport/'.$CFG->grade_profilereport.':view', $this->context)) {
537             $colspan++;
538         }
540         if ($showuseridnumber) {
541             $colspan++;
542         }
544         $levels = count($this->gtree->levels) - 1;
546         for ($i = 0; $i < $levels; $i++) {
547             $fillercell = new html_table_cell();
548             $fillercell->add_classes(array('fixedcolumn', 'cell', 'topleft'));
549             $fillercell->text = ' ';
550             $fillercell->colspan = $colspan;
551             $row = new html_table_row(array($fillercell));
552             $rows[] = $row;
553         }
555         $headerrow = new html_table_row();
556         $headerrow->add_class('heading');
558         $studentheader = new html_table_cell();
559         $studentheader->add_classes(array('header'));
560         $studentheader->scope = 'col';
561         $studentheader->header = true;
562         $studentheader->id = 'studentheader';
563         if (has_capability('gradereport/'.$CFG->grade_profilereport.':view', $this->context)) {
564             $studentheader->colspan = 2;
565         }
566         $studentheader->text = $arrows['studentname'];
568         $headerrow->cells[] = $studentheader;
570         if ($showuseridnumber) {
571             // TODO: weird, this is not used anywhere
572             $sortidnumberlink = html_writer::link(new moodle_url($this->baseurl, array('sortitemid'=>'idnumber')), get_string('idnumber'));
574             $idnumberheader = new html_table_cell();
575             $idnumberheader->add_classes(array('header', 'useridnumber'));
576             $idnumberheader->scope = 'col';
577             $idnumberheader->header = true;
578             $idnumberheader->text = $arrows['idnumber'];
580             $headerrow->cells[] = $idnumberheader;
581         }
583         $rows[] = $headerrow;
585         $rows = $this->get_left_icons_row($rows, $colspan);
587         $rowclasses = array('even', 'odd');
589         foreach ($this->users as $userid => $user) {
590             $userrow = new html_table_row();
591             $userrow->id = 'fixed_user_'.$userid;
592             $userrow->add_classes(array('r'.$this->rowcount++, $rowclasses[$this->rowcount % 2]));
594             $usercell = new html_table_cell();
595             $usercell->add_classes(array('user'));
596             $usercell->header = true;
597             $usercell->scope = 'row';
599             if ($showuserimage) {
600                 $usercell->text = $OUTPUT->container($OUTPUT->user_picture($user), 'userpic');
601             }
603             $usercell->text .= html_writer::link(new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $this->course->id)), fullname($user));
605             $userrow->cells[] = $usercell;
607             if (has_capability('gradereport/'.$CFG->grade_profilereport.':view', $this->context)) {
608                 $userreportcell = new html_table_cell();
609                 $userreportcell->add_class('userreport');
610                 $userreportcell->header = true;
611                 $a->user = fullname($user);
612                 $strgradesforuser = get_string('gradesforuser', 'grades', $a);
613                 $url = new moodle_url('/grade/report/'.$CFG->grade_profilereport.'/index.php', array('userid' => $user->id, 'id' => $this->course->id));
614                 $userreportcell->text = $OUTPUT->action_icon($url, new pix_icon('t/grades', $strgradesforuser));
615                 $userrow->cells[] = $userreportcell;
616             }
618             if ($showuseridnumber) {
619                 $idnumbercell = new html_table_cell();
620                 $idnumbercell->add_classes(array('header', 'useridnumber'));
621                 $idnumbercell->header = true;
622                 $idnumbercell->scope = 'row';
623                 $userrow->cells[] = $idnumbercell;
624             }
626             $rows[] = $userrow;
627         }
629         $rows = $this->get_left_range_row($rows, $colspan);
630         $rows = $this->get_left_avg_row($rows, $colspan, true);
631         $rows = $this->get_left_avg_row($rows, $colspan);
633         return $rows;
634     }
636     /**
637      * Builds and returns the rows that will make up the right part of the grader report
638      * @return array Array of html_table_row objects
639      */
640     public function get_right_rows() {
641         global $CFG, $USER, $OUTPUT, $DB, $PAGE;
643         $rows = array();
644         $this->rowcount = 0;
645         $numrows = count($this->gtree->get_levels());
646         $numusers = count($this->users);
647         $gradetabindex = 1;
648         $columnstounset = array();
649         $strgrade = $this->get_lang_string('grade');
650         $strfeedback  = $this->get_lang_string("feedback");
651         $arrows = $this->get_sort_arrows();
653         $jsarguments = array(
654             'id'        => '#fixed_column',
655             'cfg'       => array('ajaxenabled'=>false),
656             'items'     => array(),
657             'users'     => array(),
658             'feedback'  => array()
659         );
660         $jsscales = array();
662         foreach ($this->gtree->get_levels() as $key=>$row) {
663             if ($key == 0) {
664                 // do not display course grade category
665                 // continue;
666             }
668             $headingrow = new html_table_row();
669             $headingrow->add_class('heading_name_row');
671             foreach ($row as $columnkey => $element) {
672                 $sortlink = clone($this->baseurl);
673                 if (isset($element['object']->id)) {
674                     $sortlink->param('sortitemid', $element['object']->id);
675                 }
677                 $eid    = $element['eid'];
678                 $object = $element['object'];
679                 $type   = $element['type'];
680                 $categorystate = @$element['categorystate'];
681                 $itemmodule = null;
682                 $iteminstance = null;
684                 if (!empty($element['colspan'])) {
685                     $colspan = $element['colspan'];
686                 } else {
687                     $colspan = 1;
688                 }
690                 if (!empty($element['depth'])) {
691                     $catlevel = 'catlevel'.$element['depth'];
692                 } else {
693                     $catlevel = '';
694                 }
696 // Element is a filler
697                 if ($type == 'filler' or $type == 'fillerfirst' or $type == 'fillerlast') {
698                     $fillercell = new html_table_cell();
699                     $fillercell->add_classes(array($type, $catlevel));
700                     $fillercell->colspan = $colspan;
701                     $fillercell->text = '&nbsp;';
702                     $fillercell->header = true;
703                     $fillercell->scope = 'col';
704                     $headingrow->cells[] = $fillercell;
705                 }
706 // Element is a category
707                 else if ($type == 'category') {
708                     $categorycell = new html_table_cell();
709                     $categorycell->add_classes(array('category', $catlevel));
710                     $categorycell->colspan = $colspan;
711                     $categorycell->text = shorten_text($element['object']->get_name());
712                     $categorycell->text .= $this->get_collapsing_icon($element);
713                     $categorycell->header = true;
714                     $categorycell->scope = 'col';
716                     // Print icons
717                     if ($USER->gradeediting[$this->courseid]) {
718                         $categorycell->text .= $this->get_icons($element);
719                     }
721                     $headingrow->cells[] = $categorycell;
722                 }
723 // Element is a grade_item
724                 else {
725                     $itemmodule = $element['object']->itemmodule;
726                     $iteminstance = $element['object']->iteminstance;
728                     if ($element['object']->id == $this->sortitemid) {
729                         if ($this->sortorder == 'ASC') {
730                             $arrow = $this->get_sort_arrow('up', $sortlink);
731                         } else {
732                             $arrow = $this->get_sort_arrow('down', $sortlink);
733                         }
734                     } else {
735                         $arrow = $this->get_sort_arrow('move', $sortlink);
736                     }
738                     $headerlink = $this->gtree->get_element_header($element, true, $this->get_pref('showactivityicons'), false);
740                     $itemcell = new html_table_cell();
741                     $itemcell->add_classes(array($type, $catlevel, 'highlightable'));
743                     if ($element['object']->is_hidden()) {
744                         $itemcell->add_class('hidden');
745                     }
747                     $itemcell->colspan = $colspan;
748                     $itemcell->text = shorten_text($headerlink) . $arrow;
749                     $itemcell->header = true;
750                     $itemcell->scope = 'col';
752                     $headingrow->cells[] = $itemcell;
753                 }
754                 
755             }
756             $rows[] = $headingrow;
757         }
759         $rows = $this->get_right_icons_row($rows);
761         // Preload scale objects for items with a scaleid
762         $scaleslist = array();
763         $tabindices = array();
765         foreach ($this->gtree->get_items() as $itemid=>$item) {
766             $scale = null;
767             if (!empty($item->scaleid)) {
768                 $scaleslist[] = $item->scaleid;
769                 $jsarguments['items'][$itemid] = array('id'=>$itemid, 'name'=>$item->get_name(true), 'type'=>'scale', 'scale'=>$item->scaleid, 'decimals'=>$item->get_decimals());
770             } else {
771                 $jsarguments['items'][$itemid] = array('id'=>$itemid, 'name'=>$item->get_name(true), 'type'=>'value', 'scale'=>false, 'decimals'=>$item->get_decimals());
772             }
773             $tabindices[$item->id]['grade'] = $gradetabindex;
774             $tabindices[$item->id]['feedback'] = $gradetabindex + $numusers;
775             $gradetabindex += $numusers * 2;
776         }
777         $scalesarray = array();
779         if (!empty($scaleslist)) {
780             $scalesarray = $DB->get_records_list('scale', 'id', $scaleslist);
781         }
782         $jsscales = $scalesarray;
784         $rowclasses = array('even', 'odd');
786         foreach ($this->users as $userid => $user) {
788             if ($this->canviewhidden) {
789                 $altered = array();
790                 $unknown = array();
791             } else {
792                 $hidingaffected = grade_grade::get_hiding_affected($this->grades[$userid], $this->gtree->get_items());
793                 $altered = $hidingaffected['altered'];
794                 $unknown = $hidingaffected['unknown'];
795                 unset($hidingaffected);
796             }
799             $itemrow = new html_table_row();
800             $itemrow->id = 'user_'.$userid;
801             $itemrow->add_class($rowclasses[$this->rowcount % 2]);
803             $jsarguments['users'][$userid] = fullname($user);
805             foreach ($this->gtree->items as $itemid=>$unused) {
806                 $item =& $this->gtree->items[$itemid];
807                 $grade = $this->grades[$userid][$item->id];
809                 $itemcell = new html_table_cell();
811                 $itemcell->id = 'u'.$userid.'i'.$itemid;
813                 // Get the decimal points preference for this item
814                 $decimalpoints = $item->get_decimals();
816                 if (in_array($itemid, $unknown)) {
817                     $gradeval = null;
818                 } else if (array_key_exists($itemid, $altered)) {
819                     $gradeval = $altered[$itemid];
820                 } else {
821                     $gradeval = $grade->finalgrade;
822                 }
824                 // MDL-11274
825                 // Hide grades in the grader report if the current grader doesn't have 'moodle/grade:viewhidden'
826                 if (!$this->canviewhidden and $grade->is_hidden()) {
827                     if (!empty($CFG->grade_hiddenasdate) and $grade->get_datesubmitted() and !$item->is_category_item() and !$item->is_course_item()) {
828                         // 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
829                         $itemcell->text = html_writer::tag('span', userdate($grade->get_datesubmitted(),get_string('strftimedatetimeshort')), array('class'=>'datesubmitted'));
830                     } else {
831                         $itemcell->text = '-';
832                     }
833                     $itemrow->cells[] = $itemcell;
834                     continue;
835                 }
837                 // emulate grade element
838                 $eid = $this->gtree->get_grade_eid($grade);
839                 $element = array('eid'=>$eid, 'object'=>$grade, 'type'=>'grade');
841                 $itemcell->add_class('grade');
842                 if ($item->is_category_item()) {
843                     $itemcell->add_class('cat');
844                 }
845                 if ($item->is_course_item()) {
846                     $itemcell->add_class('course');
847                 }
848                 if ($grade->is_overridden()) {
849                     $itemcell->add_class('overridden');
850                 }
852                 if ($grade->is_excluded()) {
853                     // $itemcell->add_class('excluded');
854                 }
856                 if (!empty($grade->feedback)) {
857                     $jsarguments['feedback'][] = array('user'=>$userid, 'item'=>$itemid, 'content'=>wordwrap(trim(format_string($grade->feedback, $grade->feedbackformat)), 34, '<br/ >'));
858                 }
860                 if ($grade->is_excluded()) {
861                     $itemcell->text .= html_writer::tag('span', get_string('excluded', 'grades'), array('class'=>'excludedfloater'));
862                 }
864                 // Do not show any icons if no grade (no record in DB to match)
865                 if (!$item->needsupdate and $USER->gradeediting[$this->courseid]) {
866                     $itemcell->text .= $this->get_icons($element);
867                 }
869                 $hidden = '';
870                 if ($grade->is_hidden()) {
871                     $hidden = ' hidden ';
872                 }
874                 $gradepass = ' gradefail ';
875                 if ($grade->is_passed($item)) {
876                     $gradepass = ' gradepass ';
877                 } elseif (is_null($grade->is_passed($item))) {
878                     $gradepass = '';
879                 }
881                 // if in editting mode, we need to print either a text box
882                 // or a drop down (for scales)
883                 // grades in item of type grade category or course are not directly editable
884                 if ($item->needsupdate) {
885                     $itemcell->text .= html_writer::tag('span', get_string('error'), array('class'=>"gradingerror$hidden"));
887                 } else if ($USER->gradeediting[$this->courseid]) {
889                     if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
890                         $scale = $scalesarray[$item->scaleid];
891                         $gradeval = (int)$gradeval; // scales use only integers
892                         $scales = explode(",", $scale->scale);
893                         // reindex because scale is off 1
895                         // MDL-12104 some previous scales might have taken up part of the array
896                         // so this needs to be reset
897                         $scaleopt = array();
898                         $i = 0;
899                         foreach ($scales as $scaleoption) {
900                             $i++;
901                             $scaleopt[$i] = $scaleoption;
902                         }
904                         if ($this->get_pref('quickgrading') and $grade->is_editable()) {
905                             $oldval = empty($gradeval) ? -1 : $gradeval;
906                             if (empty($item->outcomeid)) {
907                                 $nogradestr = $this->get_lang_string('nograde');
908                             } else {
909                                 $nogradestr = $this->get_lang_string('nooutcome', 'grades');
910                             }
911                             $itemcell->text .= '<input type="hidden" id="oldgrade_'.$userid.'_'.$item->id.'" name="oldgrade_'.$userid.'_'.$item->id.'" value="'.$oldval.'"/>';
912                             $attributes = array('tabindex' => $tabindices[$item->id]['grade'], 'id'=>'grade_'.$userid.'_'.$item->id);
913                             $itemcell->text .= html_writer::select($scaleopt, 'grade_'.$userid.'_'.$item->id, $gradeval, array(-1=>$nogradestr), $attributes);;
914                         } elseif(!empty($scale)) {
915                             $scales = explode(",", $scale->scale);
917                             // invalid grade if gradeval < 1
918                             if ($gradeval < 1) {
919                                 $itemcell->text .= html_writer::tag('span', '-', array('class'=>"gradevalue$hidden$gradepass"));
920                             } else {
921                                 $gradeval = $grade->grade_item->bounded_grade($gradeval); //just in case somebody changes scale
922                                 $itemcell->text .= html_writer::tag('span', $scales[$gradeval-1], array('class'=>"gradevalue$hidden$gradepass"));
923                             }
924                         } else {
925                             // no such scale, throw error?
926                         }
928                     } else if ($item->gradetype != GRADE_TYPE_TEXT) { // Value type
929                         if ($this->get_pref('quickgrading') and $grade->is_editable()) {
930                             $value = format_float($gradeval, $decimalpoints);
931                             $itemcell->text .= '<input type="hidden" id="oldgrade_'.$userid.'_'.$item->id.'" name="oldgrade_'.$userid.'_'.$item->id.'" value="'.$value.'" />';
932                             $itemcell->text .= '<input size="6" tabindex="' . $tabindices[$item->id]['grade']
933                                           . '" type="text" class="text" title="'. $strgrade .'" name="grade_'
934                                           .$userid.'_' .$item->id.'" id="grade_'.$userid.'_'.$item->id.'" value="'.$value.'" />';
935                         } else {
936                             $itemcell->text .= html_writer::tag('span', format_float($gradeval, $decimalpoints), array('class'=>"gradevalue$hidden$gradepass"));
937                         }
938                     }
941                     // If quickfeedback is on, print an input element
942                     if ($this->get_pref('showquickfeedback') and $grade->is_editable()) {
944                         $itemcell->text .= '<input type="hidden" id="oldfeedback_'.$userid.'_'.$item->id.'" name="oldfeedback_'.$userid.'_'.$item->id.'" value="' . s($grade->feedback) . '" />';
945                         $itemcell->text .= '<input class="quickfeedback" tabindex="' . $tabindices[$item->id]['feedback'].'" id="feedback_'.$userid.'_'.$item->id
946                                       . '" size="6" title="' . $strfeedback . '" type="text" name="feedback_'.$userid.'_'.$item->id.'" value="' . s($grade->feedback) . '" />';
947                     }
949                 } else { // Not editing
950                     $gradedisplaytype = $item->get_displaytype();
952                     if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
953                         $itemcell->add_class('grade_type_scale');
954                     } else if ($item->gradetype != GRADE_TYPE_TEXT) {
955                         $itemcell->add_class('grade_type_text');
956                     }
958                     if ($item->needsupdate) {
959                         $itemcell->text .= html_writer::tag('span', get_string('error'), array('class'=>"gradingerror$hidden$gradepass"));
960                     } else {
961                         $itemcell->text .= html_writer::tag('span', grade_format_gradevalue($gradeval, $item, true, $gradedisplaytype, null), array('class'=>"gradevalue$hidden$gradepass"));
962                     }
963                 }
965                 if (!empty($this->gradeserror[$item->id][$userid])) {
966                     $itemcell->text .= $this->gradeserror[$item->id][$userid];
967                 }
969                 $itemrow->cells[] = $itemcell;
970             }
971             $rows[] = $itemrow;
972         }
974         if ($this->get_pref('enableajax')) {
975             $jsarguments['cfg']['ajaxenabled'] = true;
976             $jsarguments['cfg']['scales'] = array();
977             foreach ($jsscales as $scale) {
978                 $jsarguments['cfg']['scales'][$scale->id] = explode(',',$scale->scale);
979             }
980             $jsarguments['cfg']['feedbacktrunclength'] =  $this->feedback_trunc_length;
981             $jsarguments['cfg']['feedback'] =  $this->feedbacks;
982         }
983         $jsarguments['cfg']['isediting'] = (bool)$USER->gradeediting[$this->courseid];
984         $jsarguments['cfg']['courseid'] =  $this->courseid;
985         $jsarguments['cfg']['studentsperpage'] =  $this->get_pref('studentsperpage');
986         $jsarguments['cfg']['showquickfeedback'] =  (bool)$this->get_pref('showquickfeedback');
988         $module = array(
989             'name'      => 'gradereport_grader',
990             'fullpath'  => '/grade/report/grader/module.js',
991             'requires'  => array('base', 'dom', 'event', 'event-mouseenter', 'event-key', 'io', 'json-parse', 'overlay')
992         );
993         $PAGE->requires->js_init_call('M.gradereport_grader.init_report', $jsarguments, false, $module);
994         $PAGE->requires->strings_for_js(array('addfeedback','feedback', 'grade'), 'grades');
995         $PAGE->requires->strings_for_js(array('ajaxchoosescale','ajaxclicktoclose','ajaxerror','ajaxfailedupdate', 'ajaxfieldchanged'), 'gradereport_grader');
997         $rows = $this->get_right_range_row($rows);
998         $rows = $this->get_right_avg_row($rows, true);
999         $rows = $this->get_right_avg_row($rows);
1001         return $rows;
1002     }
1004     /**
1005      * Depending on the style of report (fixedstudents vs traditional one-table),
1006      * arranges the rows of data in one or two tables, and returns the output of
1007      * these tables in HTML
1008      * @return string HTML
1009      */
1010     public function get_grade_table() {
1011         global $OUTPUT;
1012         $fixedstudents = $this->is_fixed_students();
1014         $leftrows = $this->get_left_rows();
1015         $rightrows = $this->get_right_rows();
1017         $html = '';
1020         if ($fixedstudents) {
1021             $fixedcolumntable = new html_table();
1022             $fixedcolumntable->id = 'fixed_column';
1023             $fixedcolumntable->add_class('fixed_grades_column');
1024             $fixedcolumntable->bodyclasses = 'leftbody';
1025             $fixedcolumntable->data = $leftrows;
1026             $html .= $OUTPUT->container($OUTPUT->table($fixedcolumntable), 'left_scroller');
1028             $righttable = new html_table();
1029             $righttable->id = 'user-grades';
1030             $righttable->bodyclasses = array('righttest');
1031             $righttable->data = $rightrows;
1033             $html .= $OUTPUT->container($OUTPUT->table($righttable), 'right_scroller');
1034         } else {
1035             $fulltable = new html_table();
1036             $fulltable->add_classes(array('gradestable', 'flexible', 'boxaligncenter', 'generaltable'));
1037             $fulltable->id = 'user-grades';
1039             // Extract rows from each side (left and right) and collate them into one row each
1040             foreach ($leftrows as $key => $row) {
1041                 $row->cells = array_merge($row->cells, $rightrows[$key]->cells);
1042                 $fulltable->data[] = $row;
1043             }
1044             $html .= $OUTPUT->table($fulltable);
1045         }
1046         return $OUTPUT->container($html, 'gradeparent');
1047     }
1049     /**
1050      * Builds and return the row of icons for the left side of the report.
1051      * It only has one cell that says "Controls"
1052      * @param array $rows The Array of rows for the left part of the report
1053      * @param int $colspan The number of columns this cell has to span
1054      * @return array Array of rows for the left part of the report
1055      */
1056     public function get_left_icons_row($rows=array(), $colspan=1) {
1057         global $USER;
1059         if ($USER->gradeediting[$this->courseid]) {
1060             $controlsrow = new html_table_row();
1061             $controlsrow->add_class('controls');
1062             $controlscell = new html_table_cell();
1063             $controlscell->add_classes(array('header', 'controls'));
1064             $controlscell->colspan = $colspan;
1065             $controlscell->text = $this->get_lang_string('controls','grades');
1067             $controlsrow->cells[] = $controlscell;
1068             $rows[] = $controlsrow;
1069         }
1070         return $rows;
1071     }
1073     /**
1074      * Builds and return the header for the row of ranges, for the left part of the grader report.
1075      * @param array $rows The Array of rows for the left part of the report
1076      * @param int $colspan The number of columns this cell has to span
1077      * @return array Array of rows for the left part of the report
1078      */
1079     public function get_left_range_row($rows=array(), $colspan=1) {
1080         global $CFG, $USER;
1082         if ($this->get_pref('showranges')) {
1083             $rangerow = new html_table_row();
1084             $rangerow->add_classes(array('range', 'r'.$this->rowcount++));
1085             $rangecell = new html_table_cell();
1086             $rangecell->add_classes(array('header', 'range'));
1087             $rangecell->colspan = $colspan;
1088             $rangecell->header = true;
1089             $rangecell->scope = 'row';
1090             $rangecell->text = $this->get_lang_string('range','grades');
1091             $rangerow->cells[] = $rangecell;
1092             $rows[] = $rangerow;
1093         }
1095         return $rows;
1096     }
1098     /**
1099      * Builds and return the headers for the rows of averages, for the left part of the grader report.
1100      * @param array $rows The Array of rows for the left part of the report
1101      * @param int $colspan The number of columns this cell has to span
1102      * @param bool $groupavg If true, returns the row for group averages, otherwise for overall averages
1103      * @return array Array of rows for the left part of the report
1104      */
1105     public function get_left_avg_row($rows=array(), $colspan=1, $groupavg=false) {
1106         if (!$this->canviewhidden) {
1107             // totals might be affected by hiding, if user can not see hidden grades the aggregations might be altered
1108             // better not show them at all if user can not see all hideen grades
1109             return $rows;
1110         }
1112         $showaverages = $this->get_pref('showaverages');
1113         $showaveragesgroup = $this->currentgroup && $showaverages;
1114         $straveragegroup = get_string('groupavg', 'grades');
1116         if ($groupavg) {
1117             if ($showaveragesgroup) {
1118                 $groupavgrow = new html_table_row();
1119                 $groupavgrow->add_classes(array('groupavg', 'r'.$this->rowcount++));
1120                 $groupavgcell = new html_table_cell();
1121                 $groupavgcell->add_classes(array('header', 'range'));
1122                 $groupavgcell->colspan = $colspan;
1123                 $groupavgcell->header = true;
1124                 $groupavgcell->scope = 'row';
1125                 $groupavgcell->text = $straveragegroup;
1126                 $groupavgrow->cells[] = $groupavgcell;
1127                 $rows[] = $groupavgrow;
1128             }
1129         } else {
1130             $straverage = get_string('overallaverage', 'grades');
1132             if ($showaverages) {
1133                 $avgrow = new html_table_row();
1134                 $avgrow->add_classes(array('avg', 'r'.$this->rowcount++));
1135                 $avgcell = new html_table_cell();
1136                 $avgcell->add_classes(array('header', 'range'));
1137                 $avgcell->colspan = $colspan;
1138                 $avgcell->header = true;
1139                 $avgcell->scope = 'row';
1140                 $avgcell->text = $straverage;
1141                 $avgrow->cells[] = $avgcell;
1142                 $rows[] = $avgrow;
1143             }
1144         }
1146         return $rows;
1147     }
1149     /**
1150      * Builds and return the row of icons when editing is on, for the right part of the grader report.
1151      * @param array $rows The Array of rows for the right part of the report
1152      * @return array Array of rows for the right part of the report
1153      */
1154     public function get_right_icons_row($rows=array()) {
1155         global $USER;
1156         if ($USER->gradeediting[$this->courseid]) {
1157             $iconsrow = new html_table_row();
1158             $iconsrow->add_class('controls');
1160             $showuseridnumber = $this->get_pref('showuseridnumber');
1162             foreach ($this->gtree->items as $itemid=>$unused) {
1163                 // emulate grade element
1164                 $item =& $this->gtree->get_item($itemid);
1166                 $eid = $this->gtree->get_item_eid($item);
1167                 $element = $this->gtree->locate_element($eid);
1168                 $itemcell = new html_table_cell();
1169                 $itemcell->add_classes(array('controls', 'icons'));
1170                 $itemcell->text = $this->get_icons($element);
1171                 $iconsrow->cells[] = $itemcell;
1172             }
1173             $rows[] = $iconsrow;
1174         }
1175         return $rows;
1176     }
1178     /**
1179      * Builds and return the row of ranges for the right part of the grader report.
1180      * @param array $rows The Array of rows for the right part of the report
1181      * @return array Array of rows for the right part of the report
1182      */
1183     public function get_right_range_row($rows=array()) {
1184         global $OUTPUT;
1186         if ($this->get_pref('showranges')) {
1187             $rangesdisplaytype   = $this->get_pref('rangesdisplaytype');
1188             $rangesdecimalpoints = $this->get_pref('rangesdecimalpoints');
1189             $rangerow = new html_table_row();
1190             $rangerow->add_classes(array('heading', 'range'));
1192             foreach ($this->gtree->items as $itemid=>$unused) {
1193                 $item =& $this->gtree->items[$itemid];
1194                 $itemcell = new html_table_cell();
1195                 $itemcell->header = true;
1196                 $itemcell->add_classes(array('header', 'range'));
1198                 $hidden = '';
1199                 if ($item->is_hidden()) {
1200                     $hidden = ' hidden ';
1201                 }
1203                 $formattedrange = $item->get_formatted_range($rangesdisplaytype, $rangesdecimalpoints);
1205                 $itemcell->text = $OUTPUT->container($formattedrange, 'rangevalues'.$hidden);
1206                 $rangerow->cells[] = $itemcell;
1207             }
1208             $rows[] = $rangerow;
1209         }
1210         return $rows;
1211     }
1213     /**
1214      * Builds and return the row of averages for the right part of the grader report.
1215      * @param array $rows Whether to return only group averages or all averages.
1216      * @param bool $grouponly Whether to return only group averages or all averages.
1217      * @return array Array of rows for the right part of the report
1218      */
1219     public function get_right_avg_row($rows=array(), $grouponly=false) {
1220         global $CFG, $USER, $DB, $OUTPUT;
1222         if (!$this->canviewhidden) {
1223             // totals might be affected by hiding, if user can not see hidden grades the aggregations might be altered
1224             // better not show them at all if user can not see all hideen grades
1225             return $rows;
1226         }
1228         $showaverages = $this->get_pref('showaverages');
1229         $showaveragesgroup = $this->currentgroup && $showaverages;
1231         $averagesdisplaytype   = $this->get_pref('averagesdisplaytype');
1232         $averagesdecimalpoints = $this->get_pref('averagesdecimalpoints');
1233         $meanselection         = $this->get_pref('meanselection');
1234         $shownumberofgrades    = $this->get_pref('shownumberofgrades');
1236         $avghtml = '';
1237         $avgcssclass = 'avg';
1239         if ($grouponly) {
1240             $straverage = get_string('groupavg', 'grades');
1241             $showaverages = $this->currentgroup && $this->get_pref('showaverages');
1242             $groupsql = $this->groupsql;
1243             $groupwheresql = $this->groupwheresql;
1244             $groupwheresqlparams = $this->groupwheresql_params;
1245             $avgcssclass = 'groupavg';
1246         } else {
1247             $straverage = get_string('overallaverage', 'grades');
1248             $showaverages = $this->get_pref('showaverages');
1249             $groupsql = "";
1250             $groupwheresql = "";
1251             $groupwheresqlparams = array();
1252         }
1254         if ($shownumberofgrades) {
1255             $straverage .= ' (' . get_string('submissions', 'grades') . ') ';
1256         }
1258         $totalcount = $this->get_numusers($grouponly);
1260         list($usql, $rolesparams) = $DB->get_in_or_equal(explode(',', $this->gradebookroles), SQL_PARAMS_NAMED, 'grbr0');
1262         if ($showaverages) {
1263             $params = array_merge(array('courseid'=>$this->courseid), $rolesparams, $groupwheresqlparams);
1265             // find sums of all grade items in course
1266             $SQL = "SELECT g.itemid, SUM(g.finalgrade) AS sum
1267                       FROM {grade_items} gi
1268                            JOIN {grade_grades} g      ON g.itemid = gi.id
1269                            JOIN {user} u              ON u.id = g.userid
1270                            JOIN {role_assignments} ra ON ra.userid = u.id
1271                            $groupsql
1272                      WHERE gi.courseid = :courseid
1273                            AND ra.roleid $usql
1274                            AND ra.contextid ".get_related_contexts_string($this->context)."
1275                            AND g.finalgrade IS NOT NULL
1276                            $groupwheresql
1277                   GROUP BY g.itemid";
1278             $sumarray = array();
1279             if ($sums = $DB->get_records_sql($SQL, $params)) {
1280                 foreach ($sums as $itemid => $csum) {
1281                     $sumarray[$itemid] = $csum->sum;
1282                 }
1283             }
1285             // MDL-10875 Empty grades must be evaluated as grademin, NOT always 0
1286             // This query returns a count of ungraded grades (NULL finalgrade OR no matching record in grade_grades table)
1287             $params = array_merge(array('courseid'=>$this->courseid), $rolesparams, $groupwheresqlparams);
1288             $SQL = "SELECT gi.id, COUNT(u.id) AS count
1289                       FROM {grade_items} gi
1290                            CROSS JOIN {user} u
1291                            JOIN {role_assignments} ra        ON ra.userid = u.id
1292                            LEFT OUTER JOIN  {grade_grades} g ON (g.itemid = gi.id AND g.userid = u.id AND g.finalgrade IS NOT NULL)
1293                            $groupsql
1294                      WHERE gi.courseid = :courseid
1295                            AND ra.roleid $usql
1296                            AND ra.contextid ".get_related_contexts_string($this->context)."
1297                            AND g.id IS NULL
1298                            $groupwheresql
1299                   GROUP BY gi.id";
1301             $ungradedcounts = $DB->get_records_sql($SQL, $params);
1303             $avgrow = new html_table_row();
1304             $avgrow->add_class('avg');
1306             foreach ($this->gtree->items as $itemid=>$unused) {
1307                 $item =& $this->gtree->items[$itemid];
1309                 if ($item->needsupdate) {
1310                     $avgcell = new html_table_cell();
1311                     $avgcell->text = $OUTPUT->container(get_string('error'), 'gradingerror');
1312                     $avgrow->cells[] = $avgcell;
1313                     continue;
1314                 }
1316                 if (!isset($sumarray[$item->id])) {
1317                     $sumarray[$item->id] = 0;
1318                 }
1320                 if (empty($ungradedcounts[$itemid])) {
1321                     $ungradedcount = 0;
1322                 } else {
1323                     $ungradedcount = $ungradedcounts[$itemid]->count;
1324                 }
1326                 if ($meanselection == GRADE_REPORT_MEAN_GRADED) {
1327                     $meancount = $totalcount - $ungradedcount;
1328                 } else { // Bump up the sum by the number of ungraded items * grademin
1329                     $sumarray[$item->id] += $ungradedcount * $item->grademin;
1330                     $meancount = $totalcount;
1331                 }
1333                 $decimalpoints = $item->get_decimals();
1335                 // Determine which display type to use for this average
1336                 if ($USER->gradeediting[$this->courseid]) {
1337                     $displaytype = GRADE_DISPLAY_TYPE_REAL;
1339                 } else if ($averagesdisplaytype == GRADE_REPORT_PREFERENCE_INHERIT) { // no ==0 here, please resave the report and user preferences
1340                     $displaytype = $item->get_displaytype();
1342                 } else {
1343                     $displaytype = $averagesdisplaytype;
1344                 }
1346                 // Override grade_item setting if a display preference (not inherit) was set for the averages
1347                 if ($averagesdecimalpoints == GRADE_REPORT_PREFERENCE_INHERIT) {
1348                     $decimalpoints = $item->get_decimals();
1350                 } else {
1351                     $decimalpoints = $averagesdecimalpoints;
1352                 }
1354                 if (!isset($sumarray[$item->id]) || $meancount == 0) {
1355                     $avgcell = new html_table_cell();
1356                     $avgcell->text = '-';
1357                     $avgrow->cells[] = $avgcell;
1359                 } else {
1360                     $sum = $sumarray[$item->id];
1361                     $avgradeval = $sum/$meancount;
1362                     $gradehtml = grade_format_gradevalue($avgradeval, $item, true, $displaytype, $decimalpoints);
1364                     $numberofgrades = '';
1365                     if ($shownumberofgrades) {
1366                         $numberofgrades = " ($meancount)";
1367                     }
1369                     $avgcell = new html_table_cell();
1370                     $avgcell->text = $gradehtml.$numberofgrades;
1371                     $avgrow->cells[] = $avgcell;
1372                 }
1373             }
1374             $rows[] = $avgrow;
1375         }
1376         return $rows;
1377     }
1379     /**
1380      * Given a grade_category, grade_item or grade_grade, this function
1381      * figures out the state of the object and builds then returns a div
1382      * with the icons needed for the grader report.
1383      *
1384      * @param object $object
1385      * @return string HTML
1386      */
1387     protected function get_icons($element) {
1388         global $CFG, $USER, $OUTPUT;
1390         if (!$USER->gradeediting[$this->courseid]) {
1391             return '<div class="grade_icons" />';
1392         }
1394         // Init all icons
1395         $editicon = '';
1397         if ($element['type'] != 'categoryitem' && $element['type'] != 'courseitem') {
1398             $editicon = $this->gtree->get_edit_icon($element, $this->gpr);
1399         }
1401         $editcalculationicon = '';
1402         $showhideicon        = '';
1403         $lockunlockicon      = '';
1405         if (has_capability('moodle/grade:manage', $this->context)) {
1407             if ($this->get_pref('showcalculations')) {
1408                 $editcalculationicon = $this->gtree->get_calculation_icon($element, $this->gpr);
1409             }
1411             if ($this->get_pref('showeyecons')) {
1412                $showhideicon = $this->gtree->get_hiding_icon($element, $this->gpr);
1413             }
1415             if ($this->get_pref('showlocks')) {
1416                 $lockunlockicon = $this->gtree->get_locking_icon($element, $this->gpr);
1417             }
1418         }
1420         return $OUTPUT->container($editicon.$editcalculationicon.$showhideicon.$lockunlockicon, 'grade_icons');
1421     }
1423     /**
1424      * Given a category element returns collapsing +/- icon if available
1425      * @param object $object
1426      * @return string HTML
1427      */
1428     protected function get_collapsing_icon($element) {
1429         global $OUTPUT;
1431         $icon = '';
1432         // If object is a category, display expand/contract icon
1433         if ($element['type'] == 'category') {
1434             // Load language strings
1435             $strswitchminus = $this->get_lang_string('aggregatesonly', 'grades');
1436             $strswitchplus  = $this->get_lang_string('gradesonly', 'grades');
1437             $strswitchwhole = $this->get_lang_string('fullmode', 'grades');
1439             $url = new moodle_url($this->gpr->get_return_url(null, array('target'=>$element['eid'], 'sesskey'=>sesskey())));
1441             if (in_array($element['object']->id, $this->collapsed['aggregatesonly'])) {
1442                 $url->param('action', 'switch_plus');
1443                 $icon = $OUTPUT->action_icon($url, new pix_icon('t/switch_plus', $strswitchplus));
1445             } else if (in_array($element['object']->id, $this->collapsed['gradesonly'])) {
1446                 $url->param('action', 'switch_whole');
1447                 $icon = $OUTPUT->action_icon($url, new pix_icon('t/switch_whole', $strswitchwhole));
1448                 $contractexpandicon->image->src = $OUTPUT->pix_url('t/switch_whole');
1450             } else {
1451                 $url->param('action', 'switch_minus');
1452                 $icon = $OUTPUT->action_icon($url, new pix_icon('t/switch_minus', $strswitchminus));
1453             }
1454         }
1455         return $icon;
1456     }
1458     /**
1459      * Processes a single action against a category, grade_item or grade.
1460      * @param string $target eid ({type}{id}, e.g. c4 for category4)
1461      * @param string $action Which action to take (edit, delete etc...)
1462      * @return
1463      */
1464     public function process_action($target, $action) {
1465         // TODO: this code should be in some grade_tree static method
1466         $targettype = substr($target, 0, 1);
1467         $targetid = substr($target, 1);
1468         // TODO: end
1470         if ($collapsed = get_user_preferences('grade_report_grader_collapsed_categories')) {
1471             $collapsed = unserialize($collapsed);
1472         } else {
1473             $collapsed = array('aggregatesonly' => array(), 'gradesonly' => array());
1474         }
1476         switch ($action) {
1477             case 'switch_minus': // Add category to array of aggregatesonly
1478                 if (!in_array($targetid, $collapsed['aggregatesonly'])) {
1479                     $collapsed['aggregatesonly'][] = $targetid;
1480                     set_user_preference('grade_report_grader_collapsed_categories', serialize($collapsed));
1481                 }
1482                 break;
1484             case 'switch_plus': // Remove category from array of aggregatesonly, and add it to array of gradesonly
1485                 $key = array_search($targetid, $collapsed['aggregatesonly']);
1486                 if ($key !== false) {
1487                     unset($collapsed['aggregatesonly'][$key]);
1488                 }
1489                 if (!in_array($targetid, $collapsed['gradesonly'])) {
1490                     $collapsed['gradesonly'][] = $targetid;
1491                 }
1492                 set_user_preference('grade_report_grader_collapsed_categories', serialize($collapsed));
1493                 break;
1494             case 'switch_whole': // Remove the category from the array of collapsed cats
1495                 $key = array_search($targetid, $collapsed['gradesonly']);
1496                 if ($key !== false) {
1497                     unset($collapsed['gradesonly'][$key]);
1498                     set_user_preference('grade_report_grader_collapsed_categories', serialize($collapsed));
1499                 }
1501                 break;
1502             default:
1503                 break;
1504         }
1506         return true;
1507     }
1509     /**
1510      * Returns whether or not to display fixed students column.
1511      * Includes a browser check, because IE6 doesn't support the scrollbar.
1512      *
1513      * @return bool
1514      */
1515     public function is_fixed_students() {
1516         global $USER, $CFG;
1517         return empty($USER->screenreader) && $CFG->grade_report_fixedstudents &&
1518             (check_browser_version('MSIE', '7.0') ||
1519              check_browser_version('Firefox', '2.0') ||
1520              check_browser_version('Gecko', '2006010100') ||
1521              check_browser_version('Camino', '1.0') ||
1522              check_browser_version('Opera', '6.0') ||
1523              check_browser_version('Safari', '2.0'));
1524     }
1526     /**
1527      * Refactored function for generating HTML of sorting links with matching arrows.
1528      * Returns an array with 'studentname' and 'idnumber' as keys, with HTML ready
1529      * to inject into a table header cell.
1530      * @return array An associative array of HTML sorting links+arrows
1531      */
1532     public function get_sort_arrows() {
1533         global $OUTPUT;
1534         $arrows = array();
1536         $strsortasc   = $this->get_lang_string('sortasc', 'grades');
1537         $strsortdesc  = $this->get_lang_string('sortdesc', 'grades');
1538         $strfirstname = $this->get_lang_string('firstname');
1539         $strlastname  = $this->get_lang_string('lastname');
1541         $firstlink = html_writer::link(new moodle_url($this->baseurl, array('sortitemid'=>'firstname')), $strfirstname);
1542         $lastlink = html_writer::link(new moodle_url($this->baseurl, array('sortitemid'=>'lastname')), $strlastname);
1543         $idnumberlink = html_writer::link(new moodle_url($this->baseurl, array('sortitemid'=>'idnumber')), get_string('idnumber'));
1545         $arrows['studentname'] = $lastlink;
1547         if ($this->sortitemid === 'lastname') {
1548             if ($this->sortorder == 'ASC') {
1549                 $arrows['studentname'] .= print_arrow('up', $strsortasc, true);
1550             } else {
1551                 $arrows['studentname'] .= print_arrow('down', $strsortdesc, true);
1552             }
1553         }
1555         $arrows['studentname'] .= ' ' . $firstlink;
1557         if ($this->sortitemid === 'firstname') {
1558             if ($this->sortorder == 'ASC') {
1559                 $arrows['studentname'] .= print_arrow('up', $strsortasc, true);
1560             } else {
1561                 $arrows['studentname'] .= print_arrow('down', $strsortdesc, true);
1562             }
1563         }
1565         $arrows['idnumber'] = $idnumberlink;
1567         if ('idnumber' == $this->sortitemid) {
1568             if ($this->sortorder == 'ASC') {
1569                 $arrows['idnumber'] .= print_arrow('up', $strsortasc, true);
1570             } else {
1571                 $arrows['idnumber'] .= print_arrow('down', $strsortdesc, true);
1572             }
1573         }
1575         return $arrows;
1576     }