MDL-31353 grade: added a missing YUI requires
[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      * Length at which feedback will be truncated (to the nearest word) and an ellipsis be added.
91      * TODO replace this by a report preference
92      * @var int $feedback_trunc_length
93      */
94     protected $feedback_trunc_length = 50;
96     /**
97      * Constructor. Sets local copies of user preferences and initialises grade_tree.
98      * @param int $courseid
99      * @param object $gpr grade plugin return tracking object
100      * @param string $context
101      * @param int $page The current page being viewed (when report is paged)
102      * @param int $sortitemid The id of the grade_item by which to sort the table
103      */
104     public function __construct($courseid, $gpr, $context, $page=null, $sortitemid=null) {
105         global $CFG;
106         parent::__construct($courseid, $gpr, $context, $page);
108         $this->canviewhidden = has_capability('moodle/grade:viewhidden', get_context_instance(CONTEXT_COURSE, $this->course->id));
110         // load collapsed settings for this report
111         if ($collapsed = get_user_preferences('grade_report_grader_collapsed_categories')) {
112             $this->collapsed = unserialize($collapsed);
113         } else {
114             $this->collapsed = array('aggregatesonly' => array(), 'gradesonly' => array());
115         }
117         if (empty($CFG->enableoutcomes)) {
118             $nooutcomes = false;
119         } else {
120             $nooutcomes = get_user_preferences('grade_report_shownooutcomes');
121         }
123         // if user report preference set or site report setting set use it, otherwise use course or site setting
124         $switch = $this->get_pref('aggregationposition');
125         if ($switch == '') {
126             $switch = grade_get_setting($this->courseid, 'aggregationposition', $CFG->grade_aggregationposition);
127         }
129         // Grab the grade_tree for this course
130         $this->gtree = new grade_tree($this->courseid, true, $switch, $this->collapsed, $nooutcomes);
132         $this->sortitemid = $sortitemid;
134         // base url for sorting by first/last name
136         $this->baseurl = new moodle_url('index.php', array('id' => $this->courseid));
138         $studentsperpage = $this->get_pref('studentsperpage');
139         if (!empty($studentsperpage)) {
140             $this->baseurl->params(array('perpage' => $studentsperpage, 'page' => $this->page));
141         }
143         $this->pbarurl = new moodle_url('/grade/report/grader/index.php', array('id' => $this->courseid, 'perpage' => $studentsperpage));
145         $this->setup_groups();
147         $this->setup_sortitemid();
148     }
150     /**
151      * Processes the data sent by the form (grades and feedbacks).
152      * Caller is responsible for all access control checks
153      * @param array $data form submission (with magic quotes)
154      * @return array empty array if success, array of warnings if something fails.
155      */
156     public function process_data($data) {
157         global $DB;
158         $warnings = array();
160         $separategroups = false;
161         $mygroups       = array();
162         if ($this->groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $this->context)) {
163             $separategroups = true;
164             $mygroups = groups_get_user_groups($this->course->id);
165             $mygroups = $mygroups[0]; // ignore groupings
166             // reorder the groups fro better perf below
167             $current = array_search($this->currentgroup, $mygroups);
168             if ($current !== false) {
169                 unset($mygroups[$current]);
170                 array_unshift($mygroups, $this->currentgroup);
171             }
172         }
174         // always initialize all arrays
175         $queue = array();
176         foreach ($data as $varname => $postedvalue) {
178             $needsupdate = false;
180             // skip, not a grade nor feedback
181             if (strpos($varname, 'grade') === 0) {
182                 $datatype = 'grade';
183             } else if (strpos($varname, 'feedback') === 0) {
184                 $datatype = 'feedback';
185             } else {
186                 continue;
187             }
189             $gradeinfo = explode("_", $varname);
190             $userid = clean_param($gradeinfo[1], PARAM_INT);
191             $itemid = clean_param($gradeinfo[2], PARAM_INT);
193             $oldvalue = $data->{'old'.$varname};
195             // was change requested?
196             if ($oldvalue == $postedvalue) { // string comparison
197                 continue;
198             }
200             if (!$gradeitem = grade_item::fetch(array('id'=>$itemid, 'courseid'=>$this->courseid))) { // we must verify course id here!
201                 print_error('invalidgradeitmeid');
202             }
204             // Pre-process grade
205             if ($datatype == 'grade') {
206                 $feedback = false;
207                 $feedbackformat = false;
208                 if ($gradeitem->gradetype == GRADE_TYPE_SCALE) {
209                     if ($postedvalue == -1) { // -1 means no grade
210                         $finalgrade = null;
211                     } else {
212                         $finalgrade = $postedvalue;
213                     }
214                 } else {
215                     $finalgrade = unformat_float($postedvalue);
216                 }
218                 $errorstr = '';
219                 // Warn if the grade is out of bounds.
220                 if (is_null($finalgrade)) {
221                     // ok
222                 } else {
223                     $bounded = $gradeitem->bounded_grade($finalgrade);
224                     if ($bounded > $finalgrade) {
225                     $errorstr = 'lessthanmin';
226                     } else if ($bounded < $finalgrade) {
227                         $errorstr = 'morethanmax';
228                     }
229                 }
230                 if ($errorstr) {
231                     $user = $DB->get_record('user', array('id' => $userid), 'id, firstname, lastname');
232                     $gradestr = new stdClass();
233                     $gradestr->username = fullname($user);
234                     $gradestr->itemname = $gradeitem->get_name();
235                     $warnings[] = get_string($errorstr, 'grades', $gradestr);
236                 }
238             } else if ($datatype == 'feedback') {
239                 $finalgrade = false;
240                 $trimmed = trim($postedvalue);
241                 if (empty($trimmed)) {
242                      $feedback = NULL;
243                 } else {
244                      $feedback = $postedvalue;
245                 }
246             }
248             // group access control
249             if ($separategroups) {
250                 // note: we can not use $this->currentgroup because it would fail badly
251                 //       when having two browser windows each with different group
252                 $sharinggroup = false;
253                 foreach($mygroups as $groupid) {
254                     if (groups_is_member($groupid, $userid)) {
255                         $sharinggroup = true;
256                         break;
257                     }
258                 }
259                 if (!$sharinggroup) {
260                     // either group membership changed or somebody is hacking grades of other group
261                     $warnings[] = get_string('errorsavegrade', 'grades');
262                     continue;
263                 }
264             }
266             $gradeitem->update_final_grade($userid, $finalgrade, 'gradebook', $feedback, FORMAT_MOODLE);
267         }
269         return $warnings;
270     }
273     /**
274      * Setting the sort order, this depends on last state
275      * all this should be in the new table class that we might need to use
276      * for displaying grades.
277      */
278     private function setup_sortitemid() {
280         global $SESSION;
282         if ($this->sortitemid) {
283             if (!isset($SESSION->gradeuserreport->sort)) {
284                 if ($this->sortitemid == 'firstname' || $this->sortitemid == 'lastname') {
285                     $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC';
286                 } else {
287                     $this->sortorder = $SESSION->gradeuserreport->sort = 'DESC';
288                 }
289             } else {
290                 // this is the first sort, i.e. by last name
291                 if (!isset($SESSION->gradeuserreport->sortitemid)) {
292                     if ($this->sortitemid == 'firstname' || $this->sortitemid == 'lastname') {
293                         $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC';
294                     } else {
295                         $this->sortorder = $SESSION->gradeuserreport->sort = 'DESC';
296                     }
297                 } else if ($SESSION->gradeuserreport->sortitemid == $this->sortitemid) {
298                     // same as last sort
299                     if ($SESSION->gradeuserreport->sort == 'ASC') {
300                         $this->sortorder = $SESSION->gradeuserreport->sort = 'DESC';
301                     } else {
302                         $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC';
303                     }
304                 } else {
305                     if ($this->sortitemid == 'firstname' || $this->sortitemid == 'lastname') {
306                         $this->sortorder = $SESSION->gradeuserreport->sort = 'ASC';
307                     } else {
308                         $this->sortorder = $SESSION->gradeuserreport->sort = 'DESC';
309                     }
310                 }
311             }
312             $SESSION->gradeuserreport->sortitemid = $this->sortitemid;
313         } else {
314             // not requesting sort, use last setting (for paging)
316             if (isset($SESSION->gradeuserreport->sortitemid)) {
317                 $this->sortitemid = $SESSION->gradeuserreport->sortitemid;
318             }else{
319                 $this->sortitemid = 'lastname';
320             }
322             if (isset($SESSION->gradeuserreport->sort)) {
323                 $this->sortorder = $SESSION->gradeuserreport->sort;
324             } else {
325                 $this->sortorder = 'ASC';
326             }
327         }
328     }
330     /**
331      * pulls out the userids of the users to be display, and sorts them
332      */
333     public function load_users() {
334         global $CFG, $DB;
336         //limit to users with a gradeable role
337         list($gradebookrolessql, $gradebookrolesparams) = $DB->get_in_or_equal(explode(',', $this->gradebookroles), SQL_PARAMS_NAMED, 'grbr0');
339         //limit to users with an active enrollment
340         list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->context);
342         //fields we need from the user table
343         $userfields = user_picture::fields('u');
344         $userfields .= get_extra_user_fields_sql($this->context);
346         $sortjoin = $sort = $params = null;
348         //if the user has clicked one of the sort asc/desc arrows
349         if (is_numeric($this->sortitemid)) {
350             $params = array_merge(array('gitemid'=>$this->sortitemid), $gradebookrolesparams, $this->groupwheresql_params, $enrolledparams);
352             $sortjoin = "LEFT JOIN {grade_grades} g ON g.userid = u.id AND g.itemid = $this->sortitemid";
353             $sort = "g.finalgrade $this->sortorder";
355         } else {
356             $sortjoin = '';
357             switch($this->sortitemid) {
358                 case 'lastname':
359                     $sort = "u.lastname $this->sortorder, u.firstname $this->sortorder";
360                     break;
361                 case 'firstname':
362                     $sort = "u.firstname $this->sortorder, u.lastname $this->sortorder";
363                     break;
364                 case 'idnumber':
365                 default:
366                     $sort = "u.idnumber $this->sortorder";
367                     break;
368             }
370             $params = array_merge($gradebookrolesparams, $this->groupwheresql_params, $enrolledparams);
371         }
373         $sql = "SELECT $userfields
374                   FROM {user} u
375                   JOIN ($enrolledsql) je ON je.id = u.id
376                        $this->groupsql
377                        $sortjoin
378                   JOIN (
379                            SELECT DISTINCT ra.userid
380                              FROM {role_assignments} ra
381                             WHERE ra.roleid IN ($this->gradebookroles)
382                               AND ra.contextid " . get_related_contexts_string($this->context) . "
383                        ) rainner ON rainner.userid = u.id
384                    AND u.deleted = 0
385                    $this->groupwheresql
386               ORDER BY $sort";
388         $this->users = $DB->get_records_sql($sql, $params, $this->get_pref('studentsperpage') * $this->page, $this->get_pref('studentsperpage'));
390         if (empty($this->users)) {
391             $this->userselect = '';
392             $this->users = array();
393             $this->userselect_params = array();
394         } else {
395             list($usql, $uparams) = $DB->get_in_or_equal(array_keys($this->users), SQL_PARAMS_NAMED, 'usid0');
396             $this->userselect = "AND g.userid $usql";
397             $this->userselect_params = $uparams;
399             //add a flag to each user indicating whether their enrolment is active
400             $sql = "SELECT ue.userid
401                       FROM {user_enrolments} ue
402                       JOIN {enrol} e ON e.id = ue.enrolid
403                      WHERE ue.userid $usql
404                            AND ue.status = :uestatus
405                            AND e.status = :estatus
406                            AND e.courseid = :courseid
407                   GROUP BY ue.userid";
408             $coursecontext = get_course_context($this->context);
409             $params = array_merge($uparams, array('estatus'=>ENROL_INSTANCE_ENABLED, 'uestatus'=>ENROL_USER_ACTIVE, 'courseid'=>$coursecontext->instanceid));
410             $useractiveenrolments = $DB->get_records_sql($sql, $params);
412             foreach ($this->users as $user) {
413                 $this->users[$user->id]->suspendedenrolment = !array_key_exists($user->id, $useractiveenrolments);
414             }
415         }
417         return $this->users;
418     }
420     /**
421      * we supply the userids in this query, and get all the grades
422      * pulls out all the grades, this does not need to worry about paging
423      */
424     public function load_final_grades() {
425         global $CFG, $DB;
427         // please note that we must fetch all grade_grades fields if we want to construct grade_grade object from it!
428         $params = array_merge(array('courseid'=>$this->courseid), $this->userselect_params);
429         $sql = "SELECT g.*
430                   FROM {grade_items} gi,
431                        {grade_grades} g
432                  WHERE g.itemid = gi.id AND gi.courseid = :courseid {$this->userselect}";
434         $userids = array_keys($this->users);
437         if ($grades = $DB->get_records_sql($sql, $params)) {
438             foreach ($grades as $graderec) {
439                 if (in_array($graderec->userid, $userids) and array_key_exists($graderec->itemid, $this->gtree->get_items())) { // some items may not be present!!
440                     $this->grades[$graderec->userid][$graderec->itemid] = new grade_grade($graderec, false);
441                     $this->grades[$graderec->userid][$graderec->itemid]->grade_item =& $this->gtree->get_item($graderec->itemid); // db caching
442                 }
443             }
444         }
446         // prefil grades that do not exist yet
447         foreach ($userids as $userid) {
448             foreach ($this->gtree->get_items() as $itemid=>$unused) {
449                 if (!isset($this->grades[$userid][$itemid])) {
450                     $this->grades[$userid][$itemid] = new grade_grade();
451                     $this->grades[$userid][$itemid]->itemid = $itemid;
452                     $this->grades[$userid][$itemid]->userid = $userid;
453                     $this->grades[$userid][$itemid]->grade_item =& $this->gtree->get_item($itemid); // db caching
454                 }
455             }
456         }
457     }
459     /**
460      * Builds and returns a div with on/off toggles.
461      * @return string HTML code
462      */
463     public function get_toggles_html() {
464         global $CFG, $USER, $COURSE, $OUTPUT;
466         $html = '';
467         if ($USER->gradeediting[$this->courseid]) {
468             if (has_capability('moodle/grade:manage', $this->context) or has_capability('moodle/grade:hide', $this->context)) {
469                 $html .= $this->print_toggle('eyecons');
470             }
471             if (has_capability('moodle/grade:manage', $this->context)
472              or has_capability('moodle/grade:lock', $this->context)
473              or has_capability('moodle/grade:unlock', $this->context)) {
474                 $html .= $this->print_toggle('locks');
475             }
476             if (has_capability('moodle/grade:manage', $this->context)) {
477                 $html .= $this->print_toggle('quickfeedback');
478             }
480             if (has_capability('moodle/grade:manage', $this->context)) {
481                 $html .= $this->print_toggle('calculations');
482             }
483         }
485         if ($this->canviewhidden) {
486             $html .= $this->print_toggle('averages');
487         }
489         $html .= $this->print_toggle('ranges');
490         if (!empty($CFG->enableoutcomes)) {
491             $html .= $this->print_toggle('nooutcomes');
492         }
494         return $OUTPUT->container($html, 'grade-report-toggles');
495     }
497     /**
498     * Shortcut function for printing the grader report toggles.
499     * @param string $type The type of toggle
500     * @param bool $return Whether to return the HTML string rather than printing it
501     * @return void
502     */
503     public function print_toggle($type) {
504         global $CFG, $OUTPUT;
506         $icons = array('eyecons' => 't/hide',
507                        'calculations' => 't/calc',
508                        'locks' => 't/lock',
509                        'averages' => 't/mean',
510                        'quickfeedback' => 't/feedback',
511                        'nooutcomes' => 't/outcomes');
513         $prefname = 'grade_report_show' . $type;
515         if (array_key_exists($prefname, $CFG)) {
516             $showpref = get_user_preferences($prefname, $CFG->$prefname);
517         } else {
518             $showpref = get_user_preferences($prefname);
519         }
521         $strshow = $this->get_lang_string('show' . $type, 'grades');
522         $strhide = $this->get_lang_string('hide' . $type, 'grades');
524         $showhide = 'show';
525         $toggleaction = 1;
527         if ($showpref) {
528             $showhide = 'hide';
529             $toggleaction = 0;
530         }
532         if (array_key_exists($type, $icons)) {
533             $imagename = $icons[$type];
534         } else {
535             $imagename = "t/$type";
536         }
538         $string = ${'str' . $showhide};
540         $url = new moodle_url($this->baseurl, array('toggle' => $toggleaction, 'toggle_type' => $type));
542         $retval = $OUTPUT->container($OUTPUT->action_icon($url, new pix_icon($imagename, $string))); // TODO: this container looks wrong here
544         return $retval;
545     }
547     /**
548      * Builds and returns the rows that will make up the left part of the grader report
549      * This consists of student names and icons, links to user reports and id numbers, as well
550      * as header cells for these columns. It also includes the fillers required for the
551      * categories displayed on the right side of the report.
552      * @return array Array of html_table_row objects
553      */
554     public function get_left_rows() {
555         global $CFG, $USER, $OUTPUT;
557         $rows = array();
559         $showuserimage = $this->get_pref('showuserimage');
560         $fixedstudents = $this->is_fixed_students();
562         $strfeedback  = $this->get_lang_string("feedback");
563         $strgrade     = $this->get_lang_string('grade');
565         $extrafields = get_extra_user_fields($this->context);
567         $arrows = $this->get_sort_arrows($extrafields);
569         $colspan = 1;
570         if (has_capability('gradereport/'.$CFG->grade_profilereport.':view', $this->context)) {
571             $colspan++;
572         }
573         $colspan += count($extrafields);
575         $levels = count($this->gtree->levels) - 1;
577         for ($i = 0; $i < $levels; $i++) {
578             $fillercell = new html_table_cell();
579             $fillercell->attributes['class'] = 'fixedcolumn cell topleft';
580             $fillercell->text = ' ';
581             $fillercell->colspan = $colspan;
582             $row = new html_table_row(array($fillercell));
583             $rows[] = $row;
584         }
586         $headerrow = new html_table_row();
587         $headerrow->attributes['class'] = 'heading';
589         $studentheader = new html_table_cell();
590         $studentheader->attributes['class'] = 'header';
591         $studentheader->scope = 'col';
592         $studentheader->header = true;
593         $studentheader->id = 'studentheader';
594         if (has_capability('gradereport/'.$CFG->grade_profilereport.':view', $this->context)) {
595             $studentheader->colspan = 2;
596         }
597         $studentheader->text = $arrows['studentname'];
599         $headerrow->cells[] = $studentheader;
601         foreach ($extrafields as $field) {
602             $fieldheader = new html_table_cell();
603             $fieldheader->attributes['class'] = 'header userfield user' . $field;
604             $fieldheader->scope = 'col';
605             $fieldheader->header = true;
606             $fieldheader->text = $arrows[$field];
608             $headerrow->cells[] = $fieldheader;
609         }
611         $rows[] = $headerrow;
613         $rows = $this->get_left_icons_row($rows, $colspan);
615         $rowclasses = array('even', 'odd');
617         $suspendedstring = null;
618         foreach ($this->users as $userid => $user) {
619             $userrow = new html_table_row();
620             $userrow->id = 'fixed_user_'.$userid;
621             $userrow->attributes['class'] = 'r'.$this->rowcount++.' '.$rowclasses[$this->rowcount % 2];
623             $usercell = new html_table_cell();
624             $usercell->attributes['class'] = 'user';
626             $usercell->header = true;
627             $usercell->scope = 'row';
629             if ($showuserimage) {
630                 $usercell->text = $OUTPUT->user_picture($user);
631             }
633             $usercell->text .= html_writer::link(new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $this->course->id)), fullname($user));
635             if (!empty($user->suspendedenrolment)) {
636                 $usercell->attributes['class'] .= ' usersuspended';
638                 //may be lots of suspended users so only get the string once
639                 if (empty($suspendedstring)) {
640                     $suspendedstring = get_string('userenrolmentsuspended', 'grades');
641                 }
642                 $usercell->text .= html_writer::empty_tag('img', array('src'=>$OUTPUT->pix_url('i/enrolmentsuspended'), 'title'=>$suspendedstring, 'alt'=>$suspendedstring, 'class'=>'usersuspendedicon'));
643             }
645             $userrow->cells[] = $usercell;
647             if (has_capability('gradereport/'.$CFG->grade_profilereport.':view', $this->context)) {
648                 $userreportcell = new html_table_cell();
649                 $userreportcell->attributes['class'] = 'userreport';
650                 $userreportcell->header = true;
651                 $a = new stdClass();
652                 $a->user = fullname($user);
653                 $strgradesforuser = get_string('gradesforuser', 'grades', $a);
654                 $url = new moodle_url('/grade/report/'.$CFG->grade_profilereport.'/index.php', array('userid' => $user->id, 'id' => $this->course->id));
655                 $userreportcell->text = $OUTPUT->action_icon($url, new pix_icon('t/grades', $strgradesforuser));
656                 $userrow->cells[] = $userreportcell;
657             }
659             foreach ($extrafields as $field) {
660                 $fieldcell = new html_table_cell();
661                 $fieldcell->attributes['class'] = 'header userfield user' . $field;
662                 $fieldcell->header = true;
663                 $fieldcell->scope = 'row';
664                 $fieldcell->text = $user->{$field};
665                 $userrow->cells[] = $fieldcell;
666             }
668             $rows[] = $userrow;
669         }
671         $rows = $this->get_left_range_row($rows, $colspan);
672         $rows = $this->get_left_avg_row($rows, $colspan, true);
673         $rows = $this->get_left_avg_row($rows, $colspan);
675         return $rows;
676     }
678     /**
679      * Builds and returns the rows that will make up the right part of the grader report
680      * @return array Array of html_table_row objects
681      */
682     public function get_right_rows() {
683         global $CFG, $USER, $OUTPUT, $DB, $PAGE;
685         $rows = array();
686         $this->rowcount = 0;
687         $numrows = count($this->gtree->get_levels());
688         $numusers = count($this->users);
689         $gradetabindex = 1;
690         $columnstounset = array();
691         $strgrade = $this->get_lang_string('grade');
692         $strfeedback  = $this->get_lang_string("feedback");
693         $arrows = $this->get_sort_arrows();
695         $jsarguments = array(
696             'id'        => '#fixed_column',
697             'cfg'       => array('ajaxenabled'=>false),
698             'items'     => array(),
699             'users'     => array(),
700             'feedback'  => array()
701         );
702         $jsscales = array();
704         foreach ($this->gtree->get_levels() as $key=>$row) {
705             if ($key == 0) {
706                 // do not display course grade category
707                 // continue;
708             }
710             $headingrow = new html_table_row();
711             $headingrow->attributes['class'] = 'heading_name_row';
713             foreach ($row as $columnkey => $element) {
714                 $sortlink = clone($this->baseurl);
715                 if (isset($element['object']->id)) {
716                     $sortlink->param('sortitemid', $element['object']->id);
717                 }
719                 $eid    = $element['eid'];
720                 $object = $element['object'];
721                 $type   = $element['type'];
722                 $categorystate = @$element['categorystate'];
724                 if (!empty($element['colspan'])) {
725                     $colspan = $element['colspan'];
726                 } else {
727                     $colspan = 1;
728                 }
730                 if (!empty($element['depth'])) {
731                     $catlevel = 'catlevel'.$element['depth'];
732                 } else {
733                     $catlevel = '';
734                 }
736 // Element is a filler
737                 if ($type == 'filler' or $type == 'fillerfirst' or $type == 'fillerlast') {
738                     $fillercell = new html_table_cell();
739                     $fillercell->attributes['class'] = $type . ' ' . $catlevel;
740                     $fillercell->colspan = $colspan;
741                     $fillercell->text = '&nbsp;';
742                     $fillercell->header = true;
743                     $fillercell->scope = 'col';
744                     $headingrow->cells[] = $fillercell;
745                 }
746 // Element is a category
747                 else if ($type == 'category') {
748                     $categorycell = new html_table_cell();
749                     $categorycell->attributes['class'] = 'category ' . $catlevel;
750                     $categorycell->colspan = $colspan;
751                     $categorycell->text = shorten_text($element['object']->get_name());
752                     $categorycell->text .= $this->get_collapsing_icon($element);
753                     $categorycell->header = true;
754                     $categorycell->scope = 'col';
756                     // Print icons
757                     if ($USER->gradeediting[$this->courseid]) {
758                         $categorycell->text .= $this->get_icons($element);
759                     }
761                     $headingrow->cells[] = $categorycell;
762                 }
763 // Element is a grade_item
764                 else {
765                     //$itemmodule = $element['object']->itemmodule;
766                     //$iteminstance = $element['object']->iteminstance;
768                     if ($element['object']->id == $this->sortitemid) {
769                         if ($this->sortorder == 'ASC') {
770                             $arrow = $this->get_sort_arrow('up', $sortlink);
771                         } else {
772                             $arrow = $this->get_sort_arrow('down', $sortlink);
773                         }
774                     } else {
775                         $arrow = $this->get_sort_arrow('move', $sortlink);
776                     }
778                     $headerlink = $this->gtree->get_element_header($element, true, $this->get_pref('showactivityicons'), false);
780                     $itemcell = new html_table_cell();
781                     $itemcell->attributes['class'] = $type . ' ' . $catlevel . 'highlightable';
783                     if ($element['object']->is_hidden()) {
784                         $itemcell->attributes['class'] .= ' hidden';
785                     }
787                     $itemcell->colspan = $colspan;
788                     $itemcell->text = shorten_text($headerlink) . $arrow;
789                     $itemcell->header = true;
790                     $itemcell->scope = 'col';
792                     $headingrow->cells[] = $itemcell;
793                 }
794             }
795             $rows[] = $headingrow;
796         }
798         $rows = $this->get_right_icons_row($rows);
800         // Preload scale objects for items with a scaleid and initialize tab indices
801         $scaleslist = array();
802         $tabindices = array();
804         foreach ($this->gtree->get_items() as $itemid=>$item) {
805             $scale = null;
806             if (!empty($item->scaleid)) {
807                 $scaleslist[] = $item->scaleid;
808                 $jsarguments['items'][$itemid] = array('id'=>$itemid, 'name'=>$item->get_name(true), 'type'=>'scale', 'scale'=>$item->scaleid, 'decimals'=>$item->get_decimals());
809             } else {
810                 $jsarguments['items'][$itemid] = array('id'=>$itemid, 'name'=>$item->get_name(true), 'type'=>'value', 'scale'=>false, 'decimals'=>$item->get_decimals());
811             }
812             $tabindices[$item->id]['grade'] = $gradetabindex;
813             $tabindices[$item->id]['feedback'] = $gradetabindex + $numusers;
814             $gradetabindex += $numusers * 2;
815         }
816         $scalesarray = array();
818         if (!empty($scaleslist)) {
819             $scalesarray = $DB->get_records_list('scale', 'id', $scaleslist);
820         }
821         $jsscales = $scalesarray;
823         $rowclasses = array('even', 'odd');
825         foreach ($this->users as $userid => $user) {
827             if ($this->canviewhidden) {
828                 $altered = array();
829                 $unknown = array();
830             } else {
831                 $hidingaffected = grade_grade::get_hiding_affected($this->grades[$userid], $this->gtree->get_items());
832                 $altered = $hidingaffected['altered'];
833                 $unknown = $hidingaffected['unknown'];
834                 unset($hidingaffected);
835             }
838             $itemrow = new html_table_row();
839             $itemrow->id = 'user_'.$userid;
840             $itemrow->attributes['class'] = $rowclasses[$this->rowcount % 2];
842             $jsarguments['users'][$userid] = fullname($user);
844             foreach ($this->gtree->items as $itemid=>$unused) {
845                 $item =& $this->gtree->items[$itemid];
846                 $grade = $this->grades[$userid][$item->id];
848                 $itemcell = new html_table_cell();
850                 $itemcell->id = 'u'.$userid.'i'.$itemid;
852                 // Get the decimal points preference for this item
853                 $decimalpoints = $item->get_decimals();
855                 if (in_array($itemid, $unknown)) {
856                     $gradeval = null;
857                 } else if (array_key_exists($itemid, $altered)) {
858                     $gradeval = $altered[$itemid];
859                 } else {
860                     $gradeval = $grade->finalgrade;
861                 }
863                 // MDL-11274
864                 // Hide grades in the grader report if the current grader doesn't have 'moodle/grade:viewhidden'
865                 if (!$this->canviewhidden and $grade->is_hidden()) {
866                     if (!empty($CFG->grade_hiddenasdate) and $grade->get_datesubmitted() and !$item->is_category_item() and !$item->is_course_item()) {
867                         // 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
868                         $itemcell->text = html_writer::tag('span', userdate($grade->get_datesubmitted(),get_string('strftimedatetimeshort')), array('class'=>'datesubmitted'));
869                     } else {
870                         $itemcell->text = '-';
871                     }
872                     $itemrow->cells[] = $itemcell;
873                     continue;
874                 }
876                 // emulate grade element
877                 $eid = $this->gtree->get_grade_eid($grade);
878                 $element = array('eid'=>$eid, 'object'=>$grade, 'type'=>'grade');
880                 $itemcell->attributes['class'] .= ' grade';
881                 if ($item->is_category_item()) {
882                     $itemcell->attributes['class'] .= ' cat';
883                 }
884                 if ($item->is_course_item()) {
885                     $itemcell->attributes['class'] .= ' course';
886                 }
887                 if ($grade->is_overridden()) {
888                     $itemcell->attributes['class'] .= ' overridden';
889                 }
891                 if ($grade->is_excluded()) {
892                     // $itemcell->attributes['class'] .= ' excluded';
893                 }
895                 if (!empty($grade->feedback)) {
896                     //should we be truncating feedback? ie $short_feedback = shorten_text($feedback, $this->feedback_trunc_length);
897                     $jsarguments['feedback'][] = array('user'=>$userid, 'item'=>$itemid, 'content'=>wordwrap(trim(format_string($grade->feedback, $grade->feedbackformat)), 34, '<br/ >'));
898                 }
900                 if ($grade->is_excluded()) {
901                     $itemcell->text .= html_writer::tag('span', get_string('excluded', 'grades'), array('class'=>'excludedfloater'));
902                 }
904                 // Do not show any icons if no grade (no record in DB to match)
905                 if (!$item->needsupdate and $USER->gradeediting[$this->courseid]) {
906                     $itemcell->text .= $this->get_icons($element);
907                 }
909                 $hidden = '';
910                 if ($grade->is_hidden()) {
911                     $hidden = ' hidden ';
912                 }
914                 $gradepass = ' gradefail ';
915                 if ($grade->is_passed($item)) {
916                     $gradepass = ' gradepass ';
917                 } elseif (is_null($grade->is_passed($item))) {
918                     $gradepass = '';
919                 }
921                 // if in editing mode, we need to print either a text box
922                 // or a drop down (for scales)
923                 // grades in item of type grade category or course are not directly editable
924                 if ($item->needsupdate) {
925                     $itemcell->text .= html_writer::tag('span', get_string('error'), array('class'=>"gradingerror$hidden"));
927                 } else if ($USER->gradeediting[$this->courseid]) {
929                     if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
930                         $scale = $scalesarray[$item->scaleid];
931                         $gradeval = (int)$gradeval; // scales use only integers
932                         $scales = explode(",", $scale->scale);
933                         // reindex because scale is off 1
935                         // MDL-12104 some previous scales might have taken up part of the array
936                         // so this needs to be reset
937                         $scaleopt = array();
938                         $i = 0;
939                         foreach ($scales as $scaleoption) {
940                             $i++;
941                             $scaleopt[$i] = $scaleoption;
942                         }
944                         if ($this->get_pref('quickgrading') and $grade->is_editable()) {
945                             $oldval = empty($gradeval) ? -1 : $gradeval;
946                             if (empty($item->outcomeid)) {
947                                 $nogradestr = $this->get_lang_string('nograde');
948                             } else {
949                                 $nogradestr = $this->get_lang_string('nooutcome', 'grades');
950                             }
951                             $itemcell->text .= '<input type="hidden" id="oldgrade_'.$userid.'_'.$item->id.'" name="oldgrade_'.$userid.'_'.$item->id.'" value="'.$oldval.'"/>';
952                             $attributes = array('tabindex' => $tabindices[$item->id]['grade'], 'id'=>'grade_'.$userid.'_'.$item->id);
953                             $itemcell->text .= html_writer::select($scaleopt, 'grade_'.$userid.'_'.$item->id, $gradeval, array(-1=>$nogradestr), $attributes);;
954                         } elseif(!empty($scale)) {
955                             $scales = explode(",", $scale->scale);
957                             // invalid grade if gradeval < 1
958                             if ($gradeval < 1) {
959                                 $itemcell->text .= html_writer::tag('span', '-', array('class'=>"gradevalue$hidden$gradepass"));
960                             } else {
961                                 $gradeval = $grade->grade_item->bounded_grade($gradeval); //just in case somebody changes scale
962                                 $itemcell->text .= html_writer::tag('span', $scales[$gradeval-1], array('class'=>"gradevalue$hidden$gradepass"));
963                             }
964                         } else {
965                             // no such scale, throw error?
966                         }
968                     } else if ($item->gradetype != GRADE_TYPE_TEXT) { // Value type
969                         if ($this->get_pref('quickgrading') and $grade->is_editable()) {
970                             $value = format_float($gradeval, $decimalpoints);
971                             $itemcell->text .= '<input type="hidden" id="oldgrade_'.$userid.'_'.$item->id.'" name="oldgrade_'.$userid.'_'.$item->id.'" value="'.$value.'" />';
972                             $itemcell->text .= '<input size="6" tabindex="' . $tabindices[$item->id]['grade']
973                                           . '" type="text" class="text" title="'. $strgrade .'" name="grade_'
974                                           .$userid.'_' .$item->id.'" id="grade_'.$userid.'_'.$item->id.'" value="'.$value.'" />';
975                         } else {
976                             $itemcell->text .= html_writer::tag('span', format_float($gradeval, $decimalpoints), array('class'=>"gradevalue$hidden$gradepass"));
977                         }
978                     }
981                     // If quickfeedback is on, print an input element
982                     if ($this->get_pref('showquickfeedback') and $grade->is_editable()) {
984                         $itemcell->text .= '<input type="hidden" id="oldfeedback_'.$userid.'_'.$item->id.'" name="oldfeedback_'.$userid.'_'.$item->id.'" value="' . s($grade->feedback) . '" />';
985                         $itemcell->text .= '<input class="quickfeedback" tabindex="' . $tabindices[$item->id]['feedback'].'" id="feedback_'.$userid.'_'.$item->id
986                                       . '" size="6" title="' . $strfeedback . '" type="text" name="feedback_'.$userid.'_'.$item->id.'" value="' . s($grade->feedback) . '" />';
987                     }
989                 } else { // Not editing
990                     $gradedisplaytype = $item->get_displaytype();
992                     if ($item->scaleid && !empty($scalesarray[$item->scaleid])) {
993                         $itemcell->attributes['class'] .= ' grade_type_scale';
994                     } else if ($item->gradetype != GRADE_TYPE_TEXT) {
995                         $itemcell->attributes['class'] .= ' grade_type_text';
996                     }
998                     if ($this->get_pref('enableajax')) {
999                         $itemcell->attributes['class'] .= ' clickable';
1000                     }
1002                     if ($item->needsupdate) {
1003                         $itemcell->text .= html_writer::tag('span', get_string('error'), array('class'=>"gradingerror$hidden$gradepass"));
1004                     } else {
1005                         $itemcell->text .= html_writer::tag('span', grade_format_gradevalue($gradeval, $item, true, $gradedisplaytype, null), array('class'=>"gradevalue$hidden$gradepass"));
1006                         if ($this->get_pref('showanalysisicon')) {
1007                             $itemcell->text .= $this->gtree->get_grade_analysis_icon($grade);
1008                         }
1009                     }
1010                 }
1012                 if (!empty($this->gradeserror[$item->id][$userid])) {
1013                     $itemcell->text .= $this->gradeserror[$item->id][$userid];
1014                 }
1016                 $itemrow->cells[] = $itemcell;
1017             }
1018             $rows[] = $itemrow;
1019         }
1021         if ($this->get_pref('enableajax')) {
1022             $jsarguments['cfg']['ajaxenabled'] = true;
1023             $jsarguments['cfg']['scales'] = array();
1024             foreach ($jsscales as $scale) {
1025                 $jsarguments['cfg']['scales'][$scale->id] = explode(',',$scale->scale);
1026             }
1027             $jsarguments['cfg']['feedbacktrunclength'] =  $this->feedback_trunc_length;
1029             //feedbacks are now being stored in $jsarguments['feedback'] in get_right_rows()
1030             //$jsarguments['cfg']['feedback'] =  $this->feedbacks;
1031         }
1032         $jsarguments['cfg']['isediting'] = (bool)$USER->gradeediting[$this->courseid];
1033         $jsarguments['cfg']['courseid'] =  $this->courseid;
1034         $jsarguments['cfg']['studentsperpage'] =  $this->get_pref('studentsperpage');
1035         $jsarguments['cfg']['showquickfeedback'] =  (bool)$this->get_pref('showquickfeedback');
1037         $module = array(
1038             'name'      => 'gradereport_grader',
1039             'fullpath'  => '/grade/report/grader/module.js',
1040             'requires'  => array('base', 'dom', 'event', 'event-mouseenter', 'event-key', 'io-queue', 'json-parse', 'overlay')
1041         );
1042         $PAGE->requires->js_init_call('M.gradereport_grader.init_report', $jsarguments, false, $module);
1043         $PAGE->requires->strings_for_js(array('addfeedback','feedback', 'grade'), 'grades');
1044         $PAGE->requires->strings_for_js(array('ajaxchoosescale','ajaxclicktoclose','ajaxerror','ajaxfailedupdate', 'ajaxfieldchanged'), 'gradereport_grader');
1046         $rows = $this->get_right_range_row($rows);
1047         $rows = $this->get_right_avg_row($rows, true);
1048         $rows = $this->get_right_avg_row($rows);
1050         return $rows;
1051     }
1053     /**
1054      * Depending on the style of report (fixedstudents vs traditional one-table),
1055      * arranges the rows of data in one or two tables, and returns the output of
1056      * these tables in HTML
1057      * @return string HTML
1058      */
1059     public function get_grade_table() {
1060         global $OUTPUT;
1061         $fixedstudents = $this->is_fixed_students();
1063         $leftrows = $this->get_left_rows();
1064         $rightrows = $this->get_right_rows();
1066         $html = '';
1069         if ($fixedstudents) {
1070             $fixedcolumntable = new html_table();
1071             $fixedcolumntable->id = 'fixed_column';
1072             $fixedcolumntable->data = $leftrows;
1073             $html .= $OUTPUT->container(html_writer::table($fixedcolumntable), 'left_scroller');
1075             $righttable = new html_table();
1076             $righttable->id = 'user-grades';
1077             $righttable->data = $rightrows;
1079             $html .= $OUTPUT->container(html_writer::table($righttable), 'right_scroller');
1080         } else {
1081             $fulltable = new html_table();
1082             $fulltable->attributes['class'] = 'gradestable flexible boxaligncenter generaltable';
1083             $fulltable->id = 'user-grades';
1085             // Extract rows from each side (left and right) and collate them into one row each
1086             foreach ($leftrows as $key => $row) {
1087                 $row->cells = array_merge($row->cells, $rightrows[$key]->cells);
1088                 $fulltable->data[] = $row;
1089             }
1090             $html .= html_writer::table($fulltable);
1091         }
1092         return $OUTPUT->container($html, 'gradeparent');
1093     }
1095     /**
1096      * Builds and return the row of icons for the left side of the report.
1097      * It only has one cell that says "Controls"
1098      * @param array $rows The Array of rows for the left part of the report
1099      * @param int $colspan The number of columns this cell has to span
1100      * @return array Array of rows for the left part of the report
1101      */
1102     public function get_left_icons_row($rows=array(), $colspan=1) {
1103         global $USER;
1105         if ($USER->gradeediting[$this->courseid]) {
1106             $controlsrow = new html_table_row();
1107             $controlsrow->attributes['class'] = 'controls';
1108             $controlscell = new html_table_cell();
1109             $controlscell->attributes['class'] = 'header controls';
1110             $controlscell->colspan = $colspan;
1111             $controlscell->text = $this->get_lang_string('controls','grades');
1113             $controlsrow->cells[] = $controlscell;
1114             $rows[] = $controlsrow;
1115         }
1116         return $rows;
1117     }
1119     /**
1120      * Builds and return the header for the row of ranges, for the left part of the grader report.
1121      * @param array $rows The Array of rows for the left part of the report
1122      * @param int $colspan The number of columns this cell has to span
1123      * @return array Array of rows for the left part of the report
1124      */
1125     public function get_left_range_row($rows=array(), $colspan=1) {
1126         global $CFG, $USER;
1128         if ($this->get_pref('showranges')) {
1129             $rangerow = new html_table_row();
1130             $rangerow->attributes['class'] = 'range r'.$this->rowcount++;
1131             $rangecell = new html_table_cell();
1132             $rangecell->attributes['class'] = 'header range';
1133             $rangecell->colspan = $colspan;
1134             $rangecell->header = true;
1135             $rangecell->scope = 'row';
1136             $rangecell->text = $this->get_lang_string('range','grades');
1137             $rangerow->cells[] = $rangecell;
1138             $rows[] = $rangerow;
1139         }
1141         return $rows;
1142     }
1144     /**
1145      * Builds and return the headers for the rows of averages, for the left part of the grader report.
1146      * @param array $rows The Array of rows for the left part of the report
1147      * @param int $colspan The number of columns this cell has to span
1148      * @param bool $groupavg If true, returns the row for group averages, otherwise for overall averages
1149      * @return array Array of rows for the left part of the report
1150      */
1151     public function get_left_avg_row($rows=array(), $colspan=1, $groupavg=false) {
1152         if (!$this->canviewhidden) {
1153             // totals might be affected by hiding, if user can not see hidden grades the aggregations might be altered
1154             // better not show them at all if user can not see all hideen grades
1155             return $rows;
1156         }
1158         $showaverages = $this->get_pref('showaverages');
1159         $showaveragesgroup = $this->currentgroup && $showaverages;
1160         $straveragegroup = get_string('groupavg', 'grades');
1162         if ($groupavg) {
1163             if ($showaveragesgroup) {
1164                 $groupavgrow = new html_table_row();
1165                 $groupavgrow->attributes['class'] = 'groupavg r'.$this->rowcount++;
1166                 $groupavgcell = new html_table_cell();
1167                 $groupavgcell->attributes['class'] = 'header range';
1168                 $groupavgcell->colspan = $colspan;
1169                 $groupavgcell->header = true;
1170                 $groupavgcell->scope = 'row';
1171                 $groupavgcell->text = $straveragegroup;
1172                 $groupavgrow->cells[] = $groupavgcell;
1173                 $rows[] = $groupavgrow;
1174             }
1175         } else {
1176             $straverage = get_string('overallaverage', 'grades');
1178             if ($showaverages) {
1179                 $avgrow = new html_table_row();
1180                 $avgrow->attributes['class'] = 'avg r'.$this->rowcount++;
1181                 $avgcell = new html_table_cell();
1182                 $avgcell->attributes['class'] = 'header range';
1183                 $avgcell->colspan = $colspan;
1184                 $avgcell->header = true;
1185                 $avgcell->scope = 'row';
1186                 $avgcell->text = $straverage;
1187                 $avgrow->cells[] = $avgcell;
1188                 $rows[] = $avgrow;
1189             }
1190         }
1192         return $rows;
1193     }
1195     /**
1196      * Builds and return the row of icons when editing is on, for the right part of the grader report.
1197      * @param array $rows The Array of rows for the right part of the report
1198      * @return array Array of rows for the right part of the report
1199      */
1200     public function get_right_icons_row($rows=array()) {
1201         global $USER;
1202         if ($USER->gradeediting[$this->courseid]) {
1203             $iconsrow = new html_table_row();
1204             $iconsrow->attributes['class'] = 'controls';
1206             foreach ($this->gtree->items as $itemid=>$unused) {
1207                 // emulate grade element
1208                 $item =& $this->gtree->get_item($itemid);
1210                 $eid = $this->gtree->get_item_eid($item);
1211                 $element = $this->gtree->locate_element($eid);
1212                 $itemcell = new html_table_cell();
1213                 $itemcell->attributes['class'] = 'controls icons';
1214                 $itemcell->text = $this->get_icons($element);
1215                 $iconsrow->cells[] = $itemcell;
1216             }
1217             $rows[] = $iconsrow;
1218         }
1219         return $rows;
1220     }
1222     /**
1223      * Builds and return the row of ranges for the right part of the grader report.
1224      * @param array $rows The Array of rows for the right part of the report
1225      * @return array Array of rows for the right part of the report
1226      */
1227     public function get_right_range_row($rows=array()) {
1228         global $OUTPUT;
1230         if ($this->get_pref('showranges')) {
1231             $rangesdisplaytype   = $this->get_pref('rangesdisplaytype');
1232             $rangesdecimalpoints = $this->get_pref('rangesdecimalpoints');
1233             $rangerow = new html_table_row();
1234             $rangerow->attributes['class'] = 'heading range';
1236             foreach ($this->gtree->items as $itemid=>$unused) {
1237                 $item =& $this->gtree->items[$itemid];
1238                 $itemcell = new html_table_cell();
1239                 $itemcell->header = true;
1240                 $itemcell->attributes['class'] .= ' header range';
1242                 $hidden = '';
1243                 if ($item->is_hidden()) {
1244                     $hidden = ' hidden ';
1245                 }
1247                 $formattedrange = $item->get_formatted_range($rangesdisplaytype, $rangesdecimalpoints);
1249                 $itemcell->text = $OUTPUT->container($formattedrange, 'rangevalues'.$hidden);
1250                 $rangerow->cells[] = $itemcell;
1251             }
1252             $rows[] = $rangerow;
1253         }
1254         return $rows;
1255     }
1257     /**
1258      * Builds and return the row of averages for the right part of the grader report.
1259      * @param array $rows Whether to return only group averages or all averages.
1260      * @param bool $grouponly Whether to return only group averages or all averages.
1261      * @return array Array of rows for the right part of the report
1262      */
1263     public function get_right_avg_row($rows=array(), $grouponly=false) {
1264         global $CFG, $USER, $DB, $OUTPUT;
1266         if (!$this->canviewhidden) {
1267             // totals might be affected by hiding, if user can not see hidden grades the aggregations might be altered
1268             // better not show them at all if user can not see all hidden grades
1269             return $rows;
1270         }
1272         $showaverages = $this->get_pref('showaverages');
1273         $showaveragesgroup = $this->currentgroup && $showaverages;
1275         $averagesdisplaytype   = $this->get_pref('averagesdisplaytype');
1276         $averagesdecimalpoints = $this->get_pref('averagesdecimalpoints');
1277         $meanselection         = $this->get_pref('meanselection');
1278         $shownumberofgrades    = $this->get_pref('shownumberofgrades');
1280         $avghtml = '';
1281         $avgcssclass = 'avg';
1283         if ($grouponly) {
1284             $straverage = get_string('groupavg', 'grades');
1285             $showaverages = $this->currentgroup && $this->get_pref('showaverages');
1286             $groupsql = $this->groupsql;
1287             $groupwheresql = $this->groupwheresql;
1288             $groupwheresqlparams = $this->groupwheresql_params;
1289             $avgcssclass = 'groupavg';
1290         } else {
1291             $straverage = get_string('overallaverage', 'grades');
1292             $showaverages = $this->get_pref('showaverages');
1293             $groupsql = "";
1294             $groupwheresql = "";
1295             $groupwheresqlparams = array();
1296         }
1298         if ($shownumberofgrades) {
1299             $straverage .= ' (' . get_string('submissions', 'grades') . ') ';
1300         }
1302         $totalcount = $this->get_numusers($grouponly);
1304         //limit to users with a gradeable role
1305         list($gradebookrolessql, $gradebookrolesparams) = $DB->get_in_or_equal(explode(',', $this->gradebookroles), SQL_PARAMS_NAMED, 'grbr0');
1307         //limit to users with an active enrollment
1308         list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->context);
1310         if ($showaverages) {
1311             $params = array_merge(array('courseid'=>$this->courseid), $gradebookrolesparams, $enrolledparams, $groupwheresqlparams);
1313             // find sums of all grade items in course
1314             $sql = "SELECT g.itemid, SUM(g.finalgrade) AS sum
1315                       FROM {grade_items} gi
1316                       JOIN {grade_grades} g ON g.itemid = gi.id
1317                       JOIN {user} u ON u.id = g.userid
1318                       JOIN ($enrolledsql) je ON je.id = u.id
1319                       JOIN (
1320                                SELECT DISTINCT ra.userid
1321                                  FROM {role_assignments} ra
1322                                 WHERE ra.roleid $gradebookrolessql
1323                                   AND ra.contextid " . get_related_contexts_string($this->context) . "
1324                            ) rainner ON rainner.userid = u.id
1325                       $groupsql
1326                      WHERE gi.courseid = :courseid
1327                        AND u.deleted = 0
1328                        AND g.finalgrade IS NOT NULL
1329                        $groupwheresql
1330                      GROUP BY g.itemid";
1331             $sumarray = array();
1332             if ($sums = $DB->get_records_sql($sql, $params)) {
1333                 foreach ($sums as $itemid => $csum) {
1334                     $sumarray[$itemid] = $csum->sum;
1335                 }
1336             }
1338             // MDL-10875 Empty grades must be evaluated as grademin, NOT always 0
1339             // This query returns a count of ungraded grades (NULL finalgrade OR no matching record in grade_grades table)
1340             $sql = "SELECT gi.id, COUNT(DISTINCT u.id) AS count
1341                       FROM {grade_items} gi
1342                       CROSS JOIN {user} u
1343                       JOIN ($enrolledsql) je
1344                            ON je.id = u.id
1345                       JOIN {role_assignments} ra
1346                            ON ra.userid = u.id
1347                       LEFT OUTER JOIN {grade_grades} g
1348                            ON (g.itemid = gi.id AND g.userid = u.id AND g.finalgrade IS NOT NULL)
1349                       $groupsql
1350                      WHERE gi.courseid = :courseid
1351                            AND ra.roleid $gradebookrolessql
1352                            AND ra.contextid ".get_related_contexts_string($this->context)."
1353                            AND u.deleted = 0
1354                            AND g.id IS NULL
1355                            $groupwheresql
1356                   GROUP BY gi.id";
1358             $ungradedcounts = $DB->get_records_sql($sql, $params);
1360             $avgrow = new html_table_row();
1361             $avgrow->attributes['class'] = 'avg';
1363             foreach ($this->gtree->items as $itemid=>$unused) {
1364                 $item =& $this->gtree->items[$itemid];
1366                 if ($item->needsupdate) {
1367                     $avgcell = new html_table_cell();
1368                     $avgcell->text = $OUTPUT->container(get_string('error'), 'gradingerror');
1369                     $avgrow->cells[] = $avgcell;
1370                     continue;
1371                 }
1373                 if (!isset($sumarray[$item->id])) {
1374                     $sumarray[$item->id] = 0;
1375                 }
1377                 if (empty($ungradedcounts[$itemid])) {
1378                     $ungradedcount = 0;
1379                 } else {
1380                     $ungradedcount = $ungradedcounts[$itemid]->count;
1381                 }
1383                 if ($meanselection == GRADE_REPORT_MEAN_GRADED) {
1384                     $meancount = $totalcount - $ungradedcount;
1385                 } else { // Bump up the sum by the number of ungraded items * grademin
1386                     $sumarray[$item->id] += $ungradedcount * $item->grademin;
1387                     $meancount = $totalcount;
1388                 }
1390                 $decimalpoints = $item->get_decimals();
1392                 // Determine which display type to use for this average
1393                 if ($USER->gradeediting[$this->courseid]) {
1394                     $displaytype = GRADE_DISPLAY_TYPE_REAL;
1396                 } else if ($averagesdisplaytype == GRADE_REPORT_PREFERENCE_INHERIT) { // no ==0 here, please resave the report and user preferences
1397                     $displaytype = $item->get_displaytype();
1399                 } else {
1400                     $displaytype = $averagesdisplaytype;
1401                 }
1403                 // Override grade_item setting if a display preference (not inherit) was set for the averages
1404                 if ($averagesdecimalpoints == GRADE_REPORT_PREFERENCE_INHERIT) {
1405                     $decimalpoints = $item->get_decimals();
1407                 } else {
1408                     $decimalpoints = $averagesdecimalpoints;
1409                 }
1411                 if (!isset($sumarray[$item->id]) || $meancount == 0) {
1412                     $avgcell = new html_table_cell();
1413                     $avgcell->text = '-';
1414                     $avgrow->cells[] = $avgcell;
1416                 } else {
1417                     $sum = $sumarray[$item->id];
1418                     $avgradeval = $sum/$meancount;
1419                     $gradehtml = grade_format_gradevalue($avgradeval, $item, true, $displaytype, $decimalpoints);
1421                     $numberofgrades = '';
1422                     if ($shownumberofgrades) {
1423                         $numberofgrades = " ($meancount)";
1424                     }
1426                     $avgcell = new html_table_cell();
1427                     $avgcell->text = $gradehtml.$numberofgrades;
1428                     $avgrow->cells[] = $avgcell;
1429                 }
1430             }
1431             $rows[] = $avgrow;
1432         }
1433         return $rows;
1434     }
1436     /**
1437      * Given a grade_category, grade_item or grade_grade, this function
1438      * figures out the state of the object and builds then returns a div
1439      * with the icons needed for the grader report.
1440      *
1441      * @param array $object
1442      * @return string HTML
1443      */
1444     protected function get_icons($element) {
1445         global $CFG, $USER, $OUTPUT;
1447         if (!$USER->gradeediting[$this->courseid]) {
1448             return '<div class="grade_icons" />';
1449         }
1451         // Init all icons
1452         $editicon = '';
1454         if ($element['type'] != 'categoryitem' && $element['type'] != 'courseitem') {
1455             $editicon = $this->gtree->get_edit_icon($element, $this->gpr);
1456         }
1458         $editcalculationicon = '';
1459         $showhideicon        = '';
1460         $lockunlockicon      = '';
1462         if (has_capability('moodle/grade:manage', $this->context)) {
1463             if ($this->get_pref('showcalculations')) {
1464                 $editcalculationicon = $this->gtree->get_calculation_icon($element, $this->gpr);
1465             }
1467             if ($this->get_pref('showeyecons')) {
1468                $showhideicon = $this->gtree->get_hiding_icon($element, $this->gpr);
1469             }
1471             if ($this->get_pref('showlocks')) {
1472                 $lockunlockicon = $this->gtree->get_locking_icon($element, $this->gpr);
1473             }
1475         }
1477         $gradeanalysisicon   = '';
1478         if ($this->get_pref('showanalysisicon') && $element['type'] == 'grade') {
1479             $gradeanalysisicon .= $this->gtree->get_grade_analysis_icon($element['object']);
1480         }
1482         return $OUTPUT->container($editicon.$editcalculationicon.$showhideicon.$lockunlockicon.$gradeanalysisicon, 'grade_icons');
1483     }
1485     /**
1486      * Given a category element returns collapsing +/- icon if available
1487      * @param object $object
1488      * @return string HTML
1489      */
1490     protected function get_collapsing_icon($element) {
1491         global $OUTPUT;
1493         $icon = '';
1494         // If object is a category, display expand/contract icon
1495         if ($element['type'] == 'category') {
1496             // Load language strings
1497             $strswitchminus = $this->get_lang_string('aggregatesonly', 'grades');
1498             $strswitchplus  = $this->get_lang_string('gradesonly', 'grades');
1499             $strswitchwhole = $this->get_lang_string('fullmode', 'grades');
1501             $url = new moodle_url($this->gpr->get_return_url(null, array('target'=>$element['eid'], 'sesskey'=>sesskey())));
1503             if (in_array($element['object']->id, $this->collapsed['aggregatesonly'])) {
1504                 $url->param('action', 'switch_plus');
1505                 $icon = $OUTPUT->action_icon($url, new pix_icon('t/switch_plus', $strswitchplus));
1507             } else if (in_array($element['object']->id, $this->collapsed['gradesonly'])) {
1508                 $url->param('action', 'switch_whole');
1509                 $icon = $OUTPUT->action_icon($url, new pix_icon('t/switch_whole', $strswitchwhole));
1511             } else {
1512                 $url->param('action', 'switch_minus');
1513                 $icon = $OUTPUT->action_icon($url, new pix_icon('t/switch_minus', $strswitchminus));
1514             }
1515         }
1516         return $icon;
1517     }
1519     /**
1520      * Processes a single action against a category, grade_item or grade.
1521      * @param string $target eid ({type}{id}, e.g. c4 for category4)
1522      * @param string $action Which action to take (edit, delete etc...)
1523      * @return
1524      */
1525     public function process_action($target, $action) {
1526         // TODO: this code should be in some grade_tree static method
1527         $targettype = substr($target, 0, 1);
1528         $targetid = substr($target, 1);
1529         // TODO: end
1531         if ($collapsed = get_user_preferences('grade_report_grader_collapsed_categories')) {
1532             $collapsed = unserialize($collapsed);
1533         } else {
1534             $collapsed = array('aggregatesonly' => array(), 'gradesonly' => array());
1535         }
1537         switch ($action) {
1538             case 'switch_minus': // Add category to array of aggregatesonly
1539                 if (!in_array($targetid, $collapsed['aggregatesonly'])) {
1540                     $collapsed['aggregatesonly'][] = $targetid;
1541                     set_user_preference('grade_report_grader_collapsed_categories', serialize($collapsed));
1542                 }
1543                 break;
1545             case 'switch_plus': // Remove category from array of aggregatesonly, and add it to array of gradesonly
1546                 $key = array_search($targetid, $collapsed['aggregatesonly']);
1547                 if ($key !== false) {
1548                     unset($collapsed['aggregatesonly'][$key]);
1549                 }
1550                 if (!in_array($targetid, $collapsed['gradesonly'])) {
1551                     $collapsed['gradesonly'][] = $targetid;
1552                 }
1553                 set_user_preference('grade_report_grader_collapsed_categories', serialize($collapsed));
1554                 break;
1555             case 'switch_whole': // Remove the category from the array of collapsed cats
1556                 $key = array_search($targetid, $collapsed['gradesonly']);
1557                 if ($key !== false) {
1558                     unset($collapsed['gradesonly'][$key]);
1559                     set_user_preference('grade_report_grader_collapsed_categories', serialize($collapsed));
1560                 }
1562                 break;
1563             default:
1564                 break;
1565         }
1567         return true;
1568     }
1570     /**
1571      * Returns whether or not to display fixed students column.
1572      * Includes a browser check, because IE6 doesn't support the scrollbar.
1573      *
1574      * @return bool
1575      */
1576     public function is_fixed_students() {
1577         global $USER, $CFG;
1578         return empty($USER->screenreader) && $CFG->grade_report_fixedstudents &&
1579             (check_browser_version('MSIE', '7.0') ||
1580              check_browser_version('Firefox', '2.0') ||
1581              check_browser_version('Gecko', '2006010100') ||
1582              check_browser_version('Camino', '1.0') ||
1583              check_browser_version('Opera', '6.0') ||
1584              check_browser_version('Chrome', '6') ||
1585              check_browser_version('Safari', '300'));
1586     }
1588     /**
1589      * Refactored function for generating HTML of sorting links with matching arrows.
1590      * Returns an array with 'studentname' and 'idnumber' as keys, with HTML ready
1591      * to inject into a table header cell.
1592      * @param array $extrafields Array of extra fields being displayed, such as
1593      *   user idnumber
1594      * @return array An associative array of HTML sorting links+arrows
1595      */
1596     public function get_sort_arrows(array $extrafields = array()) {
1597         global $OUTPUT;
1598         $arrows = array();
1600         $strsortasc   = $this->get_lang_string('sortasc', 'grades');
1601         $strsortdesc  = $this->get_lang_string('sortdesc', 'grades');
1602         $strfirstname = $this->get_lang_string('firstname');
1603         $strlastname  = $this->get_lang_string('lastname');
1605         $firstlink = html_writer::link(new moodle_url($this->baseurl, array('sortitemid'=>'firstname')), $strfirstname);
1606         $lastlink = html_writer::link(new moodle_url($this->baseurl, array('sortitemid'=>'lastname')), $strlastname);
1608         $arrows['studentname'] = $lastlink;
1610         if ($this->sortitemid === 'lastname') {
1611             if ($this->sortorder == 'ASC') {
1612                 $arrows['studentname'] .= print_arrow('up', $strsortasc, true);
1613             } else {
1614                 $arrows['studentname'] .= print_arrow('down', $strsortdesc, true);
1615             }
1616         }
1618         $arrows['studentname'] .= ' ' . $firstlink;
1620         if ($this->sortitemid === 'firstname') {
1621             if ($this->sortorder == 'ASC') {
1622                 $arrows['studentname'] .= print_arrow('up', $strsortasc, true);
1623             } else {
1624                 $arrows['studentname'] .= print_arrow('down', $strsortdesc, true);
1625             }
1626         }
1628         foreach ($extrafields as $field) {
1629             $fieldlink = html_writer::link(new moodle_url($this->baseurl,
1630                     array('sortitemid'=>$field)), get_user_field_name($field));
1631             $arrows[$field] = $fieldlink;
1633             if ($field == $this->sortitemid) {
1634                 if ($this->sortorder == 'ASC') {
1635                     $arrows[$field] .= print_arrow('up', $strsortasc, true);
1636                 } else {
1637                     $arrows[$field] .= print_arrow('down', $strsortdesc, true);
1638                 }
1639             }
1640         }
1642         return $arrows;
1643     }