MDL-12972 Added icons next to each student name in the grader report, which link...
[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                     $colspan = 1;
576                     if (has_capability('gradereport/user:view', $this->context)) {
577                         $colspan++;
578                     }
579                     $colspan='colspan="'.$colspan.'"';
581                     $sortfirstname = html_link::make(clone($this->baseurl), $strfirstname);
582                     $sortfirstname->url->param('sortitemid', 'firstname');
583                     $sortlastname = html_link::make(clone($this->baseurl), $strlastname);
584                     $sortlastname->url->param('sortitemid', 'lastname');
585                     $headerhtml .= '<th '.$colspan.' class="header c'.$columncount++.'" scope="col">' . $OUTPUT->link($sortfirstname)
586                             . $firstarrow. '/ ' . $OUTPUT->link($sortlastname) . $lastarrow .'</th>';
587                     if ($showuseridnumber) {
588                         if ('idnumber' == $this->sortitemid) {
589                             if ($this->sortorder == 'ASC') {
590                                 $idnumberarrow = print_arrow('up', $strsortasc, true);
591                             } else {
592                                 $idnumberarrow = print_arrow('down', $strsortdesc, true);
593                             }
594                         } else {
595                             $idnumberarrow = '';
596                         }
597                         $sortidnumber = html_link::make(clone($this->baseurl), get_string('idnumber'));
598                         $sortidnumber->url->param('sortitemid', 'idnumber');
599                         $headerhtml .= '<th class="header cc'.$columncount++.' useridnumber" scope="col">' . $OUTPUT->link($sortidnumber) . $idnumberarrow . '</th>';
600                     }
601                 } else {
602                     $colspan = 1;
603                     if (has_capability('gradereport/user:view', $this->context)) {
604                         $colspan++;
605                     }
606                     if ($showuseridnumber) {
607                         $colspan++;
608                     }
610                     $colspan='colspan="'.$colspan.'"';
612                     $headerhtml .= '<td '.$colspan.'class="cell c'.$columncount++.' topleft">&nbsp;</td>';
614                     if ($showuseridnumber) {
615                         $columncount++;
616                     }
617                 }
618             }
621             foreach ($row as $columnkey => $element) {
622                 $sortlink = clone($this->baseurl);
623                 if (isset($element['object']->id)) {
624                     $sortlink->param('sortitemid', $element['object']->id);
625                 }
627                 $eid    = $element['eid'];
628                 $object = $element['object'];
629                 $type   = $element['type'];
630                 $categorystate = @$element['categorystate'];
631                 $itemmodule = null;
632                 $iteminstance = null;
634                 $columnclass = 'c' . $columncount++;
635                 if (!empty($element['colspan'])) {
636                     $colspan = 'colspan="'.$element['colspan'].'"';
637                     $columnclass = '';
638                 } else {
639                     $colspan = '';
640                 }
642                 if (!empty($element['depth'])) {
643                     $catlevel = ' catlevel'.$element['depth'];
644                 } else {
645                     $catlevel = '';
646                 }
648 // Element is a filler
649                 if ($type == 'filler' or $type == 'fillerfirst' or $type == 'fillerlast') {
650                     $headerhtml .= '<th class="'.$columnclass.' '.$type.$catlevel.'" '.$colspan.' scope="col">&nbsp;</th>';
651                 }
652 // Element is a category
653                 else if ($type == 'category') {
654                     $headerhtml .= '<th class=" '. $columnclass.' category'.$catlevel.'" '.$colspan.' scope="col">'
655                                 . shorten_text($element['object']->get_name());
656                     $headerhtml .= $this->get_collapsing_icon($element);
658                     // Print icons
659                     if ($USER->gradeediting[$this->courseid]) {
660                         $headerhtml .= $this->get_icons($element);
661                     }
663                     $headerhtml .= '</th>';
664                 }
665 // Element is a grade_item
666                 else {
667                     $itemmodule = $element['object']->itemmodule;
668                     $iteminstance = $element['object']->iteminstance;
670                     if ($element['object']->id == $this->sortitemid) {
671                         if ($this->sortorder == 'ASC') {
672                             $arrow = $this->get_sort_arrow('up', $sortlink);
673                         } else {
674                             $arrow = $this->get_sort_arrow('down', $sortlink);
675                         }
676                     } else {
677                         $arrow = $this->get_sort_arrow('move', $sortlink);
678                     }
680                     $hidden = '';
681                     if ($element['object']->is_hidden()) {
682                         $hidden = ' hidden ';
683                     }
685                     $headerlink = $this->gtree->get_element_header($element, true, $this->get_pref('showactivityicons'), false);
686                     $headerhtml .= '<th class=" '.$columnclass.' '.$type.$catlevel.$hidden.'" scope="col" onclick="set_col(this.cellIndex)">'
687                                 . shorten_text($headerlink) . $arrow;
688                     $headerhtml .= '</th>';
689                 }
691             }
693             $headerhtml .= '</tr>';
694         }
695         return $headerhtml;
696     }
698     /**
699      * Builds and return the HTML rows of the table (grades headed by student).
700      * @return string HTML
701      */
702     public function get_studentshtml() {
703         global $CFG, $USER, $DB, $OUTPUT;
705         $studentshtml = '';
706         $strfeedback  = $this->get_lang_string("feedback");
707         $strgrade     = $this->get_lang_string('grade');
708         $gradetabindex = 1;
709         $numusers      = count($this->users);
710         $showuserimage = $this->get_pref('showuserimage');
711         $showuseridnumber = $this->get_pref('showuseridnumber');
712         $fixedstudents = $this->is_fixed_students();
714         // Preload scale objects for items with a scaleid
715         $scaleslist = array();
716         $tabindices = array();
718         foreach ($this->gtree->get_items() as $item) {
719             if (!empty($item->scaleid)) {
720                 $scaleslist[] = $item->scaleid;
721             }
723             $tabindices[$item->id]['grade'] = $gradetabindex;
724             $tabindices[$item->id]['feedback'] = $gradetabindex + $numusers;
725             $gradetabindex += $numusers * 2;
726         }
727         $scalesarray = array();
729         if (!empty($scaleslist)) {
730             $scalesarray = $DB->get_records_list('scale', 'id', $scaleslist);
731         }
733         $rowclasses = array(' even ', ' odd ');
735         $rowclasses = array(' even ', ' odd ');
737         foreach ($this->users as $userid => $user) {
739             if ($this->canviewhidden) {
740                 $altered = array();
741                 $unknown = array();
742             } else {
743                 $hidingaffected = grade_grade::get_hiding_affected($this->grades[$userid], $this->gtree->get_items());
744                 $altered = $hidingaffected['altered'];
745                 $unknown = $hidingaffected['unknown'];
746                 unset($hidingaffected);
747             }
749             $columncount = 0;
750             if ($fixedstudents) {
751                 $studentshtml .= '<tr class="r'.$this->rowcount++ . $rowclasses[$this->rowcount % 2] . '">';
752             } else {
753                 // Student name and link
754                 $userpic = null;
755                 if ($showuserimage) {
756                     $userpic = $OUTPUT->container($OUTPUT->user_picture(moodle_user_picture::make($user, $this->courseid)), 'userpic');
757                 }
759                 $userreportcell = '';
761                 if (has_capability('gradereport/user:view', $this->context)) {
762                     $a->user = fullname($user);
763                     $strgradesforuser = get_string('gradesforuser', 'grades', $a);
764                     $userreporticon = new moodle_action_icon();
765                     $userreporticon->link->url = new moodle_url($CFG->wwwroot.'/grade/report/user/index.php', array('userid' => $user->id, 'id' => $this->course->id));
766                     $userreporticon->image->add_class('iconsmall');
767                     $userreporticon->image->src = $OUTPUT->old_icon_url('t/grades');
768                     $userreporticon->image->alt = $strgradesforuser;
769                     $userreportcell = '<th class="userreport">'.$OUTPUT->action_icon($userreporticon).'</th>';
770                 }
772                 $userlink = html_link::make(new moodle_url($CFG->wwwroot.'/user/view.php', array('id' => $user->id, 'course' => $this->course->id)), fullname($user));
773                 $studentshtml .= '<tr class="r'.$this->rowcount++ . $rowclasses[$this->rowcount % 2] . '">'
774                               .'<th class="c'.$columncount++.' user" scope="row" onclick="set_row(this.parentNode.rowIndex);">'.$userpic
775                               .$OUTPUT->link($userlink).$userreportcell.'</th>';
777                 if ($showuseridnumber) {
778                     $studentshtml .= '<th class="c'.$columncount++.' useridnumber" onclick="set_row(this.parentNode.rowIndex);">'.
779                             $user->idnumber.'</th>';
780                 }
782             }
784             foreach ($this->gtree->items as $itemid=>$unused) {
785                 $item =& $this->gtree->items[$itemid];
786                 $grade = $this->grades[$userid][$item->id];
788                 // Get the decimal points preference for this item
789                 $decimalpoints = $item->get_decimals();
791                 if (in_array($itemid, $unknown)) {
792                     $gradeval = null;
793                 } else if (array_key_exists($itemid, $altered)) {
794                     $gradeval = $altered[$itemid];
795                 } else {
796                     $gradeval = $grade->finalgrade;
797                 }
799                 // MDL-11274
800                 // Hide grades in the grader report if the current grader doesn't have 'moodle/grade:viewhidden'
801                 if (!$this->canviewhidden and $grade->is_hidden()) {
802                     if (!empty($CFG->grade_hiddenasdate) and $grade->get_datesubmitted() and !$item->is_category_item() and !$item->is_course_item()) {
803                         // 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
804                         $studentshtml .= '<td class="cell c'.$columncount++.'">'
805                                 . $OUTPUT->span(userdate($grade->get_datesubmitted(),get_string('strftimedatetimeshort')), 'datesubmitted') . '</td>';
806                     } else {
807                         $studentshtml .= '<td class="cell c'.$columncount++.'">-</td>';
808                     }
809                     continue;
810                 }
812                 // emulate grade element
813                 $eid = $this->gtree->get_grade_eid($grade);
814                 $element = array('eid'=>$eid, 'object'=>$grade, 'type'=>'grade');
816                 $cellclasses = 'grade cell c'.$columncount++;
817                 if ($item->is_category_item()) {
818                     $cellclasses .= ' cat';
819                 }
820                 if ($item->is_course_item()) {
821                     $cellclasses .= ' course';
822                 }
823                 if ($grade->is_overridden()) {
824                     $cellclasses .= ' overridden';
825                 }
827                 if ($grade->is_excluded()) {
828                     // $cellclasses .= ' excluded';
829                 }
831                 $gradetitle = $OUTPUT->container(fullname($user), 'fullname');
832                 $gradetitle .= $OUTPUT->container($item->get_name(true), 'itemname');
834                 if (!empty($grade->feedback) && !$USER->gradeediting[$this->courseid]) {
835                     $gradetitle .= $OUTPUT->container(wordwrap(trim(format_string($grade->feedback, $grade->feedbackformat)), 34, '<br/ >'), 'feedback');
836                 }
838                 $studentshtml .= '<td class="'.$cellclasses.'" title="'.s($gradetitle).'">';
840                 if ($grade->is_excluded()) {
841                     $studentshtml .= $OUTPUT->span(get_string('excluded', 'grades'), 'excludedfloater');
842                 }
844                 // Do not show any icons if no grade (no record in DB to match)
845                 if (!$item->needsupdate and $USER->gradeediting[$this->courseid]) {
846                     $studentshtml .= $this->get_icons($element);
847                 }
849                 $hidden = '';
850                 if ($grade->is_hidden()) {
851                     $hidden = ' hidden ';
852                 }
854                 $gradepass = ' gradefail ';
855                 if ($grade->is_passed($item)) {
856                     $gradepass = ' gradepass ';
857                 } elseif (is_null($grade->is_passed($item))) {
858                     $gradepass = '';
859                 }
861                 // if in editting mode, we need to print either a text box
862                 // or a drop down (for scales)
863                 // grades in item of type grade category or course are not directly editable
864                 if ($item->needsupdate) {
865                     $studentshtml .= $OUTPUT->span(get_string('error'), "gradingerror$hidden");
867                 } else if ($USER->gradeediting[$this->courseid]) {
869                     if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
870                         $scale = $scalesarray[$item->scaleid];
871                         $gradeval = (int)$gradeval; // scales use only integers
872                         $scales = explode(",", $scale->scale);
873                         // reindex because scale is off 1
875                         // MDL-12104 some previous scales might have taken up part of the array
876                         // so this needs to be reset
877                         $scaleopt = array();
878                         $i = 0;
879                         foreach ($scales as $scaleoption) {
880                             $i++;
881                             $scaleopt[$i] = $scaleoption;
882                         }
884                         if ($this->get_pref('quickgrading') and $grade->is_editable()) {
885                             $oldval = empty($gradeval) ? -1 : $gradeval;
886                             if (empty($item->outcomeid)) {
887                                 $nogradestr = $this->get_lang_string('nograde');
888                             } else {
889                                 $nogradestr = $this->get_lang_string('nooutcome', 'grades');
890                             }
891                             $studentshtml .= '<input type="hidden" name="oldgrade_'.$userid.'_'
892                                           .$item->id.'" value="'.$oldval.'"/>';
893                             $select = html_select::make($scaleopt, 'grade_'.$userid.'_'.$item->id,$gradeval, $nogradestr);
894                             $select->nothingvalue = '-1';
895                             $select->tabindex = $tabindices[$item->id]['grade'];
896                             $studentshtml .= $OUTPUT->select($select);
897                         } elseif(!empty($scale)) {
898                             $scales = explode(",", $scale->scale);
900                             // invalid grade if gradeval < 1
901                             if ($gradeval < 1) {
902                                 $studentshtml .= $OUTPUT->span('-', "gradevalue$hidden$gradepass");
903                             } else {
904                                 $gradeval = $grade->grade_item->bounded_grade($gradeval); //just in case somebody changes scale
905                                 $studentshtml .= $OUTPUT->span($scales[$gradeval-1], "gradevalue$hidden$gradepass");
906                             }
907                         } else {
908                             // no such scale, throw error?
909                         }
911                     } else if ($item->gradetype != GRADE_TYPE_TEXT) { // Value type
912                         if ($this->get_pref('quickgrading') and $grade->is_editable()) {
913                             $value = format_float($gradeval, $decimalpoints);
914                             $studentshtml .= '<input type="hidden" name="oldgrade_'.$userid.'_'.$item->id.'" value="'.$value.'" />';
915                             $studentshtml .= '<input size="6" tabindex="' . $tabindices[$item->id]['grade']
916                                           . '" type="text" class="text" title="'. $strgrade .'" name="grade_'
917                                           .$userid.'_' .$item->id.'" value="'.$value.'" />';
918                         } else {
919                             $studentshtml .= $OUTPUT->span(format_float($gradeval, $decimalpoints), "gradevalue$hidden$gradepass");
920                         }
921                     }
924                     // If quickfeedback is on, print an input element
925                     if ($this->get_pref('showquickfeedback') and $grade->is_editable()) {
927                         $studentshtml .= '<input type="hidden" name="oldfeedback_'
928                                       .$userid.'_'.$item->id.'" value="' . s($grade->feedback) . '" />';
929                         $studentshtml .= '<input class="quickfeedback" tabindex="' . $tabindices[$item->id]['feedback']
930                                       . '" size="6" title="' . $strfeedback . '" type="text" name="feedback_'
931                                       .$userid.'_'.$item->id.'" value="' . s($grade->feedback) . '" />';
932                     }
934                 } else { // Not editing
935                     $gradedisplaytype = $item->get_displaytype();
937                     // If feedback present, surround grade with feedback tooltip: Open span here
939                     if ($item->needsupdate) {
940                         $studentshtml .= $OUTPUT->span(get_string('error'), "gradingerror$hidden$gradepass");
941                     } else {
942                         $studentshtml .= $OUTPUT->span(grade_format_gradevalue($gradeval, $item, true, $gradedisplaytype, null), "gradevalue$hidden$gradepass");
943                     }
944                 }
946                 if (!empty($this->gradeserror[$item->id][$userid])) {
947                     $studentshtml .= $this->gradeserror[$item->id][$userid];
948                 }
950                 $studentshtml .=  '</td>' . "\n";
951             }
952             $studentshtml .= '</tr>';
953         }
954         return $studentshtml;
955     }
957     function get_studentnameshtml() {
958         global $CFG, $USER, $OUTPUT;
959         $studentshtml = '';
961         $showuserimage = $this->get_pref('showuserimage');
962         $showuseridnumber = $this->get_pref('showuseridnumber');
963         $fixedstudents = $this->is_fixed_students();
965         $strsortasc   = $this->get_lang_string('sortasc', 'grades');
966         $strsortdesc  = $this->get_lang_string('sortdesc', 'grades');
967         $strfirstname = $this->get_lang_string('firstname');
968         $strlastname  = $this->get_lang_string('lastname');
970         if ($this->sortitemid === 'lastname') {
971             if ($this->sortorder == 'ASC') {
972                 $lastarrow = print_arrow('up', $strsortasc, true);
973             } else {
974                 $lastarrow = print_arrow('down', $strsortdesc, true);
975             }
976         } else {
977             $lastarrow = '';
978         }
980         if ($this->sortitemid === 'firstname') {
981             if ($this->sortorder == 'ASC') {
982                 $firstarrow = print_arrow('up', $strsortasc, true);
983             } else {
984                 $firstarrow = print_arrow('down', $strsortdesc, true);
985             }
986         } else {
987             $firstarrow = '';
988         }
990         if ($fixedstudents) {
991             $fixedcolumntable = new html_table();
992             $fixedcolumntable->id = 'fixed_column';
993             $fixedcolumntable->add_class('fixed_grades_column');
994             $fixedcolumntable->bodyclasses = 'leftbody';
996             $colspan = 1;
998             if (has_capability('gradereport/user:view', $this->context)) {
999                 $colspan++;
1000             }
1002             if ($showuseridnumber) {
1003                 $colspan++;
1004             }
1006             $levels = count($this->gtree->levels) - 1;
1008             for ($i = 0; $i < $levels; $i++) {
1009                 $fillercell = new html_table_cell();
1010                 $fillercell->add_classes(array('fixedcolumn', 'cell', 'c0', 'topleft'));
1011                 $fillercell->text = ' ';
1012                 $fillercell->colspan = $colspan;
1013                 $fixedcolumntable->data[] = html_table_row::make(array($fillercell));
1014             }
1016             $sortfirstname = html_link::make(clone($this->baseurl), $strfirstname);
1017             $sortfirstname->url->param('sortitemid', 'firstname');
1018             $sortlastname = html_link::make(clone($this->baseurl), $strlastname);
1019             $sortlastname->url->param('sortitemid', 'lastname');
1021             $headerrow = new html_table_row();
1022             $headerrow->add_class('heading');
1024             $studentheader = new html_table_cell();
1025             $studentheader->add_classes(array('header', 'c0'));
1026             $studentheader->scope = 'col';
1027             $studentheader->header = true;
1028             $studentheader->id = 'studentheader';
1029             if (has_capability('gradereport/user:view', $this->context)) {
1030                 $studentheader->colspan = 2;
1031             }
1032             $studentheader->text = $OUTPUT->link($sortfirstname) . $firstarrow. '/ ' . $OUTPUT->link($sortlastname) . $lastarrow;
1034             $headerrow->cells[] = $studentheader;
1036             if ($showuseridnumber) {
1037                 $sortidnumberlink = html_link::make(clone($this->baseurl), get_string('idnumber'));
1038                 $sortidnumberlink->url->param('sortitemid', 'idnumber');
1040                 $idnumberheader = new html_table_cell();
1041                 $idnumberheader->add_classes(array('header', 'c0', 'useridnumber'));
1042                 $idnumberheader->scope = 'col';
1043                 $idnumberheader->header = true;
1044                 $idnumberheader->text = $OUTPUT->link($sortidnumberlink);
1046                 if ('idnumber' == $this->sortitemid) {
1047                     if ($this->sortorder == 'ASC') {
1048                         $idnumberheader->text .= print_arrow('up', $strsortasc, true);
1049                     } else {
1050                         $idnumberheader->text .= print_arrow('down', $strsortdesc, true);
1051                     }
1052                 }
1053                 $headerrow->cells[] = $idnumberheader;
1054             }
1056             $fixedcolumntable->data[] = $headerrow;
1058             if ($USER->gradeediting[$this->courseid]) {
1059                 $controlsrow = new html_table_row();
1060                 $controlsrow->add_class('controls');
1061                 $controlscell = new html_table_cell();
1062                 $controlscell->add_classes(array('header', 'c0', 'controls'));
1063                 $controlscell->colspan = $colspan;
1064                 $controlscell->text = $this->get_lang_string('controls','grades');
1066                 $controlsrow->cells[] = $controlscell;
1067                 $fixedcolumntable->data[] = $controlsrow;
1068             }
1070             $rowclasses = array('even', 'odd');
1072             foreach ($this->users as $userid => $user) {
1073                 $userrow = new html_table_row();
1074                 $userrow->add_classes(array('r'.$this->rowcount++, $rowclasses[$this->rowcount % 2]));
1076                 $usercell = new html_table_cell();
1077                 $usercell->add_classes(array('c0', 'user'));
1078                 $usercell->header = true;
1079                 $usercell->scope = 'row';
1080                 $usercell->add_action('click', 'yui_set_row');
1082                 if ($showuserimage) {
1083                     $usercell->text = $OUTPUT->container($OUTPUT->user_picture(moodle_user_picture::make($user, $this->courseid)), 'userpic');
1084                 }
1086                 $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)));
1088                 $userrow->cells[] = $usercell;
1090                 if (has_capability('gradereport/user:view', $this->context)) {
1091                     $userreportcell = new html_table_cell();
1092                     $userreportcell->add_class('userreport');
1093                     $userreportcell->header = true;
1094                     $a->user = fullname($user);
1095                     $strgradesforuser = get_string('gradesforuser', 'grades', $a);
1096                     $userreporticon = new moodle_action_icon();
1097                     $userreporticon->link->url = new moodle_url($CFG->wwwroot.'/grade/report/user/index.php', array('userid' => $user->id, 'id' => $this->course->id));
1098                     $userreporticon->image->add_class('iconsmall');
1099                     $userreporticon->image->src = $OUTPUT->old_icon_url('t/grades');
1100                     $userreporticon->image->alt = $strgradesforuser;
1101                     $userreportcell->text = $OUTPUT->action_icon($userreporticon);
1102                     $userrow->cells[] = $userreportcell;
1103                 }
1105                 if ($showuseridnumber) {
1106                     $idnumbercell = new html_table_cell();
1107                     $idnumbercell->add_classes(array('header', 'c0', 'useridnumber'));
1108                     $idnumbercell->header = true;
1109                     $idnumbercell->scope = 'row';
1110                     $idnumbercell->add_action('click', 'yui_set_row');
1111                     $userrow->cells[] = $idnumbercell;
1112                 }
1113                 $fixedcolumntable->data[] = $userrow;
1114             }
1116             if ($this->get_pref('showranges')) {
1117                 $rangerow = new html_table_row();
1118                 $rangerow->add_classes(array('range', 'r'.$this->rowcount++));
1119                 $rangecell = new html_table_cell();
1120                 $rangecell->add_classes(array('header', 'c0', 'range'));
1121                 $rangecell->colspan = $colspan;
1122                 $rangecell->header = true;
1123                 $rangecell->scope = 'row';
1124                 $rangecell->text = $this->get_lang_string('range','grades');
1125                 $rangerow->cells[] = $rangecell;
1126                 $fixedcolumntable->data[] = $rangerow;
1127             }
1129             // Averages heading
1131             $straveragegroup = get_string('groupavg', 'grades');
1132             $straverage = get_string('overallaverage', 'grades');
1133             $showaverages = $this->get_pref('showaverages');
1134             $showaveragesgroup = $this->currentgroup && $showaverages;
1136             if ($showaveragesgroup) {
1137                 $groupavgrow = new html_table_row();
1138                 $groupavgrow->add_classes(array('groupavg', 'r'.$this->rowcount++));
1139                 $groupavgcell = new html_table_cell();
1140                 $groupavgcell->add_classes(array('header', 'c0', 'range'));
1141                 $groupavgcell->colspan = $colspan;
1142                 $groupavgcell->header = true;
1143                 $groupavgcell->scope = 'row';
1144                 $groupavgcell->text = $straveragegroup;
1145                 $groupavgrow->cells[] = $groupavgcell;
1146                 $fixedcolumntable->data[] = $groupavgrow;
1147             }
1149             if ($showaverages) {
1150                 $avgrow = new html_table_row();
1151                 $avgrow->add_classes(array('avg', 'r'.$this->rowcount++));
1152                 $avgcell = new html_table_cell();
1153                 $avgcell->add_classes(array('header', 'c0', 'range'));
1154                 $avgcell->colspan = $colspan;
1155                 $avgcell->header = true;
1156                 $avgcell->scope = 'row';
1157                 $avgcell->text = $straverage;
1158                 $avgrow->cells[] = $avgcell;
1159                 $fixedcolumntable->data[] = $avgrow;
1160             }
1162             $studentshtml .= $OUTPUT->container($OUTPUT->table($fixedcolumntable), 'left_scroller');
1163             $studentshtml .= '
1164             <div class="right_scroller">
1165                 <table id="user-grades" class="">
1166                     <tbody class="righttest">';
1168         } else {
1169             $studentshtml .= '<table id="user-grades" class="gradestable flexible boxaligncenter generaltable">
1170                                 <tbody>';
1171         }
1173         return $studentshtml;
1174     }
1176     /**
1177      * Closes all open elements
1178      */
1179     public function get_endhtml() {
1180         global $CFG, $USER;
1182         $fixedstudents = $this->is_fixed_students();
1184         if ($fixedstudents) {
1185             return "</tbody></table></div>";
1186         } else {
1187             return "</tbody></table>";
1188         }
1189     }
1191     /**
1192      * Builds and return the HTML row of column totals.
1193      * @param  bool $grouponly Whether to return only group averages or all averages.
1194      * @return string HTML
1195      */
1196     public function get_avghtml($grouponly=false) {
1197         global $CFG, $USER, $DB;
1199         if (!$this->canviewhidden) {
1200             // totals might be affected by hiding, if user can not see hidden grades the aggregations might be altered
1201             // better not show them at all if user can not see all hideen grades
1202             return;
1203         }
1205         $averagesdisplaytype   = $this->get_pref('averagesdisplaytype');
1206         $averagesdecimalpoints = $this->get_pref('averagesdecimalpoints');
1207         $meanselection         = $this->get_pref('meanselection');
1208         $shownumberofgrades    = $this->get_pref('shownumberofgrades');
1210         $avghtml = '';
1211         $avgcssclass = 'avg';
1213         if ($grouponly) {
1214             $straverage = get_string('groupavg', 'grades');
1215             $showaverages = $this->currentgroup && $this->get_pref('showaverages');
1216             $groupsql = $this->groupsql;
1217             $groupwheresql = $this->groupwheresql;
1218             $groupwheresqlparams = $this->groupwheresql_params;
1219             $avgcssclass = 'groupavg';
1220         } else {
1221             $straverage = get_string('overallaverage', 'grades');
1222             $showaverages = $this->get_pref('showaverages');
1223             $groupsql = "";
1224             $groupwheresql = "";
1225             $groupwheresqlparams = array();
1226         }
1228         if ($shownumberofgrades) {
1229             $straverage .= ' (' . get_string('submissions', 'grades') . ') ';
1230         }
1232         $totalcount = $this->get_numusers($grouponly);
1234         list($usql, $rolesparams) = $DB->get_in_or_equal(explode(',', $this->gradebookroles), SQL_PARAMS_NAMED, 'grbr0');
1236         if ($showaverages) {
1237             $params = array_merge(array('courseid'=>$this->courseid), $rolesparams, $groupwheresqlparams);
1239             // find sums of all grade items in course
1240             $SQL = "SELECT g.itemid, SUM(g.finalgrade) AS sum
1241                       FROM {grade_items} gi
1242                            JOIN {grade_grades} g      ON g.itemid = gi.id
1243                            JOIN {user} u              ON u.id = g.userid
1244                            JOIN {role_assignments} ra ON ra.userid = u.id
1245                            $groupsql
1246                      WHERE gi.courseid = :courseid
1247                            AND ra.roleid $usql
1248                            AND ra.contextid ".get_related_contexts_string($this->context)."
1249                            AND g.finalgrade IS NOT NULL
1250                            $groupwheresql
1251                   GROUP BY g.itemid";
1252             $sumarray = array();
1253             if ($sums = $DB->get_records_sql($SQL, $params)) {
1254                 foreach ($sums as $itemid => $csum) {
1255                     $sumarray[$itemid] = $csum->sum;
1256                 }
1257             }
1259             $columncount=0;
1260             $avghtml = '<tr class="' . $avgcssclass . ' r'.$this->rowcount++.'">';
1262             // MDL-10875 Empty grades must be evaluated as grademin, NOT always 0
1263             // This query returns a count of ungraded grades (NULL finalgrade OR no matching record in grade_grades table)
1264             $params = array_merge(array('courseid'=>$this->courseid), $rolesparams, $groupwheresqlparams);
1265             $SQL = "SELECT gi.id, COUNT(u.id) AS count
1266                       FROM {grade_items} gi
1267                            CROSS JOIN {user} u
1268                            JOIN {role_assignments} ra        ON ra.userid = u.id
1269                            LEFT OUTER JOIN  {grade_grades} g ON (g.itemid = gi.id AND g.userid = u.id AND g.finalgrade IS NOT NULL)
1270                            $groupsql
1271                      WHERE gi.courseid = :courseid
1272                            AND ra.roleid $usql
1273                            AND ra.contextid ".get_related_contexts_string($this->context)."
1274                            AND g.id IS NULL
1275                            $groupwheresql
1276                   GROUP BY gi.id";
1278             $ungradedcounts = $DB->get_records_sql($SQL, $params);
1280             $fixedstudents = $this->is_fixed_students();
1281             if (!$fixedstudents) {
1282                 $colspan='';
1283                 if ($this->get_pref('showuseridnumber')) {
1284                     $colspan = 'colspan="2" ';
1285                 }
1286                 $avghtml .= '<th class="header c0 range" '.$colspan.' scope="row">'.$straverage.'</th>';
1287             }
1289             foreach ($this->gtree->items as $itemid=>$unused) {
1290                 $item =& $this->gtree->items[$itemid];
1292                 if ($item->needsupdate) {
1293                     $avghtml .= '<td class="cell c' . $columncount++.'"><span class="gradingerror">'.get_string('error').'</span></td>';
1294                     continue;
1295                 }
1297                 if (!isset($sumarray[$item->id])) {
1298                     $sumarray[$item->id] = 0;
1299                 }
1301                 if (empty($ungradedcounts[$itemid])) {
1302                     $ungradedcount = 0;
1303                 } else {
1304                     $ungradedcount = $ungradedcounts[$itemid]->count;
1305                 }
1307                 if ($meanselection == GRADE_REPORT_MEAN_GRADED) {
1308                     $meancount = $totalcount - $ungradedcount;
1309                 } else { // Bump up the sum by the number of ungraded items * grademin
1310                     $sumarray[$item->id] += $ungradedcount * $item->grademin;
1311                     $meancount = $totalcount;
1312                 }
1314                 $decimalpoints = $item->get_decimals();
1316                 // Determine which display type to use for this average
1317                 if ($USER->gradeediting[$this->courseid]) {
1318                     $displaytype = GRADE_DISPLAY_TYPE_REAL;
1320                 } else if ($averagesdisplaytype == GRADE_REPORT_PREFERENCE_INHERIT) { // no ==0 here, please resave the report and user preferences
1321                     $displaytype = $item->get_displaytype();
1323                 } else {
1324                     $displaytype = $averagesdisplaytype;
1325                 }
1327                 // Override grade_item setting if a display preference (not inherit) was set for the averages
1328                 if ($averagesdecimalpoints == GRADE_REPORT_PREFERENCE_INHERIT) {
1329                     $decimalpoints = $item->get_decimals();
1331                 } else {
1332                     $decimalpoints = $averagesdecimalpoints;
1333                 }
1335                 if (!isset($sumarray[$item->id]) || $meancount == 0) {
1336                     $avghtml .= '<td class="cell c' . $columncount++.'">-</td>';
1337                 } else {
1338                     $sum = $sumarray[$item->id];
1339                     $avgradeval = $sum/$meancount;
1340                     $gradehtml = grade_format_gradevalue($avgradeval, $item, true, $displaytype, $decimalpoints);
1342                     $numberofgrades = '';
1343                     if ($shownumberofgrades) {
1344                         $numberofgrades = " ($meancount)";
1345                     }
1347                     $avghtml .= '<td class="cell c' . $columncount++.'">'.$gradehtml.$numberofgrades.'</td>';
1348                 }
1349             }
1350             $avghtml .= '</tr>';
1351         }
1352         return $avghtml;
1353     }
1355     /**
1356      * Builds and return the HTML row of ranges for each column (i.e. range).
1357      * @return string HTML
1358      */
1359     public function get_rangehtml() {
1360         global $CFG, $USER;
1362         $rangehtml = '';
1363         if ($this->get_pref('showranges')) {
1364             $rangesdisplaytype   = $this->get_pref('rangesdisplaytype');
1365             $rangesdecimalpoints = $this->get_pref('rangesdecimalpoints');
1367             $columncount=0;
1368             $rangehtml = '<tr class="range r'.$this->rowcount++.' heading">';
1370             $fixedstudents = $this->is_fixed_students();
1371             if (!$fixedstudents) {
1372                 $colspan='';
1373                 if ($this->get_pref('showuseridnumber')) {
1374                     $colspan = 'colspan="2" ';
1375                 }
1376                 $rangehtml .= '<th class="header c0 range" '.$colspan.' scope="row">'.$this->get_lang_string('range','grades').'</th>';
1377             }
1379             foreach ($this->gtree->items as $itemid=>$unused) {
1380                 $item =& $this->gtree->items[$itemid];
1383                 $hidden = '';
1384                 if ($item->is_hidden()) {
1385                     $hidden = ' hidden ';
1386                 }
1388                 $formattedrange = $item->get_formatted_range($rangesdisplaytype, $rangesdecimalpoints);
1390                 $rangehtml .= '<th class="header c'.$columncount++.' range"><span class="rangevalues'.$hidden.'">'. $formattedrange .'</span></th>';
1392             }
1393             $rangehtml .= '</tr>';
1394         }
1395         return $rangehtml;
1396     }
1398     /**
1399      * Builds and return the HTML row of ranges for each column (i.e. range).
1400      * @return string HTML
1401      */
1402     public function get_iconshtml() {
1403         global $USER, $CFG;
1405         $iconshtml = '';
1406         if ($USER->gradeediting[$this->courseid]) {
1408             $iconshtml = '<tr class="controls">';
1410             $fixedstudents = $this->is_fixed_students();
1411             $showuseridnumber = $this->get_pref('showuseridnumber');
1413             $colspan = '';
1414             if ($showuseridnumber) {
1415                 $colspan = 'colspan="2"';
1416             }
1418             if (!$fixedstudents) {
1419                 $iconshtml .= '<th class="header c0 controls" scope="row" '.$colspan.'>'.$this->get_lang_string('controls','grades').'</th>';
1420             }
1422             $columncount = 0;
1423             foreach ($this->gtree->items as $itemid=>$unused) {
1424                 // emulate grade element
1425                 $item =& $this->gtree->get_item($itemid);
1427                 $eid = $this->gtree->get_item_eid($item);
1428                 $element = $this->gtree->locate_element($eid);
1430                 $iconshtml .= '<td class="controls cell c'.$columncount++.' icons">' . $this->get_icons($element) . '</td>';
1431             }
1432             $iconshtml .= '</tr>';
1433         }
1434         return $iconshtml;
1435     }
1437     /**
1438      * Given a grade_category, grade_item or grade_grade, this function
1439      * figures out the state of the object and builds then returns a div
1440      * with the icons needed for the grader report.
1441      *
1442      * @param object $object
1443      * @return string HTML
1444      */
1445     protected function get_icons($element) {
1446         global $CFG, $USER, $OUTPUT;
1448         if (!$USER->gradeediting[$this->courseid]) {
1449             return '<div class="grade_icons" />';
1450         }
1452         // Init all icons
1453         $editicon = '';
1455         if ($element['type'] != 'categoryitem' && $element['type'] != 'courseitem') {
1456             $editicon = $this->gtree->get_edit_icon($element, $this->gpr);
1457         }
1459         $editcalculationicon = '';
1460         $showhideicon        = '';
1461         $lockunlockicon      = '';
1463         if (has_capability('moodle/grade:manage', $this->context)) {
1465             if ($this->get_pref('showcalculations')) {
1466                 $editcalculationicon = $this->gtree->get_calculation_icon($element, $this->gpr);
1467             }
1469             if ($this->get_pref('showeyecons')) {
1470                $showhideicon = $this->gtree->get_hiding_icon($element, $this->gpr);
1471             }
1473             if ($this->get_pref('showlocks')) {
1474                 $lockunlockicon = $this->gtree->get_locking_icon($element, $this->gpr);
1475             }
1476         }
1478         return $OUTPUT->container($editicon.$editcalculationicon.$showhideicon.$lockunlockicon, 'grade_icons');
1479     }
1481     /**
1482      * Given a category element returns collapsing +/- icon if available
1483      * @param object $object
1484      * @return string HTML
1485      */
1486     protected function get_collapsing_icon($element) {
1487         global $OUTPUT;
1489         $icon = '';
1490         // If object is a category, display expand/contract icon
1491         if ($element['type'] == 'category') {
1492             // Load language strings
1493             $strswitchminus = $this->get_lang_string('aggregatesonly', 'grades');
1494             $strswitchplus  = $this->get_lang_string('gradesonly', 'grades');
1495             $strswitchwhole = $this->get_lang_string('fullmode', 'grades');
1497             $contractexpandicon = new moodle_action_icon();
1498             $contractexpandicon->link->url = new moodle_url($this->gpr->get_return_url(null, array('target'=>$element['eid'], 'action'=>'switch_minus', 'sesskey'=>sesskey())));
1499             $contractexpandicon->image->add_class('iconsmall');
1500             $contractexpandicon->image->src = $OUTPUT->old_icon_url('t/switch_minus');
1501             $contractexpandicon->image->alt = $strswitchminus;
1503             if (in_array($element['object']->id, $this->collapsed['aggregatesonly'])) {
1504                 $contractexpandicon->image->src = $OUTPUT->old_icon_url('t/switch_plus');
1505                 $contractexpandicon->image->alt = $strswitchplus;
1506                 $contractexpandicon->link->url->param('action', 'switch_plus');
1507             } elseif (in_array($element['object']->id, $this->collapsed['gradesonly'])) {
1508                 $contractexpandicon->image->src = $OUTPUT->old_icon_url('t/switch_whole');
1509                 $contractexpandicon->image->alt = $strswitchwhole;
1510                 $contractexpandicon->link->url->param('action', 'switch_whole');
1511             }
1512             $icon = $OUTPUT->action_icon($contractexpandicon);
1513         }
1514         return $icon;
1515     }
1517     /**
1518      * Processes a single action against a category, grade_item or grade.
1519      * @param string $target eid ({type}{id}, e.g. c4 for category4)
1520      * @param string $action Which action to take (edit, delete etc...)
1521      * @return
1522      */
1523     public function process_action($target, $action) {
1524         // TODO: this code should be in some grade_tree static method
1525         $targettype = substr($target, 0, 1);
1526         $targetid = substr($target, 1);
1527         // TODO: end
1529         if ($collapsed = get_user_preferences('grade_report_grader_collapsed_categories')) {
1530             $collapsed = unserialize($collapsed);
1531         } else {
1532             $collapsed = array('aggregatesonly' => array(), 'gradesonly' => array());
1533         }
1535         switch ($action) {
1536             case 'switch_minus': // Add category to array of aggregatesonly
1537                 if (!in_array($targetid, $collapsed['aggregatesonly'])) {
1538                     $collapsed['aggregatesonly'][] = $targetid;
1539                     set_user_preference('grade_report_grader_collapsed_categories', serialize($collapsed));
1540                 }
1541                 break;
1543             case 'switch_plus': // Remove category from array of aggregatesonly, and add it to array of gradesonly
1544                 $key = array_search($targetid, $collapsed['aggregatesonly']);
1545                 if ($key !== false) {
1546                     unset($collapsed['aggregatesonly'][$key]);
1547                 }
1548                 if (!in_array($targetid, $collapsed['gradesonly'])) {
1549                     $collapsed['gradesonly'][] = $targetid;
1550                 }
1551                 set_user_preference('grade_report_grader_collapsed_categories', serialize($collapsed));
1552                 break;
1553             case 'switch_whole': // Remove the category from the array of collapsed cats
1554                 $key = array_search($targetid, $collapsed['gradesonly']);
1555                 if ($key !== false) {
1556                     unset($collapsed['gradesonly'][$key]);
1557                     set_user_preference('grade_report_grader_collapsed_categories', serialize($collapsed));
1558                 }
1560                 break;
1561             default:
1562                 break;
1563         }
1565         return true;
1566     }
1568     /**
1569      * Returns whether or not to display fixed students column.
1570      * Includes a browser check, because IE6 doesn't support the scrollbar.
1571      *
1572      * @return bool
1573      */
1574     public function is_fixed_students() {
1575         global $USER, $CFG;
1576         return empty($USER->screenreader) && $CFG->grade_report_fixedstudents &&
1577             (check_browser_version('MSIE', '7.0') ||
1578              check_browser_version('Firefox', '2.0') ||
1579              check_browser_version('Gecko', '2006010100') ||
1580              check_browser_version('Camino', '1.0') ||
1581              check_browser_version('Opera', '6.0') ||
1582              check_browser_version('Safari', '2.0'));
1583     }
1585 ?>