0446fbe10315bf4875d6f841b2b81de9a002c3ae
[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('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         $toggleicon = new moodle_action_icon();
506         $toggleicon->image->src = $OUTPUT->old_icon_url($imagename);
507         $toggleicon->image->add_class('iconsmall');
508         $toggleicon->alt = $string;
509         $toggleicon->title = $string;
510         $toggleicon->link->url = $this->baseurl->out(false, array('toggle' => $toggleaction, 'toggle_type' => $type), false);
512         $retval = $OUTPUT->container($OUTPUT->action_icon($toggleicon, 'gradertoggle'));
514         return $retval;
515     }
517     /**
518      * Builds and returns the HTML code for the headers.
519      * @return string $headerhtml
520      */
521     public function get_headerhtml() {
522         global $CFG, $USER, $OUTPUT;
524         $this->rowcount = 0;
525         $fixedstudents = $this->is_fixed_students();
527         if (!$fixedstudents) {
528             $strsortasc   = $this->get_lang_string('sortasc', 'grades');
529             $strsortdesc  = $this->get_lang_string('sortdesc', 'grades');
530             $strfirstname = $this->get_lang_string('firstname');
531             $strlastname  = $this->get_lang_string('lastname');
532             $showuseridnumber = $this->get_pref('showuseridnumber');
534             if ($this->sortitemid === 'lastname') {
535                 if ($this->sortorder == 'ASC') {
536                     $lastarrow = print_arrow('up', $strsortasc, true);
537                 } else {
538                     $lastarrow = print_arrow('down', $strsortdesc, true);
539                 }
540             } else {
541                 $lastarrow = '';
542             }
544             if ($this->sortitemid === 'firstname') {
545                 if ($this->sortorder == 'ASC') {
546                     $firstarrow = print_arrow('up', $strsortasc, true);
547                 } else {
548                     $firstarrow = print_arrow('down', $strsortdesc, true);
549                 }
550             } else {
551                 $firstarrow = '';
552             }
554         }
556         // Prepare Table Headers
557         $headerhtml = '';
559         $numrows = count($this->gtree->get_levels());
561         $columnstounset = array();
563         foreach ($this->gtree->get_levels() as $key=>$row) {
564             $columncount = 0;
565             if ($key == 0) {
566                 // do not display course grade category
567                 // continue;
568             }
570             if ($fixedstudents) {
571                 $headerhtml .= '<tr class="heading_name_row">';
572             } else {
573                 $headerhtml .= '<tr class="heading r'.$this->rowcount++.'">';
574                 if ($key == $numrows - 1) {
575                     $sortfirstname = html_link::make(clone($this->baseurl), $strfirstname);
576                     $sortfirstname->url->param('sortitemid', 'firstname');
577                     $sortlastname = html_link::make(clone($this->baseurl), $strlastname);
578                     $sortlastname->url->param('sortitemid', 'lastname');
579                     $headerhtml .= '<th class="header c'.$columncount++.'" scope="col">' . $OUTPUT->link($sortfirstname)
580                             . $firstarrow. '/ ' . $OUTPUT->link($sortlastname) . $lastarrow .'</th>';
581                     if ($showuseridnumber) {
582                         if ('idnumber' == $this->sortitemid) {
583                             if ($this->sortorder == 'ASC') {
584                                 $idnumberarrow = print_arrow('up', $strsortasc, true);
585                             } else {
586                                 $idnumberarrow = print_arrow('down', $strsortdesc, true);
587                             }
588                         } else {
589                             $idnumberarrow = '';
590                         }
591                         $sortidnumber = html_link::make(clone($this->baseurl), get_string('idnumber'));
592                         $sortidnumber->url->param('sortitemid', 'idnumber');
593                         $headerhtml .= '<th class="header cc'.$columncount++.' useridnumber" scope="col">' . $OUTPUT->link($sortidnumber) . $idnumberarrow . '</th>';
594                     }
595                  } else {
596                     $colspan='';
597                     if ($showuseridnumber) {
598                         $colspan = 'colspan="2" ';
599                     }
601                     $headerhtml .= '<td '.$colspan.'class="cell c'.$columncount++.' topleft">&nbsp;</td>';
603                     if ($showuseridnumber) {
604                         $columncount++;
605                     }
606                 }
607             }
610             foreach ($row as $columnkey => $element) {
611                 $sortlink = clone($this->baseurl);
612                 if (isset($element['object']->id)) {
613                     $sortlink->param('sortitemid', $element['object']->id);
614                 }
616                 $eid    = $element['eid'];
617                 $object = $element['object'];
618                 $type   = $element['type'];
619                 $categorystate = @$element['categorystate'];
620                 $itemmodule = null;
621                 $iteminstance = null;
623                 $columnclass = 'c' . $columncount++;
624                 if (!empty($element['colspan'])) {
625                     $colspan = 'colspan="'.$element['colspan'].'"';
626                     $columnclass = '';
627                 } else {
628                     $colspan = '';
629                 }
631                 if (!empty($element['depth'])) {
632                     $catlevel = ' catlevel'.$element['depth'];
633                 } else {
634                     $catlevel = '';
635                 }
637 // Element is a filler
638                 if ($type == 'filler' or $type == 'fillerfirst' or $type == 'fillerlast') {
639                     $headerhtml .= '<th class="'.$columnclass.' '.$type.$catlevel.'" '.$colspan.' scope="col">&nbsp;</th>';
640                 }
641 // Element is a category
642                 else if ($type == 'category') {
643                     $headerhtml .= '<th class=" '. $columnclass.' category'.$catlevel.'" '.$colspan.' scope="col">'
644                                 . shorten_text($element['object']->get_name());
645                     $headerhtml .= $this->get_collapsing_icon($element);
647                     // Print icons
648                     if ($USER->gradeediting[$this->courseid]) {
649                         $headerhtml .= $this->get_icons($element);
650                     }
652                     $headerhtml .= '</th>';
653                 }
654 // Element is a grade_item
655                 else {
656                     $itemmodule = $element['object']->itemmodule;
657                     $iteminstance = $element['object']->iteminstance;
659                     if ($element['object']->id == $this->sortitemid) {
660                         if ($this->sortorder == 'ASC') {
661                             $arrow = $this->get_sort_arrow('up', $sortlink);
662                         } else {
663                             $arrow = $this->get_sort_arrow('down', $sortlink);
664                         }
665                     } else {
666                         $arrow = $this->get_sort_arrow('move', $sortlink);
667                     }
669                     $hidden = '';
670                     if ($element['object']->is_hidden()) {
671                         $hidden = ' hidden ';
672                     }
674                     $headerlink = $this->gtree->get_element_header($element, true, $this->get_pref('showactivityicons'), false);
675                     $headerhtml .= '<th class=" '.$columnclass.' '.$type.$catlevel.$hidden.'" scope="col" onclick="set_col(this.cellIndex)">'
676                                 . shorten_text($headerlink) . $arrow;
677                     $headerhtml .= '</th>';
678                 }
680             }
682             $headerhtml .= '</tr>';
683         }
684         return $headerhtml;
685     }
687     /**
688      * Builds and return the HTML rows of the table (grades headed by student).
689      * @return string HTML
690      */
691     public function get_studentshtml() {
692         global $CFG, $USER, $DB, $OUTPUT;
694         $studentshtml = '';
695         $strfeedback  = $this->get_lang_string("feedback");
696         $strgrade     = $this->get_lang_string('grade');
697         $gradetabindex = 1;
698         $numusers      = count($this->users);
699         $showuserimage = $this->get_pref('showuserimage');
700         $showuseridnumber = $this->get_pref('showuseridnumber');
701         $fixedstudents = $this->is_fixed_students();
703         // Preload scale objects for items with a scaleid
704         $scaleslist = array();
705         $tabindices = array();
707         foreach ($this->gtree->get_items() as $item) {
708             if (!empty($item->scaleid)) {
709                 $scaleslist[] = $item->scaleid;
710             }
712             $tabindices[$item->id]['grade'] = $gradetabindex;
713             $tabindices[$item->id]['feedback'] = $gradetabindex + $numusers;
714             $gradetabindex += $numusers * 2;
715         }
716         $scalesarray = array();
718         if (!empty($scaleslist)) {
719             $scalesarray = $DB->get_records_list('scale', 'id', $scaleslist);
720         }
722         $rowclasses = array(' even ', ' odd ');
724         $rowclasses = array(' even ', ' odd ');
726         foreach ($this->users as $userid => $user) {
728             if ($this->canviewhidden) {
729                 $altered = array();
730                 $unknown = array();
731             } else {
732                 $hidingaffected = grade_grade::get_hiding_affected($this->grades[$userid], $this->gtree->get_items());
733                 $altered = $hidingaffected['altered'];
734                 $unknown = $hidingaffected['unknown'];
735                 unset($hidingaffected);
736             }
738             $columncount = 0;
739             if ($fixedstudents) {
740                 $studentshtml .= '<tr class="r'.$this->rowcount++ . $rowclasses[$this->rowcount % 2] . '">';
741             } else {
742                 // Student name and link
743                 $userpic = null;
744                 if ($showuserimage) {
745                     $userpic = $OUTPUT->container($OUTPUT->user_picture(moodle_user_picture::make($user, $this->courseid)), 'userpic');
746                 }
748                 $userlink = html_link::make(new moodle_url($CFG->wwwroot.'/user/view.php', array('id' => $user->id, 'course' => $this->course->id)), fullname($user));
749                 $studentshtml .= '<tr class="r'.$this->rowcount++ . $rowclasses[$this->rowcount % 2] . '">'
750                               .'<th class="c'.$columncount++.' user" scope="row" onclick="set_row(this.parentNode.rowIndex);">'.$userpic
751                               .$OUTPUT->link($userlink).'</th>';
753                 if ($showuseridnumber) {
754                     $studentshtml .= '<th class="c'.$columncount++.' useridnumber" onclick="set_row(this.parentNode.rowIndex);">'.
755                             $user->idnumber.'</th>';
756                 }
758             }
760             foreach ($this->gtree->items as $itemid=>$unused) {
761                 $item =& $this->gtree->items[$itemid];
762                 $grade = $this->grades[$userid][$item->id];
764                 // Get the decimal points preference for this item
765                 $decimalpoints = $item->get_decimals();
767                 if (in_array($itemid, $unknown)) {
768                     $gradeval = null;
769                 } else if (array_key_exists($itemid, $altered)) {
770                     $gradeval = $altered[$itemid];
771                 } else {
772                     $gradeval = $grade->finalgrade;
773                 }
775                 // MDL-11274
776                 // Hide grades in the grader report if the current grader doesn't have 'moodle/grade:viewhidden'
777                 if (!$this->canviewhidden and $grade->is_hidden()) {
778                     if (!empty($CFG->grade_hiddenasdate) and $grade->get_datesubmitted() and !$item->is_category_item() and !$item->is_course_item()) {
779                         // 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
780                         $studentshtml .= '<td class="cell c'.$columncount++.'">'
781                                 . $OUTPUT->span(userdate($grade->get_datesubmitted(),get_string('strftimedatetimeshort')), 'datesubmitted') . '</td>';
782                     } else {
783                         $studentshtml .= '<td class="cell c'.$columncount++.'">-</td>';
784                     }
785                     continue;
786                 }
788                 // emulate grade element
789                 $eid = $this->gtree->get_grade_eid($grade);
790                 $element = array('eid'=>$eid, 'object'=>$grade, 'type'=>'grade');
792                 $cellclasses = 'grade cell c'.$columncount++;
793                 if ($item->is_category_item()) {
794                     $cellclasses .= ' cat';
795                 }
796                 if ($item->is_course_item()) {
797                     $cellclasses .= ' course';
798                 }
799                 if ($grade->is_overridden()) {
800                     $cellclasses .= ' overridden';
801                 }
803                 if ($grade->is_excluded()) {
804                     // $cellclasses .= ' excluded';
805                 }
807                 $gradetitle = $OUTPUT->container(fullname($user), 'fullname');
808                 $gradetitle .= $OUTPUT->container($item->get_name(true), 'itemname');
810                 if (!empty($grade->feedback) && !$USER->gradeediting[$this->courseid]) {
811                     $gradetitle .= $OUTPUT->container(wordwrap(trim(format_string($grade->feedback, $grade->feedbackformat)), 34, '<br/ >'), 'feedback');
812                 }
814                 $studentshtml .= '<td class="'.$cellclasses.'" title="'.s($gradetitle).'">';
816                 if ($grade->is_excluded()) {
817                     $studentshtml .= $OUTPUT->span(get_string('excluded', 'grades'), 'excludedfloater');
818                 }
820                 // Do not show any icons if no grade (no record in DB to match)
821                 if (!$item->needsupdate and $USER->gradeediting[$this->courseid]) {
822                     $studentshtml .= $this->get_icons($element);
823                 }
825                 $hidden = '';
826                 if ($grade->is_hidden()) {
827                     $hidden = ' hidden ';
828                 }
830                 $gradepass = ' gradefail ';
831                 if ($grade->is_passed($item)) {
832                     $gradepass = ' gradepass ';
833                 } elseif (is_null($grade->is_passed($item))) {
834                     $gradepass = '';
835                 }
837                 // if in editting mode, we need to print either a text box
838                 // or a drop down (for scales)
839                 // grades in item of type grade category or course are not directly editable
840                 if ($item->needsupdate) {
841                     $studentshtml .= $OUTPUT->span(get_string('error'), "gradingerror$hidden");
843                 } else if ($USER->gradeediting[$this->courseid]) {
845                     if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
846                         $scale = $scalesarray[$item->scaleid];
847                         $gradeval = (int)$gradeval; // scales use only integers
848                         $scales = explode(",", $scale->scale);
849                         // reindex because scale is off 1
851                         // MDL-12104 some previous scales might have taken up part of the array
852                         // so this needs to be reset
853                         $scaleopt = array();
854                         $i = 0;
855                         foreach ($scales as $scaleoption) {
856                             $i++;
857                             $scaleopt[$i] = $scaleoption;
858                         }
860                         if ($this->get_pref('quickgrading') and $grade->is_editable()) {
861                             $oldval = empty($gradeval) ? -1 : $gradeval;
862                             if (empty($item->outcomeid)) {
863                                 $nogradestr = $this->get_lang_string('nograde');
864                             } else {
865                                 $nogradestr = $this->get_lang_string('nooutcome', 'grades');
866                             }
867                             $studentshtml .= '<input type="hidden" name="oldgrade_'.$userid.'_'
868                                           .$item->id.'" value="'.$oldval.'"/>';
869                             $select = html_select::make($scaleopt, 'grade_'.$userid.'_'.$item->id,$gradeval, $nogradestr);
870                             $select->nothingvalue = '-1';
871                             $select->tabindex = $tabindices[$item->id]['grade'];
872                             $studentshtml .= $OUTPUT->select($select);
873                         } elseif(!empty($scale)) {
874                             $scales = explode(",", $scale->scale);
876                             // invalid grade if gradeval < 1
877                             if ($gradeval < 1) {
878                                 $studentshtml .= $OUTPUT->span('-', "gradevalue$hidden$gradepass");
879                             } else {
880                                 $gradeval = $grade->grade_item->bounded_grade($gradeval); //just in case somebody changes scale
881                                 $studentshtml .= $OUTPUT->span($scales[$gradeval-1], "gradevalue$hidden$gradepass");
882                             }
883                         } else {
884                             // no such scale, throw error?
885                         }
887                     } else if ($item->gradetype != GRADE_TYPE_TEXT) { // Value type
888                         if ($this->get_pref('quickgrading') and $grade->is_editable()) {
889                             $value = format_float($gradeval, $decimalpoints);
890                             $studentshtml .= '<input type="hidden" name="oldgrade_'.$userid.'_'.$item->id.'" value="'.$value.'" />';
891                             $studentshtml .= '<input size="6" tabindex="' . $tabindices[$item->id]['grade']
892                                           . '" type="text" class="text" title="'. $strgrade .'" name="grade_'
893                                           .$userid.'_' .$item->id.'" value="'.$value.'" />';
894                         } else {
895                             $studentshtml .= $OUTPUT->span(format_float($gradeval, $decimalpoints), "gradevalue$hidden$gradepass");
896                         }
897                     }
900                     // If quickfeedback is on, print an input element
901                     if ($this->get_pref('showquickfeedback') and $grade->is_editable()) {
903                         $studentshtml .= '<input type="hidden" name="oldfeedback_'
904                                       .$userid.'_'.$item->id.'" value="' . s($grade->feedback) . '" />';
905                         $studentshtml .= '<input class="quickfeedback" tabindex="' . $tabindices[$item->id]['feedback']
906                                       . '" size="6" title="' . $strfeedback . '" type="text" name="feedback_'
907                                       .$userid.'_'.$item->id.'" value="' . s($grade->feedback) . '" />';
908                     }
910                 } else { // Not editing
911                     $gradedisplaytype = $item->get_displaytype();
913                     // If feedback present, surround grade with feedback tooltip: Open span here
915                     if ($item->needsupdate) {
916                         $studentshtml .= $OUTPUT->span(get_string('error'), "gradingerror$hidden$gradepass");
917                     } else {
918                         $studentshtml .= $OUTPUT->span(grade_format_gradevalue($gradeval, $item, true, $gradedisplaytype, null), "gradevalue$hidden$gradepass");
919                     }
920                 }
922                 if (!empty($this->gradeserror[$item->id][$userid])) {
923                     $studentshtml .= $this->gradeserror[$item->id][$userid];
924                 }
926                 $studentshtml .=  '</td>' . "\n";
927             }
928             $studentshtml .= '</tr>';
929         }
930         return $studentshtml;
931     }
933     function get_studentnameshtml() {
934         global $CFG, $USER, $OUTPUT;
935         $studentshtml = '';
937         $showuserimage = $this->get_pref('showuserimage');
938         $showuseridnumber = $this->get_pref('showuseridnumber');
939         $fixedstudents = $this->is_fixed_students();
941         $strsortasc   = $this->get_lang_string('sortasc', 'grades');
942         $strsortdesc  = $this->get_lang_string('sortdesc', 'grades');
943         $strfirstname = $this->get_lang_string('firstname');
944         $strlastname  = $this->get_lang_string('lastname');
946         if ($this->sortitemid === 'lastname') {
947             if ($this->sortorder == 'ASC') {
948                 $lastarrow = print_arrow('up', $strsortasc, true);
949             } else {
950                 $lastarrow = print_arrow('down', $strsortdesc, true);
951             }
952         } else {
953             $lastarrow = '';
954         }
956         if ($this->sortitemid === 'firstname') {
957             if ($this->sortorder == 'ASC') {
958                 $firstarrow = print_arrow('up', $strsortasc, true);
959             } else {
960                 $firstarrow = print_arrow('down', $strsortdesc, true);
961             }
962         } else {
963             $firstarrow = '';
964         }
966         if ($fixedstudents) {
967             $fixedcolumntable = new html_table();
968             $fixedcolumntable->id = 'fixed_column';
969             $fixedcolumntable->add_class('fixed_grades_column');
970             $fixedcolumntable->bodyclasses = 'leftbody';
972             $colspan = null;
973             if ($showuseridnumber) {
974                 $colspan = 2;
975             }
977             $levels = count($this->gtree->levels) - 1;
979             for ($i = 0; $i < $levels; $i++) {
980                 $fillercell = new html_table_cell();
981                 $fillercell->add_classes(array('fixedcolumn', 'cell', 'c0', 'topleft'));
982                 $fillercell->text = ' ';
983                 $fillercell->colspan = $colspan;
984                 $fixedcolumntable->data[] = html_table_row::make(array($fillercell));
985             }
987             $sortfirstname = html_link::make(clone($this->baseurl), $strfirstname);
988             $sortfirstname->url->param('sortitemid', 'firstname');
989             $sortlastname = html_link::make(clone($this->baseurl), $strlastname);
990             $sortlastname->url->param('sortitemid', 'lastname');
992             $headerrow = new html_table_row();
993             $headerrow->add_class('heading');
995             $studentheader = new html_table_cell();
996             $studentheader->add_classes(array('header', 'c0'));
997             $studentheader->scope = 'col';
998             $studentheader->header = true;
999             $studentheader->id = 'studentheader';
1000             $studentheader->text = $OUTPUT->link($sortfirstname) . $firstarrow. '/ ' . $OUTPUT->link($sortlastname) . $lastarrow;
1002             $headerrow->cells[] = $studentheader;
1004             if ($showuseridnumber) {
1005                 $sortidnumberlink = html_link::make(clone($this->baseurl), get_string('idnumber'));
1006                 $sortidnumberlink->url->param('sortitemid', 'idnumber');
1008                 $idnumberheader = new html_table_cell();
1009                 $idnumberheader->add_classes(array('header', 'c0', 'useridnumber'));
1010                 $idnumberheader->scope = 'col';
1011                 $idnumberheader->header = true;
1012                 $idnumberheader->text = $OUTPUT->link($sortidnumberlink);
1014                 if ('idnumber' == $this->sortitemid) {
1015                     if ($this->sortorder == 'ASC') {
1016                         $idnumberheader->text .= print_arrow('up', $strsortasc, true);
1017                     } else {
1018                         $idnumberheader->text .= print_arrow('down', $strsortdesc, true);
1019                     }
1020                 }
1021                 $headerrow->cells[] = $idnumberheader;
1022             }
1024             $fixedcolumntable->data[] = $headerrow;
1026             if ($USER->gradeediting[$this->courseid]) {
1027                 $controlsrow = new html_table_row();
1028                 $controlsrow->add_class('controls');
1029                 $controlscell = new html_table_cell();
1030                 $controlscell->add_classes(array('header', 'c0', 'controls'));
1031                 $controlscell->colspan = $colspan;
1032                 $controlscell->text = $this->get_lang_string('controls','grades');
1034                 $controlsrow->cells[] = $controlscell;
1035                 $fixedcolumntable->data[] = $controlsrow;
1036             }
1038             $rowclasses = array('even', 'odd');
1040             foreach ($this->users as $userid => $user) {
1041                 $userrow = new html_table_row();
1042                 $userrow->add_classes(array('r'.$this->rowcount++, $rowclasses[$this->rowcount % 2]));
1044                 $usercell = new html_table_cell();
1045                 $usercell->add_classes(array('c0', 'user'));
1046                 $usercell->header = true;
1047                 $usercell->scope = 'row';
1048                 $usercell->add_action('click', 'yui_set_row');
1050                 if ($showuserimage) {
1051                     $usercell->text = $OUTPUT->container($OUTPUT->user_picture(moodle_user_picture::make($user, $this->courseid)), 'userpic');
1052                 }
1054                 $usercell->text .= $OUTPUT->link(html_link::make(new moodle_url($CFG->wwwroot.'/user/view.php', array('id' => $user->id, 'course' => $this->course->id)), fullname($user)));
1055                 $userrow->cells[] = $usercell;
1057                 if ($showuseridnumber) {
1058                     $idnumbercell = new html_table_cell();
1059                     $idnumbercell->add_classes(array('header', 'c0', 'useridnumber'));
1060                     $idnumbercell->header = true;
1061                     $idnumbercell->scope = 'row';
1062                     $idnumbercell->add_action('click', 'yui_set_row');
1063                     $userrow->cells[] = $idnumbercell;
1064                 }
1065                 $fixedcolumntable->data[] = $userrow;
1066             }
1068             if ($this->get_pref('showranges')) {
1069                 $rangerow = new html_table_row();
1070                 $rangerow->add_classes(array('range', 'r'.$this->rowcount++));
1071                 $rangecell = new html_table_cell();
1072                 $rangecell->add_classes(array('header', 'c0', 'range'));
1073                 $rangecell->colspan = $colspan;
1074                 $rangecell->header = true;
1075                 $rangecell->scope = 'row';
1076                 $rangecell->text = $this->get_lang_string('range','grades');
1077                 $rangerow->cells[] = $rangecell;
1078                 $fixedcolumntable->data[] = $rangerow;
1079             }
1081             // Averages heading
1083             $straveragegroup = get_string('groupavg', 'grades');
1084             $straverage = get_string('overallaverage', 'grades');
1085             $showaverages = $this->get_pref('showaverages');
1086             $showaveragesgroup = $this->currentgroup && $showaverages;
1088             if ($showaveragesgroup) {
1089                 $groupavgrow = new html_table_row();
1090                 $groupavgrow->add_classes(array('groupavg', 'r'.$this->rowcount++));
1091                 $groupavgcell = new html_table_cell();
1092                 $groupavgcell->add_classes(array('header', 'c0', 'range'));
1093                 $groupavgcell->colspan = $colspan;
1094                 $groupavgcell->header = true;
1095                 $groupavgcell->scope = 'row';
1096                 $groupavgcell->text = $straveragegroup;
1097                 $groupavgrow->cells[] = $groupavgcell;
1098                 $fixedcolumntable->data[] = $groupavgrow;
1099             }
1101             if ($showaverages) {
1102                 $avgrow = new html_table_row();
1103                 $avgrow->add_classes(array('avg', 'r'.$this->rowcount++));
1104                 $avgcell = new html_table_cell();
1105                 $avgcell->add_classes(array('header', 'c0', 'range'));
1106                 $avgcell->colspan = $colspan;
1107                 $avgcell->header = true;
1108                 $avgcell->scope = 'row';
1109                 $avgcell->text = $straverage;
1110                 $avgrow->cells[] = $avgcell;
1111                 $fixedcolumntable->data[] = $avgrow;
1112             }
1114             $studentshtml .= $OUTPUT->container($OUTPUT->table($fixedcolumntable), 'left_scroller');
1115             $studentshtml .= '
1116             <div class="right_scroller">
1117                 <table id="user-grades" class="">
1118                     <tbody class="righttest">';
1120         } else {
1121             $studentshtml .= '<table id="user-grades" class="gradestable flexible boxaligncenter generaltable">
1122                                 <tbody>';
1123         }
1125         return $studentshtml;
1126     }
1128     /**
1129      * Closes all open elements
1130      */
1131     public function get_endhtml() {
1132         global $CFG, $USER;
1134         $fixedstudents = $this->is_fixed_students();
1136         if ($fixedstudents) {
1137             return "</tbody></table></div>";
1138         } else {
1139             return "</tbody></table>";
1140         }
1141     }
1143     /**
1144      * Builds and return the HTML row of column totals.
1145      * @param  bool $grouponly Whether to return only group averages or all averages.
1146      * @return string HTML
1147      */
1148     public function get_avghtml($grouponly=false) {
1149         global $CFG, $USER, $DB;
1151         if (!$this->canviewhidden) {
1152             // totals might be affected by hiding, if user can not see hidden grades the aggregations might be altered
1153             // better not show them at all if user can not see all hideen grades
1154             return;
1155         }
1157         $averagesdisplaytype   = $this->get_pref('averagesdisplaytype');
1158         $averagesdecimalpoints = $this->get_pref('averagesdecimalpoints');
1159         $meanselection         = $this->get_pref('meanselection');
1160         $shownumberofgrades    = $this->get_pref('shownumberofgrades');
1162         $avghtml = '';
1163         $avgcssclass = 'avg';
1165         if ($grouponly) {
1166             $straverage = get_string('groupavg', 'grades');
1167             $showaverages = $this->currentgroup && $this->get_pref('showaverages');
1168             $groupsql = $this->groupsql;
1169             $groupwheresql = $this->groupwheresql;
1170             $groupwheresqlparams = $this->groupwheresql_params;
1171             $avgcssclass = 'groupavg';
1172         } else {
1173             $straverage = get_string('overallaverage', 'grades');
1174             $showaverages = $this->get_pref('showaverages');
1175             $groupsql = "";
1176             $groupwheresql = "";
1177             $groupwheresqlparams = array();
1178         }
1180         if ($shownumberofgrades) {
1181             $straverage .= ' (' . get_string('submissions', 'grades') . ') ';
1182         }
1184         $totalcount = $this->get_numusers($grouponly);
1186         list($usql, $rolesparams) = $DB->get_in_or_equal(explode(',', $this->gradebookroles), SQL_PARAMS_NAMED, 'grbr0');
1188         if ($showaverages) {
1189             $params = array_merge(array('courseid'=>$this->courseid), $rolesparams, $groupwheresqlparams);
1191             // find sums of all grade items in course
1192             $SQL = "SELECT g.itemid, SUM(g.finalgrade) AS sum
1193                       FROM {grade_items} gi
1194                            JOIN {grade_grades} g      ON g.itemid = gi.id
1195                            JOIN {user} u              ON u.id = g.userid
1196                            JOIN {role_assignments} ra ON ra.userid = u.id
1197                            $groupsql
1198                      WHERE gi.courseid = :courseid
1199                            AND ra.roleid $usql
1200                            AND ra.contextid ".get_related_contexts_string($this->context)."
1201                            AND g.finalgrade IS NOT NULL
1202                            $groupwheresql
1203                   GROUP BY g.itemid";
1204             $sumarray = array();
1205             if ($sums = $DB->get_records_sql($SQL, $params)) {
1206                 foreach ($sums as $itemid => $csum) {
1207                     $sumarray[$itemid] = $csum->sum;
1208                 }
1209             }
1211             $columncount=0;
1212             $avghtml = '<tr class="' . $avgcssclass . ' r'.$this->rowcount++.'">';
1214             // MDL-10875 Empty grades must be evaluated as grademin, NOT always 0
1215             // This query returns a count of ungraded grades (NULL finalgrade OR no matching record in grade_grades table)
1216             $params = array_merge(array('courseid'=>$this->courseid), $rolesparams, $groupwheresqlparams);
1217             $SQL = "SELECT gi.id, COUNT(u.id) AS count
1218                       FROM {grade_items} gi
1219                            CROSS JOIN {user} u
1220                            JOIN {role_assignments} ra        ON ra.userid = u.id
1221                            LEFT OUTER JOIN  {grade_grades} g ON (g.itemid = gi.id AND g.userid = u.id AND g.finalgrade IS NOT NULL)
1222                            $groupsql
1223                      WHERE gi.courseid = :courseid
1224                            AND ra.roleid $usql
1225                            AND ra.contextid ".get_related_contexts_string($this->context)."
1226                            AND g.id IS NULL
1227                            $groupwheresql
1228                   GROUP BY gi.id";
1230             $ungradedcounts = $DB->get_records_sql($SQL, $params);
1232             $fixedstudents = $this->is_fixed_students();
1233             if (!$fixedstudents) {
1234                 $colspan='';
1235                 if ($this->get_pref('showuseridnumber')) {
1236                     $colspan = 'colspan="2" ';
1237                 }
1238                 $avghtml .= '<th class="header c0 range" '.$colspan.' scope="row">'.$straverage.'</th>';
1239             }
1241             foreach ($this->gtree->items as $itemid=>$unused) {
1242                 $item =& $this->gtree->items[$itemid];
1244                 if ($item->needsupdate) {
1245                     $avghtml .= '<td class="cell c' . $columncount++.'"><span class="gradingerror">'.get_string('error').'</span></td>';
1246                     continue;
1247                 }
1249                 if (!isset($sumarray[$item->id])) {
1250                     $sumarray[$item->id] = 0;
1251                 }
1253                 if (empty($ungradedcounts[$itemid])) {
1254                     $ungradedcount = 0;
1255                 } else {
1256                     $ungradedcount = $ungradedcounts[$itemid]->count;
1257                 }
1259                 if ($meanselection == GRADE_REPORT_MEAN_GRADED) {
1260                     $meancount = $totalcount - $ungradedcount;
1261                 } else { // Bump up the sum by the number of ungraded items * grademin
1262                     $sumarray[$item->id] += $ungradedcount * $item->grademin;
1263                     $meancount = $totalcount;
1264                 }
1266                 $decimalpoints = $item->get_decimals();
1268                 // Determine which display type to use for this average
1269                 if ($USER->gradeediting[$this->courseid]) {
1270                     $displaytype = GRADE_DISPLAY_TYPE_REAL;
1272                 } else if ($averagesdisplaytype == GRADE_REPORT_PREFERENCE_INHERIT) { // no ==0 here, please resave the report and user preferences
1273                     $displaytype = $item->get_displaytype();
1275                 } else {
1276                     $displaytype = $averagesdisplaytype;
1277                 }
1279                 // Override grade_item setting if a display preference (not inherit) was set for the averages
1280                 if ($averagesdecimalpoints == GRADE_REPORT_PREFERENCE_INHERIT) {
1281                     $decimalpoints = $item->get_decimals();
1283                 } else {
1284                     $decimalpoints = $averagesdecimalpoints;
1285                 }
1287                 if (!isset($sumarray[$item->id]) || $meancount == 0) {
1288                     $avghtml .= '<td class="cell c' . $columncount++.'">-</td>';
1289                 } else {
1290                     $sum = $sumarray[$item->id];
1291                     $avgradeval = $sum/$meancount;
1292                     $gradehtml = grade_format_gradevalue($avgradeval, $item, true, $displaytype, $decimalpoints);
1294                     $numberofgrades = '';
1295                     if ($shownumberofgrades) {
1296                         $numberofgrades = " ($meancount)";
1297                     }
1299                     $avghtml .= '<td class="cell c' . $columncount++.'">'.$gradehtml.$numberofgrades.'</td>';
1300                 }
1301             }
1302             $avghtml .= '</tr>';
1303         }
1304         return $avghtml;
1305     }
1307     /**
1308      * Builds and return the HTML row of ranges for each column (i.e. range).
1309      * @return string HTML
1310      */
1311     public function get_rangehtml() {
1312         global $CFG, $USER;
1314         $rangehtml = '';
1315         if ($this->get_pref('showranges')) {
1316             $rangesdisplaytype   = $this->get_pref('rangesdisplaytype');
1317             $rangesdecimalpoints = $this->get_pref('rangesdecimalpoints');
1319             $columncount=0;
1320             $rangehtml = '<tr class="range r'.$this->rowcount++.' heading">';
1322             $fixedstudents = $this->is_fixed_students();
1323             if (!$fixedstudents) {
1324                 $colspan='';
1325                 if ($this->get_pref('showuseridnumber')) {
1326                     $colspan = 'colspan="2" ';
1327                 }
1328                 $rangehtml .= '<th class="header c0 range" '.$colspan.' scope="row">'.$this->get_lang_string('range','grades').'</th>';
1329             }
1331             foreach ($this->gtree->items as $itemid=>$unused) {
1332                 $item =& $this->gtree->items[$itemid];
1335                 $hidden = '';
1336                 if ($item->is_hidden()) {
1337                     $hidden = ' hidden ';
1338                 }
1340                 $formattedrange = $item->get_formatted_range($rangesdisplaytype, $rangesdecimalpoints);
1342                 $rangehtml .= '<th class="header c'.$columncount++.' range"><span class="rangevalues'.$hidden.'">'. $formattedrange .'</span></th>';
1344             }
1345             $rangehtml .= '</tr>';
1346         }
1347         return $rangehtml;
1348     }
1350     /**
1351      * Builds and return the HTML row of ranges for each column (i.e. range).
1352      * @return string HTML
1353      */
1354     public function get_iconshtml() {
1355         global $USER, $CFG;
1357         $iconshtml = '';
1358         if ($USER->gradeediting[$this->courseid]) {
1360             $iconshtml = '<tr class="controls">';
1362             $fixedstudents = $this->is_fixed_students();
1363             $showuseridnumber = $this->get_pref('showuseridnumber');
1365             $colspan = '';
1366             if ($showuseridnumber) {
1367                 $colspan = 'colspan="2"';
1368             }
1370             if (!$fixedstudents) {
1371                 $iconshtml .= '<th class="header c0 controls" scope="row" '.$colspan.'>'.$this->get_lang_string('controls','grades').'</th>';
1372             }
1374             $columncount = 0;
1375             foreach ($this->gtree->items as $itemid=>$unused) {
1376                 // emulate grade element
1377                 $item =& $this->gtree->get_item($itemid);
1379                 $eid = $this->gtree->get_item_eid($item);
1380                 $element = $this->gtree->locate_element($eid);
1382                 $iconshtml .= '<td class="controls cell c'.$columncount++.' icons">' . $this->get_icons($element) . '</td>';
1383             }
1384             $iconshtml .= '</tr>';
1385         }
1386         return $iconshtml;
1387     }
1389     /**
1390      * Given a grade_category, grade_item or grade_grade, this function
1391      * figures out the state of the object and builds then returns a div
1392      * with the icons needed for the grader report.
1393      *
1394      * @param object $object
1395      * @return string HTML
1396      */
1397     protected function get_icons($element) {
1398         global $CFG, $USER, $OUTPUT;
1400         if (!$USER->gradeediting[$this->courseid]) {
1401             return '<div class="grade_icons" />';
1402         }
1404         // Init all icons
1405         $editicon = '';
1407         if ($element['type'] != 'categoryitem' && $element['type'] != 'courseitem') {
1408             $editicon = $this->gtree->get_edit_icon($element, $this->gpr);
1409         }
1411         $editcalculationicon = '';
1412         $showhideicon        = '';
1413         $lockunlockicon      = '';
1415         if (has_capability('moodle/grade:manage', $this->context)) {
1417             if ($this->get_pref('showcalculations')) {
1418                 $editcalculationicon = $this->gtree->get_calculation_icon($element, $this->gpr);
1419             }
1421             if ($this->get_pref('showeyecons')) {
1422                $showhideicon = $this->gtree->get_hiding_icon($element, $this->gpr);
1423             }
1425             if ($this->get_pref('showlocks')) {
1426                 $lockunlockicon = $this->gtree->get_locking_icon($element, $this->gpr);
1427             }
1428         }
1430         return $OUTPUT->container($editicon.$editcalculationicon.$showhideicon.$lockunlockicon, 'grade_icons');
1431     }
1433     /**
1434      * Given a category element returns collapsing +/- icon if available
1435      * @param object $object
1436      * @return string HTML
1437      */
1438     protected function get_collapsing_icon($element) {
1439         global $OUTPUT;
1441         $icon = '';
1442         // If object is a category, display expand/contract icon
1443         if ($element['type'] == 'category') {
1444             // Load language strings
1445             $strswitchminus = $this->get_lang_string('aggregatesonly', 'grades');
1446             $strswitchplus  = $this->get_lang_string('gradesonly', 'grades');
1447             $strswitchwhole = $this->get_lang_string('fullmode', 'grades');
1449             $contractexpandicon = new moodle_action_icon();
1450             $contractexpandicon->link->url = new moodle_url($this->gpr->get_return_url(null, array('target'=>$element['eid'], 'action'=>'switch_minus', 'sesskey'=>sesskey())));
1451             $contractexpandicon->image->add_class('iconsmall');
1452             $contractexpandicon->image->src = $OUTPUT->old_icon_url('t/switch_minus');
1453             $contractexpandicon->image->alt = $strswitchminus;
1455             if (in_array($element['object']->id, $this->collapsed['aggregatesonly'])) {
1456                 $contractexpandicon->image->src = $OUTPUT->old_icon_url('t/switch_plus');
1457                 $contractexpandicon->image->alt = $strswitchplus;
1458                 $contractexpandicon->link->url->param('action', 'switch_plus');
1459             } elseif (in_array($element['object']->id, $this->collapsed['gradesonly'])) {
1460                 $contractexpandicon->image->src = $OUTPUT->old_icon_url('t/switch_whole');
1461                 $contractexpandicon->image->alt = $strswitchwhole;
1462                 $contractexpandicon->link->url->param('action', 'switch_whole');
1463             }
1464             $icon = $OUTPUT->action_icon($contractexpandicon);
1465         }
1466         return $icon;
1467     }
1469     /**
1470      * Processes a single action against a category, grade_item or grade.
1471      * @param string $target eid ({type}{id}, e.g. c4 for category4)
1472      * @param string $action Which action to take (edit, delete etc...)
1473      * @return
1474      */
1475     public function process_action($target, $action) {
1476         // TODO: this code should be in some grade_tree static method
1477         $targettype = substr($target, 0, 1);
1478         $targetid = substr($target, 1);
1479         // TODO: end
1481         if ($collapsed = get_user_preferences('grade_report_grader_collapsed_categories')) {
1482             $collapsed = unserialize($collapsed);
1483         } else {
1484             $collapsed = array('aggregatesonly' => array(), 'gradesonly' => array());
1485         }
1487         switch ($action) {
1488             case 'switch_minus': // Add category to array of aggregatesonly
1489                 if (!in_array($targetid, $collapsed['aggregatesonly'])) {
1490                     $collapsed['aggregatesonly'][] = $targetid;
1491                     set_user_preference('grade_report_grader_collapsed_categories', serialize($collapsed));
1492                 }
1493                 break;
1495             case 'switch_plus': // Remove category from array of aggregatesonly, and add it to array of gradesonly
1496                 $key = array_search($targetid, $collapsed['aggregatesonly']);
1497                 if ($key !== false) {
1498                     unset($collapsed['aggregatesonly'][$key]);
1499                 }
1500                 if (!in_array($targetid, $collapsed['gradesonly'])) {
1501                     $collapsed['gradesonly'][] = $targetid;
1502                 }
1503                 set_user_preference('grade_report_grader_collapsed_categories', serialize($collapsed));
1504                 break;
1505             case 'switch_whole': // Remove the category from the array of collapsed cats
1506                 $key = array_search($targetid, $collapsed['gradesonly']);
1507                 if ($key !== false) {
1508                     unset($collapsed['gradesonly'][$key]);
1509                     set_user_preference('grade_report_grader_collapsed_categories', serialize($collapsed));
1510                 }
1512                 break;
1513             default:
1514                 break;
1515         }
1517         return true;
1518     }
1520     /**
1521      * Returns whether or not to display fixed students column.
1522      * Includes a browser check, because IE6 doesn't support the scrollbar.
1523      *
1524      * @return bool
1525      */
1526     public function is_fixed_students() {
1527         global $USER, $CFG;
1528         return empty($USER->screenreader) && $CFG->grade_report_fixedstudents &&
1529             (check_browser_version('MSIE', '7.0') ||
1530              check_browser_version('Firefox', '2.0') ||
1531              check_browser_version('Gecko', '2006010100') ||
1532              check_browser_version('Camino', '1.0') ||
1533              check_browser_version('Opera', '6.0') ||
1534              check_browser_version('Safari', '2.0'));
1535     }
1537 ?>